Search is not available for this dataset
query
stringlengths
7
355k
document
stringlengths
9
341k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
If the map position is out of range, move it back
function checkBounds() { // Perform the check and return if OK if (allowedBounds.contains(map.getCenter())) { return; } // It`s not OK, so find the nearest allowed point and move there var C = map.getCenter(); var X = C.lng(); var Y = C.lat(); var AmaxX = allowedBounds.getNorthEast().lng(); var AmaxY = allowedBounds.getNorthEast().lat(); var AminX = allowedBounds.getSouthWest().lng(); var AminY = allowedBounds.getSouthWest().lat(); if (X < AminX) {X = AminX;} if (X > AmaxX) {X = AmaxX;} if (Y < AminY) {Y = AminY;} if (Y > AmaxY) {Y = AmaxY;} //alert ("Restricting "+Y+" "+X); map.setCenter(new GLatLng(Y,X)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "move() {\n //Move the kid to the determined location\n this.x = this.nextMoveX;\n this.y = this.nextMoveY;\n //Check in case the kid touches the edges of the map,\n // if so, prevent them from leaving.\n this.handleConstraints();\n }", "stop() {\n dataMap.get(this).moveX = 0;\n dataMap.get(this).moveY = 0;\n }", "moveUp() {\n dataMap.get(this).moveY = -5;\n }", "_onMoveEnd() {\n this._map.locate({\n 'watch': true,\n 'setView': false,\n 'enableHighAccuracy': true,\n });\n }", "function dragMapStop() {\n\tif (dragging) {\n\t\tlastMapPosition = currentMapPosition; \n\t}\n}", "function move(dir, dist) {\n var newx = player['x'];\n var newy = player['y'];\n // set default distance to 1\n mode = typeof mode !== 'undefined' ? mode : 1;\n // adjust position based on distance to be moved\n if (dir == 0) newx+=dist;\n if (dir == 1) newy-=dist;\n if (dir == 2) newx-=dist;\n if (dir == 3) newy+=dist;\n // check that the move is possible:\n var fail = false; // gets set to true if dist > 1 and we fail a check_move\n \n // checks if a tile we want to move onto is currently in motion, &\n // if so, don't allow the move\n // TODO 'newy' & 'newx' are undefined if attempting to move/jump off the map, which throws some type errors.\n // check for this in the future to suppress that crap\n if (map[newy][newx]['x'] != map[newy][newx]['newx']\n || map[newy][newx]['y'] != map[newy][newx]['newy']) {\n fail = true;\n }\n\n // check moves that are > 1 space\n if (dist > 1) { \n // we need to check all possible spaces that the player will pass over,\n // and need to check that both the side we are moving from and the side\n // we are moving out of are free, otherwise don't even check the end tile\n // as we do below\n var tempnewx = player['x'];\n var tempnewy = player['y'];\n // check the space 2 away to make sure we can move OFF the space we are jumping over,\n // as well as ONTO it (which is checked with tempnewx, tempnewy)\n var tempnewx2 = player['x'];\n var tempnewy2 = player['y'];\n\n for (i=1; i<dist; i++) {\n if (dir == 0) tempnewx = player['x'] + i;\n if (dir == 1) tempnewy = player['y'] - i;\n if (dir == 2) tempnewx = player['x'] - i;\n if (dir == 3) tempnewy = player['y'] + i;\n if (dir == 0) tempnewx2 = player['x'] + (i + 1);\n if (dir == 1) tempnewy2 = player['y'] - (i + 1);\n if (dir == 2) tempnewx2 = player['x'] - (i + 1);\n if (dir == 3) tempnewy2 = player['y'] + (i + 1);\n\n // if any of the spaces we move over fail a check_move check\n // if the tile is lava we can ignore the check_move result\n if (map[tempnewy][tempnewx]['type'] != ' '\n // if there is a NON-LAVA tile, then the check_move for that tile needs to pass\n && (!(check_move(player['x'], player['y'], tempnewx, tempnewy, dir)) \n || !(check_move(tempnewx, tempnewy, tempnewx2, tempnewy2, dir)))) {\n //console.log(\"JUMPBLOCKED\")\n fail = true; // don't really need this because we break i guess\n break;\n } \n }\n }\n\n // check the start space and end space (above code checks in between spaces if dist > 1)\n if (!fail && (check_move(player['x'], player['y'], newx, newy, dir))) {\n // console.log('Player moved from (' + player[0] + ', ' + player[1] +\n // ') to (' + x + ', ' + y + ')');\n //add_move(player[0], player[1], x, y, dir, TWEENSPEED);\n player['newx'] = newx;\n player['newy'] = newy;\n }\n}", "returnToLastPos() {\n if (this.previousPos) {\n this.x = this.previousPos.x\n this.y = this.previousPos.y\n }\n }", "function mapMove(x, y) {\n if (windowW >= mapW)\n x = 0;\n else {\n if (x > 0) x = 0;\n else if (x < -mapW + windowW) x = -mapW + windowW;\n }\n if (windowH >= mapH)\n y = 0;\n else {\n if (y > 0) y = 0;\n else if (y < -mapH + windowH) y = -mapH + windowH;\n }\n $(\"#map\")[0].style.marginLeft = x + \"px\";\n $(\"#map\")[0].style.marginTop = y + \"px\";\n}", "function rePosition(){\r\n piece.pos.y = 0; // this and next line puts the next piece at the top centered\r\n piece.pos.x = ( (arena[0].length / 2) | 0) - ( (piece.matrix[0].length / 2) | 0);\r\n }", "moveDown() {\n dataMap.get(this).moveY = 5;\n }", "function move_tiles(){\r\n\t\toriginalTop = parseInt(this.style.top);\r\n\t\toriginalLeft = parseInt(this.style.left);\r\n\t\tif (originalTop == eTop && originalLeft == (eLeft-100) || originalTop == eTop && originalLeft == (eLeft+100) || originalTop == (eTop-100) && originalLeft == eLeft || originalTop == (eTop+100) && originalLeft == eLeft){\r\n\t\t\tthis.style.top = eTop + \"px\";\r\n\t\t\tthis.style.left = eLeft + \"px\";\r\n\t\t\teTop = originalTop;\r\n\t\t\teLeft = originalLeft;\r\n\t\t}\r\n\t}", "updatePosition(position, move) {\n position[move.to] = position[move.from];\n position[move.from] = null;\n }", "function processMove(){\n\t\tmyTile.pop();\n\t\ttryTile.push(obj);\n\t\tobj.move(x, y);\n\t\tmapGroup.addChild(obj);\n\t\treturn true;\n\t}", "moveLeft() {\n dataMap.get(this).moveX = -5;\n }", "moveRight() {\n dataMap.get(this).moveX = 5;\n }", "function moveMap(location) {\n\tif (location == \"home\") {\n\t\tSuperSecretMap.setCenter(myLatLng)\n\t} else {\n\t\tSuperSecretMap.setCenter(location)\n\t}\n}", "function handleUpadateLocation() {\n resetMap();\n}", "moveForward () {\n let posAux = Object.assign({}, this.position);\n switch (this.position.orientation) {\n case 'N':\n this.position.column++;\n break;\n case 'S':\n this.position.column--;\n break;\n case 'E':\n this.position.row--;\n break;\n case 'W':\n this.position.row++;\n break;\n default:\n break;\n }\n this.isLost(posAux);\n }", "move() {\n this.x = this.x - 7\n }", "find_possible_directions(map, sprite_xpos, sprite_ypos) {\r\n \r\n // Possible new directions\r\n var new_directions = [\r\n { name: 'UP', dEnum: this.directionEnum.UP, value: 1 },\r\n { name: 'RIGHT', dEnum: this.directionEnum.RIGHT, value: 1 },\r\n { name: 'DOWN', dEnum: this.directionEnum.DOWN, value: 1 },\r\n { name: 'LEFT', dEnum: this.directionEnum.LEFT, value: 1 }\r\n ];\r\n\r\n // we can change direction - but we cannot reverse direction (normally)\r\n // So remove opposite directions from possibles\r\n var in_ghost_house = this.in_ghost_house();\r\n \r\n // Stop reverse direction. \r\n if (in_ghost_house == false) \r\n { // If we are not in the ghost house then we cannot reverse direction. \r\n if (this.ghost.direction_current != null) { \r\n if (this.ghost.direction_current.dEnum == this.directionEnum.UP) { new_directions[this.directionEnum.DOWN].value = 0; }\r\n if (this.ghost.direction_current.dEnum == this.directionEnum.RIGHT) { new_directions[this.directionEnum.LEFT].value = 0; }\r\n if (this.ghost.direction_current.dEnum == this.directionEnum.DOWN) { new_directions[this.directionEnum.UP].value = 0; }\r\n if (this.ghost.direction_current.dEnum == this.directionEnum.LEFT) { new_directions[this.directionEnum.RIGHT].value = 0; }\r\n }\r\n }\r\n\r\n // If in ghost house and release count > 0;\r\n // stop left and right movement.\r\n if (in_ghost_house && this.ghost.release_count > 0) {\r\n // If we are in the ghost house restric left and right movement.\r\n new_directions[this.directionEnum.LEFT].value = 0;\r\n new_directions[this.directionEnum.RIGHT].value = 0;\r\n }\r\n\r\n\r\n // Do any of the surrounding tiles prevent movement ?\r\n // Remove direction available to travel based on the map tile\r\n var map_tiles = new Array(' ', '.','p');\r\n var surrounding_tiles = map.get_map_surrounding_tiles_pixel_coords(sprite_xpos, sprite_ypos); \r\n\r\n // Allow ghost through door of ghost house.\r\n if (this.sprite.status == this.statusEnum.DEAD && surrounding_tiles[2].value=='x') {\r\n map_tiles.push('x');\r\n }\r\n else if (this.ghost.release_count == 0 && surrounding_tiles[0].value=='x') {\r\n map_tiles.push('x');\r\n }\r\n\r\n\r\n if (map_tiles.indexOf(surrounding_tiles[this.directionEnum.UP].value) == -1)\r\n new_directions[this.directionEnum.UP].value = 0;\r\n\r\n if (map_tiles.indexOf(surrounding_tiles[this.directionEnum.RIGHT].value) == -1)\r\n new_directions[this.directionEnum.RIGHT].value = 0;\r\n\r\n if (map_tiles.indexOf(surrounding_tiles[this.directionEnum.DOWN].value) == -1)\r\n new_directions[this.directionEnum.DOWN].value = 0;\r\n\r\n if (map_tiles.indexOf(surrounding_tiles[this.directionEnum.LEFT].value) == -1)\r\n new_directions[this.directionEnum.LEFT].value = 0; \r\n\r\n return new_directions;\r\n }", "goForward() {\n const actualPosition = this.mower.position.clone();\n const nextPosition = this.getNextPositionForward(actualPosition);\n if(this.isNextPositionAllowed(nextPosition)) {\n this.updatePosition(nextPosition);\n }\n }", "function move_missiles()\n{\t\t\t\n\tmissile_timer -= 1;\n\tfor(var i = 0;i<missiles.length;i++)\n\t{\n\t\tif (missiles[i]['direction'] == 'right')\n\t\t{\n\t\t\tmissiles[i]['position'][0] += 10;\n\t\t}\n\t\telse if (missiles[i]['direction'] == 'left')\n\t\t{\n\t\t\tmissiles[i]['position'][0] -= 10;\n\t\t}\n\t\telse if (missiles[i]['direction'] == 'up')\n\t\t{\n\t\t\tmissiles[i]['position'][1] -= 10;\n\t\t}\n\t\telse if (missiles[i]['direction'] == 'down')\n\t\t{\n\t\t\tmissiles[i]['position'][1] += 10;\n\t\t}\n\t}\n}", "function moveMap(coords) {\n map.panTo(coords);\n}", "move(){\n this.x = this.x + this.s;\n if (this.x > width){\n this.x = 0;\n }\n }", "move() {\n\t\tthis.lastPosition = [ this.x, this.y ];\n\n\t\tthis.x += this.nextMove[0];\n\t\tthis.y += this.nextMove[1];\n\t}", "move() {\n if (this.crashed) {\n return;\n }\n if (this.direction == 1) {\n this.y -= settings.step;\n }\n else if (this.direction == 2) {\n this.x += settings.step;\n }\n else if (this.direction == 3) {\n this.y += settings.step;\n }\n else if (this.direction == 4) {\n this.x -= settings.step;\n }\n }", "function move() {\n\n var t = d3.event.translate;\n var s = d3.event.scale; \n interact_map(t, s);\n}", "move() {\n if (!this.isOnTabletop()) return;\n let [dx, dy]=FacingOptions.getFacingMoment(this.facing);\n let nx=this.x+dx;\n let ny=this.y+dy;\n if (this.tabletop.isOutOfBoundary(nx, ny)) return;\n this.x=nx;\n this.y=ny;\n }", "function teleport(AIMap)\n {\n var i, j;\n do\n {\n i = randomintAtoB(1,GRIDSIZE-2);\n j = randomintAtoB(1,GRIDSIZE-2);\n }\n while ( occupied(i,j) && GRID[i][j] != GRID_BLANK); \t // search for empty square\n\n //set old i and j to null\n AIMap['oldI'] = null;\n AIMap['oldJ'] = null;\n\n //set new position\n AIMap['i'] = i;\n AIMap['j'] = j;\n\n }", "function legalMove(posX, posY)\n{\n //Check within map bounds\n if (posY >= 0 && posY < mapHeight && posX >= 0 && posX < mapWidth)\n {\n //Check if visible tile\n if (map[((posY*mapWidth)+posX)] != 1)\n {\n return true;\n }\n }\n return false;\n}", "moveActor() {\n // used to work as tunnel if left and right are empty pacman/ghosts can easily move in tunnel\n if (this.tileTo[0] < -1) {\n this.tileTo[0] = this.gameMap.layoutMap.column;\n }\n if (this.tileTo[0] > this.gameMap.layoutMap.column) {\n this.tileTo[0] = -1;\n }\n\n // used to work as tunnel if top and bottom are empty pacman/ghosts can easily move in tunnel\n if (this.tileTo[1] < -1) {\n this.tileTo[1] = this.gameMap.layoutMap.row;\n }\n if (this.tileTo[1] > this.gameMap.layoutMap.row) {\n this.tileTo[1] = -1;\n }\n\n // as our pacman/ghosts needs to move constantly widthout key press,\n // also pacman/ghosts should stop when there is obstacle the code has become longer\n\n // if pacman/ghosts is moving up check of upper box is empty and go otherise stop\n if (this.movingDirection === MOVING_DIRECTION.UP) {\n if (this.isBlockUpperThanActorEmpty()) {\n this.tileTo[1] -= 1;\n }\n }\n\n // if pacman/ghosts is moving down check of down box is empty and go otherise stop\n if (this.movingDirection === MOVING_DIRECTION.DOWN) {\n if (this.isBlockLowerThanActorEmpty()) {\n this.tileTo[1] += 1;\n }\n }\n\n // if pacman/ghosts is moving left check of left box is empty and go otherise stop\n if (this.movingDirection === MOVING_DIRECTION.LEFT) {\n if (this.isBlockLeftThanActorEmpty()) {\n this.tileTo[0] -= 1;\n }\n }\n\n // if pacman/ghosts is moving right check of right box is empty and go otherise stop\n if (this.movingDirection === MOVING_DIRECTION.RIGHT) {\n if (this.isBlockRightThanActorEmpty()) {\n this.tileTo[0] += 1;\n }\n }\n }", "move(mapX, mapY) {\n // check if it is a walkable tile\n let walkable = this.dontTreadOnMe();\n if (this.state.healing) {\n walkable[this.state.villager.map[0]-1][this.state.villager.map[1]-1] = 0;\n }\n if (walkable[mapX-1][mapY-1] === 0) {\n // use easy-astar npm to generate array of coordinates to goal\n const startPos = {x:this.state.playerMap[0], y:this.state.playerMap[1]};\n const endPos = {x:mapX,y:mapY};\n const aStarPath = aStar((x, y)=>{\n if (walkable[x-1][y-1] === 0) {\n return true; // 0 means road\n } else {\n return false; // 1 means wall\n }\n }, startPos, endPos);\n let path = aStarPath.map( element => [element.x, element.y]);\n if (this.state.healing) { path.pop() };\n this.setState({moving: true}, () => this.direction(path));\n };\n }", "function moveMap(loc){\n\n\tvar point = map.getCenter();\n\n\teasingAnimator.easeProp({\n\t\tlat: point.lat(),\n\t\tlng: point.lng()\n\t}, {lat: loc.lat(), lng: loc.lng() });\n\n}", "function outOfBound(newMove) {\n if (newMove > 410 || newMove < 10) {\n promptError(\"You shall not pass!\");\n return true;\n } else return false;\n}", "function clearNextMovesMarkers() {\n mapSquares(square => square.canBeNextMove = false);\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapAcid.resize();\n roeMapAcid.reposition();\n }", "function move()\n{\n\tif (player.direction == MOVE_NONE)\n\t{\n \tplayer.moving = false;\n\t\t//console.log(\"y: \" + ((player.y-20)/40));\n\t\t//console.log(\"x: \" + ((player.x-20)/40));\n \treturn;\n \t}\n \tplayer.moving = true;\n \t//console.log(\"move\");\n \n\tif (player.direction == MOVE_LEFT)\n\t{\n \tif(player.angle != -90)\n\t\t{\n\t\t\tplayer.angle = -90;\n\t\t}\n\t\tif(map[playerPos.x][playerPos.y-1].walkable)\n\t\t{\n\t\t\tplayer.moving = true;\n\t\t\tplayerPos.y -=1;\n\t\t\tvar newX = player.position.x - 40;\n\t\t\tcheckCharms(playerPos.x, playerPos.y);\n\t\t\tcreatejs.Tween.get(player).to({x: newX, y: player.position.y}, 250).call(move);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPIXI.sound.play('wrongWay');\n\t\t\tplayer.direction = MOVE_NONE;\n\t\t\tmove();\n\t\t}\n \t}\n\tif (player.direction == MOVE_RIGHT)\n\t{\n \tif(player.angle != 90)\n\t\t{\n\t\t\tplayer.angle = 90;\n\t\t}\n\t\tif(map[playerPos.x][playerPos.y+1].walkable)\n\t\t{\n\t\t\tplayer.moving = true;\n\t\t\tplayerPos.y+=1;\n\t\t\tcheckCharms(playerPos.x, playerPos.y);\n\t\t\tvar newX = player.position.x + 40;\n\t\t\tcreatejs.Tween.get(player).to({x: newX, y: player.position.y}, 250).call(move);\n\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPIXI.sound.play('wrongWay');\n\t\t\tplayer.direction = MOVE_NONE;\n\t\t\tmove();\n\t\t}\n\t}\n \tif (player.direction == MOVE_UP)\n\t{\n\t if(player.angle != 0)\n\t\t{\n\t\t\tplayer.angle = 0;\n\t\t}\n\t\tif(map[playerPos.x-1][playerPos.y].walkable)\n\t\t{\n\t\t\tplayer.moving = true;\n\t\t\tplayerPos.x-=1;\n\t\t\tvar newy = player.position.y - 40;\n\t\t\tcheckCharms(playerPos.x, playerPos.y);\n\t\t\tcreatejs.Tween.get(player).to({y: newy}, 250).call(move);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPIXI.sound.play('wrongWay');\n\t\t\tplayer.direction = MOVE_NONE;\n\t\t\tmove();\n\t\t}\n\t}\n \tif (player.direction == MOVE_DOWN)\n\t{\n\t if(player.angle != 180)\n\t\t{\n\t\t\tplayer.angle = 180;\n\t\t}\n\t\tif(map[playerPos.x+1][playerPos.y].walkable)\n\t\t{\n\t\t\tplayer.moving = true;\n\t\t\tplayerPos.x+=1;\n\t\t\tcheckCharms(playerPos.x, playerPos.y);\n\t\t\tvar newy = player.position.y + 40;\n\t\t\tcreatejs.Tween.get(player).to({x: player.position.x, y: newy}, 250).call(move);\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPIXI.sound.play('wrongWay');\n\t\t\tplayer.direction = MOVE_NONE;\n\t\t\tmove();\n\t\t}\n\t}\n}", "function move(from, to) {\n\n}", "moveRight() {\n\n if (this.posX <= 670 && pause == false)\n this.posX = this.posX + 5;\n }", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapAbsSea.resize();\n roeMapAbsSea.reposition();\n }", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapSulf.resize();\n roeMapSulf.reposition();\n }", "moveBack(tile, num, wario, goomba) {\n tile.viewportDiff += num;\n wario.viewportDiff += num;\n goomba.viewportDiff += num;\n }", "function moveTile() {\n moveTileHelper(this);\n }", "moveToOriginal() {\r\n if (this.mesh.position.manhattanDistanceTo(this.originalPosition) < Number.EPSILON) return;\r\n\r\n this.moveTransition(this.originalPosition, this.originalRotation);\r\n this.atOriginalPosition = true;\r\n }", "resetPosition() {\n Animated.spring(this.state.position, {\n toValue: { x: 0, y: 0 }\n }).start();\n }", "move(movement) {\n let newPosition = kontra.vector(\n clamp(this.x + movement.x, 0, map.width - this.width),\n clamp(this.y + movement.y, 0, map.height - this.height));\n this.position = newPosition;\n }", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapTemp.resize();\n roeMapTemp.reposition();\n }", "_resetPosition() {\n let {startY, movedY} = this.state;\n let _maxScrollY = this._maxScrollY;\n let distY = startY + movedY;\n if (distY > 0) {\n // console.log(`Reset To Top: ${distY}, ${startY}, ${movedY}`);\n this._scrollTo(0, 0, 400, 0, distY);\n return true;\n }\n if (!this.locked && distY < _maxScrollY) {\n // console.log('Reset To Bottom');\n this._scrollTo(0, _maxScrollY, 400, 0, _maxScrollY - distY);\n return true;\n }\n\n return false;\n }", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapLong.resize();\n roeMapLong.reposition();\n }", "function moveUp() {\r\n var min = 99;\r\n for(index of shipArray) {\r\n if(min > index) {\r\n min = index;\r\n }\r\n }\r\n if(min > 9) {\r\n for(i in shipArray) {\r\n shipArray[i] = shipArray[i] - 10;\r\n }\r\n }\r\n //If it is possible to move the ship here, then do so\r\n if(checkPlacement() == true) {\r\n updatePosColor();\r\n }\r\n}", "if (!game.inEditorMode) {\n // revert pos\n this.pos = lastPos;\n }", "function moveMap(point) {\r\n\t\tvar sets = $['mapsettings'];\r\n\t\tvar $this = sets.element;\r\n\t\t// To center the map to point, get width & height centers and subtract the point location.\r\n\t\tvar location = new Point(($this.innerWidth()/2)-(point.x),($this.innerHeight()/2)-(point.y))\r\n\t\tsetInnerDimentions(location);\r\n\t}", "function panTheNokiaMapUp()\r\n{ \r\n \r\n map.pan(0, 0, 0, -100);\r\n \r\n}", "function moveForward(rover){\nswitch(rover.direction){ //switch para ver en que dirección esta el rover y if para ver si esta en el limite del grid 10x10.\n case 'W':\n if (rover.positionX < 0 || rover.positionX > 10 ){\n console.log(\"limite\");\n }else{ //else - sino esta en el limite se puede mover adelante.\n rover.positionX -= 1;\n }\n break;\n case 'N': \n if (rover.positionY <= 0 || rover.positionY > 10){\n console.log(\"limite\");\n }else{ \n rover.positionY -=1;\n }\n break;\n case 'S':\n if (rover.positionY < 0 || rover.positionY >10){\n console.log(\"limite\");\n }else{\n rover.positionY +=1;\n }\n break;\n case 'E':\n if (rover.positionX < 0 || rover.positionX >10){\n console.log(\"limite\");\n }else{\n rover.positionX +=1;\n }\n break;\n } \nconsole.log(\"Avanza\"); \n}", "up () {\n let first = this.props.game.getTileList();\n this.props.game.board.moveTileUp();\n let second = this.props.game.getTileList();\n if (this.moveWasLegal(first, second) === false) {\n this.updateBoard();\n return;\n } else {\n this.props.game.placeTile();\n this.updateBoard();\n }\n }", "moveUp() {\n this.y>0?this.y-=83:false;\n }", "function moveForward(rover){\r\n let outBoundaries=false; \r\n \r\n switch(rover.direction){ \r\n case \"N\":\r\n { \r\n if(rover.position.y===0)\r\n outBoundaries=true;\r\n else\r\n {\r\n rover.position.y--; \r\n rover.travelLog.push({x:rover.position.x,y:rover.position.y});\r\n }\r\n \r\n }\r\n break;\r\n case \"W\":\r\n {\r\n if(rover.position.x===0)\r\n outBoundaries=true;\r\n else\r\n {\r\n rover.position.x--; \r\n rover.travelLog.push({x:rover.position.x,y:rover.position.y});\r\n } \r\n \r\n }\r\n break;\r\n case \"S\":\r\n { \r\n if(rover.position.y===9)\r\n outBoundaries=true;\r\n else\r\n {\r\n rover.position.y++; \r\n rover.travelLog.push({x:rover.position.x,y:rover.position.y});\r\n } \r\n \r\n }\r\n break;\r\n case \"E\":\r\n {\r\n if(rover.position.x===9)\r\n outBoundaries=true;\r\n else\r\n {\r\n rover.position.x++; \r\n rover.travelLog.push({x:rover.position.x,y:rover.position.y});\r\n } \r\n }\r\n break;\r\n } \r\n\r\n if(outBoundaries)\r\n console.log(\"You can't place player outside of the board!\");\r\n\r\n}", "move() \n\t{\n\t\tthis.raindrop.nudge(0,-1,0);\n\n\t\tif (this.raindrop.getY() <= this.belowplane ) \n\t\t{\n\t\t\t//setting the y value to a certain number\n\t\t\tthis.raindrop.setY(random(200,400))\n\t\t}\n\t}", "function positionUpdater(player, oldY, oldX) {\n mapArrays[player.y + oldY][player.x + oldX].playerHere = false;\n mapArrays[player.y][player.x].playerHere = true;\n}", "moveBackward(){\n if (this.state.position + 800 > 0) {\n this.setState({position: 0});\n } else {\n this.setState({position: this.state.position + 800});\n }\n }", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapWetS.resize();\n roeMapWetS.reposition();\n }", "function move_player()\n{\t\t\t\n\tif (player['position'][0] < 0)\n\t{\n\t\twarp.currentTime = 0;\n\t\twarp.play();\n\t\tplayer['position'][0] = 392;\n\t} \n\telse if (player['position'][0] > 392)\n\t{\n\t\twarp.currentTime = 0;\n\t\twarp.play();\n\t\tplayer['position'][0] = 0;\n\t} \n\telse if (player['position'][1] < 0)\n\t{\n\t\twarp.currentTime = 0;\n\t\twarp.play();\n\t\tplayer['position'][1] = 392;\n\t}\n\telse if (player['position'][1] > 392)\n\t{\n\t\twarp.currentTime = 0;\n\t\twarp.play();\n\t\tplayer['position'][1] = 0;\n\t}\n\t\n\n\tplayer['position'][0] += direction[player['direction']][0];\n\tplayer['position'][1] += direction[player['direction']][1];\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapWetN.resize();\n roeMapWetN.reposition();\n }", "function reposition() {\r\n\r\n\tif(play && isGameOver() === true) {\r\n\t\tif(verifyVacancy(DIR.down, xAxis.default)) {\r\n\t\t\ttry {\r\n\t\t\t\tmoveTo(block, DIR.down, xAxis.default);\r\n\t\t\t\tsetThePositions(currentRow, currentColl, nextRow - xAxis.default, nextColl + DIR.down);\r\n\t\t\t} catch(err) {\r\n\t\t\t\tconsole.log(err);\r\n\t\t\t}\r\n\t\t\tdeleteLastPosition();\r\n\t\t} else {\r\n\t\t\tblock.className = 'positioned-block';\r\n\t\t\tmatrix[currentRow][currentColl] = 1;\r\n\t\t\tresetPositions();\r\n\t\t\tclearInterval(movingBlock);\r\n\t\t\tstart();\r\n\t\t}\r\n\t} else {\r\n\t\tclearInterval(movingBlock);\r\n\t\tplay = true;\r\n\t}\r\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapGulf.resize();\n roeMapGulf.reposition();\n }", "move() {\r\n\t\tlet style = this.element.style;\r\n\t\tstyle.top = this.element.offsetTop + this.speed + \"px\"; \r\n\t\tif (this.element.offsetTop > 500) {\r\n\t\t\tsetScore(playerScore-1);\r\n\t\t\tdelete letters[letters.indexOf(this)];\r\n\t\t\tgameboard.removeChild(this.element);\r\n\t\t}\r\n\t}", "move_to(x, y) {\n this.move(x - this.abs_x, y - this.abs_y)\n }", "function awayFromPacMan(ghost) {\n ghost.goodPositions = ghost.goodDirections.map(x => x + ghost.ghostIndex)\n ghost.positionMove = ghost.goodPositions.reduce(function(prev, curr) {\n return (Math.abs(curr - pacIndex) > Math.abs(prev - pacIndex) ? curr : prev)\n })\n return ghost.positionMove\n }", "function canFrameShift(map, row, col, dir) {\n // console.log(`r,c=${row},${col} dir=${dir}`)\n if (row < 0 || col < 0 || row >= map.rows || col >= map.cols) {\n//\tconsole.log(\"can't shift: off the world\")\n\treturn false\n }\n if (!map.hasObstacleAt(row, col)) {\n\t//console.log(\"the map has no obstacle at row, col\")\n\tif (map.hasObjectTouching(row, col)) {\n\t // console.log(\"there's an obj touching row, col\")\n\t var obj = map.getObjectTouching(row, col)\n\t if (obj.isMoving === false) {\n\t//\tconsole.log(\"the obj is not moving\")\n\t\treturn false\n\t }\n\t // console.log(\"the object is moving\")\n\t return checkFrontier(map, obj, row, col, dir)\n\t}\n//\tconsole.log(\"there is no obj touching\")\n\tlet v = true\n\tmap.objList.forEach(function(obj) {\n\t if (obj.isMoving) {\n\t\tif (obj !== player && checkFrontier(map, obj, row, col, dir) == false) v = false\n\t }\n\t})\n\treturn v //prevent sideways collision\n }\n // console.log(\"there is obstacle at row col\")\n \n return false //is obstacle\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapCarbon.resize();\n roeMapCarbon.reposition();\n }", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapPrecip.resize();\n roeMapPrecip.reposition();\n }", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapNLCD.resize();\n roeMapNLCD.reposition();\n }", "function checkUpMovementOutOfArray() {\r\n let notAnyToolCanMoveCheck = false;\r\n if (((oldPositionY -2) >=0) && ((oldPositionX -2) >=0))\r\n {\r\n newPositionY = oldPositionY -2;\r\n newPositionX = oldPositionX -2;\r\n if((canPawnOrKingMove(notAnyToolCanMoveCheck, oldPositionX, oldPositionY, newPositionX, newPositionY)) == true) {\r\n isForcedJump = true;\r\n }\r\n }\r\n if (((oldPositionY - 2) >=0) && (((oldPositionX) +2) <=7))\r\n {\r\n newPositionY = oldPositionY -2;\r\n newPositionX = parseInt(oldPositionX) +2;\r\n if((canPawnOrKingMove(notAnyToolCanMoveCheck, oldPositionX, oldPositionY, newPositionX, newPositionY)) == true) {\r\n isForcedJump = true;\r\n }\r\n }\r\n }", "function shiftTiles() {\n //Mover\n for (var i = 0; i < level.columns; i++) {\n for (var j = level.rows - 1; j >= 0; j--) {\n //De baixo pra cima\n if (level.tiles[i][j].type == -1) {\n //Insere um radomico\n level.tiles[i][j].type = getRandomTile();\n } else {\n //Move para o valor que está armazenado\n var shift = level.tiles[i][j].shift;\n if (shift > 0) {\n swap(i, j, i, j + shift)\n }\n }\n //Reseta o movimento daquele tile\n level.tiles[i][j].shift = 0;\n }\n }\n }", "function move(e) {\n for (let i = 99; i > 0; i--) {\n if (i != 99) {\n xPositions[i] = xPositions[i - 1];\n yPositions[i] = yPositions[i - 1];\n }\n }\n xPositions[0] = e.pageX;\n yPositions[0] = e.pageY;\n}", "move() {\n this.x += 3;\n this.y += 0;\n if (this.x > 50) {\n this.x += 0;\n this.y += 4;\n }\n if (this.x > 1200) {\n this.y = this.dy;\n this.x = this.dx;\n }\n }", "function moveMapListener() {\n var x, y;\n x = parseInt($(\"#map\")[0].style.marginLeft);\n y = parseInt($(\"#map\")[0].style.marginTop);\n x += moveByX;\n y += moveByY;\n mapMove(x, y);\n setTimeout(\"moveMapListener();\", 50);\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapEco.resize();\n roeMapEco.reposition();\n }", "function movePlayer(direction) {\n if (playerState !== \"locked\") {\n playerState = \"walking\";\n playerDirection = direction;\n if (!moving && checkPermittedMove(direction)) {\n //if not already moving and the next square is valid, move\n switch (direction) {\n case \"up\":\n playerY--;\n break;\n case \"down\":\n playerY++;\n break;\n case \"left\":\n playerX--;\n break;\n case \"right\":\n playerX++;\n break;\n default:\n };\n var squareType = mapLocations[currentLocation][0][playerY][playerX];\n if (typeof squareType === \"string\") {\n playerState = \"locked\";\n loadNewMapArea(squareType);\n } else if (squareType === 0) {\n walkingAnimation(direction);\n } else if (squareType === 4) {\n walkingAnimation(direction);\n if (Math.random() < 0.15) {\n changeMusic(\"route1\", \"wildPokemonFight\");\n clearInterval(moveInterval);\n playerState = \"locked\";\n walkingAnimation(direction);\n setTimeout(function() { enterFightMode(\"wild\"); }, 1000); \n }\n } else if (squareType === 5) {\n // If walking over a ledge, move the player one square further\n movePlayer(direction);\n }\n // Reposition background as player moves\n var mapY = ((6 - playerY) * squareSize) + \"vw\"; \n var mapX = ((6 - playerX) * squareSize) + \"vw\";\n $(\"#screen\").css(\"top\", mapY);\n $(\"#screen\").css(\"left\", mapX);\n // Prevent movePlayer from executing again until the first move has finished\n moving = true;\n setTimeout(function() { moving = false }, 150)\n } else {\n walkingAnimation(direction);\n }\n }\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapTNit.resize();\n roeMapTNit.reposition();\n }", "function moveBackward(rover){\n switch(rover.direction) {\n case 'N' :\n if (rover.y>-5){\n goDown();\n }\n else {\n return mapLimit\n }\n break;\n case 'S' :\n if (rover.y<5) {\n goUp();\n }\n else {\n return mapLimit\n }\n break;\n case 'E':\n if (rover.x>-5) {\n goLeft();\n }\n else {\n return mapLimit\n }\n break;\n case 'W':\n if (rover.x<5) {\n goRight();\n }\n else {\n return mapLimit\n }\n travelLogPush()\n }\n displayCoor()\n}", "function movePacMan(spaces) {\n squares[currentPacManIndex].classList.remove(\"pacman\")\n\n if (layout[currentPacManIndex + spaces] !== 1) {\n \n currentPacManIndex += spaces\n \n } else if ( (currentPacManIndex === 364) && (spaces === -1) ) {\n\n currentPacManIndex = 391\n\n } else if ( (currentPacManIndex === 391) && (spaces === 1) ) {\n\n currentPacManIndex = 364\n }\n\n squares[currentPacManIndex].classList.add(\"pacman\")\n updatePositionDisplay()\n}", "function move(player, direction)\n{\n //Return if movement is attempted without stamina\n if (stamina <= 0 && player == currentPlayer)\n {\n return false;\n }\n \n //Return if the player cannot be found\n if (!getLocation(player))\n {\n return false;\n }\n \n //Attempt to move Up\n if (direction == \"UP\")\n {\n //Check if the tile can be moved to\n if (legalMove(targetLocation.x,targetLocation.y-1))\n {\n //Trigger powerup and move to tile\n powerTrigger(player, targetLocation.x,targetLocation.y-1);\n map[(((targetLocation.y)*mapWidth)+targetLocation.x)] = 0;\n targetLocation.y = targetLocation.y-1;\n map[(((targetLocation.y)*mapWidth)+targetLocation.x)] = player;\n //Decrement the stamina for this client\n if (player == currentPlayer)\n {\n stamina--;\n }\n return true;\n }\n }\n //Attempt to move Down\n else if (direction == \"DOWN\")\n {\n //Check if the tile can be moved to\n if (legalMove(targetLocation.x,targetLocation.y+1))\n {\n //Trigger powerup and move to tile\n powerTrigger(player, targetLocation.x,targetLocation.y+1);\n map[(((targetLocation.y)*mapWidth)+targetLocation.x)] = 0;\n targetLocation.y = targetLocation.y+1;\n map[(((targetLocation.y)*mapWidth)+targetLocation.x)] = player;\n if (player == currentPlayer)\n {\n stamina--;\n }\n return true;\n }\n }\n //Attempt to move Left\n else if (direction == \"LEFT\")\n {\n //Check if the tile can be moved to\n if (legalMove(targetLocation.x-1,targetLocation.y))\n {\n //Trigger powerup and move to tile\n powerTrigger(player, targetLocation.x-1,targetLocation.y);\n map[(((targetLocation.y)*mapWidth)+targetLocation.x)] = 0;\n targetLocation.x = targetLocation.x-1;\n map[(((targetLocation.y)*mapWidth)+targetLocation.x)] = player;\n if (player == currentPlayer)\n {\n stamina--;\n }\n return true;\n }\n }\n //Attempt to move Right\n else if (direction == \"RIGHT\")\n {\n //Check if the tile can be moved to\n if (legalMove(targetLocation.x+1,targetLocation.y))\n {\n //Trigger powerup and move to tile\n powerTrigger(player, targetLocation.x+1,targetLocation.y);\n map[(((targetLocation.y)*mapWidth)+targetLocation.x)] = 0;\n targetLocation.x = targetLocation.x+1;\n map[(((targetLocation.y)*mapWidth)+targetLocation.x)] = player;\n if (player == currentPlayer)\n {\n stamina--;\n }\n return true;\n }\n }\n return false;\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapFPL.resize();\n roeMapFPL.reposition();\n }", "function releaseToPosition(x) {\n // if it's over 50% in either direction, move to that index.\n // otherwise, snap back to existing index.\n var threshold = width / 2;\n if (Math.abs(x) > threshold) {\n if (x < 0 && index < maxIndex) {\n onRequestChange(index + 1);\n }\n else if (x > 0 && index > minIndex) {\n onRequestChange(index - 1);\n }\n else {\n set({ x: index * -100 });\n }\n }\n else {\n // return back!\n set({ x: index * -100, onRest: onRest });\n }\n }", "function check_move(x, y, newx, newy, dir) {\n // if the map ends in either direction, disallow the desired move\n if (player['x'] === 0 && dir === 2) return false;\n if (player['x'] === MAP_WIDTH-1 && dir === 0) return false;\n if (player['y'] === 0 && dir === 1) return false;\n if (player['y'] === MAP_HEIGHT-1 && dir === 3) return false;\n\n // disallow moves onto lava\n if (map[newy][newx]['type'] === ' ') {\n return false;\n }\n\n // don't allow moves onto tiles that are currently rotating\n if (map[newy][newx]['tweenrot'] !== 0) {\n return false;\n }\n\n // (dir + 2) % 4 checks the side opposite the side we are moving into\n // eg. o if we are moving left ONTO this object, then dir = 2,\n // o o <- so then (dir+2)%4 = 0, meaning the right side must be \n // x open, 0, for us to be able to move onto it, which is true.\n // \n // o if instead we wanted to move up, dir=1, onto this object,\n // o o then (dir+2)%4 = 3, which corrosponds to the bottom, which is\n // x 1 in this case, so we cannot complete this move.\n // ^\n // |\n //\n // the blocked list for this object would be: [right, top, left, bottom] = [0,0,0,1]\n if ( !(is_blocked(newx, newy, (dir + 2) % 4, false))\n && !(is_blocked(x, y, (dir + 2) % 4, true)) ) {\n return true;\n }\n //console.log(\"direction IS blocked\");\n return false;\n}", "function on_mouseup_back(event){\n\tif(PLACE=='game' && MAP_SCROLL_CONTROLL==true){\n\t\tMAP_SCROLL_CONTROLL=false;\n\t\tif(MAP_SCROLL_MODE==1)\n\t\t\tmove_to_place_reset();\n\t\t}\n\t}", "movePosition() {\n const toX = (this.destination.x - this.position.x) * this.ease;\n const toY = (this.destination.y - this.position.y) * this.ease;\n\n this.isPanning = (Math.abs(toX) > this.treshold || Math.abs(toY) > this.treshold);\n\n this.position.x += toX;\n this.position.y += toY;\n \n // Round up the values to 2 decimals\n this.position.x = Math.round(this.position.x * 100) / 100;\n this.position.y = Math.round(this.position.y * 100) / 100;\n\n // How much has it moved form it's initial position ?\n this.offsetFromOrigin.x = ~~(.5 * this.size.offsetX - this.position.x);\n this.offsetFromOrigin.y = ~~(.5 * this.size.offsetY - this.position.y);\n }", "resetPosition() {\n\t\tAnimated.spring(this.state.position, {\n\t\t\ttoValue: { x: 0, y: 0 }\n\t\t}).start();\n\t}", "moveIsValid() {}", "function myMove(e) {\n x = e.pageX - canvas.offsetLeft;\n y = e.pageY - canvas.offsetTop;\n\n for (c = 0; c < tileColumnCount; c++) {\n for (r = 0; r < tileRowCount; r++) {\n if (c * (tileW + 3) < x && x < c * (tileW + 3) + tileW && r * (tileH + 3) < y && y < r * (tileH + 3) + tileH) {\n if (tiles[c][r].state == \"e\" && (c != boundX || r != boundY)) {\n tiles[c][r].state = \"w\";\n\n boundX = c;\n boundY = r;\n\n }\n else if (tiles[c][r].state == \"w\" && (c != boundX || r != boundY)) {\n tiles[c][r].state = \"e\";\n\n boundX = c;\n boundY = r;\n\n }\n }\n }\n }\n}", "function moveRight()\r\n {\r\n undraw()\r\n const isAtRightEdge = currentTetromino.some(index => (currentPosition + index) % 10 === 9)\r\n\r\n if(!isAtRightEdge)\r\n currentPosition +=1\r\n if(currentTetromino.some(index => squares[currentPosition + index].classList.contains('taken')))\r\n currentPosition -= 1\r\n draw()\r\n }", "function moveTo(x, y) {\r\n var t = currentmap.getTile(x, y);\r\n if (t) {\r\n if (!t.doesCollide) {\r\n player.x = x;\r\n player.y = y;\r\n lastMouseX = -1;\r\n lastMouseY = -1;\r\n } else if (t.actionable) {\r\n tileActions[t.id](currentmap, x, y);\r\n }\r\n }\r\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapRadon.resize();\n roeMapRadon.reposition();\n }", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapBio.resize();\n roeMapBio.reposition();\n }", "function moveObject(pointX, pointY, newX, newY, speed)\n{\n\tif(objMap.isOutOfBounds(pointX,pointY))\n\t{\n\t\talert(\"original location doesnt exist\");\n\t\treturn false;\n\t}else{\n\t\tif(objMap.isOutOfBounds(newX,newY))\n\t\t{\n\t\t\t//alert(\"target location doesnt exist\");\n\t\t\treturn false;\n\t\t}else{\n\t\t\tif(objMap.intersects(pointX, pointY, newX, newY) == false)\n\t\t\t{\n\t\t\t\tvar obj = objMap.getTileData(pointX,pointY);\n\t\t\t\tobj.setLocation(newX,newY, speed);\n\t\t\t\tobjMap.moveTileData(pointX,pointY,newX,newY);\n\t\t\t\treturn true;\n\t\t\t}else{\n\t\t\t\t//alert(\"cant move to occupied location\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n}", "function moveBack() {\n\tif (currentMoveNum > 0 && currentMoveNum <= totalMoves) {\n\t\tvar move = moveListLog[currentMoveNum - 1];\n\t\tundoLogMove(move);\n\t\tcurrentMoveNum -= 1;\n\t}\n}", "function refreshMapPosition() {\n //alert(\"on Map\");\n roeMapRel.resize();\n roeMapRel.reposition();\n }", "move(predicate) {\n //console.log(predicate);\n const moveBy = this.moveMap[this.state.heading];\n // console.log(moveBy);\n const nextPos = { x: this.state.pos.x, y: this.state.pos.y };\n //console.log(nextPos);\n // Set next position\n nextPos[moveBy.plane] += moveBy.amount;\n\n // Check if move is legal\n const isLegal = predicate(nextPos);\n\n if (isLegal) {\n this.state.pos = nextPos;\n }\n }", "resetPosition() {\n //\"Spring\" into position\n Animated.spring(this.state.position, {\n toValue: { x: 0, y: 0 }\n }).start();\n }", "function legalMove(globals, ui, start, end) {\n return (!(end == start) && end >= globals.leftBound && start >= globals.leftBound && end <= globals.rightBound && start <= globals.rightBound);\n}" ]
[ "0.6972546", "0.6672955", "0.6629053", "0.6550322", "0.649555", "0.64214694", "0.6351626", "0.6306547", "0.623804", "0.620808", "0.6173601", "0.6154243", "0.612907", "0.61056775", "0.6096429", "0.60478914", "0.60388273", "0.60315776", "0.6029463", "0.60246664", "0.5997767", "0.59530926", "0.5952565", "0.59497035", "0.59407514", "0.5939984", "0.5928273", "0.5926774", "0.5923233", "0.5915807", "0.5902673", "0.5901462", "0.5898187", "0.5889657", "0.5884267", "0.58726054", "0.58710223", "0.58684665", "0.58626485", "0.58590204", "0.5852631", "0.58493054", "0.5847935", "0.5832407", "0.5831306", "0.58308005", "0.58252347", "0.5813442", "0.5806879", "0.5796199", "0.5794542", "0.57877564", "0.5787742", "0.57837343", "0.5782558", "0.57788616", "0.5768891", "0.5767638", "0.57609576", "0.5749502", "0.57478595", "0.57467866", "0.5746543", "0.57338434", "0.5728425", "0.57270634", "0.5725692", "0.57239556", "0.57229936", "0.57200843", "0.57183665", "0.57173413", "0.57134426", "0.5705961", "0.57028687", "0.57012373", "0.56983703", "0.569216", "0.5685545", "0.5678845", "0.56738406", "0.5662282", "0.5661107", "0.5654486", "0.56533676", "0.56504625", "0.56487936", "0.5648291", "0.56452346", "0.5641743", "0.56411517", "0.5640586", "0.56394446", "0.56391615", "0.56367594", "0.5630193", "0.5627206", "0.5626362", "0.5625797", "0.562254", "0.56174284" ]
0.0
-1
Manually invoke existing renderer.
render() { this.$.overlay.render(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addRenderer(renderer) {\n this.renderer = renderer;\n }", "registerRenderer(renderer) {\n this._renderer = renderer;\n this.performTransition();\n }", "rendererCallback () {\n // TODO: cannot move code here because tests expects renderer function to still exist on constructor!\n return this.constructor.renderer(this);\n }", "rendererCallback () {\n // TODO: cannot move code here because tests expects renderer function to still exist on constructor!\n return this.constructor.renderer(this);\n }", "function Renderer() {}", "setRenderer(renderer) {\n this.renderer = renderer;\n }", "getRenderer () {}", "function updateRenderer() {\n var choice = document.querySelector(\"#renderer\").value;\n\n switch (choice) {\n case \"template\":\n // Declarative template defined in the html\n renderer = document.getElementById(\"itemTemplate\");\n break;\n\n case \"simplefunc\":\n // Simple function for the renderer\n renderer = simpleRenderer;\n break;\n\n case \"placeholder\":\n //Simple rendering function that can return results before the data is available\n renderer = placeholderRenderer;\n break;\n\n case \"recycling\":\n //Evolution of the placeholder to be able to reuse elements\n renderer = recyclingPlaceholderRenderer;\n break;\n\n case \"multistage\":\n //Evolution of the recycling renderer that will queue the fetching of images\n renderer = multistageRenderer;\n break;\n\n case \"batched\":\n thumbnailBatch = createBatch();\n renderer = batchRenderer;\n break;\n\n }\n updateDatasource();\n }", "_notifyRenderer() {\n this.renderer.notify();\n }", "setCurrentRenderer(renderer) {\n this.currentRenderer = renderer;\n }", "setCurrentRenderer(renderer) {\n this.currentRenderer = renderer;\n }", "setCurrentRenderer(renderer) {\n this.currentRenderer = renderer;\n }", "function Renderer() {\n}", "function Renderer(args) {\n\n\n}", "render(){if(this.renderer){this.renderer.call(this.owner,this.content,this.owner,this.model)}}", "static renderer (elem) {\n if (!elem.shadowRoot) {\n elem.attachShadow({ mode: 'open' });\n }\n patchInner(elem.shadowRoot, () => {\n const possibleFn = elem.renderCallback(elem);\n if (isFunction(possibleFn)) {\n possibleFn();\n } else if (Array.isArray(possibleFn)) {\n possibleFn.forEach((fn) => {\n if (isFunction(fn)) {\n fn();\n }\n });\n }\n });\n }", "render() {\n if (this.renderer) {\n this.renderer.call(this.owner, this.content, this.owner, this.model);\n }\n }", "static renderer (elem) {\n if (!elem.shadowRoot) {\n elem.attachShadow({ mode: 'open' });\n }\n patchInner_1(elem.shadowRoot, () => {\n const possibleFn = elem.renderCallback(elem);\n if (isFunction(possibleFn)) {\n possibleFn();\n } else if (Array.isArray(possibleFn)) {\n possibleFn.forEach((fn) => {\n if (isFunction(fn)) {\n fn();\n }\n });\n }\n });\n }", "onRender()/*: void*/ {\n this.render();\n }", "onBeforeRendering() {}", "function main() {\n\t\t\ttry{\n\t\t\t\trender();\n\t\t\t} catch(e) {\n\t\t\t\tconsole.log(e);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif(rendering == true) {\n\t\t\t\traf(main.bind(this));\n\t\t\t}\n\t\t}", "function render() {\n renderRegistry();\n renderDirectory();\n renderOverride();\n}", "rendererReady() {\n const message = new Message(Message.rendererReadyTitle, 'void').toString();\n this.ipc.send('update-message', message);\n }", "initializeRenderer ()\n {\n const compatErrors = Renderer.getCompatibilityErrors();\n\n if (compatErrors)\n {\n this.showError(compatErrors);\n }\n else\n {\n const options = {\n viewport: this.viewerState.viewport,\n outerElement: this.viewerState.outerElement,\n innerElement: this.viewerState.innerElement\n };\n\n const hooks = {\n onViewWillLoad: () =>\n {\n this.viewerState.viewHandler.onViewWillLoad();\n },\n onViewDidLoad: () =>\n {\n this.updatePageOverlays();\n this.viewerState.viewHandler.onViewDidLoad();\n },\n onViewDidUpdate: (pages, targetPage) =>\n {\n this.updatePageOverlays();\n this.viewerState.viewHandler.onViewDidUpdate(pages, targetPage);\n },\n onViewDidTransition: () =>\n {\n this.updatePageOverlays();\n },\n onPageWillLoad: (pageIndex) =>\n {\n this.publish('PageWillLoad', pageIndex);\n },\n onZoomLevelWillChange: (zoomLevel) =>\n {\n this.publish('ZoomLevelWillChange', zoomLevel);\n }\n };\n\n this.viewerState.renderer = new Renderer(options, hooks);\n }\n }", "render(container) {\n this.renderer.render(container);\n }", "render() { this.screen.render() }", "render() {\n\t\tthis.patch();\n\t}", "function ObjectOrientedRenderer3() {}", "function ObjectOrientedRenderer3() {}", "function ObjectOrientedRenderer3() {}", "function BaseRenderer() {\n }", "function Renderer() {\n RenderController.apply(this, arguments)\n this.container = new Container(this.options.spinner)\n}", "start() {\n _renderer.render();\n requestAnimationFrame(_renderer.start);\n }", "function init() { render(this); }", "_renderNewRootComponent(/* instance, ... */) { }", "function DOMRenderer() {}", "updateRendererState()\r\n {\r\n // update the renderer state object\r\n this.updateRendererStateObject();\r\n \r\n // create a new update id for the render\r\n this.updateRandomUpdateId();\r\n \r\n this.emit(\"rendererStateChanged\", this, this.rendererState);\r\n }", "function ObjectOrientedRenderer3(){}", "function render() {\n\t\t\t}", "get renderer() {\n return this._renderer;\n }", "function render() {\n\t}", "init() {\n this.render();\n }", "init() {\n this.render();\n }", "function render() {\n\tclearCanvas();\n\tRenderer.draw();\n\t\n\t\t\n}", "function updateRenderer(params) {\n var layer = params.layer, rendererType = params.rendererType, view = params.view;\n if (view.zoom <= 9) {\n switch (rendererType) {\n case \"total\":\n var renderer = totalJobsInitial();\n break;\n case \"sector 1\":\n var renderer = sector1JobsInitial();\n break;\n case \"sector 2\":\n var renderer = sector2JobsInitial();\n break;\n case \"sector 3\":\n var renderer = sector3JobsInitial();\n break;\n case \"sector 4\":\n var renderer = sector4JobsInitial();\n break;\n case \"sector 5\":\n var renderer = sector5JobsInitial();\n break;\n case \"sector 6\":\n var renderer = sector6JobsInitial();\n break;\n case \"sector 7\":\n var renderer = sector7JobsInitial();\n break;\n case \"sector 8\":\n var renderer = sector8JobsInitial();\n break;\n case \"sector 9\":\n var renderer = sector9JobsInitial();\n break;\n case \"sector 10\":\n var renderer = sector10JobsInitial();\n break;\n case \"sector 11\":\n var renderer = sector11JobsInitial();\n break;\n case \"sector 12\":\n var renderer = sector12JobsInitial();\n break;\n case \"sector 13\":\n var renderer = sector13JobsInitial();\n break;\n case \"sector 14\":\n var renderer = sector14JobsInitial();\n break;\n case \"sector 15\":\n var renderer = sector15JobsInitial();\n break;\n case \"sector 16\":\n var renderer = sector16JobsInitial();\n break;\n case \"sector 17\":\n var renderer = sector17JobsInitial();\n break;\n case \"sector 18\":\n var renderer = sector18JobsInitial();\n break;\n case \"sector 19\":\n var renderer = sector19JobsInitial();\n break;\n case \"sector 20\":\n var renderer = sector20JobsInitial();\n break;\n }\n layer.renderer = renderer;\n }\n else {\n switch (rendererType) {\n case \"total\":\n var renderer = createTotalRenderer();\n break;\n case \"sector 1\":\n var renderer = createSector1Renderer();\n break;\n case \"sector 2\":\n var renderer = createSector2Renderer();\n break;\n case \"sector 3\":\n var renderer = createSector3Renderer();\n break;\n case \"sector 4\":\n var renderer = createSector4Renderer();\n break;\n case \"sector 5\":\n var renderer = createSector5Renderer();\n break;\n case \"sector 6\":\n var renderer = createSector6Renderer();\n break;\n case \"sector 7\":\n var renderer = createSector7Renderer();\n break;\n case \"sector 8\":\n var renderer = createSector8Renderer();\n break;\n case \"sector 9\":\n var renderer = createSector9Renderer();\n break;\n case \"sector 10\":\n var renderer = createSector10Renderer();\n break;\n case \"sector 11\":\n var renderer = createSector11Renderer();\n break;\n case \"sector 12\":\n var renderer = createSector12Renderer();\n break;\n case \"sector 13\":\n var renderer = createSector13Renderer();\n break;\n case \"sector 14\":\n var renderer = createSector14Renderer();\n break;\n case \"sector 15\":\n var renderer = createSector15Renderer();\n break;\n case \"sector 16\":\n var renderer = createSector16Renderer();\n break;\n case \"sector 17\":\n var renderer = createSector17Renderer();\n break;\n case \"sector 18\":\n var renderer = createSector18Renderer();\n break;\n case \"sector 19\":\n var renderer = createSector19Renderer();\n break;\n case \"sector 20\":\n var renderer = createSector20Renderer();\n break;\n }\n layer.renderer = renderer;\n }\n }", "render(camera) {\n if (!this.renderer) throw new Error(\"Component doesn't have a renderer\");\n this.renderer.update(this, camera);\n this.renderer.render(this);\n }", "function main() {\n init(fontSize);\n\n renderModel = ReadModel();\n renderUI = ReaderBaseFrame(RootContainer);\n renderModel.init(function (data) {\n renderUI(data);\n });\n\n EventHandler();\n }", "setupRenderer() {\n const settings = this.settings;\n const deviceScale = this.deviceScale;\n\n this.renderer = settings.webGLEnabled\n ? PIXI.autoDetectRenderer(settings.width * deviceScale, settings.height * deviceScale, settings)\n : new PIXI.CanvasRenderer(settings.width * deviceScale, settings.height * deviceScale, settings);\n }", "function ObjectOrientedRenderer3() { }", "function ObjectOrientedRenderer3() { }", "function render() {\n\t\t\n\t}", "render () {\n throw new Error('render function must be override!')\n }", "function render() {\n\n\t\t\t}", "addRenderer(renderer) {\n this.renderers.push(renderer);\n this.getWorldObject().addWorldObject(renderer.getWorldObject());\n }", "function render() {\n if (!willRender) {\n willRender = true;\n process.nextTick(function() {\n screen.render();\n willRender = false;\n });\n }\n}", "function createRender() {\n\t\t\tsetSendIconYellow();\n }", "render() {\n\t\trenderer.render(scene, camera);\n\t}", "render() {\n\t\trenderer.render(scene, camera);\n\t}", "render() {\n // Subclasses should override\n }", "activate_render_method(method) {\n this.render_method = method;\n\n // Rerender all the existing labels now that MathJax is available.\n for (const cell of this.quiver.all_cells()) {\n cell.render_label(this);\n }\n }", "clearRenderer() {\n this.renderer.clear()\n }", "Render(){\n throw new Error(\"Render() method must be implemented in child!\");\n }", "render(...args) {\n if (this._render) {\n this.__notify(EV.BEFORE_RENDER);\n this._render(...args);\n this.__notify(EV.RENDERED);\n }\n\n this.rendered = true;\n }", "function general_render(obj) {\n obj.render();\n }", "onRender () {\n\n }", "render() { }", "RenderProbe() {}", "updateRenderers_() {\n this.renderers = this.staticRenderers.concat(this.getDynamicRenderers()).sort(rendererPrioritySort);\n }", "onAfterRendering() {}", "function Render(parent, locator) {\n this.parent = parent;\n this.locator = locator;\n this.renderer = this.locator.getService('rendererFactory');\n this.addEventListener();\n }", "function injectRenderer2() {\n return getOrCreateRenderer2(getLView());\n}", "function injectRenderer2() {\n return getOrCreateRenderer2(getLView());\n}", "myRenderer (api, rowIdx) {\n\n\t}", "function render(){\r\n\r\n\trenderer.render(scene, camera);\r\n}", "refresh() {\r\n const that = this;\r\n that._generateCode(that.renderAs);\r\n }", "render(webGLRenderer) {}", "_renderScreen() {\n\t\tif (this._el && this._component) {\n\t\t\tthis._component.render(this._el);\n\t\t}\n\t}", "function render()\n {\n renderer.render(scene, camera);\n }", "function render() {\n placeSelector();\n renderer.render(scene, camera);\n}", "startRendering () {\n if (this.d_is_rendering) return; //already rendering\n\n this.d_is_rendering = true;\n renderFrame.call(this);\n\n function renderFrame() {\n if (!this.d_pause_rendering)\n this.draw();\n\n let window = this.getCanvasWindow();\n if (this.d_is_rendering)\n window.requestAnimationFrame(renderFrame.bind(this));\n }\n }", "function _render(scene) {\n renderer.update(scene);\n }", "function TextRenderer(){}// no need for block level renderers", "didRender() {\n console.log('didRender ejecutado!');\n }", "function render () {\n // If this is called synchronously we need to\n // cancel any pending future updates\n clearFrame()\n\n // If the rendering from the previous frame is still going,\n // we'll just wait until the next frame. Ideally renders should\n // not take over 16ms to stay within a single frame, but this should\n // catch it if it does.\n if (isRendering) {\n frameId = raf(render)\n return\n } else {\n isRendering = true\n }\n\n // 1. If there isn't a native element rendered for the current mounted element\n // then we need to create it from scratch.\n // 2. If a new element has been mounted, we should diff them.\n // 3. We should update check all child components for changes.\n if (!currentNativeElement) {\n currentElement = app.element\n currentNativeElement = toNative(rootId, '0', currentElement)\n container.appendChild(currentNativeElement)\n } else if (currentElement !== app.element) {\n currentNativeElement = patch(rootId, currentElement, app.element, currentNativeElement)\n currentElement = app.element\n updateChildren(rootId)\n } else {\n updateChildren(rootId)\n }\n\n // Allow rendering again.\n isRendering = false\n }", "render() {\n }", "render() {\n // always reinit on render\n this.init();\n }", "render() {\n // always reinit on render\n this.init();\n }", "function render() {\r\n\r\n}", "function render() {\r\n\r\n}", "render() {\n\n }", "setRenderer() {\r\n // set up scene\r\n this.scene = new THREE.Scene();\r\n this.scene.background = new THREE.Color( \"#92DFF7\" );\r\n\r\n\r\n // set up renderer\r\n this.renderer = new THREE.WebGLRenderer ({\r\n canvas: this.$canvas,\r\n alpha: true\r\n });\r\n this.renderer.setClearColor(\"white\", 1);\r\n this.renderer.setPixelRatio(2); // improves anti-aliasing\r\n this.renderer.setSize(this.sizes.viewport.width, this.sizes.viewport.height);\r\n this.renderer.physicallyCorrectLights = true;\r\n this.renderer.gammaFactor = 2.2;\r\n this.renderer.gammaOutPut = true;\r\n this.renderer.autoClear = false;\r\n\r\n // adjust aspect on resize event\r\n this.sizes.on('resize', () => {\r\n this.renderer.setSize(this.sizes.viewport.width, this.sizes.viewport.height);\r\n });\r\n\r\n // render scene TODO: must change if post process passes are added.\r\n // this.time.on('update', () => {\r\n // // console.log('rendering stuff');\r\n // this.renderer.render(this.scene, this.camera.instance);\r\n // });\r\n }", "function render() {\n renderer.render(scene, camera);\n }", "render() {\n this._addChooserHandler();\n this._addLoggerListeners();\n this._addButtonHandler();\n }", "function handleRender() {\n view._isRendered = true;\n triggerDOMRefresh();\n }", "function handleRender() {\n view._isRendered = true;\n triggerDOMRefresh();\n }", "function RendererType2(){}", "onRender() {\n if ( !this.mRunning )\n return;\n\n if ( SPE_USES_PREVIEW_IMAGE ) {\n document.querySelector( '.spline-preview-image-container' ).style.display = 'none';\n\n SPE_USES_PREVIEW_IMAGE = false;\n }\n\n if ( this.mPlayHandler && !this.mPlayHandler.isEnable ) {\n this.mPlayHandler.activate();\n }\n\n if ( this.mOrbitControls ) {\n this.mOrbitControls.update();\n }\n if ( this.mScene && this.mMainCamera ) {\n this.mRenderer.autoClear = true;\n this.mRenderer.render( this.mScene, this.mMainCamera );\n }\n }", "function ProceduralRenderer3(){}", "function render() {\n\trenderer.render(scene, camera);\n}", "function render() { \n \n renderer.render(scene,camera);\n}", "function renderer(func) {\n return function (ctor) {\n Reflect.defineMetadata('custom:renderer', func, ctor);\n };\n}" ]
[ "0.69677925", "0.6877854", "0.68665683", "0.68665683", "0.6827173", "0.6821726", "0.67483604", "0.67107785", "0.66523", "0.6587107", "0.6587107", "0.6587107", "0.6569686", "0.6510735", "0.6441818", "0.6439868", "0.6435914", "0.64349604", "0.6428976", "0.6373714", "0.6342005", "0.62517893", "0.6194626", "0.6131408", "0.61313766", "0.611659", "0.61119556", "0.60861224", "0.60861224", "0.60861224", "0.6075848", "0.605613", "0.6029236", "0.6027343", "0.60148644", "0.60032606", "0.5989106", "0.5984969", "0.597627", "0.5971255", "0.5964742", "0.5962413", "0.5962413", "0.59568805", "0.5956728", "0.5933748", "0.5933133", "0.59296066", "0.592564", "0.592564", "0.59038454", "0.5898797", "0.589618", "0.5881663", "0.5869446", "0.5863758", "0.5859274", "0.5859274", "0.58578736", "0.5856966", "0.58532107", "0.5841055", "0.58374083", "0.5835608", "0.58215195", "0.58139676", "0.58128387", "0.5798082", "0.57917905", "0.5784808", "0.5782038", "0.5782038", "0.57817245", "0.57793975", "0.57783616", "0.5776726", "0.57761854", "0.5773286", "0.5765894", "0.5754677", "0.5747616", "0.57423174", "0.5737302", "0.5735283", "0.5728514", "0.5726231", "0.5726231", "0.572434", "0.572434", "0.57158756", "0.57141227", "0.57137764", "0.5711835", "0.5705628", "0.5705628", "0.57034403", "0.5694503", "0.56935704", "0.56927174", "0.56816745", "0.5676245" ]
0.0
-1
Close the dialog if `noCloseOnOutsideClick` isn't set to true
_handleOutsideClick(e) { if (this.noCloseOnOutsideClick) { e.preventDefault(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_handleOutsideClick(e) {\n if (this.state.noCloseOnOutsideClick) {\n e.preventDefault();\n }\n }", "handleClickOutside() {\n this._closeOptions();\n }", "function clickOutside(e) {\n if(e.target == modal ) {\n modal.style.display = 'none';\n }\n}", "function clickOutside(e) {\n\tif(e.target == modal){\n\t\tmodal.style.display = 'none'\n\t}\n}", "function clickOutside (e) {\n if (e.target === modal) {\n modal.style.display = 'none';\n }\n }", "function clickOutside(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n }", "function clickOutside(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n }", "function clickOutside(e) {\n\t\n\tif(e.target == modal){\n\tmodal.style.display = 'none';\n\t\n\t}\n}", "function clickOutside(e) {\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}", "function clickOutside(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n }", "function clickOutside (e) {\n if (e.target == modal) {\n modal.style.display = 'none'\n }\n}", "function _handleClickOutside(event) {\r\n if (this.options.closeMethods.indexOf('overlay') !== -1 && !_findAncestor(event.target, 'ef-modal') &&\r\n event.clientX < this.modal.clientWidth) {\r\n this.close();\r\n }\r\n }", "handleClickOutside(event) {\n if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {\n\n this.closeModal();\n }\n }", "function handleClickOutside(event) {\n if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {\n close();\n }\n }", "function handleClickOutside(event) {\n if(ref.current && !ref.current.contains(event.target)) {\n setShowModal(false)\n }\n }", "function clickOutside(e) {\r\n if(e.target === modal){\r\n modal.style.display = 'none';\r\n }\r\n}", "function handleClickOutside(e) {\n if (e.target === e.currentTarget) closeModal();\n}", "function clickOutside(e) {\r\n if(e.target == modal){\r\n modal.style.display = 'none';\r\n }\r\n \r\n}", "function handleClickOutside(event) {\r\n if (ref.current && !ref.current.contains(event.target)) {\r\n setShow(false)\r\n }\r\n }", "function handleClickOutside (event) {\n if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {\n action()\n }\n }", "function clickOutside(e){\n if(e.target == modal){\n modal.style.display = 'none'; \n }\n\n}", "function closeOverlayOnOutsideClick(e) {\n\n\tif (jQuery('.formOverlayWrapper').is(':visible')) {\n\t\tvar ele = jQuery(e.target);\n\t\tif (!ele.hasClass(\"formOverlay\")) {\n\t\t\tcloseOverlay();\n\t\t};\n\t};\n}", "function closeOverlayOnOutsideClick(e) { \n\t\tif (jQuery('.formOverlayWrapper').is(':visible')) {\n\t\t\tvar ele = jQuery(e.target);\n\t\t\tif (!ele.hasClass(\"formOverlay\"))\n\t\t\t{\n\t\t\t\tcloseOverlay();\n\t\t\t};\n\t\t};\n\t}", "function clickOutside(e) {\n let modal=document.getElementsByClassName('modal')[0];\n if (e.target === modal) {\n modal.style.display = 'none';\n }\n}", "function handleClickOutside(event) {\n if (popupRef.current && !popupRef.current.contains(event.target)) {\n props.setSearchHover(false);\n }\n }", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n props.setOpen(false);\n }\n }", "function handleClickOutside(event) {\n if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {\n setPanelOpen(false);\n }\n }", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n setOpen(false);\n }\n }", "function closeBoxIfClickedOutside(){\r\n if(express_form.style.display==='block' || question_form.style.display === 'block'|| cl_form.style.display === 'block'){\r\n document.addEventListener(\"click\", function(event) {\r\n // If user clicks inside the element, do nothing\r\n if (event.target.closest('.express-form-box') || event.target.closest('.express-popup') || event.target.closest('.question-form-box') || event.target.closest('.question-popup') || event.target.closest('.check-list-popup') || event.target.closest('.check-list-form-box')) {\r\n return;\r\n }else{\r\n // If user clicks outside the element, hide it!\r\n express_form.style.display = 'none'; \r\n question_form.style.display = 'none'; \r\n cl_form.style.display = 'none'; \r\n };\r\n });\r\n }\r\n}", "handleClickOutside(e) {\n if (this.emojiBox && this.emojiBox.contains(e.target)) return;\n this.setState({hidePicker: true});\n }", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n props.setIsOpen(false);\n }\n }", "clickOutsideListener(event) {\r\n this.elementVisible = true;\r\n \r\n \r\n this.$emit(\"onHighlightChange\");\r\n if (this.debug === true) {\r\n if (this.display == \"\" || this.display == undefined) {\r\n if (this.$el && !this.$el.contains(event.target)) {\r\n this.close();\r\n this.icon = false;\r\n this.Focusinputbox = false;\r\n }\r\n }\r\n } else {\r\n if (this.$el && !this.$el.contains(event.target)) {\r\n this.close();\r\n this.icon = false;\r\n this.Focusinputbox = false;\r\n }\r\n }\r\n }", "function handleClickOutside(event) {\n if (\n ref.current &&\n !ref.current.contains(event.target) &&\n !ref.current.hidden\n ) {\n ref.current.hidden = true;\n }\n }", "function clickOutside(e){\n if(e.target == modal || e.target == modal2 || e.target == modal3 || e.target ==modal4 || e.target == modal5){\n modal.style.display='none';\n modal2.style.display='none';\n modal3.style.display='none';\n modal4.style.display='none';\n modal5.style.display='none';\n\n document.body.style.overflow = \"auto\";\n }\n}", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n props.isPopoverOpen(false);\n }\n }", "function handleClickOutside (event) {\n if (ref.current && !ref.current.contains(event.target)) {\n setShowResults(false)\n } else if (text !== '') {\n setShowResults(true)\n } else {\n setShowResults(false)\n }\n }", "function handleClickOutside(event) {\n if (dateRef.current && !dateRef.current.contains(event.target) && visible) {\n visibilityCallback(false)\n }\n }", "function clickOutside(e) {\n if (e.target == popUpSection) popUpSection.style.display = \"none\";\n }", "function handleClickOutside (event) {\n if (ref.current && !ref.current.contains(event.target)) {\n onClickOutside()\n }\n }", "listenOnClickOutsideClose(targetDialog) {\n let modalElement = document.querySelector(targetDialog);\n if (\n modalElement &&\n modalElement.dataset &&\n modalElement.classList &&\n (\n !modalElement.dataset.clickOutsideNotClose ||\n modalElement.dataset.clickOutsideNotClose !== 'true'\n ) &&\n modalElement.classList.contains('rd-dialog-modal')\n ) {\n // if no html attribute `data-click-outside-not-close=\"true\"` and there is modal element then click outside to close the dialog.\n modalElement.addEventListener('click', function handler(event) {\n if (event.target === modalElement) {\n // if clicking target is on the modal element.\n if (event.target.querySelector('[data-dismiss=\"dialog\"]')) {\n event.target.querySelector('[data-dismiss=\"dialog\"]').click();\n modalElement.removeEventListener('click', handler);\n }\n }\n });\n }\n }", "handleClickOutside(e) {\n \te.preventDefault();\n\t\t//this.composeData();\n\t\t//TODO\n\t\tthis.setEditorFocus(false);\n\t}", "function clickOutside(e) {\n if(e.target == modal){\n document.querySelector(\"#modal\").classList.remove(\"display\");\n}\n}", "function clickoutside(e){\n if(e.target == modal)\n modal.style.display=\"none\";\n}", "function handleOutsideClick(e) {\n if (!closeOnOutsideClick) {\n return;\n }\n\n const isOutside =\n overlayRef.current &&\n overlayRef.current.contains(e.target) &&\n childrenRef.current &&\n !childrenRef.current.contains(e.target);\n\n if (isOutside && open && onClose) {\n onClose();\n }\n }", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n setPrintShow(false);\n }\n }", "function handleClickOutside(event) {\n if (refr.current && !refr.current.contains(event.target)) {\n setShowGuestCounter(false);\n setShowInDateFilter(false);\n setShowOutDateFilter(false);\n setDatePickerIsOpen(false);\n setShowlocationfilter(false);\n }\n }", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n }", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n }", "function clickOutside(e) {\n e.preventDefault();\n\n if(!$(e.target).closest('.content', this.el).length) {\n $('>a.close', this.el).trigger('click');\n }\n}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n }", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none'\n }\n }", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n }", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n }", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n handler();\n }\n }", "closeIfFocusOutside() {\n\t\tif (\n\t\t\t! this.containerRef.current.contains( document.activeElement ) &&\n\t\t\t! document.activeElement.closest( '[role=\"dialog\"]' )\n\t\t) {\n\t\t\tthis.close();\n\t\t}\n\t}", "function outsideClick(e) {\r\n\t\t if (e.target == modal) {\r\n\t\t modal.style.display = 'none';\r\n\t\t }\r\n\t\t}", "function outsideClick2(e){\n     if(e.taget == modal2){\n     modal2.style.display = 'none';\n     }\n }", "handleClickOutside() {\n // eslint-disable-line\n if (this.state.isOpen) {\n this.setState({ isOpen: false });\n }\n }", "function handleClickOutside(event) {\n if(dropdown.current && !dropdown.current.contains(event.target)) {\n setFocus(false)\n }\n }", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}", "function outsideClick(e) {\n\tif (e.target == modal || e.target == modalForm || e.target == modalSuccess) {\n\t\tmodal.style.display = 'none';\n\t\tmodalForm.style.display = 'none';\n\t\tmodalSuccess.style.display = 'none';\n\t}\n}", "function outsideClick(e) {\n \t\t\tif (e.target == modal) {\n \t\tmodal.style.display = 'none';\n \t\t}\n \t\t}", "function outsideClick(e) {\n \t\t\tif (e.target == modal) {\n \t\tmodal.style.display = 'none';\n \t\t}\n \t\t}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n}", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = \"none\";\n }\n}", "function outsideClick(e) {\n if(e.target === modal) {\n modal.style.display = 'none';\n }\n}", "function outsideClick (e) {\n if(e.target == modal) {\n modal.style.display = 'none';\n }\n}", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n dispatch(closeAddTeamModal())\n }\n }", "clickedOutside(event) {\n if (this.isActive) {\n if (Array.isArray(this.autoClose)) {\n if (this.autoClose.indexOf('outside') >= 0) {\n if (!this.isInWhiteList(event.target)) this.isActive = false;\n }\n\n if (this.autoClose.indexOf('inside') >= 0) {\n if (this.isInWhiteList(event.target)) this.isActive = false;\n }\n }\n }\n }", "function outsideClick(e) {\r\n if (e.target == modal) {\r\n modal.style.display = 'none';\r\n }\r\n}", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n setLoginForm(false) || setClientRegisterForm(false) || setAnnotaterRegisterForm(false)\n }\n }", "function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n }\n}", "function handleClickOutside(event) {\n if (option === 'fullMenu') {\n if (ref.current && !ref.current.contains(event.target)) {\n setshowFullMenu(false)\n }\n }\n if (option === 'cart') {\n if (ref.current && !ref.current.contains(event.target)) {\n setshowCart(false)\n }\n }\n }", "function outsideClick(e){\r\n if(e.target == modal){\r\n modal.style.display = 'none';\r\n vModal.style.display = 'none';\r\n }\r\n }", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n setPopoverCart(false);\n setPopoverUser(false);\n }\n }", "function outsideClick(e) {\n if(e.target === modal3) {\n modal.style.display = 'none';\n }\n}", "function outsideClick(e) {\r\n if (e.target == modal) {\r\n modal.style.display = 'none';\r\n }\r\n}", "function outsideClick(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}", "function outsideClick(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}", "function handleClickOutside(event) {\n if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {\n displaySideBar();\n }\n }", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n setVerticalState_state(false);\n // alert(\"You clicked outside of me!\");\n }\n }", "handleClickOutside(event) {\n if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {\n //https://stackoverflow.com/questions/26176519/reactjs-call-parent-method\n //https://stackoverflow.com/a/26180068/2592454\n if (typeof this.props.onOutsideClick === 'function') {\n this.props.onOutsideClick(event.target.value);\n }\n }\n }", "function outsideClick(e){\r\n if(e.target == modal){\r\n modal.style.display = 'none';\r\n }\r\n}", "handleClickOutside(event) {\n if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {\n this.setState({clicked: true});\n this.props.hideDropdown();\n } else {\n this.setState({clicked: false});\n }\n }", "handleClickOutside(event) {\n\t\tif (\n\t\t\tthis.mobileSelectorRef &&\n\t\t\t!this.mobileSelectorRef.current.contains(event.target) &&\n\t\t\tthis.state.mobileSelected\n\t\t) {\n\t\t\tthis.setState({ mobileSelected: false });\n\t\t}\n\t}", "function outsideClick(e) {\n if (e.target == popup) {\n popup.style.display = \"none\";\n }\n}", "function outsideClick(e){\n if(e.target === modal){\n modal.style.display = \"none\";\n }\n}", "function outsideClick(e) {\r\n\tif (e.target == modal) {\r\n\t\tmodal.style.display = 'none';\r\n\t}\r\n}", "function handleClickOutside(event) {\n if (ref.current && !ref.current.contains(event.target)) {\n forceUpdate;\n socialSwitch(false);\n }\n }", "function outsideclick(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}", "handleHidesOnOutsideClick(show) {\n if (show) {\n if (this._listenersAttached) {\n // skip assigning listeners if already opened\n return;\n }\n\n let wasClickInside = false;\n\n this._preventCloseOnOutsideEvent= () => {\n wasClickInside = true;\n setTimeout(() => {\n wasClickInside = false;\n });\n };\n\n // handle capture phase and schedule the hide if needed\n this._onCaptureOverlayActionEvent = (e) => {\n setTimeout(() => {\n if (wasClickInside === false && !this.isElementAllowed(this, e)) {\n this.hide();\n }\n });\n }\n }\n\n this.handleOverlayListeners(show);\n }", "function outsideClick(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}", "function outsideClick(e){\n if(e.target == modal){\n modal.style.display = 'none';\n }\n}" ]
[ "0.7278886", "0.7171496", "0.70916253", "0.70806336", "0.7067941", "0.70525706", "0.705054", "0.7002624", "0.6982755", "0.69816595", "0.69748914", "0.6971101", "0.6967399", "0.6961027", "0.694508", "0.68863404", "0.6875455", "0.68377805", "0.6834997", "0.6704097", "0.67016554", "0.66994685", "0.66538864", "0.6651947", "0.66007924", "0.65952444", "0.65941703", "0.6590598", "0.65756136", "0.6532316", "0.6468239", "0.6465211", "0.6450339", "0.6445378", "0.6436806", "0.64357686", "0.6379019", "0.6374477", "0.63675046", "0.6364386", "0.633002", "0.63296103", "0.63271445", "0.6311467", "0.6308692", "0.6298953", "0.6281062", "0.6281062", "0.6278969", "0.6273743", "0.62718046", "0.62716585", "0.6248599", "0.62335765", "0.620983", "0.61972874", "0.6188839", "0.6176531", "0.6165944", "0.6153191", "0.6153191", "0.6153191", "0.6153191", "0.6153191", "0.6153191", "0.6141074", "0.61381626", "0.61381626", "0.6134787", "0.6134787", "0.6134787", "0.61346966", "0.61339796", "0.6129729", "0.612228", "0.61078143", "0.6097112", "0.60950494", "0.6093724", "0.6090221", "0.6086904", "0.6077229", "0.6073581", "0.6072846", "0.6072846", "0.6072263", "0.6061433", "0.6060331", "0.6058599", "0.6055769", "0.6048795", "0.6038582", "0.60345364", "0.60323787", "0.6031752", "0.6023597", "0.6017882", "0.6014947", "0.6014947" ]
0.7693915
1
Close the dialog if `noCloseOnEsc` isn't set to true
_handleEscPress(e) { if (this.noCloseOnEsc) { e.preventDefault(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function checkEsc(name) {\r\n // Capture the Esc key to close the dialog.\r\n $(document).on(\"keyup.dialog\", function (event) {\r\n if (event.keyCode === 27) {\r\n event.stopPropagation();\r\n close(name);\r\n }\r\n });\r\n }", "_handleEscPress(e) {\n if (this.state.noCloseOnEsc) {\n e.preventDefault();\n }\n }", "function onEsc(e) {\n if (e.code === \"Escape\") {\n onCloseClick();\n }\n}", "function escapeKeyToClose(e) {\n // if escape pressed\n if(e.keyCode == 27) {\n hideModal(e);\n e.preventDefault();\n }\n}", "function modalDialog2_handleEscapeKey(e) { \r\n\t\tif (e.keyCode == 27) \r\n\t \tmodalDialog2_destroyModal(e);\r\n\t}", "function handleClose() {\n setDialog(false);\n }", "function handleClose() {\n setDialog(false);\n }", "function closeByEscape(e) {\n\t\t\t\t\tif (e.keyCode === 27) {\n\t\t\t\t\t\tclose();\n\t\t\t\t\t}\n\t\t\t\t}", "function escapeToClose(e) {\n\tif (e.keyCode == 27) {\n\t\tcloseCertModal();\n\t}\n}", "escCloseModal(event) {\n if (event.keyCode === 27 && this.props.modalActive) {\n this.modalClose();\n }\n }", "function close_dialog() {\r\n\t dialog.hide();\r\n\t return_focus.focus();\r\n\t return false;\r\n\t }", "function closeOverlayOnEsc(evt) {\n var evt = (evt) ? evt : ((event) ? event : null);\n\t\n\t// handle ESC key code\n\tif (evt.keyCode == 27) {\n\t\tcloseOverlay();\n\t\t// Force page reload, otherwise the div#main with position absolute will be wrongly displayed\n\t\t// The wrong display happens only when iFrame with anchors are present in the Help Inline Doc.\n\t\twindow.location.href=window.location.href\n\t}\n}", "function closeModalByEscape(e) {\n if (e.code === 'Escape') {\n removeEl(modal);\n }\n}", "function ESCclose(evt) {\n if (evt.keyCode === 27) {\n const openModalWindow = document.querySelector('.modal_open');\n closeModal(openModalWindow);\n }\n}", "listenOnEscapeKeyPressClose() {\n document.body.addEventListener('keyup', function handler(event) {\n if (\n event.key === 'Escape' &&\n event.altKey === false &&\n event.ctrlKey === false &&\n event.metaKey === false &&\n event.shiftKey === false &&\n !document.querySelector('.rd-alertdialog-modal.show')// make sure that alert dialog is not opened. if opened, close it before close dialog.\n ) {\n // if target key press.\n // close dialog that without modal.\n if (\n document.querySelector('.rd-dialog.show') &&\n document.querySelector('.rd-dialog.show').dataset &&\n document.querySelector('.rd-dialog.show').dataset.escKeyNotClose !== 'true'\n ) {\n if (document.querySelector('.rd-dialog.show [data-dismiss=\"dialog\"]')) {\n document.querySelector('.rd-dialog.show [data-dismiss=\"dialog\"]').focus();\n document.querySelector('.rd-dialog.show [data-dismiss=\"dialog\"]').click();\n }\n }\n // close dialog with modal.\n if (document.querySelector('.rd-dialog-modal.show')) {\n if (\n document.querySelector('.rd-dialog-modal.show .rd-dialog') &&\n document.querySelector('.rd-dialog-modal.show .rd-dialog').dataset &&\n document.querySelector('.rd-dialog-modal.show .rd-dialog').dataset.escKeyNotClose !== 'true'\n ) {\n if (document.querySelector('.rd-dialog-modal.show [data-dismiss=\"dialog\"]')) {\n document.querySelector('.rd-dialog-modal.show [data-dismiss=\"dialog\"]').focus();\n document.querySelector('.rd-dialog-modal.show [data-dismiss=\"dialog\"]').click();\n }\n }\n }\n }\n });\n }", "function onDialogCancel()\n{\n\tdialogClosed();\n\treturn true;\n}", "function handleClose() {\n props.handleDialog(false);\n }", "function modalClose(event) {\n if (modalOpen && ( !event.keyCode || event.keyCode === 27 )) {\n mOverlay.setAttribute('aria-hidden', 'true');\n modal.setAttribute('tabindex', '-1');\n modalOpen = false;\n lastFocus.focus();\n }\n }", "_onKey( e ) {\n if ( e.keyCode == 27 ) {\n this.closeModal( e );\n }\n }", "function onKeybordPress(event) {\n if (event.code === 'Escape') {\n closeModal();\n }\n}", "function close() {\n\t\ttry{ $dialog.close(); }catch(e){};\n\t\twindow.clearTimeout(timer);\n\t\tif (opts.easyClose) {\n\t\t\t$document.unbind(\"mouseup\", close);\n\t\t}\n\t}", "trapEscape(ev) {\n\t\tif(ev.keyCode === 27) {\n\t\t\tthis.props.close();\n\t\t}\n\t}", "function closeByPressEsc(e) {\n if (e.code === 'Escape') {\n removeClass();\n window.removeEventListener('keydown', closeByPressEsc);\n }\n}", "function close() {\n\t\t\ttry {\n\t\t\t\t$dialog.close();\n\t\t\t} catch (e) {\n\t\t\t}\n\t\t\twindow.clearTimeout(timer);\n\t\t\tif (opts.easyClose) {\n\t\t\t\t$document.unbind(\"mousedown\", close);\n\t\t\t}\n\t\t}", "function close() {\n\t\t\ttry {\n\t\t\t\t$dialog.close();\n\t\t\t} catch (e) {\n\t\t\t}\n\t\t\twindow.clearTimeout(timer);\n\t\t\tif (opts.easyClose) {\n\t\t\t\t$document.unbind(\"mousedown\", close);\n\t\t\t}\n\t\t}", "function handleClose() {\n navigate(\"/EscolherCondominio\"); // vai pra tela de condominios\n setDialog(false);\n }", "function close_ok_dialog() {\r\n\t \tdialog.hide();\r\n\t \treturn_focus.focus();\r\n\t }", "function close() {\r\n\t\ttry{ $dialog.close(); }catch(e){};\r\n\t\twindow.clearTimeout(timer);\r\n\t\tif (opts.easyClose) {\r\n\t\t\t$document.unbind(\"mouseup\", close);\r\n\t\t}\r\n\t}", "handleCancelButtonDialog() {\n this.showDialog(false);\n }", "handleEscKey(event) {\n // Bail if escape disabled via props\n if (this.props.disableEsc === true) return;\n\n if (this.props.cancelFunction !== noop) {\n this.props.cancelFunction(event);\n }\n }", "handleEscape(e) {\n e.preventDefault();\n if(e.keyCode === 27) {\n this.props.exitModal();\n }\n }", "handleHidesOnOutsideEsc(show) {\n if (show) {\n this._escKeyHandler = ev => ev.key === 'Escape' && this.hide();\n document.addEventListener('keyup', this._escKeyHandler);\n } else {\n document.removeEventListener('keyup', this._escKeyHandler);\n }\n }", "function cancelClicked()\n{\n dwscripts.setCommandReturnValue(\"\");\n\n window.close();\n}", "function pressEsc() {\n $(document).on('keydown', function (event) {\n if (event.key == \"Escape\") {\n clearModal();\n $(\"#addAirport\").modal('hide');\n }\n });\n}", "function onCancelButtonPress(){\n\tdlgMain.close(cancelButtonID);\n}", "function isSafeToClose() {\n //console.log(\"issafetoclose\");\n if (projectModified) {\n $(\"#dialog-confirm\").data('recentProjectPath', null).dialog(\"open\");\n $('.ui-dialog :button').blur();\n return false;\n } else {\n return true;\n }\n}", "cancel(e) {\n // reset and close dialog\n this.close();\n }", "function observeKeyPress(e) {\n if((e.keyCode == 27 || (e.DOM_VK_ESCAPE == 27 && e.which==0)) && opts.closeEsc) closeLightbox();\n }", "function keyup(e) {\n if (e.keyCode === 27) {\n close();\n }\n }", "catchEscape(event) {\n if (event.keyCode === 27) {\n this.closeHandler();\n }\n }", "function onCloseImageByEsc(evt) {\n if (evt.keyCode === ESC_KEYCODE || evt.keyCode === ENTER_KEYCODE && evt.target.classList.contains('gallery-overlay-close')) {\n hideImage();\n }\n }", "closeIfFocusOutside() {\n\t\tif (\n\t\t\t! this.containerRef.current.contains( document.activeElement ) &&\n\t\t\t! document.activeElement.closest( '[role=\"dialog\"]' )\n\t\t) {\n\t\t\tthis.close();\n\t\t}\n\t}", "function X_Emer() {\n $(\"#Dialog_emergente\").dialog(\"close\");\n}", "function closePresentation(callback){\n robot.keyTap(\"escape\")\n }", "checkForClose(e) {\n if (e.keyCode && e.keyCode === 27 ||\n (e.type === 'click' && !utils.areElementsNested(this.searchBox.$elm, e.target))) {\n this.closeSearchBox();\n }\n }", "function checkKey(event){\n if (event.keyCode==27){\n close();\n }\n}", "function checkCancel(event) {\n if (event.which === 27) {\n preventDefault(event);\n cancel();\n }\n } // prevent ghost click that might occur after a finished", "function closeDialog() {\n setDialogOpen(false)\n }", "closeDialog_(event) {\n this.userActed('close');\n }", "function hideLoginOptionsOnEscape(e) {\n\tif (readMyPressedKey(e) == \"Escape\") {\n\t\thideLoginOptionsMenu();\n\t}\n}", "function onDocumentKeyup(e) {\n if (options.closeByEscape) {\n if (e.keyCode === 27) {\n deactivate();\n }\n }\n }", "function closeOpDialog(e) {\n e.stopPropagation();\n $(\"#dlgairops\").css(\"display\", \"none\");\n $(\"#dlgoverlay\").css(\"display\", \"none\");\n}", "function _close() {\n\t\tif (dialogBox) {\n\t\t\t$dialogInput.off(\"blur\");\n\t\t\tdialogBox.parentNode.removeChild(dialogBox);\n\t\t\tdialogBox = null;\n\t\t}\n\t\tEditorManager.focusEditor();\n\t\t_removeHighlights();\n\t\t$(currentEditor).off(\"scroll\");\n\t}", "onCloseButtonClick(event) {\n if ((event.type === 'click' || event.type === 'touch')) {\n\n [].forEach.call(this.content.querySelectorAll(this.options.closeButtonsSelector), closeButton => {\n if (closeButton === event.target || closeButton.contains(event.target)) {\n this.callCustom('preEsc');\n event.stopPropagation();\n this.close('onCloseButtonClickEvent');\n this.callCustom('postEsc');\n }\n });\n }\n }", "close(returnValue) {\n this.returnValue = returnValue || this.returnValue;\n this.style.pointerEvents = 'auto';\n this.open = false;\n this.dispatchEvent(new CustomEvent('close')); // MDN: \"Fired when the dialog is closed.\"\n }", "function onKeyEsc() {\n ctrl.blur();\n }", "function closeESC(e) {\n if (e.keyCode == 27) {\n menu.classList.remove('active');\n btn.classList.remove('active');\n }\n}", "function checkCancel(event) {\n\n if (event.which === 27) {\n event.preventDefault();\n\n cancel();\n }\n }", "askClose () {\n if (this.isClean) {\n return Promise.resolve(true);\n }\n const input = dialog.showMessageBox(this.win, {\n title: translate(\"ask-close-title\"),\n message: translate(\"ask-close-message\", {title: this.title}),\n buttons: [\n translate(\"ask-close-cancel\"),\n translate(\"ask-close-without-saving\"),\n translate(\"ask-close-save-before\")\n ],\n defaultId: 2,\n noLink: true\n });\n if (input === 2) {\n return this.save();\n }\n const mustClose = input === 1;\n return Promise.resolve(mustClose);\n }", "handleKeyboardEvents_(event) {\n const code = event.keyCode;\n if (code == KeyCodes.ESCAPE) {\n this.close_();\n }\n }", "function onCloseButtonClick(){\n\t\tt.hide();\n\t}", "function onCancelButtonClick() {\n modal.close();\n }", "function onCancelButtonClick() {\n modal.close();\n }", "function handleCancel()\n{\n // for browswers that handle .returnValue properly\n window.returnValue = \"\";\n\n // if not, attach returnValue to the opener\n if (window.opener) {\n window.opener.returnValue = \"\";\n }\n\n window.close();\n}", "function confirmClose()\r\n{\r\n if (g_bActive && event.clientY < 0)\r\n {\r\n event.returnValue = 'And do you want to quit this chat session also?';\r\n// setTimeout('myclose=false',100);\r\n// myclose=true;\r\n }\r\n}", "function onClose(e) {\n // Allow for quick refresh loads only with devtools opened.\n if (mainWindow.isDevToolsOpened()) {\n if (!document.hasFocus()) {\n app.relaunch();\n app.exit();\n }\n }\n\n checkModeClose(true);\n e.preventDefault();\n e.returnValue = false;\n}", "cancel() {\n atom.views.getView(atom.workspace).removeEventListener('keyup', this.handleKeyup);\n this.modalPanel.hide();\n }", "function onescapeclose(){\n\t\twindow.onkeydown = function( event ) {\n\t\t if ( event.keyCode === 27 ) {\n\t\t var elements = document.querySelectorAll('.js-popup--open');\n\t\t [].forEach.call(elements, function(element){\n\t\t \tremoveClass(element, 'js-popup--open');\n\t\t });\n\t\t }\n\t\t};\n\t}", "function checkCancel(event) {\n\n if (event.which === 27) {\n preventDefault(event);\n\n cancel();\n }\n }", "function actionCanceled() { \n\tOK = 3;\n\tdlg.hide();\n}", "function onCancel () \n{\n // Cancel app launcher.\n try \n {\n printProgress.processCanceledByUser = true;\n }\n catch( exception ) {return true;}\n \n // don't Close up dialog by returning false, the backend will close the dialog when everything will be aborted.\n return false;\n}", "function X_Inac() {\n $(\"#Dialog_Inactivar\").dialog(\"close\");\n}", "function handleEscape(e) {\n if (closeOnEscape && open && onClose) {\n onKey('escape', onClose)(e);\n }\n }", "function slide_closeMsgBox() {\n slide_hideExifInfos();\n slide_hideOptions();\n slide_hideHelp();\n slide_addBinds();\n return true;\n}", "function checkCancel(event) {\n\n if (isKey('Escape', event)) {\n preventDefault(event);\n\n cancel();\n }\n }", "function checkCancel(event) {\n if (event.which === 27) {\n preventDefault(event);\n cancel();\n }\n }", "_handleCloseClick() {\n\t\tthis.close();\n\t}", "function forcedClose_p () {\n// --------------------------------------------------------\n window_o.close(true);\n}", "onCancel_() {\n this.close();\n }", "onDialogBlur(ev) {\n if (!this.props.showCloseIcon) {\n ev.preventDefault();\n // Firefox loses focus unless we wrap the call to\n // this.focusDialog in setTimeout\n setTimeout(this.focusDialog);\n }\n }", "function userNavEscHandler(e){\n\n if (e.keyCode === 27 && !modalVisible) { // esc keycode\n toggleUserNav(e);\n }\n}", "function cancel(event) {\n let dialog = document.getElementById(\"dialog\");\n document.getElementById(\"title\").value = \"\";\n document.getElementById(\"post\").value = \"\";\n document.getElementById(\"submit-btn\").innerHTML = \"Submit\";\n dialog.open = false;\n console.log(\"cancel\");\n}", "function closeModalsKeyboardPressed() {\n\t$(document).keyup(function(e) {\n\t if (e.keyCode == 27) { // escape key maps to keycode `27`\n\t hideWriter('slow');\n\t hideReader();\n\t }\n\t});\n}", "function onKeyDown(evt) {\n if(evt.which === Constant.KEY_CODE.ESCAPE){\n close();\n\n evt.preventDefault();\n evt.stopPropagation();\n }\n }", "function menuEsc(e) {\n\tif ((e.keyCode == 27) && ($('#menu').hasClass('display'))) {\n\t\ttoggleMenu();\n\t}\n}", "onDocumentKeyUp(e) {\n if (e.keyCode === KeyCode.Escape) {\n // Close automatically covers case of `!isClosable`, so check not needed.\n this.close();\n }\n }", "onKey(event) {\n let code;\n code = event.charCode || event.keyCode;\n\n if (event.type === 'keydown' && code === 27) {\n //topmost modal only\n if (this.chrome.parentNode === document.body) {\n this.close('onEscKey');\n }\n }\n }", "function modalDialog2_handleKeys(e) {\r\n\t\t//var window = e.data.window;\r\n\t\tvar button = e.data.button;\r\n\t\t\r\n\t\tif (e.which == 27)\r\n\t\t{\r\n\t\t\tmodalDialog2_destroyModal(e);\r\n\t\t\te.preventDefault();\r\n\t\t}\r\n\t\telse if (e.which == 13)\r\n\t\t{\r\n\t\t\tbutton.click();\r\n\t\t\te.preventDefault();\r\n\t\t}\r\n\t}", "function closeContentEditor(){\n $.PercBlockUI();\n cancelCallback(assetid);\n dialog.remove();\n $.unblockUI();\n $.PercDirtyController.setDirty(false);\n }", "function confirmCancel() {\n let confirmDialogID = document.getElementById(\"confirmCustomDialog\");\n confirmDialogID.close();\n document.getElementById(\"resultTxt\").innerHTML=\"Confirm result: false\";\n}", "function onKeyDown(ev){var isEscape=ev.keyCode===$mdConstant.KEY_CODE.ESCAPE;return isEscape?close(ev):$q.when(true);}", "escFunction(e){\r\n if (this.state.editMode) {\r\n if(e.keyCode === 27) {\r\n this.cancelEdits(e);\r\n }\r\n }\r\n }", "close(){\n isfull = false;\n myWindow.close();\n return \"bye\";\n }", "close(){\n isfull = false;\n myWindow.close();\n return \"bye\";\n }", "function closeDialog() {\n jQuery('#oexchange-dialog').hide();\n jQuery('#oexchange-remember-dialog').hide();\n refreshShareLinks();\n }", "_close(dispose = true) {\n this._animateOut();\n if (dispose) {\n this.modalObj.close();\n this._dispose();\n }\n }", "modalCancel(){\n\t\t// save nothing\n this.setValues = null;\n\t\t// and exit \n this.modalEXit();\n }", "handleClickOutside(e) {\n \te.preventDefault();\n\t\t//this.composeData();\n\t\t//TODO\n\t\tthis.setEditorFocus(false);\n\t}", "function cancelClose() {\n noteDetailPanel.classList.remove('show');\n panel.classList.remove('default');\n editor.classList.remove('default');\n if (editorWasOpen === false) { //close the editor panel if it was already closed\n closeEditor();\n }\n}" ]
[ "0.7244565", "0.7121964", "0.71005625", "0.68334466", "0.68326956", "0.67944854", "0.67944854", "0.6608705", "0.6559097", "0.65186304", "0.6463825", "0.6418731", "0.6415561", "0.64043576", "0.6350256", "0.6316218", "0.6287584", "0.6277058", "0.6260934", "0.6238183", "0.62369573", "0.62347436", "0.62230104", "0.6218876", "0.6218876", "0.62109995", "0.6205611", "0.62025994", "0.62006986", "0.6193172", "0.6165685", "0.6163385", "0.6145761", "0.61082184", "0.60941344", "0.6062058", "0.6062016", "0.6040377", "0.6032545", "0.6031972", "0.60306245", "0.6010186", "0.5999597", "0.59981406", "0.5989639", "0.59844434", "0.5980864", "0.59745425", "0.59302396", "0.59199786", "0.59170914", "0.59154165", "0.5894458", "0.58473724", "0.58379483", "0.5833111", "0.5827917", "0.5813314", "0.58123666", "0.57959354", "0.5791236", "0.5791235", "0.5791235", "0.5777558", "0.5773396", "0.5746135", "0.5737354", "0.57349396", "0.5734036", "0.57255423", "0.5718824", "0.5713109", "0.57104254", "0.5700412", "0.5700162", "0.5676032", "0.5675145", "0.56649286", "0.56646466", "0.56577235", "0.56523305", "0.56485444", "0.5645245", "0.5643912", "0.5640933", "0.5639727", "0.56338865", "0.56330836", "0.5631401", "0.562901", "0.5625103", "0.56202894", "0.56155044", "0.56155044", "0.5601098", "0.55925554", "0.55774456", "0.5570134", "0.5564878" ]
0.7540487
1
Returns the Profiles and Projects associated with the passed Interest.
function getInterestData(name) { const vendors = _.pluck(VendorTypes.collection.find({ vendorType: name }).fetch(), 'vendor'); const vendorPictures = vendors.map(vendor => Vendors.collection.findOne({ email: vendor }).picture); // console.log(_.extend({ }, data, { interests, projects: projectPictures })); return _.extend({ }, { name, vendors: vendorPictures }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getProjects() {\n return []\n }", "getProjects() {\n return this.#fetchAdvanced(this.#getProjectsURL()).then((responseJSON) => {\n let projectBOs = ProjectBO.fromJSON(responseJSON);\n //console.info(projectBOs);\n return new Promise(function (resolve) {\n resolve(projectBOs);\n })\n })\n\n }", "projects() {\r\n\t\treturn API.get(\"pm\", \"/list-projects\");\r\n\t}", "function getInterestData(name) {\n const profiles = _.pluck(ProfilesInterests.collection.find({ interest: name }).fetch(), 'profile');\n const profilePictures = profiles.map(profile => Profiles.collection.findOne({ email: profile }).picture);\n const projects = _.pluck(ProjectsInterests.collection.find({ interest: name }).fetch(), 'project');\n const projectPictures = projects.map(project => Projects.collection.findOne({ name: project }).picture);\n // console.log(_.extend({ }, data, { interests, projects: projectPictures }));\n return _.extend({ }, { name, profiles: profilePictures, projects: projectPictures });\n}", "getcurrentprojects() { }", "projects() {\n return _(this._stories)\n .uniqBy(s => s.projectName)\n .map(s => s.projectName)\n .value();\n }", "function fetchProjectInfo() {\n // Request URL for project\n var projectAPI = testRailURL + \"/index.php?/api/v2/get_projects\";\n var params = setTestRailHeaders();\n\n // Proxy the request through the container server\n gadgets.io.makeRequest(projectAPI, handleProjectResponse, params);\n}", "function getProjects () {\n projectGetWithHeaders(`project/confirmed/${data.user.id}/confirmed`, {\"token\": JSON.parse(localStorage.getItem(\"token\"))}).then(projects => {\n setdata({...data, projects: projects.data.data, isLoading: false})\n }).catch(error => {\n antdNotification(\"error\", \"Fetch Failed\", \"Error fetching project details, please reload screen\")\n })\n }", "async getActiveProjects() {\n\n return await this.request({\n name: 'project.list',\n page: Page.builder().status('ACTIVE').all()\n });\n\n }", "function getInterests( interest ) {\n return new Promise(function(resolve, reject){\n\n\n var category = _.findWhere( g.categories, { title: interest } );\n\n if( category ) {\n\n rest.get( 'lists/' + g.listId + '/interest-categories/' + category.id + '/interests')\n .then( function (data) {\n\n var list = _.map( data.interests, function( obj ) {\n return { id: obj.id, title: obj.name };\n });\n\n console.log( 'got ' + list.length + ' ' + interest + 's ' );\n g[interest] = list;\n\n resolve( list );\n })\n .catch( function( err ) {\n reject( err );\n });\n }\n else {\n reject( new Error( 'Interest not found'));\n }\n\n });\n}", "function getProjects() {\n\t\t\tvar getProjectsURL = origin.segment([ 'skdev', 'api', 'projects' ]).href();\n\t\t\t$log.debug('[workspaceSV] getProjects : ' + getProjectsURL);\n\t\t\treturn $http.get(getProjectsURL);\n\t\t}", "async function GetUserData() {\n \n \n const data = await Auth.currentUserPoolUser();\n const userInfo = { ...data.attributes };\n const userData = await API.graphql(graphqlOperation(getUser, { id: userInfo.sub }));\n const user = userData.data.getUser;\n \n const created_projects = [...user.projects_created.items];\n const temp = [...user.projects_in.items];\n const editor_projects = [];\n \n // gets all projects the user is editor_in and processes\n if(temp.length > 0) {\n \n // requests project object for each projectID\n for(let i = 0; i < temp.length; i++) {\n \n const temp_project = await API.graphql(graphqlOperation(getProject, { id: temp[i].projectID}));\n editor_projects.push(temp_project.data.getProject);\n }\n }\n\n const projects = [...created_projects, ...editor_projects];\n\n return projects;\n}", "getProtesters(protestName) {\n let protest = this.find(db.protests, protestName);\n if (protest) {\n return protest.participants\n .map((participant) => {\n return participant + \": \" + this.find(db.protesters, participant).email;\n });\n }\n return null;\n }", "gatherProjectInfo() {\n const generatorTitle = `${_consts.GENERATOR_NAME} v${_package.version}`;\n this.log(\n _yosay(\n `AWS Microservice Generator.\\n${_chalk.red(generatorTitle)} `\n )\n );\n\n this.config.set('_projectType', _consts.SUB_GEN_MICROSERVICE);\n return _prompts\n .getProjectInfo(this, true)\n .then(() => {\n return _prompts.getAuthorInfo(this, true);\n })\n .then(() => {\n return _prompts.getAwsInfo(this, true);\n });\n }", "function findProfiles() {}", "function getCurrentProjects(database = connection) {\n let allProjects = database(\"projects\")\n .select(\n \"id\",\n \"user_id\",\n \"name\",\n \"done\",\n \"image_url\",\n \"deadline\",\n \"color\",\n \"purpose\",\n \"friendOneEmail\",\n \"friendTwoEmail\"\n )\n .where(\"done\", \"=\", false);\n return allProjects.then((eachRow) => {\n console.log(makeProject(eachRow));\n return makeProject(eachRow);\n });\n}", "getInvestments() {\n var investmentsList = [];\n\n for(var projectId in this.investments)\n investmentsList.push(this.investments[projectId]);\n\n return investmentsList;\n }", "getProjectWithFullInfo(query = {}) {\n return this.getOneWithCustumQuery(query).then(async (project = {}) => {\n if (!project) {\n return [];\n }\n const {\n clients = [],\n providers = [],\n teams = [],\n reminders = []\n } = project;\n debug(clients, providers, teams, reminders);\n //instance all services\n const clientServices = new ClientsServices();\n const projectServices = new ProjectServices();\n const providerServices = new ProviderServices();\n const reminderProjectsServices = new RemindersProjectsServices();\n //convert the object into an array with just the values\n const clientsIds = clients.map(({ clientId }) => clientId);\n const providerIds = providers.map(({ providerId }) => providerId);\n const teamsIds = teams.map(({ teamId }) => teamId);\n const remindersIds = reminders.map(({ reminderId }) => reminderId);\n //get data from services\n const clientsInProject = await clientServices.getMany(clientsIds);\n const providersInProject = await providerServices.getMany(providerIds);\n const teamsInProject = await projectServices.getProjectTeams(teamsIds);\n const remindersInProject = await reminderProjectsServices.getProjectReminders(\n remindersIds\n );\n return {\n ...project,\n clients: clientsInProject || [],\n providers: providersInProject || [],\n teams: teamsInProject || [],\n reminders: remindersInProject || []\n };\n });\n }", "function getProjects(){\n\n\t\t\treturn fsp.readdir(projectsPath)\n .then(complete)\n .catch(error);\n\n function complete(dirList) {\n\n var projects = getProjectsFromDirectoryList(dirList);\n\t\t\t\treturn projects;\n }\n\n function error(err) {\n $log.error(err);\n }\n\n\t\t}", "function projget(p, cb) {\n var pn = p.projectName;\n debug && console.error(\"fetching individual project: \"+pn);\n axios.get(cfg.url+\"project/\"+pn, axopt).then((resp) => {\n // OK\n return cb(null, resp.data);\n }).catch((ex) => {\n console.log(\"Problems getting project details for: \"+pn+\" (\"+ex+\")\");\n return cb(ex, null);\n });\n}", "async function getProject (req, res) {\n console.log(`getting project ${req.params.id}...`)\n\n PROJECT.findAll({\n where: {\n ProfileId: 1,\n id: req.params.id\n },\n include: [DESCRIPTION, IMAGEPATH, TECH]\n }).then(projects => {\n res.send({\n project: projects[0]\n })\n })\n}", "getListOfSelectedProject(){\n let self = this;\n return new Promise(function(resolve, reject){\n if(!projectService.project){ // if no project selected - request a to select a project first\n console.log(\"Please select first a project before to work on it\".warn);\n resolve();\n }\n else{\n authService.checkLogin().then(function(){ \n let filter = \"Filter.Eq(Project.Id,\" + projectService.project.Id + \")\"; // build the filter on the selected project\n api.getEntityList(\"Meeting\", filter).then(function(data){ \n resolve(data);\n });\n });\n }\n });\n }", "async function getGithubInfo(profileUrl, starredRepoUrl) {\n let UserProfileInfo = [];\n try {\n const githubProfile = axios.get(profileUrl);\n const starredRepos = axios.get(starredRepoUrl);\n UserProfileInfo = await Promise.all([githubProfile, starredRepos]);\n }\n catch (err) { console.log(err); }\n\n return UserProfileInfo;\n\n}", "function getProjetos() {\r\n\t\t\t\t\t\t\t\treturn $http(\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tmethod : \"POST\",\r\n\t\t\t\t\t\t\t\t\t\t\turl : 'http://localhost/WebService/selfieCode/service/listarProj',\r\n\t\t\t\t\t\t\t\t\t\t\theaders : {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"key\" : authenticationSvc\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.getUserInfo().accessToken\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}).then(function(result) {\r\n\t\t\t\t\t\t\t\t\tprojetos = result.data;\r\n\t\t\t\t\t\t\t\t\treturn result.data;\r\n\t\t\t\t\t\t\t\t}, function(error) {\r\n\r\n\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t}", "function getActiveUserProjects() {\n var async = $q.defer();\n // var activeUserId = userSrv.getActiveUser().id;\n\n var projects = [];\n\n const parseProject = Parse.Object.extend('Project');\n const query = new Parse.Query(parseProject);\n query.equalTo(\"userId\", Parse.User.current());\n query.find().then(function (results) {\n\n for (var i = 0; i < results.length; i++) {\n projects.push(new Project(results[i]));\n }\n\n async.resolve(projects);\n\n }, function (error) {\n $log.error('Error while fetching Project', error);\n async.reject(error);\n });\n\n return async.promise;\n }", "function getProjectList(projects){\r\n let list = [];\r\n for (let i = 0; i < projects.length; i++) {\r\n list[i] = {name: projects[i].projectName.toLowerCase()};\r\n }\r\n return list;\r\n}", "async getProjectPeople(input = { projectId: '0' }) {\n\n return await this.request({\n name: 'project.people.list',\n args: [input.projectId],\n page: input.pagination\n });\n\n }", "function getProjects()\r\n{\r\n\t\r\n\tclear();\r\n\tvar n;\r\n\r\n\tvar aux = System.Gadget.Settings.read(\"noProjects\"); \r\n\t//var aux =2;\r\n\tif ( aux == \"\" ) n = 0; else n = aux;\r\n\tprojects = new Array();\t\t\r\n\tcurrentPage = 1;\r\n\tvar cur = 0;\r\n\tfor ( var cur = 0; cur < n;cur++){ \r\n\t\tvar projectURL = System.Gadget.Settings.read(\"projectURL\"+cur); \r\n\t\tvar useAuth = System.Gadget.Settings.read(\"projectUseAuthentification\"+cur); \r\n\t\tvar userName = System.Gadget.Settings.read(\"projectUserName\"+cur); \r\n\t\tvar passwordInput = System.Gadget.Settings.read(\"projectPassword\"+cur); \r\n\t\tGetProject(projectURL,useAuth,userName,passwordInput, cur);\r\n\t}\r\n\tvar refreshTime = System.Gadget.Settings.read('refresh');\r\n\tif ( refreshTime > 0 ) setTimeout( \"getProjects();\", refreshTime );\r\n\treturn;\r\n}", "getAllProfiles() {\n return this.#fetchAdvanced(this.#getAllProfilesURL()).then((responseJSON) => {\n let profileBOs = ProfileBO.fromJSON(responseJSON);\n return new Promise(function (resolve) {\n resolve(profileBOs);\n })\n })\n }", "function getCollaboratorsInfo(){\n\tvar collaborators = getCollaboratorsByProject();\n\tvar collaboratorsInfo = new Array();\n\t$.each(collaborators, function() {\t\n\t\tcollaboratorsInfo.push(getCollaboratorInfo(this));\n\t});\n\treturn collaboratorsInfo;\n}", "project() {\n return __awaiter(this, void 0, void 0, function* () {\n const channel = (yield this.channelsService.channels())[0];\n return channel.project.toObject();\n });\n }", "getProjects() {\n if (this.props.rotation === undefined) {\n return {};\n }\n return Object.keys(this.props.projects).reduce((filtered, id) => {\n if (this.props.projects[id].data.group_id === this.props.rotation.data.id) {\n filtered[id] = this.props.projects[id];\n }\n return filtered;\n }, {});\n }", "function getSelectedProjects(grid){\n\tif(!grid)\n\t\treturn null;\n\t\n\tvar projects = null;\n\tvar selectedRecords = grid.getSelectedRecords();\n\t\n\tif(selectedRecords.length)\n\t\tprojects = [];\n\t\n\tfor (var i = 0; i < selectedRecords.length; i++) {\n\t\tvar record = selectedRecords[i];\n\t\tprojects.push(record.getValue(\"project.project_id\"));\n\t}\n\t\n\treturn projects;\n}", "getProjectsList(){\n Utils.performGet(URL.projects())\n .then((response) => {\n this.setState({ projects: response.data });\n //Generate dictionary of projects\n this.projectsDict = Utils.createDictonary(response.data);\n })\n .catch((error) => {\n this.setState({ error: 'Unable to load' });\n });\n }", "getProjectTypes() {\n return this.#fetchAdvanced(this.#getProjectTypesURL()).then((responseJSON) => {\n let project_typeBOs = ProjectTypeBO.fromJSON(responseJSON);\n // console.info(projectTypeBOs);\n return new Promise(function (resolve) {\n resolve(project_typeBOs);\n })\n })\n }", "function getProjectsParents() {\n swpjt = 0;\n var pagina = 'ProjectPlans/listProjectsParents';\n var par = `[{\"pjId\":\"\"}]`;\n var tipo = 'json';\n var selector = putProjectsParents;\n fillField(pagina, par, tipo, selector);\n}", "function fetchRepoContributors(org, repo) {\n // This array is used to hold all the contributors of a repo\n var arr = [];\n\n return api.Repositories\n .getRepoContributors(org, repo, {method: \"HEAD\", qs: { sort: 'pushed', direction: 'desc', per_page: 100 } })\n .then(function gotContribData(contribData) {\n var headers = contribData;\n if (headers.hasOwnProperty(\"link\")) {\n var parsed = parse(headers['link']);\n var totalPages = parseInt(parsed.last.page);\n } else {\n var totalPages = 1;\n }\n return totalPages;\n })\n .then(function gotTotalPages(totalPages) {\n // This array is used to collect all the promises so that \n // we can wait for all of them to finish first...\n let promises = [];\n \n for(let i = 1; i <= totalPages; i++) {\n var currentPromise = api.Repositories\n .getRepoContributors(org, repo, { method:\"GET\", qs: { sort: 'pushed', direction: 'desc', per_page: 100, page:i } })\n .then(function gotContributorsOnParticularPage(contributors) {\n if (contributors!=undefined && (contributors != null || contributors.length > 0)) {\n contributors.map((contributor, i) => arr.push(contributor));\n }\n });\n // Push currentPromise to promises array\n promises.push(currentPromise);\n }\n // Waits for all the promises to resolve first, returns the array after that...\n return Promise.all(promises)\n .then(()=> {\n return arr;\n });\n })\n }", "async getProject(input = { projectId: '0' }) {\n\n return await this.request({\n name: 'project.get',\n args: [input.projectId],\n page: Page.builder(input.pagination)\n });\n\n }", "function builtInProfiles () {\n new Profile('Kevin', '../img/monk.png', 'martial arts', '1F6212', knownArray, interestArray);\n new Profile('Austin', '../img/fighter.png', 'watching movies', '404040', ['Javascript', 'HTML', 'CSS'], ['Python', 'Ruby']);\n new Profile('Zach', '../img/wizzard.png', 'Anime', '49F3FF', ['Javascript', 'HTML', 'CSS'], ['Python', 'C#']);\n new Profile('Ramon', '../img/monk.png', 'Racing motorsports', 'FF0000', ['Javascript', 'HTML', 'CSS'], ['Python']);\n new Profile('Sooz', '../img/rogue.png', 'Knitting', 'FF8C00', ['Javascript', 'HTML', 'CSS'], ['Python', 'C#']);\n new Profile('Kris', '../img/rogue.png', 'reading', 'B51A1F', ['Javascript', 'Python'], ['Java']);\n new Profile('Judah', '../img/druid.jpg', 'Cooking', '000000', ['Javascript', 'HTML', 'CSS'], ['C#']);\n new Profile('Allie', '../img/cleric.png', 'Cooking', '29B0FF', ['Javascript', 'HTML', 'CSS'], ['C#']);\n new Profile('Carl', '../img/wizzard.png', 'Cooking', '0560dd', ['Javascript', 'HTML', 'CSS'], ['C#', 'Python']);\n new Profile('Jose', '../img/rogue.png', 'Youtubing', 'af111c', ['Javascript', 'HTML', 'CSS'], ['C#', 'Python']);\n new Profile('Michael', '../img/rogue.png', 'Youtubing', '000000', ['Javascript'], ['Javascript']);\n new Profile('Han', '../img/monk.png', 'Coding', '29B0FF', ['Javascript', 'HTML', 'CSS', 'Python', 'Java'], ['C++']);\n}", "function getProjectsList(projects){\r\n let list = [];\r\n for (let i = 0; i < projects.length; i++) {\r\n list[i] = {name: projects[i].projectName.toLowerCase(), projectId: projects[i].projectId};\r\n }\r\n \r\n return list;\r\n }", "function getProjectNames(){\n var store = getProjectStore();\n var names = [];\n for(var name in store){\n names.push(name);\n }\n return names;\n }", "function getProjectMemebers(users){\n var users_to_be_returned = [];\n var y;\n for (y in users) {\n if(users[y].ProjectUser.active === true){\n users_to_be_returned.push({\n id: users[y].id,\n email: users[y].email,\n profilePicture: users[y].profilePicture,\n firstName: users[y].firstName,\n lastName: users[y].lastName,\n fullName: users[y].firstName + ' ' + users[y].lastName,\n alias: users[y].alias,\n createdAt:users[y].createdAt\n });\n }\n }\n return users_to_be_returned;\n}", "async getUserData(){\n let urlProfile = `http://api.github.com/users/${this.user}?client_id=${this.client_id}&client_secrt=${this.client_secret}`;\n let urlRepos = `http://api.github.com/users/${this.user}/repos?per_page=${this.repos_count}&sort=${this.repos_sort}&${this.client_id}&client_secrt=${this.client_secret}`;\n\n\n const profileResponse = await fetch(urlProfile);\n const reposResponse = await fetch(urlRepos);\n\n const profile = await profileResponse.json();\n const repo = await reposResponse.json();\n\n\n return{\n profile,\n repo\n }\n }", "function fetchProjectInfo() {\n // Request URL for project\n var projectAPI = testRailURL + \"/index.php?/api/v2/get_project/\" + projectID;\n var params = setTestRailHeaders();\n\n // Don't make the API call if no test plans/runs were in the XML\n if (projectID == \"0\") {\n document.getElementById('milestoneCaption').innerHTML = \"Milestone not found\";\n msg.dismissMessage(loadMessage);\n gadgets.window.adjustHeight();\n } else {\n // Proxy the request through the container server\n gadgets.io.makeRequest(projectAPI, handleProjectResponse, params);\n }\n}", "getParticipations(){\n return this.#fetchAdvanced(this.#getParticipationsURL()).then((responseJSON) => {\n let participationBOs = ParticipationBO.fromJSON(responseJSON);\n return new Promise(function (resolve) {\n resolve(participationBOs);\n })\n })\n }", "function getCompletedProjects(skipValue, takeValue) {\n $scope.loading = true;\n var getData = ProjectService.getCompletedProjects(skipValue, takeValue);\n getData.then(function (prj) {\n angular.forEach(prj.data, function (value, key) {\n $scope.completedProjects.push(value);\n })\n $scope.loading = false;\n },function () {\n console.log('Error in getting records');\n });\n }", "function getAllProjects(session) {\n\tlet groupRequest = {\n\t\turl: mockGroupUrl,\n\t\tmethod: 'get',\n\t\theaders: {\n\t\t\tCookie: session\n\t\t}\n\t}\n\taxiosInst.request(groupRequest)\n\t\t.then((res) => {\n\t\t\tlet groupList = res.data && res.data.groups;\n\t\t\tgroupList = groupList.filter((projectItem) => {\n\t\t\t\treturn projectItem.projects.length;\n\t\t\t});\n\n\t\t\tlet projects = [];\n\t\t\tfor (let group of groupList) {\n\t\t\t\t// console.log(group)\n\t\t\t\tprojects.push(...group.projects)\n\t\t\t}\n\t\t\t\n\t\t\treturn projects;\n\t\t}).then((data) => { //获取各个项目的接口\n\t\t\tlet projectApis = data.map(item => {\n\t\t\t\treturn axios.get(mockApiUrl + item.id)\n\n\t\t\t})\n\t\t\taxios.all(projectApis)\n\t\t\t\t.then(res => {\n\t\t\t\t\tlet apiList = [];\n\t\t\t\t\tfor (let item of res) {\n\t\t\t\t\t\t// console.log(item.request.path)\n\t\t\t\t\t\tlet path = item.request.path;\n\t\t\t\t\t\tlet parts = path.split('=');\n\t\t\t\t\t\tlet pid = parts[parts.length - 1];\n\t\t\t\t\t\tlet apis = item.data\n\t\t\t\t\t\t//.filter(api=>api.indexOf(''))\n\t\t\t\t\t\t .map(api=>{\n\t\t\t\t\t\t\tlet apiPath = api.replace(/\\{[^\\}]+\\}/g,(m)=>{\n\t\t\t\t\t\t\t\t// console.log(m);\n\t\t\t\t\t\t\t\treturn ':'+ m.substr(1,m.length-2)});\n\t\t\t\t\t\t\tapiPath = '/'+ trim(apiPath,'/').trim()\n\t\t\t\t\t\t\tlet keys = []\n\t\t\t\t\t\t\tlet re = pathToRegexp(apiPath.split('?')[0], keys)\n\t\t\t\t\t\t\treturn {api,pid:pid, apiPath,re,keys }\n\t\t\t\t\t\t})\n\t\t\t\t\t\tapiList.push(...apis)\n\t\t\t\t\t}\n\t\t\t\t\trouteApis = apiList;\n\t\t\t\t\t// fs.writeFile('./dist/project/apiList.js', JSON.stringify(apiList));\n\t\t\t\t\t\n\t\t\t\t})\n\n\t\t\n\t\t});\n\n}", "function getAllProjects() {\n\t\n\tuserType = getJavaScriptCookie(\"usertype\"); //From the cookies, stores the type of the user. Admin or superadmin etc\n\tt0 = new Date().getTime();\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: 'Project',\n\t\tdata: {\n\t\t\t'domain': 'project',\n\t\t\t'action': 'getAllProjects'\n\t\t}, success: function (data) {\n\t\t\tprojects = data;\n\t\t\tRETRIEVED_PROJECTS = JSON.parse(projects['projects']);\n\t\t\tlengthProjects = RETRIEVED_PROJECTS.length;\n\t\t\testablishRetrievedProjects();\n\t\t\tif(RETRIEVED_PROJECTS) console.log(\"getAllProjects() - PROJECTS HAVE BEEN RETRIEVED\");\n\t\t\tt1 = new Date().getTime();\n//\t\t\tconsole.log('took: ' + (t1 - t0) + 'ms');\n//\t\t\tconsole.log(\"PROJECTS ARE : \", RETRIEVED_PROJECTS);\n\t\t\t//getSearchCriteria();\n\t\t\t\n\t\t\t//fetchApprovalsAll();\n\t\t\t\t\t\t\t\t\n\t\t\t//fillInvsTable(data);\n\t\t\t\n\t\t\tapprovingMembers();\n\t\t\t\n\t\t\t//getInvs(1);\n\t\t}\n\t});\n}", "function getProfilesWithAssertedCompetencyAndParents(compId) {\n var cpd = selectedFrameworksCompetencyData.competencyPacketDataMap[compId];\n if (!cpd) return [];\n else {\n var asArray = getAssertionsForCompetencyPacketDataInclusive(cpd);\n if (!asArray || asArray.length == 0) return [];\n else return getUniqueProfilesForAssertions(asArray);\n }\n}", "function getExistingProjects(startRow) {\n toggleResultTable(false);\n toggleSearchingIndicator(true);\n clearTable();\n receivedProjects = 0;\n for (var i = startRow; i < currentPage * elementsPerPage; i++) {\n //end is reached\n if (typeof projects[i] == \"undefined\") {\n break;\n } else {\n receivedProjects++;\n addProjectToTable(projects[i]);\n }\n }\n checkPages();\n toggleSearchingIndicator(false);\n toggleResultTable(true);\n}", "function getProjectsResponse(data) {\n // response = JSON.parse(response);\n\n // add projects to the page\n for (var i = 0; i < data.length; i++) {\n addSectionToPortfolio(data[i], i);\n // addPortfolioModal(response[i], i);\n };\n}", "function getIntakeInfo() {\n var intakeId = vm.TemplateModelInfo.matterId ? vm.TemplateModelInfo.matterId : vm.TemplateModelInfo.intakeId;\n var dataObj = {\n \"page_number\": 1,\n \"page_size\": 250,\n \"intake_id\": intakeId,\n \"is_migrated\": 2\n };\n var promise = intakeFactory.getMatterList(dataObj);\n promise\n .then(function (response) {\n var matterInfo = response.intakeData[0];\n vm.referredById = utils.isNotEmptyVal(matterInfo.referredBy) ? matterInfo.referredBy : \"\";\n\n // Intake assigned user\n if (utils.isNotEmptyVal(matterInfo.assignedUser)) {\n _.forEach(matterInfo.assignedUser, function (data) {\n vm.assignUsers.push(data);\n });\n }\n }, function (error) {\n });\n }", "async myParticipatedStudies(parent, args, ctx, info) {\n // check if the user has permission to see all users\n if (!ctx.request.userId) {\n throw new Error(\"You must be logged in\");\n }\n const profile = await ctx.db.query.profile(\n {\n where: {\n id: ctx.request.userId,\n },\n },\n `{ id participantIn { id } }`\n );\n return ctx.db.query.studies(\n {\n where: {\n id_in: profile.participantIn.map((study) => study.id),\n },\n orderBy: \"createdAt_DESC\",\n },\n info\n );\n }", "function getProjects() {\n\n\t// Get the project name query parameter\n\tvar params = new URLSearchParams(window.location.search);\t\n\tvar projectName = params.get('projectname');\n\n\t// Prepare the XHR request.\n\tvar xhr = new XMLHttpRequest();\n\txhr.withCredentials = true;\n\txhr.open(\"GET\", baseURL + \"getprojects\");\n\txhr.setRequestHeader(\"Cache-Control\", \"no-cache, no-store, max-age=0\");\n\n\t// Define the callback function.\n\txhr.onload = function () {\n\n\t\t// Get the response, check HTTP status.\n\t\tif (xhr.status == \"200\") {\n\n\t\t\t// Retrieve the response and check whether the request succeeded.\n\t\t\tvar response = JSON.parse(xhr.responseText);\n\t\t\tvar data = response['data'];\n\t\t\tif (data) {\n\t\t\t\tif (data.succeeded) {\n\t\t\t\t\tprojects = data['projects'];\n\t\t\t\t\tdeleteChildNodes(projectSelect);\n\t\n\t\t\t\t\t// Load the projects into the pick list.\n\t\t\t\t\tvar keys = Object.keys(projects);\n\t\t\t\t\tkeys.forEach( function (key, index) {\n\t\n\t\t\t\t\t\t// Create a new pick list item and add the project to it.\n\t\t\t\t\t\tvar option = document.createElement('option');\n\t\t\t\t\t\tprojectSelect.appendChild(option);\n\t\t\t\t\t\tproject = projects[key];\n\t\t\t\t\t\tlabel = key\n\t\t\t\t\t\tif (project['projectTitle'])\n\t\t\t\t\t\t\tlabel = label + ' - ' + project['projectTitle'];\n\t\t\t\t\t\toption.innerHTML = label;\n\t\t\t\t\t\toption.setAttribute('value', key);\n\t\n\t\t\t\t\t\t// If only one project, select it by default.\n\t\t\t\t\t\tif (keys.length==1) {\n\t\t\t\t\t\t\tselectedProjectName = key;\n\t\t\t\t\t\t\toption.selected = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t});\n\t\t\t\t\n\t\t\t\t\tsetSelected(projectSelect, projectName);\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\talert(data.errorMsg);\n\t\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\tconsole.error(xhr.responseText);\n\t\t\talert(\"Error retrieving session state\");\n\t\t}\n\n\t\tdisableProjectSelect();\n\n\t}\n\n\t// Send the request.\n\txhr.send();\n\t\n}", "render(){\n\t\treturn (\n\n\t\t\t<div className='projectdisplay'>\n\t\t\t\t{this.props.projects.map((project,i) => {return(\n\t\t\t\t\t\t<IndividualProject key={i} project={project} interestfn={this.props.interestfn}/>\n\t\t\t\t\t)}\n\t\t\t\t)}\n\t\t\t</div>)\n\t}", "function getPastProjects(database = connection) {\n let allProjects = database(\"projects\")\n .select(\n \"id\",\n \"user_id\",\n \"name\",\n \"done\",\n \"image_url\",\n \"deadline\",\n \"color\",\n \"purpose\",\n \"friendOneEmail\",\n \"friendTwoEmail\"\n )\n .where(\"done\", \"=\", true);\n return allProjects.then((eachRow) => {\n console.log(makeProject(eachRow));\n return makeProject(eachRow);\n });\n}", "getContributedStories() {\n\n return this._getCollection()\n .then(collection => collection.find().toArray());\n }", "function allProjects(){\n return new Promise((resolve,reject) => {\n projectModel.find((err,docs) => {\n if (err){\n return reject(err)\n }\n else{\n resolve(docs)\n }\n })\n })\n}", "matchProfiles() {\n return this.#fetchAdvanced(this.#matchProfilesURL()).then((responseJSON) => {\n let profileBOs = ProfileBO.fromJSON(responseJSON);\n return new Promise(function (resolve) {\n resolve(profileBOs);\n })\n })\n }", "function getProjetos() {\r\n\t\t\t\t\t\t\t\treturn $http(\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tmethod : \"POST\",\r\n\t\t\t\t\t\t\t\t\t\t\turl : 'http://localhost/WebService/selfieCode/service/listarTreino',\r\n\t\t\t\t\t\t\t\t\t\t\theaders : {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"key\" : authenticationSvc\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.getUserInfo().accessToken\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}).then(function(result) {\r\n\t\t\t\t\t\t\t\t\tprojetos = result.data;\r\n\t\t\t\t\t\t\t\t\treturn result.data;\r\n\t\t\t\t\t\t\t\t}, function(error) {\r\n\r\n\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t}", "function populateProjectContainer(){\n\t\n\tvar userId = document.getElementById(\"uId\").value;\n\t\n\tif(userId){\n\t\t\n\t\t fetch(path+\"/getAllProject/\" + userId, {\n\t\t\t method: \"GET\",\n\t\t\t headers: {\n\t\t\t \"Content-Type\": \"application/json\",\n\t\t\t },\n\t\t\t })\n\t\t\t .then((response) => response.json())\n\t\t\t .then((projects) => {\n\t\t\t \t\n\t\t\t console.log(\"Success:\", projects);\n\t\t\t console.log(\"data is fetched\");\n\t\t\t if (projects != null) {\n\t\t\t \n\t\t\t \t iteratorForProject(projects);\n\t\t\t }\n\t\t\t \n\t\t\t })\n\t\t\t .catch((error) => {\n\t\t\t console.error(\"Error:\", error);\n\t\t\t return null;\n\t\t });\n\n\t}\n\n}", "getProject(index) {\n var searchString = \"/project\";\n if (index != null) searchString = \"/project/\" + index;\n describe(\"GET\", function () {\n it(\"Return projects\", function (done) {\n request(url)\n .get(searchString)\n .auth(\"[email protected]\", \"123qwe\")\n .expect(200)\n .end(function (err, res) {\n if (err) return done(err);\n done();\n console.log(res.body);\n });\n });\n });\n }", "function getProjectTechs (req, res) {\n // var techss = []\n PROJECTTECHS.findAll({\n where: {\n ProjectId: req.params.id\n }\n }).then(techs => {\n resolveTechs(techs, res)\n // res.send(techs)\n }).catch(err => {\n console.log(err)\n res.send(false)\n })\n}", "function recieveProjects(json){\n\tconst projects = json;\n\treturn {\n\t\ttype: RECEIVE_PROJECTS,\n\t\tprojects\n\t}\n}", "function getAllProjectAPI(){\n\t\n\tvar userId = document.getElementById(\"uId\").value;\n\t\n\tfetch(path+\"/getAllProjectDashboard/\"+userId,{\n\t\t\n\t\tmethod: \"GET\",\n\t headers: {\n\t \"Content-Type\": \"application/json\",\n\t },\n\t\t\n\t})\n\t.then((response)=>response.json())\n\t.then((projects)=>{\n\t\tconsole.log(\"successfully fecth all data\", projects);\n\t\tif(projects){\n\t\t\tpopulateProject(projects);\n\t\t}\n\t})\n\t.then((error)=>{\n\t\t\n\t\treturn null;\n\t\t\n\t});\n\t\n}", "function getProvenances () {\n\t\t\t\tif (!provenance) return API.Q.resolve();\n\t\t\t\treturn API.Q.denodeify(function (callback) {\n\t\t\t\t\tvar provenances = {\n\t\t\t\t\t\tdeclaredMappings: {},\n\t\t\t\t\t\textends: {}\n\t\t\t\t\t};\n\t\t\t\t\tvar waitfor = API.WAITFOR.serial(function (err) {\n\t\t\t\t\t\tif (err) return callback(err);\n\t\t\t\t\t\treturn callback(null, provenances);\n\t\t\t\t\t});\n\t\t\t\t\tfor (var path in provenance) {\n\n\t\t\t\t\t\twaitfor(path, function (path, callback) {\n\n\t\t\t\t\t\t\treturn findGitRoot(path, function (err, gitRoot) {\n\t\t\t\t\t\t\t\tif (err) return callback(err);\n\t\t\t\t\t\t\t\tif (!gitRoot) {\n\t\t\t\t\t\t\t\t\treturn callback(new Error(\"No git root found for: \" + path));\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tvar extendsRelpath = API.PATH.relative(API.PATH.dirname(gitRoot), path);\n\t\t\t\t\t\t\t\tvar depRelpath = \"{{env.PGS_PACKAGES_DIRPATH}}/\" + extendsRelpath.split(\"/\").shift();\n\t\t\t\t\t\t\t\tif (!provenances.extends[extendsRelpath]) {\n\t\t\t\t\t\t\t\t\tprovenances.extends[extendsRelpath] = {\n\t\t\t\t\t\t\t\t\t\tlocation: \"!{{env.PGS_PACKAGES_DIRPATH}}/\" + extendsRelpath\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\treturn callback(new Error(\"Already declared (use unique containing project basenames for external mappings): \" + extendsRelpath));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tAPI.EXTEND(true, provenances.extends[extendsRelpath], provenance[path]);\n\n\t\t\t\t\t\t\t\tif (!provenances.declaredMappings[depRelpath]) {\n\t\t\t\t\t\t\t\t\tprovenances.declaredMappings[depRelpath] = {\n\t\t\t\t\t\t\t\t\t\tpath: gitRoot,\n\t\t\t\t\t\t\t\t\t\tinstall: false\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t} else\n\t\t\t\t\t\t\t\tif (provenances.declaredMappings[depRelpath].path !== gitRoot) {\n\t\t\t\t\t\t\t\t\tconsole.log(\"depRelpath\", depRelpath);\n\t\t\t\t\t\t\t\t\tconsole.log(\"provenances.declaredMappings\", provenances.declaredMappings);\n\t\t\t\t\t\t\t\t\tconsole.log(\"gitRoot\", gitRoot);\n\t\t\t\t\t\t\t\t\treturn callback(new Error(\"Already declared: \" + extendsRelpath));\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn callback(null);\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\treturn waitfor();\n\t\t\t\t})();\n\t\t\t}", "function loadProjects() {\n reviewStudentAppService.loadProjects().then(function (data) {\n vm.projects = data;\n });\n }", "function getAllProjects() {\n //get all the projects (up to 500)\n allProjects = new Array();\n var response = UrlFetchApp.fetch('https://api.10000ft.com/api/v1/projects?per_page=500&fields=custom_field_values,tags,phase_count', params);\n\n var jsonProjects = JSON.parse(response.getContentText()); //JSONified response\n\n\n //now we'll loop over each element in the jsonProject.data structure - each one is a project\n jsonProjects.data.forEach(function(element){ //this is also a good place to limit what to process. i.e. if element.state != internal\n var proj = new Object();\n proj.id = element.id;\n proj.link10K = \"=HYPERLINK(\" + \"\\\"https://app.10000ft.com/viewproject?id=\" + element.id +\"\\\"\" + \",\" + \"\\\"Link\\\")\";\n proj.name = element.name;\n proj.startDate = element.starts_at;\n proj.endDate = element.ends_at;\n proj.description = element.description;\n proj.projectCode = element.project_code;\n proj.client = element.client;\n proj.state = element.project_state;\n proj.phaseCount = element.phase_count;\n proj.beneficiaries = \"\";\n //get the custom fields\n element.custom_field_values.data.forEach(function(custFieldVal) {\n switch (custFieldVal.custom_field_id) {\n case PROJ_PHASE_ID: proj.phase = custFieldVal.value;\n break;\n case PROJ_MGR_ID: proj.projectManager = custFieldVal.value;\n break;\n case PROJ_STRAT_OBJ_ID: proj.strategicObjective = custFieldVal.value;\n break;\n case PROJ_ARCH_PARTNER_ID: proj.architectPartner = custFieldVal.value;\n break;\n case PROJ_STATUS_ID: proj.status = custFieldVal.value;\n break;\n case PROJ_BENEFICIARY: proj.beneficiaries += custFieldVal.value + \" \";\n break;\n case PROJ_PARENT_PGM: proj.programID = custFieldVal.value;\n break;\n case PROJ_DIRECTOR: proj.director = custFieldVal.value;\n break;\n case PROJ_GSB_PRIO: proj.gsbPrioStatus = custFieldVal.value;\n break;\n case PROJ_EFFORT: proj.effort = custFieldVal.value;\n break;\n case PROJ_VALUE: proj.valueToSchool = custFieldVal.value;\n break;\n case PROJ_MICITI: proj.miciti = custFieldVal.value;\n break;\n case PROJ_NOTES: proj.notes = custFieldVal.value;\n break;\n case PROJ_PRMY_CONTACT: proj.primaryContact = custFieldVal.value;\n break;\n case PROJ_NONCOMP_COST: proj.nonCompCost = custFieldVal.value;\n break;\n case PROJ_HI_BENE_IMPACT: proj.hiBeneImpact = custFieldVal.value;\n break;\n case PROJ_FORCE_PRIO: proj.forceGsbPrioritization = custFieldVal.value;\n break;\n case PROJ_FOLDER:\n //proj.folder = custFieldVal.value;\n proj.folder = \"=HYPERLINK(\" + \"\\\"\" + custFieldVal.value + \"\\\"\" + \",\\\"Link\\\")\";\n break;\n case PROJ_PMO_DECK: proj.pmoDeck = custFieldVal.value;\n break;\n case PROJ_RECORD_MGR: proj.recordMgr = custFieldVal.value;\n break;\n case PROJ_OP_PRIO: proj.operPrioStatus = custFieldVal.value;\n break;\n default:Logger.log(\"default reached in custom field line 147 or therabouts\");\n };\n });\n\n //get the project tags\n proj.tags = \"\";\n element.tags.data.forEach(function(element) {\n proj.tags += element.value;\n });\n\n //derive the external status\n if (proj.phase == \"Pre-concept\" || proj.phase == \"Concept\") {proj.externalStatus = \"Exploration\"}\n else if (proj.phase == \"High Level Design\" || proj.phase == \"Pitch\") {proj.externalStatus = \"Queued\"}\n else {proj.externalStatus = \"Active\"};\n\n /////////////////START PRIORITIZATION STUFF////////////////////\n\n // Set some defaults\n proj.gsbPrioFlag = false;\n proj.operPrioFlag = false;\n proj.inconsistencyErrors = [];\n\n\n\n\n if (proj.state == \"Internal\") {\n if (isPrioritized(proj.gsbPrioStatus) || isPrioritized(proj.operPrioStatus)) {\n proj.inconsistencyErrors.push(\"Project is internal so it shouldn't be GSB or DS prioritized.\");\n }\n }\n // Derive prioritization\n else {\n //derive if project should get gsb level prioritization\n if (proj.forceGsbPrioritization == \"Yes\" || levelHigherThan(proj.effort, 'Low') || levelHigherThan(proj.nonCompCost, 'Low')){proj.gsbPrioFlag = true}\n\n // Determine inconsistency\n\n // If it is currently not set to be prioritized.\n if (proj.gsbPrioStatus == \"No\" || proj.gsbPrioStatus == \"TBD\") {\n // Check Effort\n if (proj.effort == \"Medium\" || proj.effort == \"High\") {\n proj.inconsistencyErrors.push(\"Effort is greater than Low, but it is not set to be GSB prioritized.\");\n }\n\n // Check Non-Comp Cost\n if (proj.nonCompCost == \"Medium\" || proj.nonCompCost == \"High\") {\n proj.inconsistencyErrors.push(\"Non-Comp Cost is greater than Low, but it is not set to be GSB prioritized.\");\n }\n\n // Check Force Prioritization.\n if (proj.forceGsbPrioritization == \"Yes\") {\n proj.inconsistencyErrors.push(\"Force prioritization is selected, but it is not set to be GSB prioritized.\");\n }\n }\n // If we calculate that it shouldn't be prioritized but it is.\n else if (!proj.gsbPrioFlag) {\n proj.inconsistencyErrors.push(\"Nothing warrants it to be prioritized, but it is set to be GSB prioritized.\");\n }\n\n //derive DS prioritization\n if (!proj.gsbPrioFlag) {\n if (proj.effort == \"High\" || proj.effort == \"Medium\" || proj.effort == \"Low\" || proj.nonCompCost == \"High\" || proj.nonCompCost == \"Medium\" || proj.nonCompCost == \"Low\"){proj.operPrioFlag = true}\n\n // Check for inconsistency\n if (proj.operPrioStatus == \"No\" || proj.operPrioStatus == \"TBD\") {\n // Check Effort\n if (proj.effort == \"Low\") {\n proj.inconsistencyErrors.push(\"Effort is Low, but it is not set to be DS prioritized.\");\n }\n\n // Check Non-Comp Cost\n if (proj.nonCompCost == \"Low\") {\n proj.inconsistencyErrors.push(\"Non-Comp Cost is Low, but it is not set to be DS prioritized.\");\n }\n }\n }\n else {\n // Check for consistency\n if (proj.operPrioStatus != \"No\") {\n proj.inconsistencyErrors.push(\"It is GSB prioritized so DS prioritization should be No.\")\n }\n }\n }\n\n\n // If there are no errors set the message to none.\n // Otherwise join the errors together with new lines and * as bullet points.\n if (!proj.inconsistencyErrors.length) {\n proj.inconsistencyMessage = '-None-';\n }\n else {\n proj.inconsistencyMessage = \"* \" + proj.inconsistencyErrors.join(\"\\n\\n* \");\n }\n\n //////////////////////END PRIORITIZATION STUFF//////////////////////////\n\n //get current resources\n proj.team = getStringifiedProjectResources(proj.id);\n\n\n //if the project has phases then get the current ones (if any)\n if (proj.phaseCount > 0) {\n proj.activePhases = getStringifiedCurrentPhases(proj.id);\n }\n else {\n //get the phase from the DS phase mapping\n proj.activePhases = \"None\";\n }\n //add the project to the list\n allProjects.push(proj);\n });\n\n //order the projectDetailedObjects in alpha order of element.name\n allProjects.sort(function(a,b) {\n var nameA = a.name.toUpperCase();\n var nameB = b.name.toUpperCase();\n return (nameA < nameB) ? -1 : (nameA > nameB) ? 1 : 0;\n });\n\n //now that we have all the projects with names in an array we can populate the programName if any\n allProjects.forEach(function(p){\n if (p.programID) {\n p.programName = getProjectName(p.programID);\n }\n else {\n p.programName = \"None\";\n }\n })\n\n\n}", "function ProcessProjects (data)\n{\n var Projects = data[0];\n var Members = data[1];\n\n for (var s in Projects)\n {\n Projects[s].StartDate = StringToDate(Projects[s].StartDate);\n Projects[s].EndDate = StringToDate(Projects[s].EndDate);\n }\n\n for (var s in Members)\n {\n for (var p in Projects)\n {\n if (Members[s].P_ID == Projects[p].ID)\n {\n if (!Projects[p].Team)\n {\n Projects[p].Team = [];\n }\n Projects[p].Team.push(new StaffProject(Members[s]));\n }\n }\n }\n console.log(Projects);\n return Projects;\n}", "returnPoolProfiles() {\n\t\treturn this.poolProfiles\n\t}", "async getAllProfiles() {\n const arrayProfiles = await this.store.getProfiles();\n return arrayProfiles;\n }", "gatherProjectInfo() {\n const generatorTitle = `${_consts.GENERATOR_NAME} v${_package.version}`;\n this.log(_yosay(\n `Node.js Library Generator.\\n${_chalk.red(generatorTitle)} `\n ));\n return _prompts.getProjectInfo(this, true)\n .then(() => { return _prompts.getAuthorInfo(this, true); });\n }", "function getProjectsFromDocument() {\n var result = \"\";\n var pFile = getCurrentFileOrDefault();\n if ((pFile != \"\") && (File.exists(pFile))) {\n var tFile = File.readText(pFile).split('\\n');\n tFile.forEach(function(element, index, array) {\n if (element.match(pReg)) {\n result += element.substr(0, element.indexOf(':')) + \", \";\n }\n });\n return (result.substr(0, result.length - 2));\n } else {\n return (\"\");\n }\n}", "get profiles() {\r\n return this.create(UserProfileQuery);\r\n }", "static getStudyInSession(opencgaSession, studyId) {\n let study = {};\n for (const p of opencgaSession?.projects) {\n for (const s of p.studies) {\n if (s.id === studyId || s.fqn === studyId) {\n study = s;\n break;\n }\n }\n }\n return study;\n }", "function get_proyecto(id_proyecto) {\n \n gapi.client.communicationchannel.getProyecto({\"id\":function get_proyecto(id_proyecto) {\n}).execute(function(resp){\n if (resp.code) {\n }else{\n ProyectoItems = resp.items;\n obras(ProyectoItems[i].id_Proyecto);\n }\n });\n}", "renderCompProjsList(projs) {\n return [{}].concat(projs).map(\n (proj, i) =>\n proj.sta === \"Completed\" ? \n <LinkContainer\n key={proj.noteID}\n to={`/admin/${proj.noteID}`}\n >\n <ListGroupItem header={proj.title}>\n {\"Project Manager: \" + proj.manager}<br />\n {\"Developers: \" + proj.developers}<br />\n {\"Status: \" + proj.sta}\n </ListGroupItem>\n </LinkContainer>\n : <div key={i}></div>\n )\n }", "renderPendingProjsList(projs) {\n return [{}].concat(projs).map(\n (proj, i) =>\n proj.sta === \"Pending\" ?\n <LinkContainer\n key={proj.noteID}\n to={`/admin/${proj.noteID}`}\n >\n <ListGroupItem header={proj.title}>\n {\"Project Manager: \" + proj.manager}<br />\n {\"Developers: \" + proj.developers}<br />\n {\"Status: \" + proj.sta}\n </ListGroupItem>\n </LinkContainer>\n : <div key={i}></div> \n );\n }", "function getProjectById(projectName) {\n var async = $q.defer();\n\n getActiveUserProjects().then(function (projects) {\n async.resolve(projects[projectName]);\n }, function (err) {\n async.reject(err);\n });\n\n return async.promise;\n }", "fetchProjectsForWorkspaceId(workspaceId) {\n let promise = this.remoteProjectsAPI.query({workspaceId: workspaceId}).$promise;\n let updatedPromise = promise.then((projectReferences) => {\n var remoteProjects = [];\n projectReferences.forEach((projectReference) => {\n remoteProjects.push(projectReference);\n });\n\n // add the map key\n this.projectsPerWorkspaceMap.set(workspaceId, remoteProjects);\n this.projectsPerWorkspace[workspaceId] = remoteProjects;\n\n // refresh global projects list\n this.projects.length = 0;\n\n\n for (var member in this.projectsPerWorkspace) {\n let projects = this.projectsPerWorkspace[member];\n projects.forEach((project) => {\n this.projects.push(project);\n });\n }\n }, (error) => {\n if (error.status !== 304) {\n console.log(error);\n }\n });\n\n return updatedPromise;\n }", "currentProject() {\n return currentProject;\n }", "function findProjects(id) {\n return db('users')\n .join('projects', 'users.id', 'projects.professor_id' )\n .select('projects.professor_id','projects.student_id','projects.project_name', 'projects.description', 'projects.due_date', 'projects.description', 'projects.completed')\n .where({ professor_id: id });\n}", "function getProfileDetails(storedData) {\n let result = { type: \"project\", entries: [] };\n for (let i = 0; i < storedData.length; i++) {\n result.entries.push({ name: storedData[i].firstName + \" \" + storedData[i].lastName, detail1: storedData[i].email, id: storedData[i].gtUsername });\n }\n\n return result;\n}", "function getContributions(callback){\n db.collection(\"pollination\").find().toArray(callback);\n }", "getBasecampInfo() {\n const basecamp = new Basecamp();\n\n return basecamp.getBasecampInfo();\n }", "function projects() {\n\tvar projectArray = ['>Projects:',\n\t\t'<u>Furmap.net</u>',\n\t\t'A world map with more then 800 users !',\n\t\t'<a href=\"https://furmap.net\" target=\"_blank\">furmap.net</a>',\n\t\t'<br>',\n\t\t//---\n\t\t'===',\n\t\t'<u>Patrimoine Grenoblois</u>',\n\t\t'ionic app to discover Grenoble',\n\t\t'<a href=\"https://play.google.com/store/apps/details?id=com.AR.grenoble.patrimoine&hl=fr\" target=\"_blank\">Play store</a>',\n\t\t'<br>',\n\t\t//---\n\t\t'===',\n\t\t'<u>Hololens Demo</u>',\n\t\t'<a href=\"https://github.com/Mrgove10/Hololens-Demo-Salon\" target=\"_blank\">Github</a>',\n\t\t'Hololens demo application for trade shows',\n\t\t'<br>',\n\t\t//---\n\t\t'===',\n\t\t'<u>Web Interface to start remote computers</u>',\n\t\t'<a href=\"https://github.com/Mrgove10/iowebinterface\" target=\"_blank\">Github</a>',\n\t\t'Web interface to start/stop a server remotly',\n\t\t'<br>',\n\t\t//---\n\t\t'===',\n\t\t'<u>Minecraft MiniGame</u>',\n\t\t'<a href=\"https://github.com/Mrgove10/Mine.Js\" target=\"_blank\">Github</a>',\n\t\t'Minecraft clone in javascript with Babylon.js',\n\t\t'<br>',\n\t\t//---\n\t\t'===',\n\t\t'<u>Video Game for a game jam</u>',\n\t\t'<a href=\"https://github.com/Mrgove10/SGJ2019\" target=\"_blank\">Github</a>',\n\t\t'Game made in unity in 48 hours. Goal was to show the risk of technology linked with medical treatments',\n\t];\n\tseperator();\n\tfor (var i = 0; i < projectArray.length; i++) {\n\t\tif (projectArray[i] === '===') {\n\t\t\tseperator();\n\t\t} else {\n\t\t\tvar out = '<span>' + projectArray[i] + '</span><br/>';\n\t\t\tOutput(out);\n\t\t}\n\n\t}\n}", "loadProjects({ commit }) {\n return new Promise((resolve, reject) => {\n commit(\"setProjectsLoadStatus\", 1);\n ProjectsAPI.getProjects()\n .then(response => {\n if (response.data) {\n commit(\"setProjects\", response.data);\n commit(\"setProjectsLoadStatus\", 2);\n resolve(response.data);\n }\n })\n .catch(error => {\n commit(\"setProjects\", {});\n commit(\"setProjectsLoadStatus\", 3);\n reject(error);\n });\n });\n }", "function getProfileData(){\n let headers = loadHeaders();\n callAPI(server + \"api/mdm/profiles/search\",headers,\"profilesData\"); //get main profiles list\n\n}", "function getAllProjects() {\n defer = $q.defer();\n\n $http({\n method: 'GET',\n url: DATASERVICECONSTANTS.BASE_URL + '/projects',\n timeout: 5000\n }).then(function successCallback(response) {\n defer.resolve(response);\n }, function errorCallback(response) {\n defer.reject(response);\n });\n\n return defer.promise;\n }", "renderActiveProjsList(projs) {\n return [{}].concat(projs).map(\n (proj, i) =>\n proj.sta === \"Active\" ?\n <LinkContainer\n key={proj.noteID}\n to={`/admin/${proj.noteID}`}\n >\n <ListGroupItem header={proj.title}>\n {\"Project Manager: \" + proj.manager}<br />\n {\"Developers: \" + proj.developers}<br />\n {\"Status: \" + proj.sta}\n </ListGroupItem>\n </LinkContainer>\n : <div key={i}></div> \n )\n }", "function findAll() {\n let profilesResolved = JSON.parse(JSON.stringify(profilesBuffer.toString()));\n return new Promise((resolve, reject) => {\n resolve(profilesResolved);\n });\n}", "function mapStateToProps(state, ownProps) {\n return {\n // projects: state.projects\n };\n}", "getProjectAndRole({ projectId, projectName, mutation = false }) {\n const query = {\n deleted: false,\n };\n if (projectId) {\n query._id = new ObjectId(projectId);\n } else if (projectName) {\n query.name = projectName;\n } else {\n return Promise.reject(new BadRequest('no-project-id'));\n }\n // If this is a mutation and the user is not logged in, then don't even bother doing a\n // database lookup for the project, since they won't be able to do anything.\n if (mutation && !this.user) {\n return Promise.resolve([null, Role.NONE]);\n }\n return this.db.collection('projects').findOne(query).then(project => {\n if (!project) {\n return [null, Role.NONE];\n }\n if (this.user && this.user.username === project.owningUser) {\n return [project, Role.OWNER];\n }\n if (!this.user) {\n if (project.public) {\n return [project, Role.NONE];\n } else {\n return [null, Role.NONE];\n }\n }\n return this.db.collection('projectMemberships').findOne(\n { user: this.user.username, project: project._id })\n .then(mb => {\n if (mb) {\n return [project, mb.role];\n }\n // TODO: Return null for project if it's private and user is not a member.\n return [project, Role.NONE];\n });\n });\n }", "function getProjectInfo(folderName){\n return new Promise(\nfunction(resolve, reject){\n\n let command = 'cd ' + folderName + ' && git remote -v ';\n let currentBranch = '';\n let branchList = [];\n\n exec(command, function (error, stdout, stderr) {\n if (error !== null) {\n reject(stderr);\n }\n let patt = /\\/[a-zA-Z0-9-.]{1,30}(?= \\(fetch\\))/;\n let regres = patt.exec(stdout);\n let projectName = regres.toString().substr(1);\n // console.log(\"\\r\\n\"+moment().format('Y/MM/DD HH:mm:ss\\t\\t\\t\\t')+__filename);console.log('\\tINFO:\\tprojectName = '+projectName );\n resolve({projectName : projectName});\n\n });\n});\n}", "function listProjet() {\n $http({\n \t\turl: 'http://localhost:3000/projet/getProjets',\n \t\tmethod: 'GET',\n \t\tdatatype: 'json',\n \t\tcontentType: 'text/plain',\n \t\theaders: {'Content-Type': 'application/json'}\n \t}).then(function successCallback(res) {\n $scope.projets = res.data.projets;\n console.log(res);\n return;\n }, function errorCallback(err) {\n console.log(\"Impossible d'accéder à la liste des projets.\\n\" + err.toString());\n });\n }", "getGithubInfo(username) {\n // axios.all allows to take more functions and wait till all\n // the promises are resolved and then it will pass an array\n // of data that we got back from all invokations\n return axios.all([\n getRepos(username),\n getUserInfo(username)\n ]).then(arr => ({repos: arr[0].data, bio: arr[1].data }));\n }", "function getProjects (projects) {\n // Add Flexslider to Projects Section\n $('.Projects-slider').flexslider({\n animation: 'slide',\n directionNav: true,\n slideshowSpeed: 6000000,\n prevText: '',\n nextText: ''\n });\n $('.flex-next').prependTo('.HOT-Nav-Projects');\n $('.flex-control-nav').prependTo('.HOT-Nav-Projects');\n $('.flex-prev').prependTo('.HOT-Nav-Projects');\n\n if (projects.length === 1) {\n $('.flex-next').css('display', 'none');\n }\n\n projects.forEach(function (project, i) {\n const url = tasksApi + `/projects/${project}/queries/summary/`;\n $.getJSON(url, function (projectData) {\n makeProject(projectData, i + 2);\n })\n .fail(function (err) {\n console.warn(`WARNING >> Project #${project} could not be accessed at ${url}.\\n` +\n 'The server returned the following message object:', err);\n makePlaceholderProject(project, i + 2);\n });\n });\n}", "static getProfiles() {\r\n let profiles;\r\n if (localStorage.getItem('profiles') === null) {\r\n profiles = [];\r\n } else {\r\n profiles = JSON.parse(localStorage.getItem('profiles'));\r\n }\r\n return profiles;\r\n }", "function TwiceProfiles() {\n let profiles = Profiles();\n profiles.insertBefore(TwicePicture(), profiles.firstChild);\n return profiles;\n}", "function ProfileProjects(props) {\n // TODO Better to define a schema in sanity for contribution type and mapping from type to role!\n // So that future devs can update just the schemas and don't have to track down this component\n const subjects = [\n \"Projects\",\n \"Contributions\",\n \"Editing\",\n \"Design\",\n \"Blog posts\",\n \"All\",\n ];\n const [activeCategory, setActiveCategory] = useState(\"Projects\");\n const cards = subjects.map((subject) => {\n const included = activeCategory === subject;\n return (\n <Card\n variant=\"list\"\n sx={{\n backgroundColor: included ? \"primary\" : \"inherit\",\n color: included ? \"background\" : \"inherit\",\n wordWrap: \"break-word\",\n \"&:hover\": {\n bg: included ? \"primary\" : \"muted\",\n },\n }}\n onClick={() => {\n setActiveCategory(subject);\n }}\n >\n {subject}\n </Card>\n );\n });\n const role_dict = {\n Projects: [\"author\", \"developer\"],\n Editing: [\"editor\", \"manager\"],\n Illustrations: [\"designer\", \"illustrator\"],\n Contributions: [\"contributor\"],\n };\n let nodes;\n if (activeCategory === \"Blog posts\") {\n nodes = props.blog;\n } else if (activeCategory === \"All\") {\n nodes = props.projects.concat(props.blog);\n } else {\n nodes = props.projects.filter((project) => {\n var person = project._rawMembers.filter((p) => {\n return p.person.id === props.id;\n });\n for (let role in role_dict[activeCategory]) {\n if (\n person[0].roles &&\n person[0].roles.indexOf(role_dict[activeCategory][role]) !== -1\n ) {\n return true;\n }\n }\n return false;\n });\n }\n\n return (\n <div>\n <br></br>\n <Section header={\"Latest Work\"}>\n <Grid gap={4} columns={[1, \"2fr 4fr\", \"1fr 4fr 1fr\"]}>\n <div>\n <br></br>\n {cards}\n </div>\n <div>\n <div>\n <br></br>\n {nodes && (\n <ProjectPreviewGrid nodes={nodes} horizontal columns={[1]} />\n )}\n </div>\n </div>\n </Grid>\n </Section>\n </div>\n );\n}", "fetchProjects() {\n actions.fetchProjects();\n }" ]
[ "0.5771579", "0.5649819", "0.56445163", "0.5529522", "0.5509322", "0.54768616", "0.5465083", "0.5406542", "0.5402939", "0.5383652", "0.5369943", "0.53506094", "0.530953", "0.5308078", "0.5286793", "0.5278126", "0.52184117", "0.5210045", "0.51988316", "0.5177392", "0.51467806", "0.5141304", "0.5085059", "0.5078121", "0.50553596", "0.5038395", "0.50168467", "0.49787146", "0.49612734", "0.49607506", "0.49606216", "0.495514", "0.4940511", "0.49322724", "0.4918488", "0.4916874", "0.4915765", "0.4910719", "0.49095523", "0.4904168", "0.48944643", "0.48936397", "0.48766723", "0.48532352", "0.48308262", "0.4825385", "0.48194146", "0.47988716", "0.4788609", "0.47822052", "0.47574314", "0.4749245", "0.47360572", "0.47327963", "0.47302553", "0.4725272", "0.47163877", "0.47114128", "0.47024775", "0.4701449", "0.46883327", "0.46861935", "0.4680652", "0.46806428", "0.46796098", "0.46727508", "0.46716923", "0.4664865", "0.46528262", "0.46523413", "0.46502188", "0.46487883", "0.46464062", "0.46308103", "0.46290877", "0.46288666", "0.46242458", "0.4623926", "0.46228617", "0.46153322", "0.4610062", "0.46081117", "0.4600022", "0.45935884", "0.45903558", "0.45808673", "0.4569282", "0.45625913", "0.45608065", "0.4547849", "0.454361", "0.4542106", "0.4535508", "0.45353946", "0.453113", "0.4524445", "0.45158774", "0.45151353", "0.45019868", "0.4501573", "0.4499003" ]
0.0
-1
If the subscription(s) have been received, render the page, otherwise show a loading icon.
render() { return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function showLoading() {\n if (loadingMessageId === null) {\n loadingMessageId = rcmail.display_message('loading', 'loading');\n }\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Fetching Data</Loader>;\n }", "render() {\n\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return this.props.ready ? (\n this.renderPage()\n ) : (\n <Loader active>Getting data</Loader>\n );\n }", "render() {\n return (this.props.ready && this.props.ready2) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting Vendor</Loader>;\n }", "function renderLoader() {\n $('.schedule-page__content', scheduled.$el).empty().html(scheduled.template.loadingTemplate());\n }", "function pageLoading(){\n $(document).ajaxStart(function(){\n $(\"#loadingMessage\").show();\n });\n $(document).ajaxComplete(function(event, request){\n $(\"#loadingMessage\").hide();\n });\n }", "render() {\n return ((this.props.ready && this.props.ready2 && this.props.ready3)) ? this.renderPage() :\n <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready1 && this.props.ready2) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "function subscribe() {\n $rootScope.$on('loaded', function() {\n self.loading = false;\n });\n }", "showLoading() {\n if (!this.props.loading || 0 < _.size(this.props.usersList)) {\n return false;\n }\n return (\n <div><p>Loading</p></div>\n );\n }", "function loadingShow() {\n $(\"#divLoading\").html(\n '<div class=\"loadingPage\">' +\n '<img src=\"/static/images/loader.gif\" class=\"loadingImage\"/>' +\n '</div>'\n );\n}", "function showLoadingScreen () {\n const chatContainerDom = document.getElementById('chatReadSection');\n const loadingDom = document.createElement('div');\n loadingDom.setAttribute('class', 'loading-screen');\n loadingDom.innerHTML = 'Loading Wishes...';\n chatContainerDom.appendChild(loadingDom);\n }", "function displayLoadingPage(afficher) {\n afficher = (!afficher) ? false \n : afficher;\n\tif (afficher) {\n // -- Affichier le progress bar -- //\n NProgress.start();\n // -- Afficher le frame de chargelent -- //\n $('#frame_chargement').show();\n\t} else {\n // -- Finaliser le chargement du progress bar -- //\n NProgress.done();\n // -- Cacher le frae de chargement -- //\n $('#frame_chargement').hide();\n\t}\n}", "function handleAPILoaded()\n{\n requestSubscriptionList();\n}", "function displayLoading() {\n console.log(\"Loading...\");\n }", "function showSubLoading() {\n _updateState(hotelStates.SHOW_SUB_LOADING);\n }", "render() {\n return (this.props.tickets) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "renderContentLoading() { return <Loading /> }", "setPageLoading() {\n this.pageReady = false\n }", "function showSuccessPage() {\n $.get('/checkout/successful', function(data) {\n if(data){\n // Update Shopping Cart Badge\n $('#contentData').html(data);\n\n // Empty Shopping Cart\n $('#cartBadge').html(0);\n\n }\n });\n}", "function _showSubscribersView() {\n\t\tif (RELAY_USER.isSuperAdmin()) {\n\t\t\t_subscriberProcessingStart();\n\t\t\t$('#subscribersView').fadeIn();\n\n\t\t\t// Pull entire list of subscribers (past and present)\n\t\t\t$.when(SUBSCRIBERS.getSubscribersXHR()).done(function (orgs) {\n\t\t\t\tvar tblBody = '';\n\t\t\t\t$.each(orgs, function (index, orgObj) {\n\t\t\t\t\t// `active` parameter\n\t\t\t\t\tvar $dropDownAccess = $('#tblDropdownTemplate').clone();\n\t\t\t\t\tswitch (orgObj.active) {\n\t\t\t\t\t\tcase \"1\":\n\t\t\t\t\t\t\t$dropDownAccess.find('.currentValue').text('Aktiv');\n\t\t\t\t\t\t\t$dropDownAccess.find('.dropdown-menu').append('<li style=\"cursor: pointer;\"><a class=\"btn-link btnDeactivateOrgAccess\" data-org=\"' + orgObj.org + '\">Steng tilgang</a></li>');\n\t\t\t\t\t\t\t$dropDownAccess.find('.btn').addClass('btn-success');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"0\":\n\t\t\t\t\t\t\t$dropDownAccess.find('.currentValue').text('Stengt');\n\t\t\t\t\t\t\t$dropDownAccess.find('.dropdown-menu').append('<li style=\"cursor: pointer;\"><a class=\"btn-link btnActivateOrgAccess\" data-org=\"' + orgObj.org + '\">Aktiver tilgang</a></li>');\n\t\t\t\t\t\t\t$dropDownAccess.find('.btn').addClass('btn-danger');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// `affiliation_access` parameter\n\t\t\t\t\tvar $dropDownAffiliation = $('#tblDropdownTemplate').clone();\n\t\t\t\t\t$dropDownAffiliation.find('.currentValue').text(orgObj.affiliation_access);\n\t\t\t\t\tswitch (orgObj.affiliation_access) {\n\t\t\t\t\t\tcase \"employee\":\n\t\t\t\t\t\t\t$dropDownAffiliation.find('.btn').addClass('btn-info');\n\t\t\t\t\t\t\t$dropDownAffiliation.find('.dropdown-menu').append('<li style=\"cursor: pointer;\"><a class=\"btn-link btnAddOrgStudentAccess\" data-org=\"' + orgObj.org + '\">Legg til studenttilgang</a></li>');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"member\":\n\t\t\t\t\t\t\t$dropDownAffiliation.find('.btn').addClass('btn-primary');\n\t\t\t\t\t\t\t$dropDownAffiliation.find('.dropdown-menu').append('<li style=\"cursor: pointer;\"><a class=\"btn-link btnRemoveOrgStudentAccess\" data-org=\"' + orgObj.org + '\">Fjern studenttilgang</a></li>');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Add row to table\n\t\t\t\t\ttblBody += '<tr>' +\n\t\t\t\t\t\t'<td>' + orgObj.org + '</td>' +\n\t\t\t\t\t\t//'<td>' + orgObj.affiliation_access + '</td>' +\n\t\t\t\t\t\t'<td>' + $dropDownAffiliation.html() + '</td>' +\n\t\t\t\t\t\t//'<td>' + orgObj.active + '</td>' +\n\t\t\t\t\t\t'<td>' + $dropDownAccess.html() + '</td>' +\n\t\t\t\t\t\t'<td class=\"text-center\"><button class=\"btnDeleteOrg btn-link uninett-fontColor-red\" type=\"button\" data-org=\"' + orgObj.org + '\"><span class=\"glyphicon glyphicon-remove\"></span></button></td>' +\n\t\t\t\t\t\t'</tr>';\n\t\t\t\t});\n\t\t\t\t$('#tblSubscribers').find('tbody').html(tblBody);\n\t\t\t\t//\n\t\t\t\t_subscriberProcessingEnd()\n\t\t\t});\n\t\t}\n\t}", "function showLoading() {\n\n\t$chatlogs.append($('#loadingGif'));\n\t$(\"#loadingGif\").show();\n\t$('.chat-form').css('visibility', 'hidden');\n}", "render(){\n return (this.data.dataLoaded) ? this.getContent() : <div><Loader /></div>\n }", "function showPageLoading() {\n $(\"div.loading-page\").css(\"display\", \"block\");\n $(\".main-page-core\").css(\"opacity\", \"1\");\n $(\".loading-icon\").css(\"display\", \" none\");\n}", "showPageLoadingIndicator() {\n\t\tgetComponentElementById(this,\"DataListLoading\").html('<div class=\"dx-loading\"></div>').show();\n\t}", "renderLoadingIcon() {}", "function Procesando() {\n $(\"#divLoading\").show();\n }", "function showLoading() {\n _updateState(hotelStates.SHOW_LOADING);\n }", "async function showLoadingView() {\n $('button').html('Loading..');\n $('#loading').append('<i class=\"fas fa-spinner fa-spin icon-large\"></i>');\n}", "displayFavorites() {\n this.enableStickerSelection = false;\n this.moreGifs = false;\n this.loader = true;\n this.favoriteService.getFavorites().subscribe((result) => {\n this.gifs = result;\n this.loader = false;\n });\n }", "render() {\n //indicate gifs are loading while state is set in component mount, gifs array is empty\n return (\n <div>\n <MyFaveGifs getGifs={this.getMyGifs}/>\n {\n !this.state.trendingGifs.length ? (\n <div className=\"spinner\"></div>\n ) : (\n <main>\n <ul className=\"card-container\">\n {this.renderCards.call(this, this.state.trendingGifs)}\n </ul>\n { this.state.startAt < 20 ? <LoadMoreButton onClick={this.handleLoadMoreClick} />\n : <PageEnd /> }\n </main>\n )\n }\n </div>\n )\n }", "renderBusyContent() {\n return (\n <Fragment>\n <h1>One moment <span>please...</span></h1>\n\n <p>I'm currently busy chatting with lots of other people. I'll be ready in a few minutes, so try again soon.</p>\n\n { this.renderActions() }\n </Fragment>\n );\n }", "function showLoading(selector) {\r\n var html = \"<div class = 'text-center'>\";\r\n html += \" <img src = 'images/ajax-loader.gif'></div>\";\r\n insertHtml(selector, html);\r\n }", "function showLoadingView() {\n $loader.css(\"display\", \"block\");\n }", "showLoadingView() {\n $('#start').empty();\n document.getElementById('start').innerHTML = 'Loading! ';\n $('#start').append($('<i class=\"fas fa-spinner fa-pulse\"></i>'))\n $('#load-screen').append($('<i id=\"loading\" class=\"mt-4 fas fa-spinner fa-pulse\"></i>'))\n }", "function requestSubs() {\n loadingProgress(1);\n buildServerRequest(\"/subscriptions\", {\"maxResults\": config.maxSimSubLoad})\n .then(processRequestSubs);\n}", "function showLoadingView() {\n\n}", "render() {\n this.previousState = StateManager.CopyState();\n\n let loading = \"\";\n if (StateManager.State().UI.IsLoading) {\n loading = (\n <div className={FormatCssClass(\"loading\")}>\n Loading\n </div>\n );\n }\n\n return loading;\n\n }", "render() {\n const status = this.props.status;\n\n if(status== 'Loading'){\n return (\n <div className=\"spinner-border\" role=\"status\">\n <span className=\"sr-only\">Loading...</span>\n </div>\n );\n }\n // Can't return nothing, and html comments seems not ok\n return (<div></div>)\n }", "render() {\n const { isLoaded, streamsApiData } = this.state;\n\n if (!isLoaded) {\n return (\n <div id=\"preloader-overlay\">\n <div id=\"preloader-spinner\"></div>\n </div>\n );\n } else if (streamsApiData.length === 0) {\n return this.createDivForNoStream();\n } else {\n let streams = [];\n for (let i = 0; i < streamsApiData.length; i++)\n streams.push(this.renderStream(streamsApiData, i));\n\n return <div>{ streams }</div>;\n }\n }", "render() {\n return (\n myutils.renderLoadingstate()\n );\n }", "function showLoading() {\n loading.classList.add(\"show\");\n setTimeout(callData, 2000);\n }", "function doSomethingAfterRendering(){\n displayLoading() // 로딩화면 보여주기\n fetchServer(); // 서버에서 데이터 가져오기\n }", "render() {\n return (\n <LoadingPage/>\n );\n }", "function getCustomers() {\n $.ajax({\n type: 'GET',\n url: 'customers',\n beforeSend: function () {\n // this is where we append a loading image\n },\n success: function (data) {\n // successful request; do something with the data\n var content = '<li>צפה בכל הלקוחות</li> <span class=\"fa fa-angle-left\"></span><li><a href=\"dashboard\"> &nbsp; הבית </a></li>';\n $('#page_path').html(content);\n $('.content-area').html(data);\n },\n error: function (data) {\n // failed request; give feedback to user\n notif({\n msg: \"<b>Oops:</b> שגיאה. נסה שוב מאוחר יותר..\",\n position: \"center\",\n time: 10000\n });\n }\n });\n}", "renderContentConditional() {\n if (this.props.loading) {\n return this.renderContentLoading()\n } else {\n return this.renderContent()\n }\n }", "function loadingGif(){\n $(document).ajaxSend(function(){\n $(\".cssload-container\").css(\"display\",\"block\");\n });\n $(document).ajaxComplete(function(){\n $(\".cssload-container\").css(\"display\",\"none\");\n });\n }", "function updateSubscribeUIStatus() {\n all_comic_data = settings.get('comic');\n if (all_comic_data == undefined) {\n all_comic_data = {};\n settings.set('comic', all_comic_data);\n }\n search_viewcontroller.updateSubscribeUI(all_comic_data);\n favorite_viewcontroller.updateSubscribeUI(all_comic_data, hasSubscription());\n read_viewcontroller.updateSubscribeUI(all_comic_data);\n translate_viewcontroller.translate();\n\n var page_idx = read_viewcontroller.getCurrentPageIdx();\n var titlekey = read_viewcontroller.getCurTitleKey();\n var host = read_viewcontroller.getCurHost();\n // console.log(page_idx + \":\" + titlekey + \":\" + host); \n if (host && titlekey && page_idx != 0) {\n all_comic_data[host][titlekey].lastpage = page_idx;\n settings.set('comic', all_comic_data);\n }\n}", "function renderArticles() {\n $('#articles').empty().html(current.template.loadingTemplate());\n fetchArticles(fetchArticlesSuccess, fetchArticlesError);\n }", "function showLoading()\n{\n\t$chatlogs.append($('#loadingGif'));\n\t$(\"#loadingGif\").show();\n\n\t// $('#submit').css('visibility', 'hidden');\n\t// $('input').css('visibility', 'hidden');\n\n\t$('.chat-form').css('visibility', 'hidden');\n }", "function showDataIsLoaded() {\n let loadingIndicator = document.getElementById(\"loadingIndicator\");\n loadingIndicator.innerHTML = \"Data loaded!\";\n setTimeout(() => loadingIndicator.style.display = \"none\", 1000);\n}", "function showQuiosqueLoad(){\n $(\"#myloadingDiv\" ).show();\n }", "function render() {\n if (!store.started) {\n if(store.filtered === false){\n $(\"main\").html(template.startPage());\n const html = template.generateBookmarkStrings(store.items);\n $('#bookmarkResults').html(html);\n } else{\n $(\"main\").html(template.startPage());\n $('#minimumRating').val(store.minimum);\n const filter = store.items.filter(bookmark => {\n return bookmark.rating >= store.minimum;\n \n })\n const html = template.generateBookmarkStrings(filter);\n $('#bookmarkResults').html(html);\n }\n \n \n } else {\n $(\"main\").html(template.newBookmarkTemp());\n }\n}", "function notifyLoadingRequest() {\n\tloadingRequests++;\n\tcheckLoading();\n\treturn true;\n}", "function ajaxLoadingSignalOn()\n{\n indicator = document.getElementById(loadingSignalId);\n if (indicator)\n indicator.style.visibility = \"visible\";\n}", "function renderUpdateComplete() {\n exportData.renderUpdateRunning = false;\n $loadingBar.css('opacity', 0);\n }", "function alreadyRegisteredPage() {\r\n app.getView().render('subscription/emarsys_alreadyregistered');\r\n}", "function Loading() {\n return (\n <div class=\"spinner-border load\" role=\"status\">\n <span class=\"sr-only\">Loading...</span>\n </div>\n )\n}", "function showLoading() {\n\twindow.status = \"Obtendo informações\";\n\n\tmainContent.style.display = \"none\";\n\tloading.style.display = \"block\";\n}", "function showLoadingAjax () {\n\treplaceHTMLOfElement(contentDiv, '');\n\tshowProgressBar();\n}", "function addLoadingIndicator(){\n\tlet template = document.importNode(templateLoadingIndicator.content, true);\n\tclearContainerHTML(htmlProducts);\n\thtmlProducts.appendChild(template);\n }" ]
[ "0.6480619", "0.6350569", "0.6349684", "0.629345", "0.6243007", "0.6243007", "0.6243007", "0.6243007", "0.62422377", "0.62412745", "0.61397916", "0.6128012", "0.60392493", "0.59955424", "0.5964248", "0.59292483", "0.592554", "0.5916828", "0.5914855", "0.58417475", "0.5823805", "0.5818887", "0.58056414", "0.5769396", "0.5763185", "0.5762191", "0.57527226", "0.57465166", "0.5745685", "0.5722875", "0.5721372", "0.57074326", "0.5701146", "0.56878924", "0.56850797", "0.5675432", "0.5675126", "0.5669583", "0.56604654", "0.56551254", "0.5649666", "0.56469166", "0.5589864", "0.55832356", "0.55768305", "0.55693394", "0.55681753", "0.5567222", "0.55396444", "0.55386555", "0.553205", "0.5529981", "0.55112934", "0.551059", "0.54964703", "0.54960436", "0.5495292", "0.5475887", "0.5473275", "0.5458143", "0.5456462", "0.5455099", "0.54485995", "0.54445076", "0.5442546", "0.5441964", "0.5414582", "0.54094505" ]
0.6306368
23
Render the page once subscriptions have been received.
renderPage() { const vendorTypes = _.pluck(VendorClass.collection.find().fetch(), 'vendor'); const vendorTypeData = vendorTypes.map(vendorType => getInterestData(vendorType)); return ( <div id='byCategory-Page' className='pages-background' style={{ paddingTop: '20px' }}> <Container id="interests-page"> <Card.Group> {_.map(vendorTypeData, (vendorType, index) => <MakeCard key={index} vendorType={vendorType}/>)} </Card.Group> </Container> <div className='green-gradient' style={{ paddingTop: '100px' }}/> <div className='footer-background'/> </div> ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function handleAPILoaded()\n{\n requestSubscriptionList();\n}", "function _render(){\n\t\tinfo = {\n\t\t\t\tpublishers_array: publishers_array\n\t\t}\n\t\t$element.html(Mustache.render(template, info))\n\t}", "function dataSubmittedPage() {\r\n app.getView().render('subscription/emarsys_datasubmitted');\r\n}", "function _showSubscribersView() {\n\t\tif (RELAY_USER.isSuperAdmin()) {\n\t\t\t_subscriberProcessingStart();\n\t\t\t$('#subscribersView').fadeIn();\n\n\t\t\t// Pull entire list of subscribers (past and present)\n\t\t\t$.when(SUBSCRIBERS.getSubscribersXHR()).done(function (orgs) {\n\t\t\t\tvar tblBody = '';\n\t\t\t\t$.each(orgs, function (index, orgObj) {\n\t\t\t\t\t// `active` parameter\n\t\t\t\t\tvar $dropDownAccess = $('#tblDropdownTemplate').clone();\n\t\t\t\t\tswitch (orgObj.active) {\n\t\t\t\t\t\tcase \"1\":\n\t\t\t\t\t\t\t$dropDownAccess.find('.currentValue').text('Aktiv');\n\t\t\t\t\t\t\t$dropDownAccess.find('.dropdown-menu').append('<li style=\"cursor: pointer;\"><a class=\"btn-link btnDeactivateOrgAccess\" data-org=\"' + orgObj.org + '\">Steng tilgang</a></li>');\n\t\t\t\t\t\t\t$dropDownAccess.find('.btn').addClass('btn-success');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"0\":\n\t\t\t\t\t\t\t$dropDownAccess.find('.currentValue').text('Stengt');\n\t\t\t\t\t\t\t$dropDownAccess.find('.dropdown-menu').append('<li style=\"cursor: pointer;\"><a class=\"btn-link btnActivateOrgAccess\" data-org=\"' + orgObj.org + '\">Aktiver tilgang</a></li>');\n\t\t\t\t\t\t\t$dropDownAccess.find('.btn').addClass('btn-danger');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// `affiliation_access` parameter\n\t\t\t\t\tvar $dropDownAffiliation = $('#tblDropdownTemplate').clone();\n\t\t\t\t\t$dropDownAffiliation.find('.currentValue').text(orgObj.affiliation_access);\n\t\t\t\t\tswitch (orgObj.affiliation_access) {\n\t\t\t\t\t\tcase \"employee\":\n\t\t\t\t\t\t\t$dropDownAffiliation.find('.btn').addClass('btn-info');\n\t\t\t\t\t\t\t$dropDownAffiliation.find('.dropdown-menu').append('<li style=\"cursor: pointer;\"><a class=\"btn-link btnAddOrgStudentAccess\" data-org=\"' + orgObj.org + '\">Legg til studenttilgang</a></li>');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"member\":\n\t\t\t\t\t\t\t$dropDownAffiliation.find('.btn').addClass('btn-primary');\n\t\t\t\t\t\t\t$dropDownAffiliation.find('.dropdown-menu').append('<li style=\"cursor: pointer;\"><a class=\"btn-link btnRemoveOrgStudentAccess\" data-org=\"' + orgObj.org + '\">Fjern studenttilgang</a></li>');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Add row to table\n\t\t\t\t\ttblBody += '<tr>' +\n\t\t\t\t\t\t'<td>' + orgObj.org + '</td>' +\n\t\t\t\t\t\t//'<td>' + orgObj.affiliation_access + '</td>' +\n\t\t\t\t\t\t'<td>' + $dropDownAffiliation.html() + '</td>' +\n\t\t\t\t\t\t//'<td>' + orgObj.active + '</td>' +\n\t\t\t\t\t\t'<td>' + $dropDownAccess.html() + '</td>' +\n\t\t\t\t\t\t'<td class=\"text-center\"><button class=\"btnDeleteOrg btn-link uninett-fontColor-red\" type=\"button\" data-org=\"' + orgObj.org + '\"><span class=\"glyphicon glyphicon-remove\"></span></button></td>' +\n\t\t\t\t\t\t'</tr>';\n\t\t\t\t});\n\t\t\t\t$('#tblSubscribers').find('tbody').html(tblBody);\n\t\t\t\t//\n\t\t\t\t_subscriberProcessingEnd()\n\t\t\t});\n\t\t}\n\t}", "function alreadyRegisteredPage() {\r\n app.getView().render('subscription/emarsys_alreadyregistered');\r\n}", "function render() {\n let bigString;\n console.log('render fxn ran')\n if (store.view === 'landing') {\n bigString = generateTitleTemplate(store);\n\n }\n else if (store.view === 'question') {\n bigString = generateQuestionTemplate(store);\n\n }\n else if (store.view === 'feedback') {\n bigString = generateFeedbackTemplate(store)\n\n }\n else if (store.view === 'results') {\n bigString = generateResultsTemplate(store);\n\n }\n $('main').html(bigString);\n\n //attach event listeners\n\n\n}", "render() {\n this.eventBusCollector.on(NEWPULLREQUEST.render, this._onRender.bind(this));\n this.eventBus.emit(REPOSITORY.getInfo, {});\n }", "render() {\n this.notify('initial-load', {});\n /**\n * Used to load context menu\n */\n this.trigger('load');\n this.notify('initial-end', {});\n this.renderElements();\n this.renderComplete();\n }", "render() {\n this.notify('initial-load', {});\n /**\n * Used to load context menu\n */\n this.trigger('load');\n this.notify('initial-end', {});\n this.renderElements();\n this.renderComplete();\n }", "render() {\n this.notify('initial-load', {});\n /**\n * Used to load context menu\n */\n this.trigger('load');\n this.notify('initial-end', {});\n this.renderElements();\n this.renderComplete();\n }", "function renderArticles() {\n $('#articles').empty().html(current.template.loadingTemplate());\n fetchArticles(fetchArticlesSuccess, fetchArticlesError);\n }", "render() {\n this._addChooserHandler();\n this._addLoggerListeners();\n this._addButtonHandler();\n }", "async function fetchData() {\n const channels = await getChannels();\n\n const data = {\n title: 'ChatX',\n content: component,\n state: {\n rooms: channels, // preload existing rooms\n messages: [],\n signedIn: req.session.user ? true : false\n }\n };\n\n res.status(200);\n res.render('index', data);\n }", "function handleRender() {\n view._isRendered = true;\n triggerDOMRefresh();\n }", "function handleRender() {\n view._isRendered = true;\n triggerDOMRefresh();\n }", "subscriptions () {\r\n events.on(\"url-change\", (data) => {\r\n if (data.state && data.state.selector) {\r\n const target = document.querySelector(data.state.selector);\r\n\r\n this.toggleActivePages(target);\r\n this.toggleActiveSubnav(data.state.index);\r\n }\r\n });\r\n }", "function render() {\n if (!store.started) {\n if(store.filtered === false){\n $(\"main\").html(template.startPage());\n const html = template.generateBookmarkStrings(store.items);\n $('#bookmarkResults').html(html);\n } else{\n $(\"main\").html(template.startPage());\n $('#minimumRating').val(store.minimum);\n const filter = store.items.filter(bookmark => {\n return bookmark.rating >= store.minimum;\n \n })\n const html = template.generateBookmarkStrings(filter);\n $('#bookmarkResults').html(html);\n }\n \n \n } else {\n $(\"main\").html(template.newBookmarkTemp());\n }\n}", "function render() { \n\n $body.append(templates['container']({'id':_uid}))\n $j('#' + _uid).append(templates['heading-no-links']({'title':'Countdown Promotion'}));\n $j('#' + _uid).append(templates['countdown-promo']({'id':_uid}));\n \n chtLeaderboard = new CHART.CountdownLeaderboard(_uid + '-charts-promo-leaderboard', _models.promo.getData('all'), _models.promo.getTargetSeries(20000));\n tblLeaderboard = new TABLE.CountdownLeaderboard(_uid + '-tables-promo-leaderboard', _models.promo.groupByOwner('all', 20000), _models.promo.getTotal('all', 180000)); \n chtLastWeek = new CHART.CountdownLeaderboard(_uid + '-charts-promo-lastweek', _models.promo.getData('lastweek'), _models.promo.getTargetSeries(1540));\n tblLastWeek = new TABLE.CountdownLeaderboard(_uid + '-tables-promo-lastweek', _models.promo.groupByOwner('lastweek', 1540), _models.promo.getTotal('lastweek', 13860)); \n chtWeeklySales = new CHART.CountdownWeeklySales(_uid + '-charts-promo-weeklysales', _models.promo.getData('all'));\n\n }", "function updateSubscribeUIStatus() {\n all_comic_data = settings.get('comic');\n if (all_comic_data == undefined) {\n all_comic_data = {};\n settings.set('comic', all_comic_data);\n }\n search_viewcontroller.updateSubscribeUI(all_comic_data);\n favorite_viewcontroller.updateSubscribeUI(all_comic_data, hasSubscription());\n read_viewcontroller.updateSubscribeUI(all_comic_data);\n translate_viewcontroller.translate();\n\n var page_idx = read_viewcontroller.getCurrentPageIdx();\n var titlekey = read_viewcontroller.getCurTitleKey();\n var host = read_viewcontroller.getCurHost();\n // console.log(page_idx + \":\" + titlekey + \":\" + host); \n if (host && titlekey && page_idx != 0) {\n all_comic_data[host][titlekey].lastpage = page_idx;\n settings.set('comic', all_comic_data);\n }\n}", "function requestSubs() {\n loadingProgress(1);\n buildServerRequest(\"/subscriptions\", {\"maxResults\": config.maxSimSubLoad})\n .then(processRequestSubs);\n}", "function subscriber() {\n const { count } = store.getState();\n document.getElementById('count').textContent = count.value;\n}", "subscribe() {\n this.subscriptionID = this.client.subscribe(this.channel, this.onNewData)\n this.currencyCollection.subscribe(this.render)\n this.currencyCollection.subscribe(this.drawInitialSparkLine)\n this.currencyCollection.subscribeToSparkLineEvent(this.drawSparkLine)\n }", "function render() {\n //zarejdame si templeitite i im zakachame event\n ctx.partial('./templates/welcome.hbs')\n .then(attachEvents);\n }", "function render() {\n let html = generateHeader();\n\n if (store.error) {\n generateError();\n }\n\n // check if form displayed\n if (store.adding) {\n html += generateBookmarkForm();\n }\n\n html += generateAllBookmarkCards();\n\n $('main').html(html);\n }", "function handleRender() {\n\t view._isRendered = true;\n\t triggerDOMRefresh();\n\t }", "_handleChange() {\n if (this._renderType == SERVER) {\n // We don't need to trigger any subscription callback at server. We'll\n // render twice and we're only interested in the HTML string.\n return;\n }\n\n var timestamp = this._getTimestamp();\n var state = this._store.getState();\n if (this._previousState.state == null) {\n // If no change, no need to trigger callbacks.\n this._setPreviousState(state, timestamp);\n return;\n }\n\n // Assume comparison is cheaper than re-rendering. We do way more comparison\n // when we compare each piece, with the benefits of not doing unnecessary\n // re-rendering.\n var segmentName, segment, segmentState, prevSegmentState, segmentSubscribers,\n queryId, querySubscribers, subscriberId, segmentPiece, shouldUpdate;\n for (segmentName in this._segments) {\n if (!this._segments.hasOwnProperty(segmentName)) continue;\n segment = this._segments[segmentName];\n segmentSubscribers = this._subscribers[segmentName];\n segmentState = state[segmentName];\n prevSegmentState = this._previousState.state[segmentName];\n for (queryId in segmentSubscribers) {\n if (!segmentSubscribers.hasOwnProperty(queryId)) continue;\n querySubscribers = segmentSubscribers[queryId];\n // If segmentState is previously null, then this is a new query call.\n // First getState() method call should already return the initialized\n // object, so we don't need to call update.\n // TODO: This assumption/design seems to be flawed, null to existence is a change, and we should notify listeners.\n shouldUpdate = false;\n if (prevSegmentState != null) {\n segmentPiece = segment._comparePiece(prevSegmentState, segmentState, queryId);\n shouldUpdate = segmentPiece != null;\n }\n if (shouldUpdate) {\n // Segment piece has changed, call all registered subscribers.\n for (subscriberId in querySubscribers) {\n if (!querySubscribers.hasOwnProperty(subscriberId)) continue;\n querySubscribers[subscriberId](segmentPiece[0]);\n }\n }\n }\n }\n\n // Update previous state.\n this._setPreviousState(state, timestamp);\n }", "function renderPage() {\n\n if (STORE.view === 'start') {\n if (game1.sessionToken) {\n $('start-button').attr('disabled', false);\n }\n $('.page').html(renderStartView());\n }\n if (STORE.view === 'questions') {\n console.log('about to render');\n $('.page').html(renderQuestionView());\n }\n if (STORE.view === 'feedback' && STORE.showFeedback === true) {\n $('.page').html(renderFeedbackView());\n }\n if (STORE.view === 'results') {\n $('.page').html(renderResultsView());\n }\n}", "renderPage() {\t\t\n\t\tswitch (this.props.data.active) {\n\t\t\tcase 'user': \n\t\t\t\treturn this.renderUserInfo(this.props.data.body);\t\t\t\n\t\t\tcase 'repos': \n\t\t\t\treturn this.renderRepos(this.props.data.body);\n\t\t\tcase 'about': \n\t\t\t\treturn this.renderAbout();\t\t\t\t\t\n\t\t}\n\t}", "function getSubscriptionList() {\n _debug(\"Getting subscription list\");\n\n $('.sources ul').empty(); // empty the sources list\n\n $.ajax({\n url: \"/get/subscription-list\",\n type: 'GET',\n beforeSend: function(r) {\n r.setRequestHeader(\"Auth_token\", sessvars.Auth_token);\n },\n error: function(e) {\n spinner.stop();\n miniSpinner.stop();\n\n if (e.status === 401 || e.status === 400) {\n console.log('We should refresh token');\n window.location.href = \"/auth/google\"; // TODO: refresh token\n }\n\n throw new Error('Error ' + e.status + \":\" + e);\n },\n success: function(res) {\n\n miniSpinner.stop();\n $('.sources ul').append('<li id=\"allfeeds\"><div><a href=\"#\">All unread items</a><span>0</span></div></li>');\n $.each(res.subscriptions, function(i,obj) {\n\n var\n url = obj.htmlUrl,\n name = obj.title,\n id = sanitize(obj.id);\n\n sources[id] = obj.id;\n\n $('.sources ul').append('<li id=\"' + id + '\"><div><a href=\"#\">' + name + '</a><span>0</span></div></li>');\n $('li#' + id + ' div a').truncate({ width: 200 });\n });\n\n showSources();\n\n //Get the counters for the unread articles\n $.ajax({\n url: '/get/unread-count',\n type: 'GET',\n beforeSend: function(r) {\n r.setRequestHeader(\"Auth_token\", sessvars.Auth_token);\n miniSpinner.spin(miniTarget);\n },\n success: function(resc) {\n miniSpinner.stop();\n\n var re = new RegExp(/\\/state\\/com\\.google\\/reading-list/);\n\n $.each(resc.unreadcounts, function(i, obj) {\n\n if (obj.id.match(re)) {\n totalCount = obj.count;\n updateTotalCounter(totalCount);\n } else {\n unreadCounters[obj.id] = obj.count;\n updateCount(obj.id);\n }\n\n });\n\n setFeed('all', 't');\n setSelected('allfeeds');\n }\n });\n\n $('.sources div.wrap').addClass(\"scroll-pane\");\n $('.scroll-pane').jScrollPane();\n }\n });\n}", "async initSubscriptions() {\n\n }", "static get observers(){return[\"_render(html)\"]}", "renderPage() {}", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "function filter_sub() {\n recipe_wrapper.innerHTML = \"\";\n var currentPage = window.location.href;\n var http = new XMLHttpRequest();\n http.open('GET', `${currentPage}/subscribed`, true);\n\n http.onreadystatechange = function() {\n if (http.readyState == 4 && http.status == 200) {\n subs = this.responseText.split(\"|||\");\n for (var i = 0; i < subs.length; i++) {\n if (subs[i] != \"\") {\n new_tile = create_recipe_tile(subs[i]);\n recipe_wrapper.appendChild(new_tile);\n }\n }\n format_recipe_description_for_web();\n }\n }\n\n http.send();\n}", "_renderCurrentPage() {\n this._clearRenderedCards();\n\n this._displayedCards.forEach(card => this._renderCard(card));\n this._evaluateControllers();\n }", "render() {\n\t\t\t\tif (shouldSubscribe && !this.unsubscribeStore_) {\n\t\t\t\t\tthis.unsubscribeStore_ = this.getStore().subscribe(\n\t\t\t\t\t\tthis.handleStoreChange_.bind(this)\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn <WrappedComponent {...this.getChildProps_()} />;\n\t\t\t}", "function render() {\n\tconsole.log(\"Re-rendering\")\n\tif (selectedTopicID != \"\" && selectedTopicID != null) {\n\t\tdocument.title = \"Work Log - \" + topicsDictionary[selectedTopicID].name;\n\t\t$(\"#time-elapsed-header\").html(formatCounter(topicsDictionary[selectedTopicID].time));\n\t}\n\trenderTopics();\n\trenderEvents();\n}", "function render() {\r\n //does nothing if there is not a current error\r\n renderError();\r\n\r\n let html = '';\r\n\r\n//view state changes if user has chosen to add a new bookmark\r\n if (store.adding === true) {\r\n html = addBookmark()\r\n }\r\n //if the value of error has changed state from its initial value of null displayError will inject the msg into the html\r\n else if (store.error != null) {\r\n html = displayError()\r\n }\r\n \r\n //finally, if no errors are present the initial view of the app will render\r\n else { html = generateInitialView(generateBookmarkString) }\r\n $('main').html(html)\r\n store.filter = 0\r\n}", "_renderStorage() {\n this._messageChecker();\n this.listCollection.forEach((list) => this._renderListPreviewMarkup(list));\n }", "static publish() {\r\n ViewportService.subscribers.forEach(el => {el.callback();});\r\n }", "function subscribe(){\n performance.mark('subscribing');\n client.subscribe('payload/empty', function (err) {});\n performance.mark('subscribed');\n performance.measure('subscribing to subscribed', 'subscribing', 'subscribed');\n}", "function loadAndRenderItems() {\n pageData().then(render)\n }", "async initSubscriptions() {\n const instance = this;\n for (let i = 0; i < this.subscriptions.length; i += 1) {\n const subscription = this.subscriptions[i];\n if (subscription === \"mapData\") {\n instance.stateManager.subscribe(subscription,\n async d => {\n instance[subscription] = d;\n console.log(d);\n await instance.#renderTable();\n });\n }\n }\n}", "handleSubscribe() {\n // Callback invoked whenever a new event message is received\n const messageCallback = (response) => {\n console.log(\"New Component Update message received: \", JSON.stringify(response.data.payload));\n this.doDemoComponentRefresh();\n }\n\n subscribe(this.channelName, -1, messageCallback).then((response) => {\n // Response contains the subscription information on subscribe call\n console.log(`Subscription request sent to: ${JSON.stringify(response.channel)}`);\n console.log(`Subscription request Response: ${JSON.stringify(response)}`);\n this.subscription = response;\n this.isSubscriptionRequested = false;\n this.isSubscribed = true;\n });\n }", "function processRequestSubs(response) {\n // If there is another page of subs request it.\n if ((\"undefined\" !== typeof response.nextPageToken) && (null !== response.nextPageToken)) {\n loadingProgress(1);\n buildServerRequest(\"/subscriptions\", {\"maxResults\": config.maxSimSubLoad, \"pageToken\": response.nextPageToken})\n .then(processRequestSubs);\n }\n // Create subs from the api response.\n response.items.forEach((item) => {\n if (-1 === subs.findIndex((x) => item.snippet.resourceId.channelId === x.id)) {\n subs.push(new Subscription(item.snippet));\n }\n });\n loadingProgress(-1);\n}", "function render(){\n let html='';\n if (store.quizStarted === false){\n html = generateStartPage();\n }else if (store.giveFeedback === true){\n html = generateQuestionsPage();\n } else if (store.giveFeedback === false && store.questionNumber === store.questions.length -1){\n html = generateLastPage();\n }\n else {\n html= generateRightWrong();\n }\n \n $('main').html(html);\n}", "render() {\n this.eventBusCollector.on(COMMITSPAGE.render, this._onRender.bind(this));\n this.eventBus.emit(COMMITSPAGE.getBranchList, {});\n }", "function processCheckedSubs(response) {\n // No longer subscribed\n if (0 === response.pageInfo.totalResults) {\n loadingProgress(-1, true);\n return;\n }\n // Create subs from the api response.\n response.items.forEach((item) => {\n subs.push(new Subscription(item.snippet));\n });\n loadingProgress(-1, true);\n}", "function thankYouPage() {\r\n app.getView().render('subscription/emarsys_thankyou');\r\n}", "render() {\n // If we have no articles, we will return this.renderEmpty() which in turn returns some HTML\n if (!this.state.savedArticles) {\n return this.renderEmpty();\n }\n // If we have articles, return this.renderContainer() which in turn returns all saves articles\n return this.renderContainer();\n }", "function getSubscriptions(callback, screen) {\n if(screen !== null) {\n $.ajax({\n type: \"POST\",\n url: host+\"api/tags.getSubscriptions\",\n contentType: \"application/json\",\n success: function(data) {\n callback(data, screen);\n },\n dataType: \"JSON\"\n });\n } else {\n // No screen has been passed\n console.warn(\"No screen has been passed\");\n }\n}", "render(...args) {\n if (this._render) {\n this.__notify(EV.BEFORE_RENDER);\n this._render(...args);\n this.__notify(EV.RENDERED);\n }\n\n this.rendered = true;\n }", "function getPage(filter){\nconsole.log('inside getPage');\n return function(page, model) {\n model.subscribe('todos', function () {\n\tif(filter =='active')\n\t{\n\tmodel.set('_page.newTodo', 'rajesh active');\n\t\tconsole.log('inside regtpage to render');\n\t\t}\n page.render();\n });\n }\n}", "handleSubscribe() {\n try {\n alert('Thank you for your Changes. Your posting will appear after approval.');\n history.push('/consultants');\n } catch (error) {\n alert('There seems to be a problem!');\n }\n }", "function renderPage() {\n // set up any necessary events\n Main.addClickEventToElement(document.getElementById(\"homeOptP\"), function () {\n Main.changeHash(Main.pageHashes.home);\n });\n Main.addClickEventToElement(document.getElementById(\"infoOptP\"), function () {\n Main.changeHash(Main.pageHashes.info);\n });\n Main.addClickEventToElement(document.getElementById(\"quizOptP\"), function () {\n Main.changeHash(Main.pageHashes.quiz);\n });\n Main.addClickEventToElement(document.getElementById(\"econ\"), function () {\n Main.sendAnalyticsEvent(\"UX\", \"click\", \"Economy\");\n _loadPlatformSection(_platformSections.economy);\n });\n Main.addClickEventToElement(document.getElementById(\"immigration\"), function () {\n Main.sendAnalyticsEvent(\"UX\", \"click\", \"Immigration\");\n _loadPlatformSection(_platformSections.immigration);\n });\n Main.addClickEventToElement(document.getElementById(\"domSoc\"), function () {\n Main.sendAnalyticsEvent(\"UX\", \"click\", \"Domestic Policy\");\n _loadPlatformSection(_platformSections.domestic);\n });\n Main.addClickEventToElement(document.getElementById(\"foreignPol\"), function () {\n Main.sendAnalyticsEvent(\"UX\", \"click\", \"Foreign Policy\");\n _loadPlatformSection(_platformSections.foreign);\n });\n\n // show page\n Main.sendPageview(Main.analyticPageTitles.platform);\n Main.showPage(Main.pageContainers.partyPlatformContainer);\n }", "function displayPage( response, context ) {\n var html = messageCompiled.render( context );\n response.html( html );\n}", "function renderDestinationScreen(){\r\n getTemplateAjax('./templates/destination.handlebars', function(template) {\r\n destinationData =\r\n {destinationTitle: \"Destination Screen Worked\", destinationMessage: \"Now get to work.\"}\r\n jqueryNoConflict('#destinationScreen').html(template(destinationData));\r\n })\r\n }", "function initPage() {\n $.get('/api/headlines?saved=true').done((data) => {\n articleContainer.empty();\n\n if (data && data.length > 0) {\n renderArticles(data);\n\n // Activate tooltips for the action buttons.\n $('[data-toggle=\"tooltip\"]').tooltip();\n } else {\n renderEmpty();\n }\n });\n }", "connectedCallback() {\n render(this.template(), this.shadowRoot);\n }", "function renderCvtPage(data) { \n // get cvt data from API call...\n $.getJSON(\"api/cvt\", function(data) {\n // generate the proper HTML...\n generateAllCvtHTML(data);\n\n var page = $('.cvt-report');\n page.addClass('visible'); \n });\n }", "function _setSubscriptions() {\n /**\n * Watch for changes in the area index\n * and reset the area form view model.\n */\n AreaActionObservable.subscribe((areaId) => {\n _initializeForm(areaId);\n });\n\n }", "function init() {\n if ($('.scheduled-page').length > 0) {\n setPageUrl();\n bindEvents();\n renderSwitcher();\n renderActions();\n switchPage(scheduled.currentView);\n }\n }", "function catalogueStats() {\n jQuery.ajax({\n url: \"/backend/modules/pricing/catalogues/catalogue_stats\",\n type: \"GET\",\n success: function (data) {\n $('#catalogue_stats').html(data);\n }\n });\n }", "async _handleSubscribeButtonClick() {\n if (this.state.userHasSubscribedToChair) {\n const unsubscribeRequest = await chairService.unsubscribeFromChair(\n this.props.chairId\n );\n\n if (unsubscribeRequest.status === 200) {\n this.setState({\n userHasSubscribedToChair: false,\n unsubscribeModalOpen: true\n });\n this.props.removeSubscription({ pageId: this.props.chairId });\n } else {\n }\n } else {\n const subscriptionRequest = await chairService.subscribeToChair(\n this.props.chairId\n );\n\n if (subscriptionRequest.status === 200) {\n this.setState({\n userHasSubscribedToChair: true,\n subscribeModalOpen: true\n });\n this.props.addSubscription({ pageId: this.props.chairId });\n } else {\n }\n }\n }", "render () {\n const { refetch, username } = this.state;\n return (\n <div>\n <Subscription\n subscription={subscribeToNewMessages}\n >\n {\n ({data, error, loading}) => {\n if (error || (data && data.message === null)) {\n console.error(error || `Unexpected response: ${data}`);\n return \"Error\";\n }\n if (refetch) {\n refetch();\n }\n return null;\n }\n }\n </Subscription>\n <ChatWrapper\n refetch={refetch}\n setRefetch={this.setRefetch}\n userId={this.props.userId}\n username={username}\n />\n <footer className=\"App-footer\">\n <div className=\"hasura-logo\">\n <img src=\"https://graphql-engine-cdn.hasura.io/img/powered_by_hasura_black.svg\" onClick={() => window.open(\"https://hasura.io\")} alt=\"Powered by Hasura\"/>\n &nbsp; | &nbsp;\n <a href=\"/console\" target=\"_blank\" rel=\"noopener noreferrer\">\n Backend\n </a>\n &nbsp; | &nbsp;\n <a href=\"https://github.com/hasura/graphql-engine/tree/master/community/sample-apps/realtime-chat\" target=\"_blank\" rel=\"noopener noreferrer\">\n Source\n </a>\n &nbsp; | &nbsp;\n <a href=\"https://blog.hasura.io/building-a-realtime-chat-app-with-graphql-subscriptions-d68cd33e73f\" target=\"_blank\" rel=\"noopener noreferrer\">\n Blogpost\n </a>\n </div>\n <div className=\"footer-small-text\"><span>(The database resets every 24 hours)</span></div>\n </footer>\n </div>\n );\n }", "render(){\n\t\treturn(\n\t\t\t<div>\n\t\t\t\t<h2> Our Current Clients Page </h2>\n\t\t\t\t<ClientLogos/>\n\t\t\t\t<ClientDescription/> \n\t\t\t</div>\n\t\t)\n\t}", "function subscribe() {\n $rootScope.$on('loaded', function() {\n self.loading = false;\n });\n }", "function notifySubscribers() {\n var eventPayload = {\n routeObj: getCurrentRoute(), // { route:, data: }\n fragment: getURLFragment()\n };\n\n _subject.onNext(eventPayload);\n }", "function render(response){\n checkTodos(response)\n console.log(todosPending)\n console.log(todosCompleted)\n var pending = template(todosPending)\n // var pending = template(response)\n $(\"#todo-pendientes\").html(pending)\n var completed = template(todosCompleted)\n $(\"#todo-completados\").html(completed)\n bindEvents()\n}", "static renderGlobalView() {\n GestionPages.gestionPages(\"dashboard\");\n let contenu = `\n <h5><em>Production Dashboard</em></h5>\n <div id=\"dash\">\n <div id=\"stateorders\">\n <p>State of orders</p>\n </div>\n\n <div id=\"statemachines\">\n <p>State of Machines</p>\n </div>\n\n <div id=\"statistics\">\n <p>Statistics</p>\n </div>\n </div>`;\n document.querySelector(\"#dashboard\").innerHTML = contenu;\n\n //Display page \"state of orders\"\n $(\"#stateorders\").click(event => {\n event.preventDefault();\n GestionPages.gestionPages(\"dashboard\");\n Dashboard.renderStateOrders();\n });\n\n //Display page \"state of machines\"\n $(\"#statemachines\").click(event => {\n event.preventDefault();\n GestionPages.gestionPages(\"dashboard\");\n Dashboard.renderStateMachines();\n });\n\n //Display page \"statistics\"\n $(\"#statistics\").click(event => {\n event.preventDefault();\n GestionPages.gestionPages(\"dashboard\");\n Dashboard.renderStatistics();\n });\n }", "function initPage() {\n $.get('/api/headlines?saved=false').done((data) => {\n articleContainer.empty();\n if (data && data.length > 0) {\n renderArticles(data);\n\n // Activate tooltips for the action buttons.\n $('[data-toggle=\"tooltip\"]').tooltip();\n } else {\n renderEmpty();\n }\n });\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting Vendor</Loader>;\n }", "function render(){ \n console.log('`render function` ran');\n const createdHtml = generateHtml(STORE); \n $('main').html(createdHtml);\n}", "render() {\n\t\treturn this.renderRegisterPage();\n\t}", "handleSubscribe() {\n // Callback invoked whenever a new event message is received\n const messageCallback = (response) => {\n console.log('Segment Membership PE fired: ', JSON.stringify(response));\n // Response contains the payload of the new message received\n this.notifier = JSON.stringify(response);\n this.refresh = true;\n // refresh LWC\n if(response.data.payload.Category__c == 'Segmentation') {\n this.getData();\n }\n \n\n\n };\n\n // Invoke subscribe method of empApi. Pass reference to messageCallback\n subscribe(this.channelName, -1, messageCallback).then(response => {\n // Response contains the subscription information on subscribe call\n console.log('Subscription request sent to: ', JSON.stringify(response.channel));\n this.subscription = response;\n this.toggleSubscribeButton(true);\n });\n }", "function _render() {\n DOM.$p\n .empty()\n .text(`People: ${people.length}`)\n .appendTo(DOM.$stats);\n }", "function eventsInitialRender() {\n //remove selection if it's there\n localStorage.setItem(\"mainContentCalendarSelectedCrn\", \"\");\n\n //manageClasses page\n if (document.getElementById(\"mc_manageClasses_input_crn\")) {\n manageClasses_eventsInitialRender();\n }\n\n //assign professors page\n\tif (document.getElementById(\"mc_assingProfessors_section\")) {\n assignProfessors_eventsInitialRender();\n }\n \n //scheduleRegistration\n if (document.getElementById(\"mc_scheduleRegistration_classTable\")) {\n scheduleRegistration_eventsInitialRender();\n }\n\n //TODO: handle other pages\n}", "updatePage() {\r\n\t\tvar htmlString = '';\r\n\r\n\t\tfor ( var key in this.data ) {\r\n\t\t\thtmlString = htmlString + '<li>' + this.data[key] + '</li>';\r\n\t\t}\r\n\r\n\t\tthis._dataEl.innerHTML = htmlString;\r\n\t}", "function pageInitalize(){\n\n articleContainer.empty();//Empties article container.//\n $.get(\"/api/headlines?saved=false\").then(function(data){//Runs AJAX request for unsaved\n if (data && data.length) {//Renders found headlines to the page.//\n renderArticles(data);\n }else{\n renderEmpty();//Renders no articles message.//\n }\n });\n }", "constructor() {\n super();\n\n this.state = {\n subscription: {\n budgets: Meteor.subscribe(\"userBudgets\")\n }\n };\n }", "function render() {\n\n const renderedString = createRenderString(store);\n\n // insert html into DOM\n $('main').html(renderedString);\n}", "function doSomethingAfterRendering(){\n displayLoading() // 로딩화면 보여주기\n fetchServer(); // 서버에서 데이터 가져오기\n }", "function render(){\n var state = store.getState();\n\n console.log(state);\n\n\n root.innerHTML = `\n ${Navigation(state[state.active])}\n ${Header(state)}\n ${Content(state)}\n ${Footer(state)}\n `;\n greeter.render(root);\n \n document\n .querySelector('h1')\n .addEventListener('click', (event) => {\n var animation = tween({\n 'from': {\n 'color': '#fff100',\n 'fontSize': '100%'\n },\n 'to': {\n 'color': '#fff000',\n 'fontSize': '200%'\n },\n 'duration': 750\n });\n \n var title = styler(event.target);\n \n animation.start((value) => title.set(value));\n });\n \n router.updatePageLinks();\n}", "function render(html) {\n response.renderHTML(html);\n console.log('rendering done!');\n if (\n loggedInUser &&\n loggedInUser.id &&\n !reqParams.after &&\n !reqParams.before\n )\n analytics.addVisit(loggedInUser, request.url);\n }", "function render() {\n if (store.quizStarted === false) {\n $('main').html(generateWelcome());\n return;\n }\n else if (store.questionNumber < store.questions.length) {\n let html = '';\n html = generateQuestion();\n html += generateQuestionNumberAndScore();\n $('main').html(html);\n }\n else {\n $('main').html(generateResultsScreen());\n }\n}", "function render() {\n\n isRendered = true;\n\n renderSource();\n\n }", "function refetchEvents() { // can be called as an API method\n\t\t\tfetchAndRenderEvents();\n\t\t}", "connectedCallback () {\n this.template.render(this.attrs, this)\n .then(template => {\n this.shadowRoot.appendChild(template);\n return this._subTemplates();\n })\n .then(() => {\n if(typeof this.afterConnected === 'function')\n this.afterConnected();\n });\n }", "function refreshViewers() {\n\t\tjQuery.ajax( {\n\t\t\turl: options.restAPIEndpoint + page,\n\t\t\tmethod: 'GET',\n\t\t\tbeforeSend: function( xhr ) {\n\t\t\t\txhr.setRequestHeader( 'X-WP-Nonce', options.restAPINonce );\n\t\t\t}\n\t\t} ).done( function( response ) {\n\t\t\tcurrentlyViewing = response;\n\t\t\tmaybeDisplay();\n\t\t} );\n\t}", "componentDidMount() {\n this.getSubscriptions()\n }", "function render() {\r\n let content = '';\r\n if (STORE.view === 'home') {\r\n $('main').html(welcomePage());\r\n }\r\n else if (STORE.view === 'question') {\r\n content = questionAsked();\r\n content += generateAnswers();\r\n content += questionAndScoreStanding();\r\n $('main').html(`<form>${content}</form>`);\r\n } else if (STORE.view === 'feedback') {\r\n answerFeedback();\r\n } else if (STORE.view === 'score') {\r\n finalScore();\r\n }\r\n}", "show(req, res, next) {\n var subscriptionId = req.params.id;\n\n Subscription.findById(subscriptionId, function(err, subscription) {\n if (err) return next(err);\n if (!subscription) return perf.ProcessResponse(res).send(401);\n perf.ProcessResponse(res).send(subscription);\n });\n }", "render() {\r\n document.body.insertBefore(this.element, document.querySelector('script'));\r\n\r\n this.append(this.PageContent.element, [this.NewsList, this.Footer]);\r\n this.append(this.Sidebar.element, [this.SidebarTitle, this.SourcesList]);\r\n this.append(this.element, [this.Spinner, this.PageContent, this.Sidebar, this.ToggleBtn]);\r\n }", "function printLoggedInPage(userKey, userName, newsLetter) {\n main.innerHTML = \"\";\n const loggedInPageContainer = document.createElement('section');\n main.appendChild(loggedInPageContainer);\n loggedInPageContainer.id = \"loggedInPageContainer\";\n loggedInPageContainer.setAttribute(\"class\", \"loggedin-page-container\");\n\n let newsLetterText;\n let subscribeText;\n\n if (newsLetter == true) {\n newsLetterText = \"Du prenumererar på vårat nyhetsbrev!\";\n subscribeText = `<a href=\"#\" id=\"subscribeBtn\">Avregistrera här</a>`;\n } else {\n newsLetterText = \"Du prenumererar inte på vårat nyhetsbrev!\";\n subscribeText = `<a href=\"#\" id=\"subscribeBtn\">Registrera dig här!</a>`;\n };\n\n printLoggedInText(userName, newsLetterText, subscribeText);\n\n document.getElementById('subscribeBtn').addEventListener('click', () => {\n subscription(userKey, newsLetter);\n });\n}", "function createNewSubscription() {\n\t// grab the topic from the page form\n\tvar topic = document.getElementById(\"topic\").value.trim();\n\n\t// perform some basic sanity checking.\n\tif (topic.length === 0) {\n\t\treturn;\n\t}\n\n\tif (topic in subscriptions) {\n\t\tconsole.log(\"already have a sub with this topic\");\n\t\treturn;\n\t}\n\n\t// beyond the above, we rely of the sub call to fail if\n\t// the topic string is invalid.\n\n\tconsole.log(\"create new subscription: \" + topic);\n\n\t// issue the subscribe request to the server. Only update\n\t// the page and our data structure if the subscribe is\n\t// successful (do work in success callback).\n\tclientObj.subscribe(topic, {\n\t\tonFailure : function(responseObject) {\n\t\t\tconsole.log(\"Failed to subscribe: \" + responseObject.errorCode);\n\t\t\t// don't update the page\n\t\t},\n\n\t\tonSuccess : function(responseObject) {\n\t\t\t// grab the div on the page that houses the subs display items\n\t\t\tvar subsDiv = document.getElementById(\"subscriptions\");\n\t\t\t// ensure that it's not hidden (will be when there are no subs)\n\t\t\tsubsDiv.hidden = false;\n\n\t\t\t// create a new div to house the messages\n\t\t\tvar div = document.createElement(\"DIV\");\n\t\t\tdiv.id = \"subsection_\" + topic;\n\n\t\t\t// create the delete button\n\t\t\tvar nameRef = \"button/\" + topic;\n\t\t\tvar button = document.createElement(\"BUTTON\");\n\t\t\tbutton.id = nameRef;\n\t\t\tbutton.innerHTML = \"delete subscription\";\n\n\t\t\tbutton.onclick = function() {\t\t\t\t\n\t\t\t\tconsole.log(\"delete subscription: \" + topic);\n\n\t\t\t\t// do unsub\n\t\t\t\tclientObj.unsubscribe(topic);\n\t\t\t\t// remove row...\n\t\t\t\tsubsDiv.removeChild(subscriptions[topic].div);\n\t\t\t\tsubsDiv.removeChild(subscriptions[topic].spacing);\n\t\t\t\t// remove from data structure\n\t\t\t\tdelete subscriptions[topic];\n\t\t\t\tsubCount--;\n\n\t\t\t\tif (subCount === 0) {\n\t\t\t\t\tsubsDiv.hidden = true;\n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\t// create a new table for the div\n\t\t\tvar table = document.createElement(\"TABLE\");\n\n\t\t\t// create header\n\t\t\tvar header = table.createTHead();\n\t\t\tvar hRow = header.insertRow(0);\n\t\t\tvar tCell = hRow.insertCell(0);\n\t\t\tvar bCell = hRow.insertCell(1);\n\n\t\t\ttCell.innerHTML = \"Topic: \" + topic;\n\t\t\tbCell.appendChild(button);\n\t\t\t\n\t\t\tvar textArea = document.createElement(\"TEXTAREA\");\n\t\t\ttextArea.readOnly = true;\n\t\t\ttextArea.cols = 150;\n\t\t\ttextArea.rows = 6;\n\n\t\t\tvar spacing = document.createElement(\"BR\");\n\n\t\t\tdiv.appendChild(table);\n\t\t\tdiv.appendChild(textArea);\t\t\t\n\n\t\t\t// add the div to the page\n\t\t\tsubsDiv.appendChild(div);\n\t\t\tsubsDiv.appendChild(spacing);\n\n\t\t\t// the object we will store in our subs map\n\t\t\tvar subObj = {\n\t\t\t\tdiv : div, // ref to the div (for easy deleting later)\n\t\t\t\ttext : textArea, // ref to the text area (to add msgs to)\n\t\t\t\tspacing : spacing, // ref to the <br> tag (for easy deleting)\n\t\t\t\tmsgCount : 0 // count of the messages currently displayed.\n\t\t\t};\t\t\t\n\n\t\t\t// store the obj and update our sub count\n\t\t\tsubscriptions[topic] = subObj;\t\n\t\t\tsubCount++;\n\t\t}\n\t});\n}", "function render() {\n\n\t\t\tisRendered = true;\n\n\t\t\trenderSource();\n\n\t\t}", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "function render() {\n if (STORE.view === 'start') {\n renderStartQuiz();\n $('.intro').show();\n $('.quiz').hide();\n $('.result').hide();\n $('.quizStatus').hide();\n } else if (STORE.view === 'quiz') {\n renderQuestionText();\n renderQuizStatusBar();\n $('.intro').hide();\n $('.quiz').show();\n $('.result').hide();\n $('.quizStatus').show();\n } else if (STORE.view === 'questionResult') {\n renderQuestionResult();\n renderQuizStatusBar();\n $('.intro').hide();\n $('.quiz').hide();\n $('.result').show();\n $('.quizStatus').show();\n } else if (STORE.view === 'finalResult') {\n renderFinalResult();\n $('.intro').hide();\n $('.quiz').hide();\n $('.result').show();\n $('.quizStatus').hide();\n }\n }" ]
[ "0.6166739", "0.6032917", "0.5972155", "0.5954931", "0.5884055", "0.583181", "0.57925886", "0.5769471", "0.5769471", "0.5769471", "0.56891847", "0.5639037", "0.5632166", "0.56310517", "0.56310517", "0.5630244", "0.5607981", "0.55974364", "0.55900705", "0.5580156", "0.5557037", "0.5556741", "0.5542636", "0.55395895", "0.5519016", "0.5514103", "0.5488994", "0.5470407", "0.54658186", "0.54619527", "0.54437643", "0.5435217", "0.5414592", "0.5413938", "0.540814", "0.5406047", "0.5401812", "0.5390952", "0.53906417", "0.5381136", "0.53809816", "0.53771967", "0.5364328", "0.535406", "0.5345423", "0.5343872", "0.5343788", "0.53410506", "0.5335789", "0.5327803", "0.53270143", "0.53200436", "0.5318153", "0.5310741", "0.53097934", "0.5307322", "0.53053385", "0.5302498", "0.53021866", "0.52973855", "0.5296592", "0.5290604", "0.5286029", "0.527926", "0.52711666", "0.52659124", "0.5258934", "0.5257479", "0.5255457", "0.525187", "0.5251023", "0.5250266", "0.5248", "0.5245884", "0.5245754", "0.5240281", "0.52388865", "0.5236496", "0.5235959", "0.5234187", "0.5230834", "0.5227272", "0.52261966", "0.5224764", "0.52196497", "0.5219318", "0.52165", "0.5213986", "0.5209477", "0.52078533", "0.5207303", "0.5204475", "0.5202507", "0.518981", "0.51891965", "0.518386", "0.51788956", "0.51788956", "0.51788956", "0.51788956", "0.5170913" ]
0.0
-1
Returns vanilla data with 3 circular normals
function threenorm(n) { var random = d3.randomNormal(0, 0.2), sqrt3 = Math.sqrt(3), points0 = d3.range(50).map(function() { return {x:random() + sqrt3,y: random() + 1, cluster:0} }), points1 = d3.range(50).map(function() { return {x:random() - sqrt3,y: random() + 1, cluster:0}; }), points2 = d3.range(50).map(function() { return {x:random(),y: random() - 1, cluster:0}; }), points = d3.merge([points0, points1, points2]); return points; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get DepthNormals() {}", "function generateTorso() {\n const indexArray = []; // this will be used to calculate the normal\n\n const r = radiusTop - radiusBottom;\n const slope = r * r / height * Math.sign(r); // generate positions, normals and uvs\n\n for (let y = 0; y <= heightSegments; y++) {\n const indexRow = [];\n const v = y / heightSegments; // calculate the radius of the current row\n\n const radius = v * r + radiusBottom;\n\n for (let x = 0; x <= radialSegments; ++x) {\n const u = x / radialSegments;\n const theta = u * arc;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta); // vertex\n\n positions[3 * index] = radius * sinTheta;\n positions[3 * index + 1] = v * height - halfHeight;\n positions[3 * index + 2] = radius * cosTheta; // normal\n\n Vec3.normalize(temp1$1, Vec3.set(temp2$1, sinTheta, -slope, cosTheta));\n normals[3 * index] = temp1$1.x;\n normals[3 * index + 1] = temp1$1.y;\n normals[3 * index + 2] = temp1$1.z; // uv\n\n uvs[2 * index] = (1 - u) * 2 % 1;\n uvs[2 * index + 1] = v; // save index of vertex in respective row\n\n indexRow.push(index); // increase index\n\n ++index;\n } // now save positions of the row in our index array\n\n\n indexArray.push(indexRow);\n } // generate indices\n\n\n for (let y = 0; y < heightSegments; ++y) {\n for (let x = 0; x < radialSegments; ++x) {\n // we use the index array to access the correct indices\n const i1 = indexArray[y][x];\n const i2 = indexArray[y + 1][x];\n const i3 = indexArray[y + 1][x + 1];\n const i4 = indexArray[y][x + 1]; // face one\n\n indices[indexOffset] = i1;\n ++indexOffset;\n indices[indexOffset] = i4;\n ++indexOffset;\n indices[indexOffset] = i2;\n ++indexOffset; // face two\n\n indices[indexOffset] = i4;\n ++indexOffset;\n indices[indexOffset] = i3;\n ++indexOffset;\n indices[indexOffset] = i2;\n ++indexOffset;\n }\n }\n }", "calculateNormals() {\r\n // MP2: Implement this function!\r\n \r\n }", "function setViewNormals() {\n var len = points.length;\n for (var i = 0; i < len; i += 3) {\n // The first 3 values pushed into the array are (x, y, z) of the starting point.\n shown.push(points[i]);\n shown.push(points[i + 1]);\n shown.push(points[i + 2]);\n // These 3 values are the ending point of the normal.\n shown.push(n[i] / 4 + points[i]);\n shown.push(n[i + 1] / 4 + points[i + 1]);\n shown.push(n[i + 2] / 4 + points[i + 2]);\n }\n}", "get importNormals() {}", "function calc_normal(a, b, c) {\n var t1 = subtract(b, a);\n var t2 = subtract(c, b);\n var normal = vec4(cross(t1, t2), 0);\n\n normalsArray.push(normal); \n normalsArray.push(normal); \n normalsArray.push(normal); \n}", "function generateTorso() {\n // this will be used to calculate the normal\n var slope = (radiusTop - radiusBottom) / torsoHeight; // generate positions, normals and uvs\n\n for (var y = 0; y <= torSegments; y++) {\n var indexRow = [];\n var lat = y / torSegments;\n var radius = lat * (radiusTop - radiusBottom) + radiusBottom;\n\n for (var x = 0; x <= sides; ++x) {\n var u = x / sides;\n var v = lat * torProp + bottomProp;\n var theta = u * arc - arc / 4;\n var sinTheta = Math.sin(theta);\n var cosTheta = Math.cos(theta); // vertex\n\n positions.push(radius * sinTheta);\n positions.push(lat * torsoHeight + torOffset);\n positions.push(radius * cosTheta); // normal\n\n _vec[\"default\"].normalize(temp1, _vec[\"default\"].set(temp2, sinTheta, -slope, cosTheta));\n\n normals.push(temp1.x);\n normals.push(temp1.y);\n normals.push(temp1.z); // uv\n\n uvs.push(u, v); // save index of vertex in respective row\n\n indexRow.push(index); // increase index\n\n ++index;\n } // now save positions of the row in our index array\n\n\n indexArray.push(indexRow);\n } // generate indices\n\n\n for (var _y = 0; _y < torSegments; ++_y) {\n for (var _x = 0; _x < sides; ++_x) {\n // we use the index array to access the correct indices\n var i1 = indexArray[_y][_x];\n var i2 = indexArray[_y + 1][_x];\n var i3 = indexArray[_y + 1][_x + 1];\n var i4 = indexArray[_y][_x + 1]; // face one\n\n indices.push(i1);\n indices.push(i4);\n indices.push(i2); // face two\n\n indices.push(i4);\n indices.push(i3);\n indices.push(i2);\n }\n }\n }", "generateNormals(){\n //per vertex normals\n this.numNormals = this.numVertices;\n this.nBuffer = new Array(this.numNormals*3);\n \n for(var i=0;i<this.nBuffer.length;i++)\n {\n this.nBuffer[i]=0;\n }\n \n for(var i=0;i<this.numFaces;i++)\n {\n // Get vertex coodinates\n var v1 = this.fBuffer[3*i]; \n var v1Vec = vec3.fromValues(this.vBuffer[3*v1], this.vBuffer[3*v1+1], this.vBuffer[3*v1+2]);\n var v2 = this.fBuffer[3*i+1]; \n var v2Vec = vec3.fromValues(this.vBuffer[3*v2], this.vBuffer[3*v2+1], this.vBuffer[3*v2+2]);\n var v3 = this.fBuffer[3*i+2]; \n var v3Vec = vec3.fromValues(this.vBuffer[3*v3], this.vBuffer[3*v3+1], this.vBuffer[3*v3+2]);\n \n // Create edge vectors\n var e1=vec3.create();\n vec3.subtract(e1,v2Vec,v1Vec);\n var e2=vec3.create();\n vec3.subtract(e2,v3Vec,v1Vec);\n \n // Compute normal\n var n = vec3.fromValues(0,0,0);\n vec3.cross(n,e1,e2);\n// console.log(v1+1,v2+1,v3+1);\n// console.log(n);\n \n // Accumulate\n for(var j=0;j<3;j++){\n this.nBuffer[3*v1+j]+=n[j];\n this.nBuffer[3*v2+j]+=n[j];\n this.nBuffer[3*v3+j]+=n[j];\n } \n \n }\n for(var i=0;i<this.numNormals;i++)\n {\n var n = vec3.fromValues(this.nBuffer[3*i],\n this.nBuffer[3*i+1],\n this.nBuffer[3*i+2]);\n vec3.normalize(n,n);\n this.nBuffer[3*i] = n[0];\n this.nBuffer[3*i+1]= n[1];\n this.nBuffer[3*i+2]= n[2]; \n // a debugging attempt where all normals are just 0,0,1\n// this.nBuffer[3*i] = 0 ;\n// this.nBuffer[3*i+1]= 0 ;\n// this.nBuffer[3*i+2]= 1 ; \n// another debugging version with inverted normals\n// this.nBuffer[3*i] = -1*n[0];\n// this.nBuffer[3*i+1]=-1*n[1];\n// this.nBuffer[3*i+2]=-1*n[2]; \n \n }\n// this.printBuffers();\n}", "setNormal(){\r\n for(var i = 0; i < this.fBuffer.length; i += 3){\r\n var faceVertices = [];\r\n //j = 0,1,2\r\n for(var j = 0; j < 3; j++){\r\n var temp = [];\r\n //i+j = 0,1,2...3,4,5...6,7,8\r\n temp[0] = this.vBuffer[this.fBuffer[i + j] * 3];\r\n temp[1] = this.vBuffer[this.fBuffer[i + j] * 3 + 1];\r\n temp[2] = this.vBuffer[this.fBuffer[i + j] * 3 + 2]; \r\n faceVertices[j] = vec3.fromValues.apply(this, temp);\r\n }\r\n //Find per face normal \r\n var v1_v0 = vec3.create();\r\n var v2_v0 = vec3.create();\r\n vec3.sub(v1_v0, faceVertices[1], faceVertices[0]);\r\n vec3.sub(v2_v0, faceVertices[2], faceVertices[0])\r\n var normalCP = vec3.create();\r\n vec3.cross(normalCP, v1_v0, v2_v0);\r\n \r\n for(var k = 0; k < 3; k++){\r\n this.nBuffer[this.fBuffer[i + j] * 3] += normalCP[0];\r\n this.nBuffer[this.fBuffer[i + j] * 3 + 1] += normalCP[1];\r\n this.nBuffer[this.fBuffer[i + j] * 3 + 2] += normalCP[2];\r\n }\r\n \r\n }\r\n \r\n //Finally, normals needs to be unitized \r\n for(var i = 0; i < this.nBuffer.length; i += 3){\r\n var uni = vec3.fromValues(this.nBuffer[i], this.nBuffer[i + 1], this.nBuffer[i + 2]);\r\n \r\n vec3.normalize(uni, uni);\r\n \r\n this.nBuffer[i] = uni[0];\r\n this.nBuffer[i + 1] = uni[1];\r\n this.nBuffer[i + 2] = uni[2];\r\n }\r\n \r\n}", "function computeNormals() {\n var dx = [1, 1, 0, -1, -1, 0], dy = [0, 1, 1, 0, -1, -1];\n var e1, e2;\n var i, j, k = 0, t;\n for ( i = 0; i < meshResolution; ++i )\n for ( j = 0; j < meshResolution; ++j ) {\n var p0 = getPosition(i, j), norms = [];\n for ( t = 0; t < 6; ++t ) {\n var i1 = i + dy[t], j1 = j + dx[t];\n var i2 = i + dy[(t + 1) % 6], j2 = j + dx[(t + 1) % 6];\n if ( i1 >= 0 && i1 < meshResolution && j1 >= 0 && j1 < meshResolution &&\n i2 >= 0 && i2 < meshResolution && j2 >= 0 && j2 < meshResolution ) {\n e1 = vec3.subtract(getPosition(i1, j1), p0);\n e2 = vec3.subtract(getPosition(i2, j2), p0);\n norms.push(vec3.normalize(vec3.cross(e1, e2)));\n }\n }\n e1 = vec3.create();\n for ( t = 0; t < norms.length; ++t ) vec3.add(e1, norms[t]);\n vec3.normalize(e1);\n vertexNormal[3*k] = e1[0];\n vertexNormal[3*k + 1] = e1[1];\n vertexNormal[3*k + 2] = e1[2];\n ++k;\n }\n}", "function gNormals(shape) {\n let normals = [];\n for (let i = 0; i < shape.length; i++) {\n normals.push( vec4( shape[i][0],\n shape[i][1],\n shape[i][2],\n 0.0));\n }\n return normals;\n}", "function posnormtriv( pos, norm, colors, o1, o2, o3, renderCallback ) {\n\n\t\tvar c = scope.count * 3;\n\n\t\t// positions\n\n\t\tscope.positionArray[ c + 0 ] = pos[ o1 ];\n\t\tscope.positionArray[ c + 1 ] = pos[ o1 + 1 ];\n\t\tscope.positionArray[ c + 2 ] = pos[ o1 + 2 ];\n\n\t\tscope.positionArray[ c + 3 ] = pos[ o2 ];\n\t\tscope.positionArray[ c + 4 ] = pos[ o2 + 1 ];\n\t\tscope.positionArray[ c + 5 ] = pos[ o2 + 2 ];\n\n\t\tscope.positionArray[ c + 6 ] = pos[ o3 ];\n\t\tscope.positionArray[ c + 7 ] = pos[ o3 + 1 ];\n\t\tscope.positionArray[ c + 8 ] = pos[ o3 + 2 ];\n\n\t\t// normals\n\n\t\tif ( scope.material.flatShading === true ) {\n\n\t\t\tvar nx = ( norm[ o1 + 0 ] + norm[ o2 + 0 ] + norm[ o3 + 0 ] ) / 3;\n\t\t\tvar ny = ( norm[ o1 + 1 ] + norm[ o2 + 1 ] + norm[ o3 + 1 ] ) / 3;\n\t\t\tvar nz = ( norm[ o1 + 2 ] + norm[ o2 + 2 ] + norm[ o3 + 2 ] ) / 3;\n\n\t\t\tscope.normalArray[ c + 0 ] = nx;\n\t\t\tscope.normalArray[ c + 1 ] = ny;\n\t\t\tscope.normalArray[ c + 2 ] = nz;\n\n\t\t\tscope.normalArray[ c + 3 ] = nx;\n\t\t\tscope.normalArray[ c + 4 ] = ny;\n\t\t\tscope.normalArray[ c + 5 ] = nz;\n\n\t\t\tscope.normalArray[ c + 6 ] = nx;\n\t\t\tscope.normalArray[ c + 7 ] = ny;\n\t\t\tscope.normalArray[ c + 8 ] = nz;\n\n\t\t} else {\n\n\t\t\tscope.normalArray[ c + 0 ] = norm[ o1 + 0 ];\n\t\t\tscope.normalArray[ c + 1 ] = norm[ o1 + 1 ];\n\t\t\tscope.normalArray[ c + 2 ] = norm[ o1 + 2 ];\n\n\t\t\tscope.normalArray[ c + 3 ] = norm[ o2 + 0 ];\n\t\t\tscope.normalArray[ c + 4 ] = norm[ o2 + 1 ];\n\t\t\tscope.normalArray[ c + 5 ] = norm[ o2 + 2 ];\n\n\t\t\tscope.normalArray[ c + 6 ] = norm[ o3 + 0 ];\n\t\t\tscope.normalArray[ c + 7 ] = norm[ o3 + 1 ];\n\t\t\tscope.normalArray[ c + 8 ] = norm[ o3 + 2 ];\n\n\t\t}\n\n\t\t// uvs\n\n\t\tif ( scope.enableUvs ) {\n\n\t\t\tvar d = scope.count * 2;\n\n\t\t\tscope.uvArray[ d + 0 ] = pos[ o1 + 0 ];\n\t\t\tscope.uvArray[ d + 1 ] = pos[ o1 + 2 ];\n\n\t\t\tscope.uvArray[ d + 2 ] = pos[ o2 + 0 ];\n\t\t\tscope.uvArray[ d + 3 ] = pos[ o2 + 2 ];\n\n\t\t\tscope.uvArray[ d + 4 ] = pos[ o3 + 0 ];\n\t\t\tscope.uvArray[ d + 5 ] = pos[ o3 + 2 ];\n\n\t\t}\n\n\t\t// colors\n\n\t\tif ( scope.enableColors ) {\n\n\t\t\tscope.colorArray[ c + 0 ] = colors[ o1 + 0 ];\n\t\t\tscope.colorArray[ c + 1 ] = colors[ o1 + 1 ];\n\t\t\tscope.colorArray[ c + 2 ] = colors[ o1 + 2 ];\n\n\t\t\tscope.colorArray[ c + 3 ] = colors[ o2 + 0 ];\n\t\t\tscope.colorArray[ c + 4 ] = colors[ o2 + 1 ];\n\t\t\tscope.colorArray[ c + 5 ] = colors[ o2 + 2 ];\n\n\t\t\tscope.colorArray[ c + 6 ] = colors[ o3 + 0 ];\n\t\t\tscope.colorArray[ c + 7 ] = colors[ o3 + 1 ];\n\t\t\tscope.colorArray[ c + 8 ] = colors[ o3 + 2 ];\n\n\t\t}\n\n\t\tscope.count += 3;\n\n\t\tif ( scope.count >= scope.maxCount - 3 ) {\n\n\t\t\tscope.hasPositions = true;\n\t\t\tscope.hasNormals = true;\n\n\t\t\tif ( scope.enableUvs ) {\n\n\t\t\t\tscope.hasUvs = true;\n\n\t\t\t}\n\n\t\t\tif ( scope.enableColors ) {\n\n\t\t\t\tscope.hasColors = true;\n\n\t\t\t}\n\n\t\t\trenderCallback( scope );\n\n\t\t}\n\n\t}", "function generateTorso() {\n // this will be used to calculate the normal\n const slope = (radiusTop - radiusBottom) / torsoHeight; // generate positions, normals and uvs\n\n for (let y = 0; y <= torSegments; y++) {\n const indexRow = [];\n const lat = y / torSegments;\n const radius = lat * (radiusTop - radiusBottom) + radiusBottom;\n\n for (let x = 0; x <= sides; ++x) {\n const u = x / sides;\n const v = lat * torProp + bottomProp;\n const theta = u * arc - arc / 4;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta); // vertex\n\n positions.push(radius * sinTheta);\n positions.push(lat * torsoHeight + torOffset);\n positions.push(radius * cosTheta); // normal\n\n Vec3.normalize(temp1$3, Vec3.set(temp2$3, sinTheta, -slope, cosTheta));\n normals.push(temp1$3.x);\n normals.push(temp1$3.y);\n normals.push(temp1$3.z); // uv\n\n uvs.push(u, v); // save index of vertex in respective row\n\n indexRow.push(index); // increase index\n\n ++index;\n } // now save positions of the row in our index array\n\n\n indexArray.push(indexRow);\n } // generate indices\n\n\n for (let y = 0; y < torSegments; ++y) {\n for (let x = 0; x < sides; ++x) {\n // we use the index array to access the correct indices\n const i1 = indexArray[y][x];\n const i2 = indexArray[y + 1][x];\n const i3 = indexArray[y + 1][x + 1];\n const i4 = indexArray[y][x + 1]; // face one\n\n indices.push(i1);\n indices.push(i4);\n indices.push(i2); // face two\n\n indices.push(i4);\n indices.push(i3);\n indices.push(i2);\n }\n }\n }", "placeVertexAndNormals(z){\r\n let ang = 0;\r\n\r\n this.normals.push(Math.cos(0),Math.sin(0),0);\r\n this.vertices.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),z);\r\n this.texCoords.push(0,z);\r\n for(let i=1;i<this.slices;i++){\r\n ang+=360/this.slices;\r\n this.vertices.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),z);\r\n this.normals.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),0);\r\n this.texCoords.push(i*(1/this.slices),z);\r\n\r\n }\r\n this.vertices.push(Math.cos(0),Math.sin(0),z);\r\n this.normals.push(Math.cos(0),Math.sin(0),0);\r\n this.texCoords.push(1,z);\r\n }", "function pointsToNormals(Point1, Point2, Point3){\n var Vect1 = [Point1.x - Point2.x, Point1.y - Point2.y, Point1.z - Point2.z];\n var v1 = new xyzValues(Vect1[0],Vect1[1],Vect1[2]);\n\n var Vect2 = [Point3.x - Point2.x, Point3.y - Point2.y, Point3.z - Point2.z];\n var v2 = new xyzValues(Vect2[0], Vect2[1], Vect2[2]);\n\n var x = (v2.y * v1.z) - (v2.z * v1.y) ;\n var y = (v2.z * v1.x) - (v2.x * v1.z) ;\n var z = (v2.x * v1.y) - (v2.y * v1.x) ;\n\n var mag = Math.sqrt(x*x + y*y + z*z);\n\n return [x/mag, y/mag, z/mag];\n}", "function getCylinderData(c) {\n // indices for colorList\n var mod = colorList.length;\n var j1, j2, j3;\n j1 = c;\n j2 = j1 + 1;\n j3 = j2 + 1;\n\n // Number of divisions for the circumference of the cylinder\n var NumSides = 72;\n // coords for the top and bot faces of the cylinder\n var x1, z1;\n var x2, z2;\n var y;\n // Increments of the angle based on NumSides\n var angle = 0;\n var inc = Math.PI * 2.0 / NumSides;\n\n //var points = new Array(NumSides * 6);\n //var colors = new Array(NumSides * 6);\n var topPoints = [];\n var topColors = [];\n var topNormals = [];\n\n var botPoints = [];\n var botColors = [];\n var botNormals = [];\n\n var points = [];\n var colors = [];\n var normals = [];\n\n // Currently calculated normal in the forloop\n var currNormal;\n // Normals for the bottom and top of the cylinder\n var up = [0, 1, 0];\n var down = [0, -1, 0];\n\n // coords for the center points of the bases\n x = 0;\n y = baseHeight;\n z = 0;\n\n // top base center point\n topPoints.push(x,y,z);\n topColors.push(colorList[j1], colorList[j2], colorList[j3]);\n topNormals.push(up[0], up[1], up[2]);\n\n // bot base center point\n botPoints.push(x,-y,z);\n botColors.push(colorList[j1], colorList[j2], colorList[j3]);\n botNormals.push(down[0], down[1], down[2]);\n\n // For each 'cut' of the side, add its point and color data\n for(var i=0; i < NumSides; ++i) {\n // indices for colorList\n //j1 = i % mod;\n //j2 = i+1 % mod;\n //j3 = i+2 % mod;\n\n // x,z coords for the left half of a side\n x1 = baseRadius * Math.cos(angle);\n z1 = baseRadius * Math.sin(angle);\n // x,z coords for the right half of a side\n angle += inc;\n x2 = baseRadius * Math.cos(angle);\n z2 = baseRadius * Math.sin(angle);\n\n y = baseHeight; // For now, arbitrary; change it to something later\n\n // Side vertices -----------------------------------------#\n // First triangle\n // top left vertex\n points.push(x1 * TopRadius, y, z1* TopRadius);\n colors.push(colorList[j1], colorList[j2], colorList[j3]);\n // top right vertex\n points.push(x2* TopRadius, y, z2* TopRadius);\n colors.push(colorList[j1], colorList[j2], colorList[j3]);\n // bot left vertex\n points.push(x1* BotRadius, -y, z1* BotRadius);\n colors.push(colorList[j1], colorList[j2], colorList[j3]);\n \n // Compute normals for this slice\n // cross(top left, top right)\n currNormal = m4.cross([x1 * TopRadius, y, z1* TopRadius], \n [x2* TopRadius, y, z2* TopRadius]);\n normals.push(currNormal[0], currNormal[1], currNormal[2]);\n normals.push(currNormal[0], currNormal[1], currNormal[2]);\n normals.push(currNormal[0], currNormal[1], currNormal[2]);\n \n // Second triangle\n // top right vertex\n points.push(x2* TopRadius, y, z2* TopRadius);\n colors.push(colorList[j1], colorList[j2], colorList[j3]);\n // bot right vertex\n points.push(x2* BotRadius, -y, z2* BotRadius);\n colors.push(colorList[j1], colorList[j2], colorList[j3]);\n // bot left vertex\n points.push(x1* BotRadius, -y, z1* BotRadius);\n colors.push(colorList[j1], colorList[j2], colorList[j3]);\n \n // Compute normals\n //currNormal = m4.cross([x2* TopRadius, y, z2* TopRadius], \n // [x1* BotRadius, -y, z1* BotRadius]);\n normals.push(currNormal[0], currNormal[1], currNormal[2]);\n normals.push(currNormal[0], currNormal[1], currNormal[2]);\n normals.push(currNormal[0], currNormal[1], currNormal[2]);\n \n\n // Top base vertex ---------------------------------------#\n // top left vertex\n topPoints.push(z1 * TopRadius, y, x1 * TopRadius);\n topColors.push(colorList[j1], colorList[j2], colorList[j3]);\n topNormals.push(up[0], up[1], up[2]);\n\n // Bot base vertex ---------------------------------------#\n // bot left vertex\n botPoints.push(x1 * BotRadius, -y, z1 * BotRadius);\n botColors.push(colorList[j1], colorList[j2], colorList[j3]);\n botNormals.push(down[0], down[1], down[2]);\n }\n\n // Define final vertices coords\n angle += inc;\n x1 = baseRadius * Math.cos(angle);\n z1 = baseRadius * Math.sin(angle);\n // Final vertex for top base\n topPoints.push(z1 * TopRadius, y, x1 * TopRadius);\n topColors.push(colorList[j1], colorList[j2], colorList[j3]);\n topNormals.push(up[0], up[1], up[2]);\n // Final vertex for bot base\n botPoints.push(x1 * BotRadius, -y, z1 * BotRadius);\n botColors.push(colorList[j1], colorList[j2], colorList[j3]);\n botNormals.push(down[0], down[1], down[2]);\n\n // Put all the data together\n var CylinderData = {\n points,\n colors,\n normals,\n sideLength: points.length / 3,\n baseLength: topPoints.length / 3,\n fullLength: 0,\n }\n\n points = points.concat(topPoints);\n points = points.concat(botPoints);\n colors = colors.concat(topColors);\n colors = colors.concat(botColors);\n normals = normals.concat(topNormals);\n normals = normals.concat(botNormals);\n\n CylinderData.points = points;\n CylinderData.colors = colors;\n CylinderData.normals = normals;\n CylinderData.fullLength = points.length / 3;\n\n return CylinderData;\n}", "function setNormals() {\n var len = points.length;\n for (var i = 0; i < len; i += 9) {\n var a = [points[i], points[i + 1], points[i + 2]];\n var b = [points[i + 3], points[i + 4], points[i + 5]];\n var c = [points[i + 6], points[i + 7], points[i + 8]];\n var ba = [a[0] - b[0], a[1] - b[1], a[2] - b[2]];\n var bc = [c[0] - b[0], c[1] - b[1], c[2] - b[2]];\n var normalb = [];\n\n normalb.push(bc[1] * ba[2] - bc[2] * ba[1]);\n normalb.push(ba[0] * bc[2] - ba[2] * bc[0]);\n normalb.push(bc[0] * ba[1] - bc[1] * ba[0]);\n var lenb = Math.sqrt(Math.pow(normalb[0], 2) + Math.pow(normalb[1], 2) + Math.pow(normalb[2], 2));\n normalb[0] /= lenb;\n normalb[1] /= lenb;\n normalb[2] /= lenb;\n\n n = n.concat(normalb);\n n = n.concat(normalb);\n n = n.concat(normalb);\n }\n}", "normal(p1, p2, p3){\r\n var qr = {x: p1.dx - p2.dx, y: p1.dy - p2.dy, z: p1.dz - p2.dz}\r\n var qs = {x: p3.dx - p2.dx, y: p3.dy - p2.dy, z: p3.dz - p2.dz}\r\n return {x: qr.y*qs.z - qr.z*qs.y, y: qr.z*qs.x - qr.x*qs.z, z: qr.x*qs.y - qr.y*qs.x}\r\n }", "function o$9(o){const d=t$i`vec3 decodeNormal(vec2 f) {\nfloat z = 1.0 - abs(f.x) - abs(f.y);\nreturn vec3(f + sign(f) * min(z, 0.0), z);\n}`;o.fragment.code.add(d),o.vertex.code.add(d);}", "calculateNormals() {\r\n // MP2: Implement this function!\r\n\r\n // initialize an NArray containing M normals\r\n let normals = [];\r\n for(let i = 0; i < this.numVertices; i++) {\r\n normals.push([0, 0, 0]);\r\n }\r\n\r\n // iterate all triangles\r\n for(let i = 0; i < this.numFaces; i++) {\r\n let indices = this.getTriangleVertexByIndex(i);\r\n let vertices = this.createAndGetPosDataByIndex(indices);\r\n let N = this.computeNormalForTriangles(vertices[0], vertices[1], vertices[2]);\r\n // average vertex normals by scale with factor 0.5\r\n glMatrix.vec3.scale(N, N, 0.5);\r\n\r\n indices.forEach(function(index) {\r\n normals[index] = normals[index].map((a, i) => a + N[i]);\r\n });\r\n }\r\n\r\n // normalize each normal in N array to unit length\r\n for(let i = 0; i < this.numVertices; i++) {\r\n let tmp = glMatrix.vec3.fromValues(normals[i][0], normals[i][1], normals[i][2]);\r\n glMatrix.vec3.normalize(tmp, tmp);\r\n this.normalData.push(...tmp);\r\n }\r\n }", "rawNormal(i1, i2, i3) {\n let n = new J3DIVector3(this[i3 * 3] - this[i1 * 3], this[i3 * 3 + 1] - this[i1 * 3 + 1], this[i3 * 3 + 2] - this[i1 * 3 + 2]);\n n.cross(new J3DIVector3(this[i2 * 3] - this[i1 * 3], this[i2 * 3 + 1] - this[i1 * 3 + 1], this[i2 * 3 + 2] - this[i1 * 3 + 2]));\n return n;\n }", "getNormal(u, controlPoints){\n /*Se obtiene la tangente en el punto*/\n var tangent = this.getTangent(u, controlPoints);\n var tanVec = vec3.fromValues(tangent.x, tangent.y, tangent.z);\n /*Se normaliza la tangente*/\n var nTan = vec3.create();\n vec3.normalize(nTan, tanVec);\n /*Vector del eje Y (o X si esta en el eje Y la curva)*/\n var auxVec = vec3.create();\n var multiplyVec = vec3.fromValues(0, -1, 0);\n if (tangent.x == 0 && tangent.z == 0) multiplyVec = vec3.fromValues(-1, 0, 0);\n vec3.cross(auxVec, nTan, multiplyVec);\n /*Se obtiene el vector normal como el producto vectorial entre la\n tangente y el eje Y (si la tangente es vertical no funciona)*/\n var normVec = vec3.create();\n vec3.cross(normVec, tanVec, auxVec);\n /*Se crea el punto a partir del vector obtenido*/\n var normal = new Point(normVec[0], normVec[1], normVec[2]);\n return normal;\n }", "placeVertexAndNormals(z){\r\n let ang = 0;\r\n let beta = 30;\r\n let acum_beta = beta;\r\n\r\n this.vertices.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),z);\r\n this.normals.push(Math.cos(acum_beta*Math.PI/180),Math.sin(acum_beta*Math.PI/180),0);\r\n this.texCoords.push(0,z);\r\n if(this.regular){\r\n for(let i=0;i<3;i++){\r\n ang+=60;\r\n this.vertices.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),z);\r\n this.texCoords.push((i+1)*0.25,z);\r\n this.vertices.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),z);\r\n this.texCoords.push((i+1)*0.25,z);\r\n\r\n this.normals.push(Math.cos(acum_beta*Math.PI/180),Math.sin(acum_beta*Math.PI/180),0);\r\n acum_beta+=60;\r\n if(i!=2)\r\n this.normals.push(Math.cos(acum_beta*Math.PI/180),Math.sin(acum_beta*Math.PI/180),0);\r\n else\r\n this.normals.push(Math.cos(-90*Math.PI/180),Math.sin(-90*Math.PI/180),0);\r\n }\r\n }\r\n else{\r\n for(let i=0;i<3;i++){\r\n ang+=60;\r\n if(i>0){\r\n this.vertices.push(0,Math.sin(ang*Math.PI/180),z);\r\n this.vertices.push(0,Math.sin(ang*Math.PI/180),z);\r\n }\r\n else{\r\n this.vertices.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),z);\r\n this.vertices.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),z);\r\n }\r\n this.texCoords.push((i+1)*0.25,z);\r\n this.texCoords.push((i+1)*0.25,z);\r\n\r\n this.normals.push(Math.cos(acum_beta*Math.PI/180),Math.sin(acum_beta*Math.PI/180),0);\r\n if(i>0){\r\n acum_beta+=90;\r\n }else\r\n acum_beta+=60;\r\n this.normals.push(Math.cos(acum_beta*Math.PI/180),Math.sin(acum_beta*Math.PI/180),0);\r\n }\r\n }\r\n ang = 0;\r\n this.vertices.push(Math.cos(ang*Math.PI/180),Math.sin(ang*Math.PI/180),z);\r\n this.normals.push(Math.cos(-90*Math.PI/180),Math.sin(-90*Math.PI/180),0);\r\n this.texCoords.push(1,z);\r\n }", "function makeCube() {\r\n const positionArray = new Float32Array([\r\n -1, -1, 1,\r\n 1, 1, 1,\r\n 1, -1, 1,\r\n 1, 1, 1,\r\n -1, -1, 1,\r\n -1, 1, 1,\r\n\r\n -1, -1, -1,\r\n 1, -1, -1,\r\n 1, 1, -1,\r\n 1, 1, -1,\r\n -1, 1, -1,\r\n -1, -1, -1,\r\n\r\n -1, 1, -1,\r\n 1, 1, 1,\r\n -1, 1, 1,\r\n 1, 1, 1,\r\n -1, 1, -1,\r\n 1, 1, -1,\r\n\r\n -1, -1, -1,\r\n -1, -1, 1,\r\n 1, -1, 1,\r\n 1, -1, 1,\r\n 1, -1, -1,\r\n -1, -1, -1,\r\n\r\n 1, -1, -1,\r\n 1, 1, 1,\r\n 1, 1, -1,\r\n 1, 1, 1,\r\n 1, -1, -1,\r\n 1, -1, 1,\r\n\r\n -1, -1, -1,\r\n -1, 1, -1,\r\n -1, 1, 1,\r\n -1, 1, 1,\r\n -1, -1, 1,\r\n -1, -1, -1,\r\n ]);\r\n const normalArray = positionArrayToNormalArray(positionArray);\r\n return [positionArray, normalArray];\r\n}", "function generateNormals(vertices) {\n vertexNormals = [];\n var p = 0;\n var t1, t2, t3, norm;\n for (var i = 0; i < numCurves; i++)\n { \n for (var t = 0; t < steps; t++) {\n var savedP = p;\n for (var a = 0; a < angles; a++) {\n t1 = vertices[p];\n t2 = vertices[p+1];\n t3 = vertices[p+2];\n var v1 = subtract(t2, t1);\n var v2 = subtract(t3, t1);\n norm = normalize(cross(v1,v2));\n vertexNormals[p++] = norm;\n vertexNormals[p++] = norm;\n }\n vertexNormals[p++] = vertexNormals[savedP];\n vertexNormals[p++] = vertexNormals[savedP+1];\n }\n }\n}", "function o$8(o,d){0===d.normalType&&(o.attributes.add(\"normal\",\"vec3\"),o.vertex.code.add(t$i`vec3 normalModel() {\nreturn normal;\n}`)),1===d.normalType&&(o.include(o$9),o.attributes.add(\"normalCompressed\",\"vec2\"),o.vertex.code.add(t$i`vec3 normalModel() {\nreturn decodeNormal(normalCompressed);\n}`)),3===d.normalType&&(o.extensions.add(\"GL_OES_standard_derivatives\"),o.fragment.code.add(t$i`vec3 screenDerivativeNormal(vec3 positionView) {\nreturn normalize(cross(dFdx(positionView), dFdy(positionView)));\n}`));}", "function triangle(a, b, c) \r\n{\r\n normalsArray.push(vec3(a[0], a[1], a[2]));\r\n normalsArray.push(vec3(b[0], b[1], b[2]));\r\n normalsArray.push(vec3(c[0], c[1], c[2]));\r\n \r\n pointsArray.push(a);\r\n pointsArray.push(b); \r\n pointsArray.push(c);\r\n\t \r\n\t texCoordsArray.push(texCoord[0]);\r\n\t texCoordsArray.push(texCoord[1]);\r\n\t texCoordsArray.push(texCoord[2]);\r\n\r\n sphereCount += 3;\r\n}", "function calcFaceNormals(hf: Heightfield) {\n const csz = hf.cellSize,\n xc = hf.xCount, // tile X & Y counts\n yc = hf.yCount,\n hxc = hf.xCount + 1, // height X count (1 larger than tile count)\n heights = hf.heights, // 1 less indirection\n normals = hf.faceNormals,\n v0 = Vec3.create(),\n v1 = Vec3.create(),\n n = Vec3.create(); // used to compute normals\n let i = 0;\n\n const tStart = Date.now();\n for (let iy = 0; iy < yc; ++iy) {\n for (let ix = 0; ix < xc; ++ix) {\n i = 6 * (ix + iy * xc);\n const ih = ix + iy * hxc;\n const z = heights[ih];\n\n // 2 vectors of top-left tri\n v0.x = csz;\n v0.y = csz;\n v0.z = heights[ih + hxc + 1] - z;\n\n v1.x = 0.0;\n v1.y = csz;\n v1.z = heights[ih + hxc] - z;\n\n Vec3.cross(v0, v1, n);\n Vec3.normalize(n, n);\n normals[i + 0] = n.x;\n normals[i + 1] = n.y;\n normals[i + 2] = n.z;\n\n // 2 vectors of bottom-right tri\n v0.x = csz;\n v0.y = 0.0;\n v0.z = heights[ih + 1] - z;\n\n v1.x = csz;\n v1.y = csz;\n v1.z = heights[ih + hxc + 1] - z;\n\n Vec3.cross(v0, v1, n);\n Vec3.normalize(n, n);\n normals[i + 3] = n.x;\n normals[i + 4] = n.y;\n normals[i + 5] = n.z;\n }\n }\n const dt = Date.now() - tStart;\n}", "function posnormtriv( pos, norm, o1, o2, o3, renderCallback ) {\n\n var c = scope.count * 3;\n\n // positions\n\n scope.positionArray[ c + 0 ] = pos[ o1 ];\n scope.positionArray[ c + 1 ] = pos[ o1 + 1 ];\n scope.positionArray[ c + 2 ] = pos[ o1 + 2 ];\n\n scope.positionArray[ c + 3 ] = pos[ o2 ];\n scope.positionArray[ c + 4 ] = pos[ o2 + 1 ];\n scope.positionArray[ c + 5 ] = pos[ o2 + 2 ];\n\n scope.positionArray[ c + 6 ] = pos[ o3 ];\n scope.positionArray[ c + 7 ] = pos[ o3 + 1 ];\n scope.positionArray[ c + 8 ] = pos[ o3 + 2 ];\n\n // normals\n\n scope.normalArray[ c + 0 ] = norm[ o1 ];\n scope.normalArray[ c + 1 ] = norm[ o1 + 1 ];\n scope.normalArray[ c + 2 ] = norm[ o1 + 2 ];\n\n scope.normalArray[ c + 3 ] = norm[ o2 ];\n scope.normalArray[ c + 4 ] = norm[ o2 + 1 ];\n scope.normalArray[ c + 5 ] = norm[ o2 + 2 ];\n\n scope.normalArray[ c + 6 ] = norm[ o3 ];\n scope.normalArray[ c + 7 ] = norm[ o3 + 1 ];\n scope.normalArray[ c + 8 ] = norm[ o3 + 2 ];\n\n // uvs\n\n if ( scope.enableUvs ) {\n\n var d = scope.count * 2;\n\n scope.uvArray[ d + 0 ] = pos[ o1 ];\n scope.uvArray[ d + 1 ] = pos[ o1 + 2 ];\n\n scope.uvArray[ d + 2 ] = pos[ o2 ];\n scope.uvArray[ d + 3 ] = pos[ o2 + 2 ];\n\n scope.uvArray[ d + 4 ] = pos[ o3 ];\n scope.uvArray[ d + 5 ] = pos[ o3 + 2 ];\n\n }\n\n // colors\n\n if ( scope.enableColors ) {\n\n scope.colorArray[ c + 0 ] = pos[ o1 ];\n scope.colorArray[ c + 1 ] = pos[ o1 + 1 ];\n scope.colorArray[ c + 2 ] = pos[ o1 + 2 ];\n\n scope.colorArray[ c + 3 ] = pos[ o2 ];\n scope.colorArray[ c + 4 ] = pos[ o2 + 1 ];\n scope.colorArray[ c + 5 ] = pos[ o2 + 2 ];\n\n scope.colorArray[ c + 6 ] = pos[ o3 ];\n scope.colorArray[ c + 7 ] = pos[ o3 + 1 ];\n scope.colorArray[ c + 8 ] = pos[ o3 + 2 ];\n\n }\n\n scope.count += 3;\n\n if ( scope.count >= scope.maxCount - 3 ) {\n\n scope.hasPositions = true;\n scope.hasNormals = true;\n\n if ( scope.enableUvs ) {\n\n scope.hasUvs = true;\n\n }\n\n if ( scope.enableColors ) {\n\n scope.hasColors = true;\n\n }\n\n renderCallback( scope );\n\n }\n\n }", "function c(e){var a,l,c,u=i.length/3,h=e.extractPoints(t),d=h.shape,p=h.holes;// check direction of vertices\nif(!1===Xr.isClockWise(d))// also check if holes are in the opposite direction\nfor(d=d.reverse(),a=0,l=p.length;a<l;a++)c=p[a],!0===Xr.isClockWise(c)&&(p[a]=c.reverse());var f=Xr.triangulateShape(d,p);// join vertices of inner and outer paths to a single array\nfor(a=0,l=p.length;a<l;a++)c=p[a],d=d.concat(c);// vertices, normals, uvs\nfor(a=0,l=d.length;a<l;a++){var m=d[a];i.push(m.x,m.y,0),r.push(0,0,1),o.push(m.x,m.y)}// incides\nfor(a=0,l=f.length;a<l;a++){var g=f[a],v=g[0]+u,y=g[1]+u,x=g[2]+u;n.push(v,y,x),s+=3}}", "calculateNormal(){\n this.normal = vec3.create();\n for (let i = 0; i < this.polygons.length; i++) {\n vec3.add(this.normal, this.normal, this.polygons[i].getNormal());\n }\n vec3.normalize(this.normal, this.normal)\n }", "function createVertexData() {\r\n\tvar n = 32;\r\n\tvar m = 16;\r\n\tvar R = 0.5;\r\n\tvar r = 0.1;\r\n\tvar a = 1;\r\n\tvar du = 2 * Math.PI / n;\r\n\tvar dv = 2 * Math.PI / m;\r\n\r\n\t// Counter for entries in index array.\r\n\tlet iLines = 0;\r\n\tlet iTris = 0;\r\n\r\n\t// Positions.\r\n\tvertices = new Float32Array(3 * (n + 1) * (m + 1));\r\n\r\n\t// Index data.\r\n\tindicesLines = new Uint16Array(2 * 2 * n * m);\r\n\tindicesTris = new Uint16Array(3 * 2 * n * m);\r\n\r\n\t// Colors.\r\n\tcolors = new Float32Array(3 * (n + 1) * (m + 1));\r\n\r\n\tfor (let i = 0, u = -1; i <= n; i++, u += du) {\r\n\t\tfor (let j = 0, v = -1; j <= m; j++, v += dv) {\r\n\t\t\tconst iVertex = i * (m + 1) + j;\r\n\t\t\t\r\n\t\t\tvar x = (R + r * Math.cos(v) * (a + Math.sin(u))) * Math.cos(u);\r\n\t\t\tvar y = (R + r * Math.cos(v) * (a + Math.sin(u))) * Math.sin(u);\r\n\t\t\tvar z = r * Math.sin(v) * (a + Math.sin(u));\r\n\r\n\t\t\tvertices[iVertex * 3] = x;\r\n\t\t\tvertices[iVertex * 3 + 1] = y;\r\n\t\t\tvertices[iVertex * 3 + 2] = z;\r\n\t\t\t\r\n\t\t\tif (j && i) {\r\n\t\t\t\tindicesLines[iLines++] = iVertex - 1;\r\n\t\t\t\tindicesLines[iLines++] = iVertex;\r\n\t\t\t\tindicesLines[iLines++] = iVertex - (m + 1);\r\n\t\t\t\tindicesLines[iLines++] = iVertex;\r\n\t\t\t\t\r\n\t\t\t\tindicesTris[iTris++] = iVertex;\r\n\t\t\t\tindicesTris[iTris++] = iVertex - 1;\r\n\t\t\t\tindicesTris[iTris++] = iVertex - (m + 1);\r\n\t\t\t\tindicesTris[iTris++] = iVertex - 1;\r\n\t\t\t\tindicesTris[iTris++] = iVertex - (m + 1) - 1;\r\n\t\t\t\tindicesTris[iTris++] = iVertex - (m + 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function createVertexData2() {\r\n\tvar n = 64;\r\n\tvar m = 18;\r\n\tvar a = 0.5;\r\n\tvar b = 0.3;\r\n\tvar c = 0.1;\r\n\tvar d = 6;\r\n\tvar du = 2 * Math.PI / n;\r\n\tvar dv = 2 * Math.PI / m;\r\n\r\n\t// Counter for entries in index array.\r\n\tlet iLines = 0;\r\n\tlet iTris = 0;\r\n\r\n\t// Positions.\r\n\tvertices2 = new Float32Array(3 * (n + 1) * (m + 1));\r\n\r\n\t// Index data.\r\n\tindicesLines2 = new Uint16Array(2 * 2 * n * m);\r\n\tindicesTris2 = new Uint16Array(3 * 2 * n * m);\r\n\r\n\t// Colors.\r\n\tcolors2 = new Float32Array(3 * (n + 1) * (m + 1));\r\n\r\n\tfor (let i = 0, u = -1; i <= n; i++, u += du) {\r\n\t\tfor (let j = 0, v = -1; j <= m; j++, v += dv) {\r\n\t\t\tconst iVertex = i * (m + 1) + j;\r\n \r\n\t\t\tvar x = (a + b * Math.cos(d * u) + c * Math.cos(v)) * Math.cos(u);\r\n\t\t\tvar z = a * c * Math.sin(v);\r\n\t\t\tvar y = (a + b * Math.cos(d * u) + c * Math.cos(v)) * Math.sin(u);\r\n \r\n\t\t\tvertices2[iVertex * 3] = x;\r\n\t\t\tvertices2[iVertex * 3 + 1] = y;\r\n\t\t\tvertices2[iVertex * 3 + 2] = z;\r\n\t\t\t\r\n\t\t\tif (j && i) {\r\n\t\t\t\tindicesLines2[iLines++] = iVertex - 1;\r\n\t\t\t\tindicesLines2[iLines++] = iVertex;\r\n\t\t\t\tindicesLines2[iLines++] = iVertex - (m + 1);\r\n\t\t\t\tindicesLines2[iLines++] = iVertex;\r\n\t\t\t\t\r\n\t\t\t\tindicesTris2[iTris++] = iVertex;\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - 1;\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - (m + 1);\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - 1;\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - (m + 1) - 1;\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - (m + 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function triangleSphere(a, b, c) {\n\n var t1 = subtract(b, a);\n var t2 = subtract(c, a);\n var normal = cross(t2, t1);\n normal = vec3(normal);\n //normal = vec3(1, 1, 1);\n\n points.push(a);\n points.push(b);\n points.push(c);\n normalsArray.push(normal);\n normalsArray.push(normal);\n normalsArray.push(normal);\n\n if (ghost % 3 == 2) {\n \n texCoordsArray.push(texCoord[0]);\n texCoordsArray.push(texCoord[1]);\n texCoordsArray.push(texCoord[2]);\n\n } else {\n\n texCoordsArray.push(texCoord[0]);\n texCoordsArray.push(texCoord[2]);\n texCoordsArray.push(texCoord[3]);\n\n }\n\n indexSphere += 3;\n ghost++;\n\n}", "set importNormals(value) {}", "function getSmoothNormz(outer, inner, nface, store) {\r\n var k = 0;\r\n while (k < outer-1){\r\n var rowAbove = nface[k];\r\n var rowBelow = nface[k+1];\r\n for(var t=0; t < inner-1; t++){\r\n \r\n // first 2 vertices in polygon\r\n for(var j=k; j<=k+1; j++){\r\n \r\n rowAbove = nface[j];\r\n rowBelow = nface[j+1];\r\n \r\n var x = rowAbove[t].x + rowAbove[t+1].x + rowBelow[t].x + rowBelow[t+1].x;\r\n var y = rowAbove[t].y + rowAbove[t+1].y + rowBelow[t].y + rowBelow[t+1].y;\r\n var z = rowAbove[t].z + rowAbove[t+1].z + rowBelow[t].z + rowBelow[t+1].z;\r\n\r\n var Vnorm = new Vector3([x, y, z]);\r\n Vnorm.normalize();\r\n \r\n vertexNormz.push(Vnorm.elements[0], Vnorm.elements[1], Vnorm.elements[2]);\r\n store.push(new coord(Vnorm.elements[0], Vnorm.elements[1], Vnorm.elements[2]));\r\n }\r\n \r\n // second 2 vertices in polygon\r\n for(var j=k+1; j>=k; j--){\r\n \r\n rowAbove = nface[j];\r\n rowBelow = nface[j+1];\r\n \r\n var x = rowAbove[t+1].x + rowAbove[t+2].x + rowBelow[t+1].x + rowBelow[t+2].x;\r\n var y = rowAbove[t+1].y + rowAbove[t+2].y + rowBelow[t+1].y + rowBelow[t+2].y;\r\n var z = rowAbove[t+1].z + rowAbove[t+2].z + rowBelow[t+1].z + rowBelow[t+2].z;\r\n\r\n var Vnorm = new Vector3([x, y, z]);\r\n Vnorm.normalize();\r\n vertexNormz.push(Vnorm.elements[0], Vnorm.elements[1], Vnorm.elements[2]);\r\n store.push(new coord(Vnorm.elements[0], Vnorm.elements[1], Vnorm.elements[2]));\r\n }\r\n }\r\n k++;\r\n }\r\n}", "makeObjectGeometry () {\n // A fresh, empty Geometry object that will hold the mesh geometry\n var cylGeom = new THREE.Geometry()\n var normals = []\n\n // The bottom face is set at Y = -1\n cylGeom.vertices.push(new THREE.Vector3(0, -1, 0))\n normals.push(new THREE.Vector3(0, -1, 0))\n\n // Create and push the vertices/normals of the bottom face\n for (let i = this._slices; i > 0; i--) {\n var theta = (i / this._slices) * Math.PI * 2\n cylGeom.vertices.push(new THREE.Vector3(Math.cos(theta), -1, Math.sin(theta)))\n normals.push(new THREE.Vector3(Math.cos(theta), 0, Math.sin(theta)))\n }\n\n // Push the faces for the bottom circle\n for (let i = 1; i <= this._slices; i++) {\n if (i === this._slices) {\n cylGeom.faces.push(new THREE.Face3(1, i, 0, normals[0]))\n } else {\n cylGeom.faces.push(new THREE.Face3(i + 1, i, 0, normals[0]))\n }\n }\n\n // topCircle checks the length of the vertices on the bottom circle\n // Later used to draw faces for the side\n let topCircle = cylGeom.vertices.length\n\n // // The top face is set at Y = 1\n cylGeom.vertices.push(new THREE.Vector3(0, 1, 0))\n normals.push(new THREE.Vector3(0, 1, 0))\n\n // Create and push the vertices/normals of the top face\n for (let i = this._slices; i > 0; i--) {\n theta = (i / this._slices) * Math.PI * 2\n cylGeom.vertices.push(new THREE.Vector3(Math.cos(theta), 1, Math.sin(theta)))\n normals.push(new THREE.Vector3(Math.cos(theta), 0, Math.sin(theta)))\n }\n\n // Push the faces for the top circle\n for (let i = 1; i <= this._slices; i++) {\n if (i === this._slices) {\n cylGeom.faces.push(new THREE.Face3(this._slices + 2, this._slices + 1, i + this._slices + 1, normals[this._slices + 1]))\n } else {\n cylGeom.faces.push(new THREE.Face3(i + this._slices + 2, this._slices + 1, i + this._slices + 1, normals[this._slices + 1]))\n }\n }\n\n // Push the faces for the sides\n // C---D\n // |\\ |\n // | \\ |\n // | \\|\n // A---B\n //\n for (let i = 1; i <= this._slices; i++) {\n let A = i\n let B = A + 1\n let C = topCircle + i\n let D = C + 1\n\n // Alter vertices B and D for the last face of the cylinder\n if (i === this._slices) {\n B = 1\n D = topCircle + 1\n }\n\n cylGeom.faces.push(new THREE.Face3(C, A, B, [normals[C], normals[A], normals[B]]))\n cylGeom.faces.push(new THREE.Face3(C, B, D, [normals[C], normals[B], normals[D]]))\n }\n\n // Return the finished geometry\n return cylGeom\n }", "function planeNormal(cords,origo){\r\n\tvar origo = getOrigo(cords);\r\n\treturn lineNormal(uToV(origo,cords[0]),uToV(origo,cords[1]));\r\n}", "function VectorGeometry(name)\n{\n let vectorRadius = .2\n let radialSegments = 15\n \n let vectorGeometry = new THREE.Geometry()\n\n let heightSegments = name.length\n vectorGeometry.vertices = Array((radialSegments + 1) * (heightSegments + 1))\n vectorGeometry.faces = Array(radialSegments * heightSegments)\n for (let j = 0; j <= heightSegments; j++)\n {\n for (let i = 0; i <= radialSegments; i++)\n {\n vectorGeometry.vertices[j * (radialSegments + 1) + i] = new THREE.Vector3()\n vectorGeometry.vertices[j * (radialSegments + 1) + i].x = vectorRadius * (1. - (j / heightSegments))\n vectorGeometry.vertices[j * (radialSegments + 1) + i].applyAxisAngle(yUnit, i / radialSegments * TAU)\n\n vectorGeometry.vertices[j * (radialSegments + 1) + i].y = j / heightSegments\n\n if (i < radialSegments && j < heightSegments)\n {\n vectorGeometry.faces[(j * radialSegments + i) * 2 + 0] = new THREE.Face3(\n (j + 0) * (radialSegments + 1) + (i + 0),\n (j + 0) * (radialSegments + 1) + (i + 1),\n (j + 1) * (radialSegments + 1) + (i + 1),\n new THREE.Vector3(),\n colors[name[j]]\n )\n vectorGeometry.faces[(j * radialSegments + i) * 2 + 1] = new THREE.Face3(\n (j + 0) * (radialSegments + 1) + (i + 0),\n (j + 1) * (radialSegments + 1) + (i + 1),\n (j + 1) * (radialSegments + 1) + (i + 0),\n new THREE.Vector3(),\n colors[name[j]]\n )\n }\n }\n }\n vectorGeometry.computeFaceNormals()\n vectorGeometry.computeVertexNormals()\n\n return vectorGeometry\n}", "function normalNewell(p0, p1, p2) {\r\n\tvar verts = [p0, p1, p2, p0];\r\n\tvar normal = vec4(0, 0, 0, 0);\r\n\tfor (var i = 0; i < 3; i++) {\r\n\t\tnormal[0] += (verts[i][1] - verts[i + 1][1]) * (verts[i][2] + verts[i + 1][2]);\r\n\t\tnormal[1] += (verts[i][2] - verts[i + 1][2]) * (verts[i][0] + verts[i + 1][0]);\r\n\t\tnormal[2] += (verts[i][0] - verts[i + 1][0]) * (verts[i][1] + verts[i + 1][1]);\r\n\t}\r\n\treturn normalize(normal);\r\n}", "function calculateNormals(verts,tris) {\r\n var normals = [];\r\n for (i = 0; i < flatten(tris).length/3; i++) {\r\n normals.push(normalize(vec4(cross(\r\n subtract(verts[tris[i][1]], verts[tris[i][0]]),\r\n subtract(verts[tris[i][2]], verts[tris[i][0]])),0)));\r\n }\r\n return normals;\r\n}", "function calcVertices(){\r\n //create first row of face normals set to 0\r\n normRow = [];\r\n for(var k=0; k<=shape.length; k++){\r\n normRow.push(new coord(0,0,0));\r\n }\r\n normFaces.push(normRow);\r\n\r\n for (var i=0; i<shape[0].length-1; i++) {\r\n normRow = [];\r\n for (j=0; j<shape.length-1; j++) {\r\n \r\n var index = (vert.length/3);\r\n var currentLine = shape[j];\r\n var nextLine = shape[j+1];\r\n var thirdLine = shape[j+2];\r\n\r\n //push four points to make polygon\r\n vert.push(currentLine[i].x, currentLine[i].y, currentLine[i].z);\r\n vert.push(currentLine[i + 1].x, currentLine[i + 1].y, currentLine[i + 1].z);\r\n vert.push(nextLine[i + 1].x, nextLine[i + 1].y, nextLine[i + 1].z);\r\n vert.push(nextLine[i].x, nextLine[i].y, nextLine[i].z); \r\n \r\n //1st triangle in poly\r\n ind.push(index, index + 1, index + 2); //0,1,2\r\n //2nd triangle in poly\r\n ind.push(index, index + 2, index + 3); //0,2,3\r\n \r\n //CALCULATE SURFACE NORMALS\r\n \r\n var Snorm = calcNormal(nextLine[i], currentLine[i], currentLine[i+1]);\r\n \r\n if (j===0 || j===shape.length-2){\r\n //pushes first and last faces twice for first vertex\r\n normRow.push(new coord(Snorm.elements[0], Snorm.elements[1], Snorm.elements[2]));\r\n }\r\n normRow.push(new coord(Snorm.elements[0], Snorm.elements[1], Snorm.elements[2]));\r\n \r\n Snorm.normalize();\r\n \r\n surfaceNormz.push(Snorm.elements[0], Snorm.elements[1], Snorm.elements[2]);\r\n flatNormz.push(new coord(Snorm.elements[0], Snorm.elements[1], Snorm.elements[2]));\r\n \r\n //push start point for drawing\r\n drawFnormz.push(currentLine[i].x);\r\n drawFnormz.push(currentLine[i].y);\r\n drawFnormz.push(currentLine[i].z);\r\n //push normal vector\r\n drawFnormz.push(currentLine[i].x + Snorm.elements[0]*100);\r\n drawFnormz.push(currentLine[i].y + Snorm.elements[1]*100);\r\n drawFnormz.push(currentLine[i].z + Snorm.elements[2]*100); \r\n \r\n //CALCULATE FLAT COLORS\r\n \r\n var lightDir = new Vector3([1, 1, 1]);\r\n lightDir.normalize();\r\n \r\n //cos(theta) = dot product of lightDir and normal vector\r\n var FdotP = (lightDir.elements[0]*Snorm.elements[0])+(lightDir.elements[1]*Snorm.elements[1])+ (lightDir.elements[2]*Snorm.elements[2]);\r\n //surface color = light color x base color x FdotP (DIFFUSE)\r\n var R = 1.0 * 0.0 * FdotP;\r\n var G = 1.0 * 1.0 * FdotP;\r\n var B = 1.0 * 0.0 * FdotP;\r\n\r\n flatColor.push(R, G, B);\r\n flatColor.push(R, G, B);\r\n flatColor.push(R, G, B);\r\n flatColor.push(R, G, B);\r\n }\r\n normFaces.push(normRow); //pushes new row \r\n }\r\n //create last row of face normals set to 0\r\n normRow = [];\r\n for(var c=0; c<=shape.length; c++){\r\n normRow.push(new coord(0,0,0));\r\n }\r\n normFaces.push(normRow);\r\n \r\n //push surface normal colors - red\r\n for (j=0; j<drawFnormz.length; j+=3){\r\n normColor.push(1.0);\r\n normColor.push(0.0);\r\n normColor.push(0.0);\r\n }\r\n}", "function Rombi() {\r\n const positions = [];\r\n const colors = [];\r\n const indices = [];\r\n let normals = [];\r\n\r\n let index = 0;\r\n const indexArray = [];\r\n const vertex = new THREE.Vector3();\r\n\r\n let i_max = 50;\r\n let j_max = 50;\r\n\r\n let r,g,b\r\n for (let i = 0; i <= i_max; i++) {\r\n const indexRow = [];\r\n for (let j = 0; j <= j_max; j++) {\r\n r = i/i_max;\r\n g = 0.5;\r\n b = j/j_max;\r\n\r\n if (i >= 13 && i <= 37) {\r\n vertex.x = i/20 + j/25 - 1/20;\r\n vertex.y = 0;\r\n } else if (i<=13) {\r\n vertex.x = (3 * i / 65) + (j / 25);\r\n vertex.y = 0.2 * ((13 - i) / 13) * Math.cos(((2 * j + 12.5) / 25) * Math.PI);\r\n } else {\r\n vertex.x = (3 * i / 65) + (j / 25);\r\n vertex.y = (i-37)/65 * Math.cos((2*j + 37.5)/25 * Math.PI);\r\n }\r\n vertex.z = j/25;\r\n\r\n positions.push(vertex.x, vertex.y, vertex.z);\r\n colors.push(r,g,b);\r\n indexRow.push(index ++);\r\n }\r\n indexArray.push(indexRow);\r\n }\r\n\r\n for ( let i = 0; i < i_max; i++ ) {\r\n\t\t for ( let j = 0; j < j_max; j++ ) {\r\n\t\t\t\t// we use the index array to access the correct indices\r\n\t\t\t\tconst a = indexArray[ i ][ j ];\r\n\t\t\t\tconst b = indexArray[ i + 1 ][ j ];\r\n\t\t\t\tconst c = indexArray[ i + 1 ][ j + 1 ];\r\n\t\t\t\tconst d = indexArray[ i ][ j + 1 ];\r\n\t\t\t\t// faces\r\n\t\t\t\tindices.push( a, b, d );\r\n\t\t\t\tindices.push( b, c, d );\r\n //normal\r\n let normal = new THREE.Vector3();\r\n normal.crossVectors( new THREE.Vector3(\r\n positions[3*d]-positions[3*b],\r\n positions[3*d+1]-positions[3*b+1],\r\n positions[3*d+2]-positions[3*b+2]),\r\n new THREE.Vector3(\r\n positions[3*b]-positions[3*a],\r\n positions[3*b+1]-positions[3*a+1],\r\n positions[3*b+2]-positions[3*a+2]\r\n ))\r\n normal.normalize();\r\n normals.push(normal.x, normal.y, normal.z);\r\n\t\t\t}\r\n\t\t}\r\n\r\n let geometry = new THREE.BufferGeometry();\r\n geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));\r\n geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));\r\n geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );\r\n geometry.setIndex(indices);\r\n return geometry;\r\n}", "function Unwrapper( mesh, options )\r\n{\r\n\tvar verticesBuffer = mesh.vertexBuffers[\"vertices\"];\r\n\tvar indicesBuffer = mesh.indexBuffers[\"triangles\"];\r\n\r\n\tif(!indices)\r\n\t{\r\n\t\tconsole.error(\"Only can generate UVs from indexed meshes\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tvar vertices = verticesBuffer.data;\r\n\tvar indices = IndicesBuffer.data;\r\n\tvar num_triangles = indices.length / 3;\r\n\r\n\t//triplanar separation *********************\r\n\tvar blocks = [];\r\n\tfor(var i = 0; i < 6; ++i)\r\n\t\tblocks[i] = new Unwrapper.Block();\r\n\r\n\tvar AB = vec3.create();\r\n\tvar BC = vec3.create();\r\n\tvar CA = vec3.create();\r\n\tvar N = vec3.create();\r\n\r\n\t//blocks: 0:+X, 1:-X, 2:+Y, 3:-Y, 4:+Z, 5:-Z\r\n\tvar BVs = new Float32Array(6);\r\n\tvar chart_candidates = Array(3);\r\n\r\n\t//for every triangle add it to a chart in a block\r\n\tfor(var i = 0; i < num_triangles; ++i)\r\n\t{\r\n\t\tvar Ai = indices[i*3];\r\n\t\tvar Bi = indices[i*3+1];\r\n\t\tvar Ci = indices[i*3+2];\r\n\r\n\t\tvar A = vertices.subarray( Ai, Ai + 3 );\r\n\t\tvar B = vertices.subarray( Bi, Bi + 3 );\r\n\t\tvar C = vertices.subarray( Ci, Ci + 3 );\r\n\r\n\t\tvec3.sub( AB, B, A );\r\n\t\tvec3.sub( BC, B, C );\r\n\t\tvec3.sub( CA, A, C );\r\n\r\n\t\t//compute normal\r\n\t\tvec3.cross( N, AB, CA ); //we should us AC but doesnt matter, we will fix it\r\n\t\tvar len = vec3.length( N );\r\n\t\tvec3.scale( N, N, -len ); //reverse and normalize\r\n\r\n\t\t//compute which block belongs\r\n\t\tvar max = -2; var block_id = -1;\r\n\t\tBVs[0] = N[0]; BVs[1] = N[1]; BVs[2] = N[2];\r\n\t\tBVs[3] = -N[0]; BVs[4] = -N[1]; BVs[5] = -N[2];\r\n\t\tfor(var j = 0; j < 6; ++j)\r\n\t\t{\r\n\t\t\tif(BVs[j] < max)\r\n\t\t\t\tcontinue;\r\n\t\t\tblock_id = j;\r\n\t\t\tmax = BVs[j];\r\n\t\t}\r\n\r\n\t\t//get block\r\n\t\tvar block = blocks[ block_id ];\r\n\r\n\t\t//search for chart\r\n\t\tvar ABname = Ai + \",\" + Bi;\r\n\t\tvar BCname = Bi + \",\" + Ci;\r\n\t\tvar CAname = Ci + \",\" + Ai;\r\n\r\n\t\tchart = block.by_edge[ ABname ];\r\n\t\tchart_candidates[0] = block.by_edge[ ABname ];\r\n\t\tchart_candidates[1] = block.by_edge[ BCname ];\r\n\t\tchart_candidates[2] = block.by_edge[ CAname ];\r\n\r\n\t\tif( chart_candidates[0] && chart_candidates[1] && chart_candidates[0] != chart_candidates[1] )\r\n\t\t{\r\n\t\t\tchart_candidates[0].mergeWith( chart_candidates[1] );\r\n\t\t\tblock.removeChart( chart_candidates[1] );\r\n\t\t\tchart_candidates[1] = null;\r\n\t\t}\r\n\r\n\t\tif( chart_candidates[0] && chart_candidates[2] && chart_candidates[0] != chart_candidates[2] )\r\n\t\t{\r\n\t\t\tchart_candidates[0].mergeWith( chart_candidates[2] );\r\n\t\t\tblock.removeChart( chart_candidates[2] );\r\n\t\t\tchart_candidates[2] = null;\r\n\t\t}\r\n\r\n\t\tif( chart_candidates[1] && chart_candidates[2] && chart_candidates[1] != chart_candidates[2] )\r\n\t\t{\r\n\t\t\tchart_candidates[1].mergeWith( chart_candidates[2] );\r\n\t\t\tblock.removeChart( chart_candidates[2] );\r\n\t\t\tchart_candidates[2] = null;\r\n\t\t}\r\n\r\n\t\tvar final_chart = chart_candidates[0] || chart_candidates[1] || chart_candidates[2];\r\n\r\n\t\tif( !final_chart )\r\n\t\t{\r\n\t\t\tfinal_chart = new Unwrapper.Chart();\r\n\t\t\tblock.addChart( final_chart );\r\n\t\t}\r\n\r\n\t\t//add triangle to chart\r\n\t\tfinal_chart.addTriangle( A,B,C );\r\n\t}\r\n\r\n\t//put all charts together\r\n\tvar final_chart_list = [];\r\n\tfor(var i = 0; i < blocks.length; ++i)\r\n\t{\r\n\t\tvar block = blocks[i];\r\n\t\tif(block)\r\n\t\t\tfinal_chart_list = final_chart_list.concat( block.charts );\r\n\t}\r\n\r\n\t//compute bounding and area of every chart\r\n\tvar total_area = 0;\r\n\tfor(var i = 0; i < final_chart_list.length; ++i)\r\n\t{\r\n\t\tvar chart = final_chart_list[i];\r\n\t\tchart.computeInfo();\r\n\t\ttotal_area += chart.area;\r\n\t}\r\n\r\n\t//arrange charts from big to small\r\n\tfinal_chart_list.sort( function ( A, B ) { return A.area - B.area; } );\r\n\r\n\t//compute best possible area size\r\n\tvar area_size = Math.sqrt( total_area );\r\n\tfor(var i = 0; i < final_chart_list.length; ++i)\r\n\t{\r\n\t\tvar chart = final_chart_list[i];\r\n\t\tif(area_size < chart.width)\r\n\t\t\tarea_size = chart.width;\r\n\t\tif(area_size < chart.height)\r\n\t\t\tarea_size = chart.height;\r\n\t}\r\n\r\n\tvar root = { x:0, y: 0, width: area_size, height: area_size };\r\n\r\n\t//for every Chart\r\n\t\t//check in which region belongs\r\n\t\t\t//add it to the smallest where it fits\r\n\t\t\t//subdivide\r\n\t\t//no region found, increase size and restart\r\n}", "function computeFaceNormal(v1, v2, v3)\n{\n const EPSILON = 0.000001;\n var n = [];\n\n // default return value (0, 0, 0)\n n.push(0);\n n.push(0);\n n.push(0);\n\n // find 2 edge vectors: v1-v2, v1-v3\n var ex1 = v2[0] - v1[0];\n var ey1 = v2[1] - v1[1];\n var ez1 = v2[2] - v1[2];\n var ex2 = v3[0] - v1[0];\n var ey2 = v3[1] - v1[1];\n var ez2 = v3[2] - v1[2];\n\n // cross product: e1 x e2\n var nx, ny, nz;\n nx = ey1 * ez2 - ez1 * ey2;\n ny = ez1 * ex2 - ex1 * ez2;\n nz = ex1 * ey2 - ey1 * ex2;\n\n // normalize only if the length is > 0\n var length = Math.sqrt(nx * nx + ny * ny + nz * nz);\n if(length > EPSILON)\n {\n // normalize\n var lengthInv = 1.0 / length;\n n[0] = nx * lengthInv;\n n[1] = ny * lengthInv;\n n[2] = nz * lengthInv;\n }\n\n return n;\n}", "function getNormals( NormalNode ) {\n \n var mappingType = NormalNode.MappingInformationType;\n var referenceType = NormalNode.ReferenceInformationType;\n var buffer = NormalNode.Normals.a;\n var indexBuffer = [];\n if ( referenceType === 'IndexToDirect' ) {\n \n if ( 'NormalIndex' in NormalNode ) {\n \n indexBuffer = NormalNode.NormalIndex.a;\n \n } else if ( 'NormalsIndex' in NormalNode ) {\n \n indexBuffer = NormalNode.NormalsIndex.a;\n \n }\n \n }\n \n return {\n dataSize: 3,\n buffer: buffer,\n indices: indexBuffer,\n mappingType: mappingType,\n referenceType: referenceType\n };\n \n }", "function makeTree(nfaces)\n{\n var vCone = nfaces + 2;\n var omega = (360.0 / faces) * (Math.PI / 180.0);\n var vertices = [];\n\n // The 8 raw vertices of the canopy (cone shape)\n vertices.push( vec4( 0.0, 0.0, 0.5 , 1) );\n for (var i = 0; i < faces; i++){\n vertices[i + 1] = vec4( Math.cos( i * omega) / 2.0, Math.sin( i * omega) / 2.0, 0.1, 1 ); // scale the rawVertices\n }\n\n // push the first point of the fan to complete the cone\n vertices.push(vertices[1]);\n\n var vCylinder = nfaces * 2;\n\n for (var j = 0 ; j < faces*2; j++) {\n if (j == 0 ) {\n vertices.push( vec4( Math.cos( j * omega) / 2.0, Math.sin( j * omega) / 2.0, 0.1, 1));\n vertices.push( vec4( Math.cos( j * omega) / 2.0, Math.sin( j * omega) / 2.0, 0.0, 1));\n }\n \n vertices.push( vec4( Math.cos( (j + 1) * omega) / 6.0, Math.sin( (j + 1) * omega) / 6.0, 0.1, 1));\n vertices.push( vec4( Math.cos( (j + 1) * omega) / 6.0, Math.sin( (j + 1) * omega) / 6.0, 0.0, 1));\n }\n\n\n for (var j = 0 ; j < vertices.length; j++) {\n console.log(vertices[j]);\n }\n\n return vertices;\n}", "function computeNormals(cur_curveSegments) {\n normals = [];\n for (var i = 0; i < CPlist.length; i++) {\n var a = i;\n var b = i + 1 >= CPlist.length ? 0 : i + 1;\n var cur_normals = [];\n for (var j = 0; j < cur_curveSegments; j++) {\n var normal = new THREE.Vector3();\n normal.lerpVectors(\n CPlist[a].orient,\n CPlist[b].orient,\n j * (1 / cur_curveSegments)\n );\n cur_normals.push(normal);\n }\n var normal = new THREE.Vector3();\n normal.lerpVectors(CPlist[a].orient, CPlist[b].orient, 1);\n cur_normals.push(normal);\n normals.push(cur_normals);\n }\n}", "function LoaderUtil() {\n\t\n\tthis.removeEmptyStrings = function(data) {\n\t\tvar result = [];\n\t\tfor(var i = 0; i < data.length; i++) {\n\t\t\tif(!data[i] == \"\") {\n\t\t\t\tresult.push(data[i]);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\tthis.generateNormalsCW = function(vertices, indices) {\n \tfor (var i = 0; i < indices.length; i += 3 ) {\n \t\tvar v0 = vertices[indices[i ]].getPos();\n \t var v1 = vertices[indices[i + 1]].getPos();\n \t var v2 = vertices[indices[i + 2]].getPos();\n \t \n \t var normal = v1.sub(v0).cross(v2.sub(v0)).normalize();\n \t \n \t vertices[indices[i\t ]].setNormal(vertices[indices[i ]].getNormal().push(normal));\n \t vertices[indices[i + 1]].setNormal(vertices[indices[i + 1]].getNormal().push(normal));\n \t vertices[indices[i + 2]].setNormal(vertices[indices[i + 2]].getNormal().push(normal));\n \t}\n \n \tfor (var i = 0; i < vertices.length; ++i ) {\t\n \t vertices[i].setNormal(vertices[i].getNormal().normalize());\n \t} \n\t}\n\t\n\tthis.generateNormalsCCW = function(vertices, indices)\t{\n\t for (var i = 0; i < indices.length; i += 3 ) {\n\t \tvar v0 = vertices[indices[i ]].getPos();\n\t \tvar v1 = vertices[indices[i + 1]].getPos();\n\t \tvar v2 = vertices[indices[i + 2]].getPos();\n\t \n\t \tvar normal = v2.sub(v0).cross(v1.sub(v0)).normalize();\n\t \n\t vertices[indices[i\t ]].setNormal(vertices[indices[i ]].getNormal().push(normal));\n\t vertices[indices[i + 1]].setNormal(vertices[indices[i + 1]].getNormal().push(normal));\n\t vertices[indices[i + 2]].setNormal(vertices[indices[i + 2]].getNormal().push(normal));\n\t }\n\n\t for (var i = 0; i < vertices.length; ++i ) {\t\n\t \tvertices[i].setNormal(vertices[i].getNormal().normalize());\n\t } \n\t}\n\t\n\tthis.peekLast = function() {\n\t\treturn this[this.length - 1];\n\t}\n}", "function computeVertexNormal(hf: Heightfield, vx: number, vy: number, n: Vec3) {\n const fnorms = hf.faceNormals;\n // This vertex is belongs to 4 quads\n // Do the faces this vertex is the 1st point of for this quad.\n // This is the quad up and to the right\n let qx = vx % hf.xCount;\n let qy = vy % hf.yCount;\n let ni = (qy * hf.xCount + qx) * 3 * 2;\n n.x = fnorms[ni + 0];\n n.y = fnorms[ni + 1];\n n.z = fnorms[ni + 2];\n ni += 3;\n n.x += fnorms[ni + 0];\n n.y += fnorms[ni + 1];\n n.z += fnorms[ni + 2];\n\n // 2nd tri of quad up and to the left\n qx = pmod(qx - 1, hf.xCount);\n ni = (qy * hf.xCount + qx) * 3 * 2 + 3;\n n.x += fnorms[ni + 0];\n n.y += fnorms[ni + 1];\n n.z += fnorms[ni + 2];\n\n // both tris of quad down and to the left\n qy = pmod(qy - 1, hf.yCount);\n ni = (qy * hf.xCount + qx) * 3 * 2;\n n.x += fnorms[ni + 0];\n n.y += fnorms[ni + 1];\n n.z += fnorms[ni + 2];\n ni += 3;\n n.x += fnorms[ni + 0];\n n.y += fnorms[ni + 1];\n n.z += fnorms[ni + 2];\n\n // 1st tri of quad down and to the right\n qx = (qx + 1) % hf.xCount;\n ni = (qy * hf.xCount + qx) * 3 * 2;\n n.x += fnorms[ni + 0];\n n.y += fnorms[ni + 1];\n n.z += fnorms[ni + 2];\n\n // Normalize to 'average' the result normal\n Vec3.normalize(n, n);\n}", "getVertices(n) {\n\n var angle = 2*Math.PI/n;\n\n var vertices = [];\n var theta = 0;\n\n while(theta < 2*Math.PI) {\n var x = this.radius*Math.cos(theta);\n var y = this.radius*Math.sin(theta);\n \n vertices.push(x,y);\n\n vertices.push(0, 0);\n theta += angle;\n\n x = this.radius*Math.cos(theta);\n y = this.radius*Math.sin(theta);\n\n vertices.push(x,y);\n\n \n \n }\n\n return vertices;\n\n }", "function createTriangles(){ \n\t\t/* Obj.triangles = [[0,1,2], [3,4,5], ...] */\n\t\tObj.triangles = [];\n\t\tfor(var i = 0; i<Obj.positions.length/3; ++i){\n\t\t\tObj.triangles[i] = [3*i, 3*i+1, 3*i+2];\n\t\t}\n\t}", "function makeCube()\n{\n\t // vertices of cube\n\tvar rawVertices = new Float32Array([\n\t-0.5, -0.5, 0.5,\n\t0.5, -0.5, 0.5,\n\t0.5, 0.5, 0.5,\n\t-0.5, 0.5, 0.5,\n\t-0.5, -0.5, -0.5,\n\t0.5, -0.5, -0.5,\n\t0.5, 0.5, -0.5,\n\t-0.5, 0.5, -0.5]);\n\n\tvar rawColors = new Float32Array([\n 0.4, 0.4, 1.0, 1.0, // Z blue\n 1.0, 0.4, 0.4, 1.0, // X red\n 0.0, 0.0, 0.7, 1.0, // -Z dk blue\n 0.7, 0.0, 0.0, 1.0, // -X dk red\n 0.4, 1.0, 0.4, 1.0, // Y green\n 0.0, 0.7, 0.0, 1.0, // -Y dk green\n]);\n\n\tvar rawNormals = new Float32Array([\n\t0, 0, 1,\n\t1, 0, 0,\n\t0, 0, -1,\n\t-1, 0, 0,\n\t0, 1, 0,\n\t0, -1, 0 ]);\n\n\tvar indices = new Uint16Array([\n\t0, 1, 2, 0, 2, 3, // z face\n\t1, 5, 6, 1, 6, 2, // +x face\n\t5, 4, 7, 5, 7, 6, // -z face\n\t4, 0, 3, 4, 3, 7, // -x face\n\t3, 2, 6, 3, 6, 7, // + y face\n\t4, 5, 1, 4, 1, 0 // -y face\n\t]);\n\n\tvar verticesArray = [];\n\tvar colorsArray = [];\n\tvar normalsArray = [];\n\tfor (var i = 0; i < 36; ++i)\n\t{\n\t\t// for each of the 36 vertices...\n\t\tvar face = Math.floor(i / 6);\n\t\tvar index = indices[i];\n\n\t\t// (x, y, z): three numbers for each point\n\t\tfor (var j = 0; j < 3; ++j)\n\t\t{\n\t\t\tverticesArray.push(rawVertices[3 * index + j]);\n\t\t}\n\n\t\t// (r, g, b, a): four numbers for each point\n\t\tfor (var j = 0; j < 4; ++j)\n\t\t{\n\t\t\tcolorsArray.push(rawColors[4 * face + j]);\n\t\t}\n\n\t\t// three numbers for each point\n\t\tfor (var j = 0; j < 3; ++j)\n\t\t{\n\t\t\tnormalsArray.push(rawNormals[3 * face + j]);\n\t\t}\n\t}\n\n\treturn {\n\t\tvertices: new Float32Array(verticesArray),\n\t\tcolors: new Float32Array(colorsArray),\n\t\tnormals: new Float32Array(normalsArray)\n\t};\n}", "function setupNormals() {\n faces.forEach(function(face) {\n var ia = face[0],\n ib = face[1],\n ic = face[2];\n\n if (normalVectors.length == 0) {\n calculatedNormalVectors[ia].normalize();\n calculatedNormalVectors[ib].normalize();\n calculatedNormalVectors[ic].normalize();\n normals.push(\n calculatedNormalVectors[ia].x, calculatedNormalVectors[ia].y, calculatedNormalVectors[ia].z,\n calculatedNormalVectors[ib].x, calculatedNormalVectors[ib].y, calculatedNormalVectors[ib].z,\n calculatedNormalVectors[ic].x, calculatedNormalVectors[ic].y, calculatedNormalVectors[ic].z);\n } else {\n normals.push(\n normalVectors[ia].x, normalVectors[ia].y, normalVectors[ia].z,\n normalVectors[ib].x, normalVectors[ib].y, normalVectors[ib].z,\n normalVectors[ic].x, normalVectors[ic].y, normalVectors[ic].z\n );\n }\n })\n }", "generate({ width, height, uSpan, vSpan, isUVRepeat = false, flipTextureCoordinateY = false, material }) {\n var positions = [];\n for (let i = 0; i <= vSpan; i++) {\n for (let j = 0; j <= uSpan; j++) {\n positions.push((j / uSpan - 1 / 2) * width);\n positions.push(0);\n positions.push((i / vSpan - 1 / 2) * height);\n }\n }\n var indices = [];\n for (let i = 0; i < vSpan; i++) {\n let degenerate_left_index = 0;\n let degenerate_right_index = 0;\n for (let j = 0; j <= uSpan; j++) {\n indices.push(i * (uSpan + 1) + j);\n indices.push((i + 1) * (uSpan + 1) + j);\n if (j === 0) {\n degenerate_left_index = (i + 1) * (uSpan + 1) + j;\n }\n else if (j === uSpan) {\n degenerate_right_index = (i + 1) * (uSpan + 1) + j;\n }\n }\n indices.push(degenerate_right_index);\n indices.push(degenerate_left_index);\n }\n var normals = [];\n for (let i = 0; i <= vSpan; i++) {\n for (let j = 0; j <= uSpan; j++) {\n normals.push(0);\n normals.push(1);\n normals.push(0);\n }\n }\n var texcoords = [];\n for (let i = 0; i <= vSpan; i++) {\n const i_ = flipTextureCoordinateY ? i : vSpan - i;\n for (let j = 0; j <= uSpan; j++) {\n if (isUVRepeat) {\n texcoords.push(j);\n texcoords.push(i_);\n }\n else {\n texcoords.push(j / uSpan);\n texcoords.push(i_ / vSpan);\n }\n }\n }\n // Check Size\n const attributeCompositionTypes = [_definitions_CompositionType__WEBPACK_IMPORTED_MODULE_1__[\"CompositionType\"].Vec3, _definitions_CompositionType__WEBPACK_IMPORTED_MODULE_1__[\"CompositionType\"].Vec3, _definitions_CompositionType__WEBPACK_IMPORTED_MODULE_1__[\"CompositionType\"].Vec2];\n const attributeSemantics = [_definitions_VertexAttribute__WEBPACK_IMPORTED_MODULE_2__[\"VertexAttribute\"].Position, _definitions_VertexAttribute__WEBPACK_IMPORTED_MODULE_2__[\"VertexAttribute\"].Normal, _definitions_VertexAttribute__WEBPACK_IMPORTED_MODULE_2__[\"VertexAttribute\"].Texcoord0];\n const primitiveMode = _definitions_PrimitiveMode__WEBPACK_IMPORTED_MODULE_3__[\"PrimitiveMode\"].TriangleStrip;\n const attributes = [new Float32Array(positions), new Float32Array(normals), new Float32Array(texcoords)];\n let sumOfAttributesByteSize = 0;\n attributes.forEach(attribute => {\n sumOfAttributesByteSize += attribute.byteLength;\n });\n const indexSizeInByte = indices.length * 2;\n // Create Buffer\n const buffer = _core_MemoryManager__WEBPACK_IMPORTED_MODULE_4__[\"default\"].getInstance().createBufferOnDemand(indexSizeInByte + sumOfAttributesByteSize, this);\n // Index Buffer\n const indicesBufferView = buffer.takeBufferView({ byteLengthToNeed: indexSizeInByte /*byte*/, byteStride: 0, isAoS: false });\n const indicesAccessor = indicesBufferView.takeAccessor({\n compositionType: _definitions_CompositionType__WEBPACK_IMPORTED_MODULE_1__[\"CompositionType\"].Scalar,\n componentType: _definitions_ComponentType__WEBPACK_IMPORTED_MODULE_5__[\"ComponentType\"].UnsignedShort,\n count: indices.length\n });\n for (let i = 0; i < indices.length; i++) {\n indicesAccessor.setScalar(i, indices[i], {});\n }\n // VertexBuffer\n const attributesBufferView = buffer.takeBufferView({ byteLengthToNeed: sumOfAttributesByteSize, byteStride: 0, isAoS: false });\n const attributeAccessors = [];\n const attributeComponentTypes = [];\n attributes.forEach((attribute, i) => {\n attributeComponentTypes[i] = _definitions_ComponentType__WEBPACK_IMPORTED_MODULE_5__[\"ComponentType\"].fromTypedArray(attributes[i]);\n const accessor = attributesBufferView.takeAccessor({\n compositionType: attributeCompositionTypes[i],\n componentType: _definitions_ComponentType__WEBPACK_IMPORTED_MODULE_5__[\"ComponentType\"].fromTypedArray(attributes[i]),\n count: attribute.byteLength / attributeCompositionTypes[i].getNumberOfComponents() / attributeComponentTypes[i].getSizeInBytes()\n });\n accessor.copyFromTypedArray(attribute);\n attributeAccessors.push(accessor);\n });\n const attributeMap = new Map();\n for (let i = 0; i < attributeSemantics.length; i++) {\n attributeMap.set(attributeSemantics[i], attributeAccessors[i]);\n }\n this.setData(attributeMap, primitiveMode, material, indicesAccessor);\n }", "function CalculateSurfaceNormal(X1, X2, X3, Y1, Y2, Y3, Z1, Z2, Z3){\n var U = [];\n U[0] = (X2 - X1);\n U[1] = (Y2 - Y1);\n U[2] = (Z2 - Z1);\n\n var V = [];\n V[0] = (X3 - X1);\n V[1] = (Y3 - Y1);\n V[2]= (Z3 - Z1);\n\n var Normal = [(U[1] * V[2]) - (U[2] * V[1]), (U[2] * V[0]) - (U[0] * V[2]), (U[0] * V[1]) - (U[1] * V[0])];\n return Normal;\n }", "computeNormalForTriangles(v1, v2, v3) {\r\n let sub1 = glMatrix.vec3.create();\r\n let sub2 = glMatrix.vec3.create();\r\n glMatrix.vec3.subtract(sub1, v2, v1);\r\n glMatrix.vec3.subtract(sub2, v3, v1);\r\n let res = glMatrix.vec3.create();\r\n glMatrix.vec3.cross(res, sub1, sub2);\r\n return res;\r\n }", "function calcNormal(a, b, c) {\r\n //ind 3\r\n var Ax = a.x;\r\n var Ay = a.y; \r\n var Az = a.z;\r\n //ind 0\r\n var Bx = b.x; \r\n var By = b.y;\r\n var Bz = b.z;\r\n //ind 1\r\n var Cx = c.x;\r\n var Cy = c.y;\r\n var Cz = c.z; \r\n\r\n //calculate C-B vector\r\n var CBx = Bx-Cx;\r\n var CBy = By-Cy;\r\n var CBz = Bz-Cz;\r\n var CB = new Vector3([CBx, CBy, CBz]);\r\n\r\n //calculate A-B vector\r\n var ABx = Bx-Ax;\r\n var ABy = By-Ay;\r\n var ABz = Bz-Az;\r\n var AB = new Vector3([ABx, ABy, ABz]);\r\n\r\n //calculate cross product ABxCB\r\n var cross1X = (ABy*CBz) - (ABz*CBy);\r\n var cross1Y = (ABz*CBx) - (ABx*CBz);\r\n var cross1Z = (ABx*CBy) - (ABy*CBx);\r\n\r\n var Snorm = new Vector3([cross1X, cross1Y, cross1Z]);\r\n return Snorm; \r\n}", "function makeCube2(){\n var vertexBuf = [];\n var triBuf = [];\n var normBuf = [];\n var vertices = [[0,0,1],[1,0,1],[1,1,1],[0,1,1],[0,0,0],[1,0,0],[1,1,0],[0,1,0]];\n var triangles = [[6,2,3],[3,7,6],[4,0,1],[1,5,4]];\n var normals = [[0,1,0],[0,1,0],[0,-1,0],[0,-1,0],[0,1,0],[0,1,0],[0,-1,0],[0,-1,0]];\n\n for(var i=0; i<vertices.length; i++)\n {\n vertexBuf.push(vertices[i][0],vertices[i][1],vertices[i][2]);\n }\n\n for(var i=0; i<triangles.length; i++)\n {\n triBuf.push(triangles[i][0],triangles[i][1],triangles[i][2]);\n }\n\n for(var i=0; i<normals.length; i++)\n {\n normBuf.push(normals[i][0],normals[i][1],normals[i][2]);\n }\n //triBufSize = triangles.length;\nreturn({vertices:vertexBuf, normals:normBuf, triangles:triBuf, triSize:triangles.length});\n}", "function Disc() {\n\n this.name = \"disc\";\n\n this.numTriangles = 32;\n this.numVertices = this.numTriangles * 3;\n \n\n this.vertices = [this.numVertices];\n this.colors = [this.numVertices];\n this.normals = [this.numVertices]; //normals\n\n\n var vert_colors = [\n vec4(0.0, 0.0, 0.0, 1.0), // black - v0\n vec4(1.0, 0.0, 0.0, 1.0), // red - v1\n vec4(1.0, 1.0, 0.0, 1.0), // yellow - v2\n vec4(0.0, 1.0, 0.0, 1.0), // green - v3\n vec4(0.0, 0.0, 1.0, 1.0), // blue - v4\n vec4(1.0, 0.0, 1.0, 1.0), // magenta - v5\n vec4(1.0, 1.0, 1.0, 1.0), // white - v6\n vec4(0.0, 1.0, 1.0, 1.0) // cyan - v7\n ];\n\n \n for (var i = 0; i < this.numTriangles; i++){\n \n this.vertices[i*6] = vec4(0, 0, 0, 1.0);\n this.vertices[i*6+3] = vec4(0,0,0,1.0);\n var angle1 = (2 * Math.PI * i)/this.numTriangles;\n\n\n this.vertices[i*6+1] = vec4(Math.cos(angle1), Math.sin(angle1), 0, 1.0);\n this.vertices[i*6+4] = vec4(Math.cos(angle1), Math.sin(angle1), 0, 1.0);\n var angle2 = angle1 + 2 * Math.PI/this.numTriangles;\n this.vertices[i*6+2] = vec4(Math.cos(angle2), Math.sin(angle2), 0, 1.0);\n this.vertices[i*6+5] = vec4(Math.cos(angle2), Math.sin(angle2), 0, 1.0);\n\n\n //NORMALS\n //all vectors end with 0 because they're normals\n //since it's a disk we'll go positive and negative\n\n //positive\n this.normals[i*6] = vec4(0,1,0,0);\n this.normals[i*6+1] = vec4(0,1,0,0);\n this.normals[i*6+2] = vec4(0,1,0,0);\n //negative\n this.normals[i*6+3] = vec4(0,-1,0,0);\n this.normals[i*6+4] = vec4(0,-1,0,0);\n this.normals[i*6+5] = vec4(0,-1,0,0);\n }\n \n\n for (var i = 0; i < this.numVertices; i++){\n //this.vertices[i] = unique_vertices[i];\n this.colors[i] = vert_colors[Math.floor(i/3)%2];\n }\n\n\n}", "function calc_normals(verts, inds, strip) {\r\n\tif (strip !== true && strip !== false) { strip = true; }\r\n\tlet normals = new Array(verts.length);\r\n\r\n\t// Start with all vertex normals as <0,0,0,0>\r\n\tfor (let i = 0; i < verts.length; i++) { normals[i] = vec4(0, 0, 0, 0); }\r\n\r\n\t// Calculate the face normals for each triangle then add them to the vertices\r\n\tlet inc = strip ? 1 : 3;\r\n\tfor (let i = 0; i < inds.length - 2; i+=inc) {\r\n\t\tlet j = inds[i], k = inds[i+1], l = inds[i+2];\r\n\t\tlet a = verts[j], b = verts[k], c = verts[l];\r\n\t\tlet face_norm = cross((strip && (i%2) !== 0) ? subtract(a, b) : subtract(b, a), subtract(a, c));\r\n\t\tnormals[j] = add(normals[j], face_norm);\r\n\t\tnormals[k] = add(normals[k], face_norm);\r\n\t\tnormals[l] = add(normals[l], face_norm);\r\n\t}\r\n\r\n\t// Normalize the normals\r\n\tfor (let i = 0; i < verts.length; i++) { normals[i] = normalize(normals[i]); }\r\n\treturn normals;\r\n}", "function getNormals(vertices, indexList) {\n var vertNormals = [];\n for (var i = 0; i < vertices.length; i++) {\n var faceNormals = [];\n for (var j = 0; j < indexList.length; j += 3) {\n if (indexList[j] === i || indexList[j + 1] === i || indexList[j + 2] === i) {\n var threeTimesInd = 3 * indexList[j];\n var p0 = vec3(vertices[threeTimesInd], vertices[threeTimesInd + 1], vertices[threeTimesInd + 2]);\n threeTimesInd = 3 * indexList[j + 1];\n var p1 = vec3(vertices[threeTimesInd], vertices[threeTimesInd + 1], vertices[threeTimesInd + 2]);\n threeTimesInd = 3 * indexList[j + 2];\n var p2 = vec3(vertices[threeTimesInd], vertices[threeTimesInd + 1], vertices[threeTimesInd + 2]);\n var v1 = subtract(p1, p0);\n var v2 = subtract(p2, p0);\n faceNormals.push(cross(v1, v2));\n }\n }\n var vertNormal = vec3(0, 0, 0);\n for (j = 0; j < faceNormals.length; j++) {\n vertNormal = add(vertNormal, faceNormals[j]);\n }\n vertNormal = normalize(vertNormal);\n vertNormals.push(vertNormal);\n }\n\n return vertNormals;\n}", "generateTriangles()\r\n{\r\n //Your code here\r\n var deltaX = (this.maxX - this.minX) / this.div;\r\n var deltaY = (this.maxY - this.minY) / this.div;\r\n\r\n for (var i = 0; i <= this.div; i++) {\r\n for (var j = 0; j <= this.div; j++) {\r\n // Fill the vertexes by interpolating across\r\n this.vBuffer.push(this.minX + deltaX * j);\r\n this.vBuffer.push(this.minY + deltaY * i);\r\n this.vBuffer.push(0); // set the z value to 0 initially for diamond-square\r\n // terrain is flat so normal starts with 0 in x and y\r\n this.nBuffer.push(0);\r\n this.nBuffer.push(0);\r\n this.nBuffer.push(1);\r\n }\r\n }\r\n\r\n for (var i = 0; i < this.div; i++) {\r\n for (var j = 0; j < this.div; j++) {\r\n var vid = i * (this.div + 1) + j;\r\n // fill in the faces\r\n this.fBuffer.push(vid);\r\n this.fBuffer.push(vid + 1);\r\n this.fBuffer.push(vid + this.div + 1);\r\n\r\n this.fBuffer.push(vid + 1);\r\n this.fBuffer.push(vid + 1 + this.div + 1);\r\n this.fBuffer.push(vid + this.div + 1);\r\n }\r\n }\r\n this.numVertices = this.vBuffer.length/3;\r\n this.numFaces = this.fBuffer.length/3;\r\n // Do the algorithm and then update the normals based on how the diamond square algorithm worked\r\n this.diamondSquare();\r\n this.updateVertexNormals();\r\n}", "set DepthNormals(value) {}", "function link( geoms ) {\r\n\r\n const g = new THREE.BufferGeometry( );\r\n \r\n g.faceCounts = [];\r\n g.positionCounts = [];\r\n let faceCount = 0;\r\n let positionCount = 0;\r\n \r\n for ( let i = 0; i < geoms.length; i ++ ) {\r\n \r\n g.faceCounts[ i ] = geoms[ i ].index.array.length / 3;\r\n faceCount += g.faceCounts[ i ];\r\n \r\n g.positionCounts[ i ] = geoms[ i ].attributes.position.count;\r\n positionCount += g.positionCounts[ i ];\r\n \r\n }\r\n \r\n const indices = new Uint32Array( faceCount * 3 );\r\n const positions = new Float32Array( positionCount * 3 );\r\n const normals = new Float32Array( positionCount * 3 );\r\n const uvs = new Float32Array( positionCount * 2 );\r\n \r\n g.setIndex( new THREE.BufferAttribute( indices, 1 ) );\t\r\n g.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );\r\n g.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );\r\n g.setAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );\r\n \r\n let indOffs = 0;\r\n let indVal = 0;\r\n let posOffs = 0;\r\n let uvsOffs = 0;\r\n \r\n for ( let i = 0; i < geoms.length; i ++ ) {\r\n \r\n for ( let j = 0; j <= geoms[ i ].index.array.length; j ++ ) {\r\n \r\n indices[ j + indOffs ] = indVal + geoms[ i ].index.array[ j ] ;\r\n \r\n }\r\n \r\n for ( let j = 0; j < geoms[ i ].attributes.position.count * 3; j ++ ) {\r\n \r\n positions[ j + posOffs ] = geoms[ i ].attributes.position.array[ j ];\r\n\r\n }\r\n \r\n for ( let j = 0; j < geoms[ i ].attributes.normal.count * 3; j ++ ) {\r\n \r\n normals[ j + posOffs ] = geoms[ i ].attributes.normal.array[ j ];\r\n\r\n }\r\n \r\n for ( let j = 0; j < geoms[ i ].attributes.uv.count * 2; j ++ ) {\r\n \r\n uvs[ j + uvsOffs ] = geoms[ i ].attributes.uv.array[ j ];\r\n \r\n }\r\n \r\n g.addGroup( indOffs, g.faceCounts[ i ] * 3, i ); // multi material groups\r\n \r\n indOffs += g.faceCounts[ i ] * 3;\r\n indVal += g.positionCounts[ i ];\r\n posOffs += g.positionCounts[ i ] * 3;\r\n uvsOffs += g.positionCounts[ i ] * 2;\r\n \r\n }\r\n \r\n for ( let i = 0; i < geoms.length; i ++ ) {\r\n \r\n geoms[ i ].dispose( ); // Only if the individual geometries are not required.\r\n \r\n }\r\n \r\n return g;\r\n\r\n}", "function makeSphere(ctx, radius, lats, longs) {\n\tvar geometryData = [];\n\tvar normalData = [];\n\tvar texCoordData = [];\n\tvar indexData = [];\n\n\tfor (var latNumber = 0; latNumber <= lats; ++latNumber) {\n\t\tfor (var longNumber = 0; longNumber <= longs; ++longNumber) {\n\t\t\tvar theta = latNumber * Math.PI / lats;\n\t\t\tvar phi = longNumber * 2 * Math.PI / longs;\n\t\t\tvar sinTheta = Math.sin(theta);\n\t\t\tvar sinPhi = Math.sin(phi);\n\t\t\tvar cosTheta = Math.cos(theta);\n\t\t\tvar cosPhi = Math.cos(phi);\n\n\t\t\tvar x = cosPhi * sinTheta;\n\t\t\tvar y = cosTheta;\n\t\t\tvar z = sinPhi * sinTheta;\n\t\t\tvar u = 1 - (longNumber / longs);\n\t\t\tvar v = latNumber / lats;\n\n\t\t\tnormalData.push(x);\n\t\t\tnormalData.push(y);\n\t\t\tnormalData.push(z);\n\t\t\ttexCoordData.push(u);\n\t\t\ttexCoordData.push(v);\n\t\t\tgeometryData.push(radius * x);\n\t\t\tgeometryData.push(radius * y);\n\t\t\tgeometryData.push(radius * z);\n\t\t}\n\t}\n\n\tfor (var latNumber = 0; latNumber < lats; ++latNumber) {\n\t\tfor (var longNumber = 0; longNumber < longs; ++longNumber) {\n\t\t\tvar first = (latNumber * (longs + 1)) + longNumber;\n\t\t\tvar second = first + longs + 1;\n\t\t\tindexData.push(first);\n\t\t\tindexData.push(second);\n\t\t\tindexData.push(first + 1);\n\n\t\t\tindexData.push(second);\n\t\t\tindexData.push(second + 1);\n\t\t\tindexData.push(first + 1);\n\t\t}\n\t}\n\n\tvar retval = {};\n\n\tretval.normalObject = ctx.createBuffer();\n\tctx.bindBuffer(ctx.ARRAY_BUFFER, retval.normalObject);\n\tctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(normalData), ctx.STATIC_DRAW);\n\n\tretval.texCoordObject = ctx.createBuffer();\n\tctx.bindBuffer(ctx.ARRAY_BUFFER, retval.texCoordObject);\n\tctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(texCoordData), ctx.STATIC_DRAW);\n\n\tretval.vertexObject = ctx.createBuffer();\n\tctx.bindBuffer(ctx.ARRAY_BUFFER, retval.vertexObject);\n\tctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array(geometryData), ctx.STATIC_DRAW);\n\n\tretval.numIndices = indexData.length;\n\tretval.indexObject = ctx.createBuffer();\n\tctx.bindBuffer(ctx.ELEMENT_ARRAY_BUFFER, retval.indexObject);\n\tctx.bufferData(ctx.ELEMENT_ARRAY_BUFFER, new Uint16Array(indexData), ctx.STREAM_DRAW);\n\tretval.indexType = ctx.UNSIGNED_SHORT;\n\n\treturn retval;\n}", "function getNormals(NormalNode) {\n var mappingType = NormalNode.MappingInformationType;\n var referenceType = NormalNode.ReferenceInformationType;\n var buffer = NormalNode.Normals.a;\n var indexBuffer = [];\n if (referenceType === 'IndexToDirect') {\n if ('NormalIndex' in NormalNode) {\n indexBuffer = NormalNode.NormalIndex.a;\n }\n else if ('NormalsIndex' in NormalNode) {\n indexBuffer = NormalNode.NormalsIndex.a;\n }\n }\n return {\n dataSize: 3,\n buffer: buffer,\n indices: indexBuffer,\n mappingType: mappingType,\n referenceType: referenceType\n };\n}", "updateVertexNormals() {\r\n var idx = 0;\r\n var vec3_cross_product = vec3.create();\r\n var first = vec3.create();\r\n var second = vec3.create();\r\n var third = vec3.create();\r\n var sub1 = vec3.create();\r\n var sub2 = vec3.create();\r\n var normalized = vec3.create();\r\n\r\n while (idx < this.vBuffer.length) {\r\n // Index through the buffer and find the vertexes needed for the algorithm\r\n vec3.fromValues(first, this.vBuffer[idx], this.vBuffer[idx + 1], this.vBuffer[idx + 2]);\r\n vec3.fromValues(second, this.vBuffer[idx + 3], this.vBuffer[idx + 4], this.vBuffer[idx + 5]);\r\n vec3.fromValues(third, this.vBuffer[idx + 6], this.vBuffer[idx + 7], this.vBuffer[idx + 8]);\r\n // Get the 2 vectors for cross product\r\n vec3.subtract(sub1, second, first);\r\n vec3.subtract(sub2, third, first);\r\n\r\n // Compute the normal vector\r\n vec3.cross(vec3_cross_product, sub1, sub2);\r\n vec3.normalize(normalized, vec3_cross_product);\r\n\r\n // Insert it at the 3 locations in the nBuffer\r\n this.nBuffer[idx] = normalized[0];\r\n this.nBuffer[idx + 1] += normalized[1];\r\n this.nBuffer[idx + 2] += normalized[2];\r\n this.nBuffer[idx + 3] += normalized[0];\r\n this.nBuffer[idx + 4] += normalized[1];\r\n this.nBuffer[idx + 5] += normalized[2];\r\n this.nBuffer[idx + 6] += normalized[0];\r\n this.nBuffer[idx + 8] += normalized[2];\r\n this.nBuffer[idx + 7] += normalized[1];\r\n\r\n idx = idx + 9;\r\n }\r\n }", "function getDataLayout(values){\n var normalsPresent = false;\n var colorsPresent = false;\n \n var VERTS = 0;\n var VERTS_COLS = 1;\n var VERTS_NORMS = 2;\n var VERTS_COLS_NORMS = 3;\n \n // first check if there are 9 values, which would mean we have\n // xyz rgb and normals\n \n // We can do this by counting the number of whitespace on the first line\n var i = 0;\n var numSpaces = 0;\n do{\n i++;\n if(values[i] == \" \"){\n numSpaces++;\n }\n }while(values[i] != '\\n');\n \n // Vertices, Colors, Normals:\n // 1.916 -2.421 -4.0 64 32 16 -0.3727 -0.2476 -0.8942\n if(numSpaces === 8){\n return VERTS_COLS_NORMS;\n }\n \n // Just vertices:\n // 1.916 -2.421 -4.0339\n if(numSpaces == 2){\n return VERTS;\n }\n \n var str = \"\";\n \n //\n //\n for(i = 0; i < 500; i++){\n str += values[i];\n }\n \n var str_split = str.split(/\\s+/);\n var data = [];\n \n for(var i=3; i < str_split.length;){\n data.push(str_split[i++]);\n data.push(str_split[i++]);\n data.push(str_split[i++]);\n i+=3;\n }\n \n for(var i=0; i < data.length; i++){\n if(data[i] < 0 || data[i] > 255){\n normalsPresent = true;\n return VERTS_NORMS;\n }\n }\n \n // Vertices and Normals:\n // 1.916 -2.421 -4.0 -0.3727 -0.2476 -0.8942\n return VERTS_COLS;\n }", "function getNormal(p1, p2) {\n if (p1[0] === p2[0] && p1[1] === p2[1]) {\n return [1, 0, 0];\n }\n\n var degrees2radians = Math.PI / 180;\n\n var lon1 = degrees2radians * p1[0];\n var lon2 = degrees2radians * p2[0];\n var lat1 = degrees2radians * p1[1];\n var lat2 = degrees2radians * p2[1];\n\n var a = Math.sin(lon2 - lon1) * Math.cos(lat2);\n var b = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);\n\n return __WEBPACK_IMPORTED_MODULE_5_gl_vec3_normalize___default()([], [b, 0, -a]);\n}", "get normalSmoothingAngle() {}", "function getNormal(v1, v2, v3) {\r\n const s1 = new THREE.Vector3().add(v1).sub(v2);\r\n const s2 = new THREE.Vector3().add(v2).sub(v3);\r\n return new THREE.Vector3().crossVectors(s2, s1);\r\n}", "function setFaceNormals() {\r\n\tfor (var i = 0; i < pointsArray.length; i += 3) {\r\n\t\tvar normal = normalNewell(pointsArray[i], pointsArray[i + 1], pointsArray[i + 2]);\r\n\t\tfor (var j = 0; j < 3; j++) {\r\n\t\t\tfaceNormals.push(normal);\r\n\t\t}\r\n\t}\r\n}", "function getVertices() {\n var vertices = [];\n vertices.push(vec4(0.0, -0.5, 0.0, 1.0));\n vertices.push(vec4(0.0, 0.5, 0.0, 1.0));\n vertices.push(vec4(0.5, 0.0, 0.0, 1.0));\n vertices.push(vec4(0.75, 0.0, -0.75, 1.0));\n vertices.push(vec4(0.0, 0.0, -0.5, 1.0));\n vertices.push(vec4(-0.75, 0.0, -0.75, 1.0));\n vertices.push(vec4(-0.5, 0.0, 0.0, 1.0));\n vertices.push(vec4(-0.75, 0.0, 0.75, 1.0));\n vertices.push(vec4(0.0, 0.0, 0.5, 1.0));\n vertices.push(vec4(0.75, 0.0, 0.75, 1.0));\n return vertices;\n}", "static appendTriangleNormals(geo) {\n //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n // Make sure there is enough space to for normals for each vertex\n // if not, append extra space to normals.\n let i;\n const iAry = geo.indices;\n const vAry = geo.vertices;\n const nAry = geo.normals;\n const vCnt = vAry.length;\n const nCnt = nAry.length;\n if (vCnt > nCnt) {\n for (i = nCnt; i < vCnt; i++)\n nAry.push(0);\n }\n //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n // Accumlate the normal direction for each vertex.\n const a = new Vec3();\n const b = new Vec3();\n const c = new Vec3();\n const n = new Vec3();\n const aSeg = new Vec3();\n const bSeg = new Vec3();\n const cSeg = new Vec3();\n let ai, bi, ci;\n for (i = 0; i < geo.indices.length; i += 3) {\n // Flat Vertex Index from Indices for each triangel face.\n ai = 3 * iAry[i];\n bi = 3 * iAry[i + 1];\n ci = 3 * iAry[i + 2];\n // Grab the vertex position\n a.fromBuf(vAry, ai);\n b.fromBuf(vAry, bi);\n c.fromBuf(vAry, ci);\n // Get two side of a triangle and cross product to get face direction\n bSeg.fromSub(b, a);\n cSeg.fromSub(c, a);\n aSeg.fromCross(bSeg, cSeg);\n // Add new normal to the old ones for each point in triangle.\n n.fromBuf(nAry, ai).add(aSeg).toBuf(nAry, ai);\n n.fromBuf(nAry, bi).add(aSeg).toBuf(nAry, bi);\n n.fromBuf(nAry, ci).add(aSeg).toBuf(nAry, ci);\n }\n //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n // Average Out All Normal Values by normalizing it\n for (i = 0; i < nAry.length; i += 3) {\n n.fromBuf(nAry, i).norm().toBuf(nAry, i);\n }\n }", "AABB3(values) {\n return new Float32Array(values || 6);\n }", "function importData(data) {\n // // geometry\n // var geometry = new THREE.BufferGeometry();\n\n // // attributes\n // var positions = new Float32Array( MAX_POINTS * 3 ); // 3 vertices per point\n // geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );\n var geometry = new THREE.Geometry();\n \n maxR2 = 0;\n\n var edgesAddedToMesh = {};\n\n for (var f=0; f < data.faces.length; f++) {\n var face = data.faces[f];\n for (var v=0; v < face.length; v++) {\n var nv = (v+1 >= face.length) ? 0 : v+1;\n // Check: is the reversed edge already added? If so don't add it again.\n if ([face[nv], face[v]] in edgesAddedToMesh) {\n // console.log(\"Edge already added\", face[v], face[nv]);\n continue;\n }\n // Add this edge.\n edgesAddedToMesh[[face[v], face[nv]]] = true;\n\n var v1 = data.vertices[face[v]], v2 = data.vertices[face[nv]];\n updateMaxR(v1);\n geometry.vertices.push(new THREE.Vector3(v1[0], v1[1], v1[2]));\n // was: new (Function.prototype.bind.apply(THREE.Vector3, data.vertices[face[v]-1])));\n updateMaxR(v2);\n geometry.vertices.push(new THREE.Vector3(v2[0], v2[1], v2[2]));\n // was: new (Function.prototype.bind.apply(THREE.Vector3, data.vertices[face[nv]-1])));\n }\n }\n\n maxR = Math.sqrt(maxR2);\n console.log(\"maxR: \", maxR);\n\n var material = new THREE.LineBasicMaterial( { color: 0xff888888, linewidth: 6 } ); // 0xff888888\n sphere = new THREE.LineSegments( geometry, material );\n\n scene.add(sphere);\n\n autoRotating = true; // autorotate at first\n}", "getVertexNormals() {\n return this.getVertices();\n }", "function getMorphTriangleNormals(morph, ia, ib, ic, a, b, c) {\n var iax, ibx, icx;\n var normals1 = morph.targets[morph.key1].normals;\n var normals2 = morph.targets[morph.key2].normals;\n if (morph.compressedNormals) {\n iax = ia * 2;\n ibx = ib * 2;\n icx = ic * 2;\n SceneJS_math_octDecodeVec2(normals1.subarray(iax, iax + 2), a1);\n SceneJS_math_octDecodeVec2(normals2.subarray(iax, iax + 2), a2);\n SceneJS_math_octDecodeVec2(normals1.subarray(ibx, ibx + 2), b1);\n SceneJS_math_octDecodeVec2(normals2.subarray(ibx, ibx + 2), b2);\n SceneJS_math_octDecodeVec2(normals1.subarray(icx, icx + 2), c1);\n SceneJS_math_octDecodeVec2(normals2.subarray(icx, icx + 2), c2);\n } else {\n iax = ia * 3;\n ibx = ib * 3;\n icx = ic * 3;\n a1.set(normals1.subarray(iax, iax + 3));\n a2.set(normals2.subarray(iax, iax + 3));\n b1.set(normals1.subarray(ibx, ibx + 3));\n b2.set(normals2.subarray(ibx, ibx + 3));\n c1.set(normals1.subarray(icx, icx + 3));\n c2.set(normals2.subarray(icx, icx + 3));\n }\n vec3.lerp(a, a1, a2, morph.factor);\n vec3.lerp(b, b1, b2, morph.factor);\n vec3.lerp(c, c1, c2, morph.factor);\n return true; // normals exist\n }", "function getNormal(object) {\n\tvar Pitch = object.transform.rotationX;\n\tvar Yaw = object.transform.rotationY;\n\tvar Roll = object.transform.rotationZ;\n \n\tvar hv_x = Reactive.cos(Pitch).mul(Reactive.cos(Roll)).mul(Reactive.sin(Yaw)).add(Reactive.sin(Pitch).mul(Reactive.sin(Roll)));\n\tvar hv_y = Reactive.cos(Roll).neg().mul(Reactive.sin(Pitch)).add(Reactive.cos(Pitch).mul(Reactive.sin(Yaw)).mul(Reactive.sin(Roll)));\n\tvar hv_z = Reactive.cos(Pitch).mul(Reactive.cos(Yaw));\n\n return Reactive.vector(hv_x, hv_y, hv_z);\n}", "function createSphereVertices(radius,numRings,vertPerRing) {\n\tvar r = radius\n\tnumRings = numRings+1;\n\tvar phi = Math.PI/numRings;\n\tvar theta = 2*Math.PI/vertPerRing;\n\tvar vertices = []\n\tfor (var i = 0; i<numRings+1; i++) { //Should include \"ring\" for top/bot points\n\t\tvertices.push([])\n\t\t\tfor (var j = 0; j<vertPerRing; j++) {\n\t\t\t\tvar y = r*Math.cos(i*phi)\n\t\t\t\tvar x = r*Math.sin(i*phi)*Math.cos(j*theta);// + (i/2)*theta)\n\t\t\t\tvar z = r*Math.sin(i*phi)*Math.sin(j*theta);// + (i/2)*theta)\n\t\t\t\t\n\t\t\t\tvertices[i].push([x,y,z])\n\t\t\t}\n\t}\n\tvar triangle_strip = [];\n\tfor (var i = 0; i<numRings; i++) {\n\t\tvar li = vertices[i].length\n\t\tvar li1 = vertices[i+1].length\n\t\ttriangle_strip = triangle_strip.concat(vertices[i][li-1])\n\t\ttriangle_strip = triangle_strip.concat(vertices[i+1][li1-1])\n\t\tfor (var j = 0; j<vertPerRing; j++) {\n\t\t\ttriangle_strip = triangle_strip.concat(vertices[i][j])\n\t\t\ttriangle_strip = triangle_strip.concat(vertices[i+1][j])\n\t\t}\n\t\ttriangle_strip = triangle_strip.concat(vertices[i][0])\n\t\ttriangle_strip = triangle_strip.concat(vertices[i+1][0])\n\t}\n\tvar numItems = triangle_strip.length/3\t//based on 3-vector\n\treturn [triangle_strip,numItems]\n}", "function getNormals(NormalNode) {\n\n var mappingType = NormalNode.properties.MappingInformationType;\n var referenceType = NormalNode.properties.ReferenceInformationType;\n var buffer = NormalNode.subNodes.Normals.properties.a;\n var indexBuffer = [];\n if (referenceType === 'IndexToDirect') {\n\n if ('NormalIndex' in NormalNode.subNodes) {\n\n indexBuffer = NormalNode.subNodes.NormalIndex.properties.a;\n\n } else if ('NormalsIndex' in NormalNode.subNodes) {\n\n indexBuffer = NormalNode.subNodes.NormalsIndex.properties.a;\n\n }\n\n }\n\n return {\n dataSize: 3,\n buffer: buffer,\n indices: indexBuffer,\n mappingType: mappingType,\n referenceType: referenceType\n };\n\n }", "generateTriangles()\n{\n //Your code here\n var dx = (this.maxX - this.minX) / this.div;\n var dy = (this.maxY - this.minY) / this.div;\n \n // Push vertex buffer\n for(var i = 0; i <= this.div; i ++)\n for(var j = 0; j <= this.div; j ++){\n this.vBuffer.push(this.minX + dx * j);\n this.vBuffer.push(this.minY + dy * i);\n this.vBuffer.push(0);\n }\n // Set Normal Buffer\n for(var i = 0; i <= this.div; i ++)\n for(var j = 0; j <= this.div; j ++){\n this.nBuffer.push(0);\n this.nBuffer.push(0);\n this.nBuffer.push(0);\n }\n for(var i = 0; i < this.div; i ++)\n for(var j = 0; j < this.div; j ++){\n \n // Revised div\n var rdiv = this.div + 1;\n // Revised vindex\n var vindex = i * rdiv + j;\n \n\n this.fBuffer.push(vindex);\n this.fBuffer.push(vindex + 1);\n this.fBuffer.push(vindex + rdiv);\n\n this.fBuffer.push(vindex + 1);\n this.fBuffer.push( vindex + 1 + rdiv );\n this.fBuffer.push( vindex + rdiv );\n\n }\n this.numVertices = this.vBuffer.length/3;\n this.numFaces = this.fBuffer.length/3;\n}", "getNormal(){\n if (this.normal == null) {\n this.calculateNormal();\n }\n return vec3.clone(this.normal);\n }", "function computeVertexNormal(vertexX, vertexY, vertexZ){\n //normalize\n var scale = computeScaleForLength(vertexX, vertexY, vertexZ, 1);\n var normal = []\n normal.push(vertexX * scale);\n normal.push(vertexY * scale);\n normal.push(vertexZ * scale);\n return normal;\n}", "function getNormal(p1, p2) {\n var p1x = Object(__WEBPACK_IMPORTED_MODULE_3__lib_utils__[\"f\" /* get */])(p1, 0);\n var p1y = Object(__WEBPACK_IMPORTED_MODULE_3__lib_utils__[\"f\" /* get */])(p1, 1);\n var p2x = Object(__WEBPACK_IMPORTED_MODULE_3__lib_utils__[\"f\" /* get */])(p2, 0);\n var p2y = Object(__WEBPACK_IMPORTED_MODULE_3__lib_utils__[\"f\" /* get */])(p2, 1);\n\n if (p1x === p2x && p1y === p2y) {\n return [1, 0, 0];\n }\n\n var degrees2radians = Math.PI / 180;\n var lon1 = degrees2radians * p1x;\n var lon2 = degrees2radians * p2x;\n var lat1 = degrees2radians * p1y;\n var lat2 = degrees2radians * p2y;\n var a = Math.sin(lon2 - lon1) * Math.cos(lat2);\n var b = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);\n return __WEBPACK_IMPORTED_MODULE_1_gl_vec3_normalize___default()([], [b, 0, -a]);\n}", "function computeTriangleNormals(positions, indices) {\n\n const retVal = []\n //CCconsole.log(\"computeVertexNormals \")\n // //CCconsole.log(\"positions:\", positions)\n // //CCconsole.log(\"indices:\", indices)\n for (var i = 0; i < indices.length; i += 3) {\n // //CCconsole.log(\"triangle \" + (i / 3) + \"@\" + i)\n const vs = getTriangleVertices(positions, indices, i)\n const edges = [\n bv3.minus(vs[1], vs[0]),\n bv3.minus(vs[2], vs[1]),\n bv3.minus(vs[0], vs[2])\n ]\n const normal1 = bv3.normal(edges[0], edges[1])\n // //CCconsole.log(\"normal1:\", normal1)\n retVal.push(normal1)\n\n // // check that the 2 other normals are the same!\n // const normal2 = this.normal(edges[1], edges[2])\n // const normal3 =this. normal(edges[2], edges[0])\n // //CCconsole.log(\"normal2:\",normal2)\n // //CCconsole.log(\"normal3:\",normal3)\n\n }\n\n return retVal\n}", "function circle_verts(steps, x, y)\r\n{\r\n var vert_qty = steps + 2; \r\n var step_arc = 360 / steps;\r\n var angle = 0;\r\n var radius = 0.5;\r\n\r\n var circle = [ 0.0, 0.0 ];\r\n\r\n // Step through the circle calculating coords one vert at a time.\r\n for( var vert_cur = 1; vert_cur < vert_qty; vert_cur++ )\r\n {\r\n var i = vert_cur * 2;\r\n var theta = (Math.PI / 180.0) * angle; // Winners use radians...\r\n\r\n // Convert from polar to cartesian coordinates and store point.\r\n circle.push(radius * Math.cos(theta)) + x;\r\n circle.push(radius * Math.sin(theta)) + y;\r\n\r\n angle = angle + step_arc; // Update angle for next itteration.\r\n }\r\n\r\n return new Float32Array(circle);\r\n}", "function createSphere() {\n var geometry = new THREE.Geometry({\n colorsNeedUpdate : true\n }); // define a blank geometry\n var material = new THREE.MeshBasicMaterial(\n {\n transparency: true,\n opacity: 1.0,\n wireframeLinewidth: 0.5,\n color: 0x444444\n }\n );\n material.wireframe = true;\n\n sphere_radius_3D_S = 60; // test value\n sphere_wSegs_3D_S = 60; // test value 纬带数(纬线数+1)\n sphere_hSegs_3D_S = 60; // test value 经带数\n\n // 【生成所有顶点位置】 latNumber:纬线计数器\n var totalVertex = (sphere_wSegs_3D_S+1)*(sphere_hSegs_3D_S+1);\n for (var latNumber=0; latNumber<=sphere_wSegs_3D_S; latNumber++) {\n var theta = latNumber * Math.PI / sphere_wSegs_3D_S;\n var sinTheta = Math.sin(theta);\n var cosTheta = Math.cos(theta);\n for (var longNumber=0; longNumber<=sphere_hSegs_3D_S; longNumber++) {\n var phi = longNumber * 2 * Math.PI / sphere_hSegs_3D_S;\n var sinPhi = Math.sin(phi);\n var cosPhi = Math.cos(phi);\n // 球坐标系映射到xyz\n var x = sphere_radius_3D_S * sinTheta * cosPhi;\n var y = sphere_radius_3D_S * sinTheta * sinPhi;\n var z = sphere_radius_3D_S * cosTheta;\n var p = new THREE.Vector3(x, y, z);\n geometry.vertices.push(p);\n }\n }\n // 为了把这些顶点缝合到一起,需要【建立三角面片索引列表】\n var indexData = [];\n for (var latNumber = 0; latNumber < sphere_wSegs_3D_S; latNumber++) {\n for (var longNumber = 0; longNumber < sphere_hSegs_3D_S; longNumber++) {\n var first = (latNumber * (sphere_hSegs_3D_S + 1)) + longNumber;\n var second = first + sphere_hSegs_3D_S + 1;\n indexData.push(first);\n indexData.push(second);\n indexData.push(first + 1);\n indexData.push(second);\n indexData.push(second + 1);\n indexData.push(first + 1);\n // 测试用:调整了顶点顺序\n // indexData.push(first + 1);\n // indexData.push(second);\n // indexData.push(second + 1);\n }\n }\n // create faces\n for (var vertexCounter = 0; vertexCounter<indexData.length; vertexCounter+=3) {\n // var face = new THREE.Face3(\n // indexData[vertexCounter],\n // indexData[vertexCounter+1],\n // indexData[vertexCounter+2]\n // );\n var index1 = indexData[vertexCounter];\n var index2 = indexData[vertexCounter+1];\n var index3 = indexData[vertexCounter+2];\n var face = new THREE.Face3(\n index1,\n index2,\n index3\n );\n\n //着色方案1:仅用三种颜色测试\n // var color1 = findColor2(index1);//顶点1颜色\n // var color2 = findColor2(index2);//顶点2颜色\n // var color3 = findColor2(index3);//顶点3颜色\n\n // 着色方案2:灰度→彩色映射\n // 尚未测试\n // var color1 = trans_R( gray_scale(index1,totalVertex) );\n // var color2 = trans_G( gray_scale(index2,totalVertex) );\n // var color3 = trans_B( gray_scale(index3,totalVertex) );\n\n // 着色方案3:随机颜色\n // var color1 = new THREE.Color(0xFFFFFF * Math.random());//顶点1颜色——红色\n // var color2 = new THREE.Color(0xFFFFFF * Math.random());//顶点2颜色——绿色\n // var color3 = new THREE.Color(0xFFFFFF * Math.random());//顶点3颜色——蓝色\n // var color1 = new THREE.Color(getColor());//顶点1颜色——红色 产生随机色の方法2\n // var color2 = new THREE.Color(getColor());//顶点2颜色——绿色\n // var color3 = new THREE.Color(getColor());//顶点3颜色——蓝色\n\n // 着色方案4:随顶点索引数规律变化\n var color1 = findColor(index1,totalVertex);//顶点1颜色——红色\n var color2 = findColor(index2,totalVertex);//顶点2颜色——绿色\n var color3 = findColor(index3,totalVertex);//顶点3颜色——蓝色\n\n face.vertexColors.push(color1, color2, color3);//定义三角面三个顶点的颜色\n geometry.faces.push(face);\n }\n\n sphmat_3D_S=new THREE.MeshBasicMaterial({\n vertexColors: THREE.VertexColors,//以顶点颜色为准\n //vertexColors: geometry.colors,//以顶点颜色为准\n side: THREE.DoubleSide,//两面可见\n transparent: true,\n opacity: 1.0\n });//材质对象\n\n // create sphere and add it to scene\n sphere_3D_S = new THREE.Mesh(geometry,sphmat_3D_S);//网格模型对象\n scene_3D_S.add(sphere_3D_S); //网格模型添加到场景中\n}", "function prepareTeapot() {\n\tfor (var i = 0; i < triangles.length; i+=9) {\n\t\tindices.push(triangles[i]-1, triangles[i+3]-1, triangles[i+6]-1); \n\t}\n\t\n\t//Recalculate normals\n\tvar vertLength = vertices.length / 3;\n\tindexedNormals = new Array(vertLength).fill(vec3(0,0,0));\n\t//console.log(\"Len: \" + indexedNormals.length + \" vertL: \" + vertLength);\n\tfor(var i = 2; i < triangles.length; i+=3)\n\t{\n\t\tvar selectedNorm = (triangles[i] - 1) * 3;\n\t\t\n\t\tvar normal = vec3(normals[selectedNorm], normals[selectedNorm + 1], normals[selectedNorm + 2]);\n\t\t\n\t\tif(indexedNormals[triangles[i - 2] - 1] == undefined)\n\t\t\tindexedNormals[triangles[i - 2] - 1] = normal;\n\t\telse\n\t\t\tindexedNormals[triangles[i - 2] - 1] = add(normal, indexedNormals[triangles[i - 2] - 1]);\n\t}\n\t\n\t//Normalize normals\n\tfor(var i = 0; i < indexedNormals.length; i++)\n\t{\n\t\tindexedNormals[i] = normalize(indexedNormals[i]);\n\t\t//console.log(\"[\" + i + \"]: \" + indexedNormals[i]);\n\t}\n\t\n\t//Recalculate texcoords\n\tindexedTexCoords = new Array(vertLength);\n\tfor(var i = 1; i < triangles.length; i+=3)\n\t{\n\t\tvar selectedTexc = (triangles[i] - 1) * 2;\n\t\t\n\t\tvar texCoordinate = vec2(texcoords[selectedTexc], texcoords[selectedTexc + 1]);\n\t\t\n\t\tif(indexedTexCoords[triangles[i - 1] - 1] == undefined)\n\t\t\tindexedTexCoords[triangles[i - 1] - 1] = texCoordinate;\n\t}\n}", "makeGrid() {\n\t\tlet positions = [];\n\t\tlet normals = [];\n\t\tlet length = 1000;\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tpositions.push(-(length - 1.0) / 2.0); // x\n\t\t\tpositions.push(0.0); // y\n\t\t\tpositions.push((length - 1.0) / 2.0 - i); // z\n\n\t\t\tnormals.push(0);\n\t\t\tnormals.push(1);\n\t\t\tnormals.push(0);\n\n\t\t\tpositions.push((length - 1.0) / 2.0); // x\n\t\t\tpositions.push(0.0); // y\n\t\t\tpositions.push((length - 1.0) / 2.0 - i); // z\n\n\t\t\tnormals.push(0);\n\t\t\tnormals.push(1);\n\t\t\tnormals.push(0);\n\t\t}\n\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tpositions.push(i - (length - 1.0) / 2.0); // x\n\t\t\tpositions.push(0.0); // y\n\t\t\tpositions.push((length - 1.0) / 2.0); // z\n\n\t\t\tnormals.push(0);\n\t\t\tnormals.push(1);\n\t\t\tnormals.push(0);\n\n\t\t\tpositions.push(i - (length - 1.0) / 2.0); // x\n\t\t\tpositions.push(0.0); // y\n\t\t\tpositions.push(-(length - 1.0) / 2.0); // z\n\n\t\t\tnormals.push(0);\n\t\t\tnormals.push(1);\n\t\t\tnormals.push(0);\n\t\t}\n\n\t\tlet plane = new Object3d();\n\t\tlet params = gAssetManager.makeModelParams();\n\t\tparams.positions = positions;\n\t\tparams.normals = normals;\n\t\tlet indexBuffer = [];\n\t\tfor (let i = 0; i < 4 * length; i++) indexBuffer.push(i);\n\t\tplane.setModel(\n\t\t\tgAssetManager.makeModelData(params, indexBuffer, \"LINES\")\n\t\t);\n\t\tplane.setMaterial(new DefaultMaterial([0.5, 0.3, 0.5]));\n\n\t\treturn plane;\n\t}", "constructor({ eta = 0.1, phi = 0.1, deta = 0.025, dphi = 0.025, rmin = 20, rmax = 50 }) {\n super();\n this.parameters = { eta, phi, deta, dphi, rmin, rmax };\n this.type = 'GeoTrd3Buffer';\n \n // helper arrays\n let vertices = [], // 3 entries per vector\n \tindices = []; // 1 entry per index, 3 entries form face3\n\n\t\tlet theta1 = ( Math.atan( Math.exp( ( -( eta - deta ) ) ) ) * 2 ),\n\t\t\ttheta2 = ( Math.atan( Math.exp( ( -( eta + deta ) ) ) ) * 2 ),\n\t\t\tphi1 = phi - dphi,\n\t\t\tphi2 = phi + dphi;\n\n\t\t// four vertices, upper half\n\t\tvertices.push(\trmax * Math.cos( phi2 ), rmax * Math.sin( phi2 ), rmax / Math.tan( theta1 ),\n\t\t\t\t\t\trmax * Math.cos( phi1 ), rmax * Math.sin( phi1 ), rmax / Math.tan( theta1 ),\n\t\t\t\t\t\trmax * Math.cos( phi1 ), rmax * Math.sin( phi1 ), rmax / Math.tan( theta2 ),\n\t\t\t\t\t\trmax * Math.cos( phi2 ), rmax * Math.sin( phi2 ), rmax / Math.tan( theta2 ) );\n\n\t\t// four vertices, lower half\n\t\tvertices.push(\trmin * Math.cos( phi2 ), rmin * Math.sin( phi2 ), rmin / Math.tan( theta1 ),\n\t\t\t\t\t\trmin * Math.cos( phi1 ), rmin * Math.sin( phi1 ), rmin / Math.tan( theta1 ),\n\t\t\t\t\t\trmin * Math.cos( phi1 ), rmin * Math.sin( phi1 ), rmin / Math.tan( theta2 ),\n\t\t\t\t\t\trmin * Math.cos( phi2 ), rmin * Math.sin( phi2 ), rmin / Math.tan( theta2 ) );\n\n\t\tlet i0, i1, i2, i3;\n\n\t\t// six planes of the trapezoid\n\t\ti0 = 3; i1 = 2; i2 = 1; i3 = 0;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 4; i1 = 5; i2 = 6; i3 = 7;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 4; i1 = 7; i2 = 3; i3 = 0;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 1; i1 = 2; i2 = 6; i3 = 5;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 5; i1 = 4; i2 = 0; i3 = 1;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 2; i1 = 3; i2 = 7; i3 = 6;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\n // convert data into buffers\n this.setIndex( indices );\n this.addAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );\n this.computeVertexNormals();\n }", "function geometry(surfaceGenerator, tesselationFnDir, tesselationRotDir) {\n let vertices = [];\n let normals = [];\n let normalDrawVerts = [];\n let indices = [];\n let wireIndices = [];\n let numTris = 0;\n let maxZ = 0;\n for (let t = 1; t >= -1.01; t -= 2 / (tesselationFnDir)) {\n let gen = surfaceGenerator.curve(t);\n maxZ = Math.max(maxZ, gen);\n const baseVec = vec4(gen, t, 0, 1);\n for (let theta = 0; theta < 360; theta += 360 / tesselationRotDir) {\n const rot = rotateY(theta)\n let vert = multMatVec(rot, baseVec);\n let slope = surfaceGenerator.derivative(t);\n const norm = normalize(vec4(Math.cos(radians(theta)), -slope, Math.sin(radians(theta)), 0), true);\n vertices.push(vert);\n normals.push(norm);\n normalDrawVerts.push(vert);\n normalDrawVerts.push(add(vert, scale(0.1, norm)));\n }\n }\n // 0 = top left,\n // 1 = top right,\n // 2 = bottom left,\n // 3 = botom right\n const subIndices = [1,0,2,2,1,3];\n const wireSubIndices = [1,0,0,2,2,1,1,3,3,2];\n for (let i = 0; i < tesselationFnDir; i++) {\n for (let j = 0; j < tesselationRotDir; j++) {\n let quadIndices = [\n (tesselationRotDir) * (i) + j, (tesselationRotDir) * (i) + (j + 1) % tesselationRotDir,\n (tesselationRotDir) * (i + 1) + j, (tesselationRotDir) * (i+1) + (j + 1) % tesselationRotDir\n ];\n for (let k = 0; k < wireSubIndices.length; k++) {\n wireIndices.push(quadIndices[wireSubIndices[k]])\n }\n for (let k = 0; k < subIndices.length; k++) {\n indices.push(quadIndices[subIndices[k]])\n }\n numTris += 2;\n }\n }\n return {\n vertices,\n normals,\n normalDrawVerts,\n indices,\n wireIndices,\n numTris,\n maxZ\n }\n}", "function createCube(gl) {\n var cube = [];\n // Coordinates Cube which length of one side is 1 with the origin on the center of the bottom)\n var vertices = new Float32Array([\n 0.5, 1.0, 0.5, -0.5, 1.0, 0.5, -0.5, 0.0, 0.5, 0.5, 0.0, 0.5, // v0-v1-v2-v3 front\n 0.5, 1.0, 0.5, 0.5, 0.0, 0.5, 0.5, 0.0,-0.5, 0.5, 1.0,-0.5, // v0-v3-v4-v5 right\n 0.5, 1.0, 0.5, 0.5, 1.0,-0.5, -0.5, 1.0,-0.5, -0.5, 1.0, 0.5, // v0-v5-v6-v1 up\n -0.5, 1.0, 0.5, -0.5, 1.0,-0.5, -0.5, 0.0,-0.5, -0.5, 0.0, 0.5, // v1-v6-v7-v2 left\n -0.5, 0.0,-0.5, 0.5, 0.0,-0.5, 0.5, 0.0, 0.5, -0.5, 0.0, 0.5, // v7-v4-v3-v2 down\n 0.5, 0.0,-0.5, -0.5, 0.0,-0.5, -0.5, 1.0,-0.5, 0.5, 1.0,-0.5 // v4-v7-v6-v5 back\n ]);\n\n // Normal\n var normals = new Float32Array([\n 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, // v0-v1-v2-v3 front\n 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, // v0-v3-v4-v5 right\n 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, // v0-v5-v6-v1 up\n -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, // v1-v6-v7-v2 left\n 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, // v7-v4-v3-v2 down\n 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0, 0.0, 0.0,-1.0 // v4-v7-v6-v5 back\n ]);\n\n // Indices of the vertices\n var indices = new Uint8Array([\n 0, 1, 2, 0, 2, 3, // front\n 4, 5, 6, 4, 6, 7, // right\n 8, 9,10, 8,10,11, // up\n 12,13,14, 12,14,15, // left\n 16,17,18, 16,18,19, // down\n 20,21,22, 20,22,23 // back\n ]);\n\n cube.vertexBuffer = initArrayBufferForLaterUse(gl,vertices,3,gl.FLOAT);\n cube.normalBuffer = initArrayBufferForLaterUse(gl,normals,3,gl.FLOAT);\n cube.indexBuffer = initElementArrayBufferForLaterUse(gl,indices,gl.STATIC_DRAW);\n cube.num_vertices = indices.length;\n cube.drawtype = gl.TRIANGLES;\n\n return cube;\n}", "function addNormal (words) {\n objData.normals.push([Number(words[1]), Number(words[2]), Number(words[3])])\n }", "static setNormalizeV3(xyz) {\nvar len;\n//--------------\nlen = this.lengthV3(xyz);\nif (1e-5 <= len) {\nreturn this.setInverseScaleV3(xyz, len);\n} else {\nreturn xyz;\n}\n}", "constructor() {\n this.numLights = 100;\n this.extentMin = vec3.fromValues(-14, -1, -6);\n this.extentMax = vec3.fromValues(14, 20, 6);\n const extent = vec3.create();\n vec3.sub(extent, this.extentMax, this.extentMin);\n\n // layout:\n // vec4 position;\n // vec3 color; float radius;\n this.lightDataStride = 64; // offset 256 / 4 byte\n this.data = new Float32Array(this.numLights * this.lightDataStride);\n\n // init\n let offset = 0;\n for (let i = 0; i < this.numLights; i++) {\n offset = this.lightDataStride * i;\n //position\n for (let i = 0; i < 3; i++) {\n tmpVec4[i] = Math.random() * extent[i] + this.extentMin[i];\n }\n tmpVec4[3] = 1;\n this.setV4(this.data, offset, tmpVec4);\n // color\n tmpVec4[0] = Math.random() * 2;\n tmpVec4[1] = Math.random() * 2;\n tmpVec4[2] = Math.random() * 2;\n // radius\n tmpVec4[3] = 4.0;\n this.setV4(this.data, offset + 4, tmpVec4);\n }\n }", "constructor({ numberOfSlices = 20, radius = 1.0, height = 1.0 }) {\n super();\n /* Points 0, 1, 2, ..., N-1 are on the base circle */\n for (let k = 0; k < numberOfSlices; k++) {\n const angle = (k / numberOfSlices) * 2 * Math.PI;\n const xVal = radius * Math.cos(angle);\n const yVal = radius * Math.sin(angle);\n this.vertices.push([xVal, yVal, 0.0]); // At z=0\n }\n /* Point N is the base center */\n this.vertices.push([0, 0, 0]); // center at base\n /* Point N+1 is the cone tip */\n this.vertices.push([0, 0, height]); // tip of the cone\n\n for (let k = 0; k < numberOfSlices; k++) {\n /* cells for the circle base are\n [N,0,1], [N,1,2], ..., [N,N-2,N-1], [N, N-1, 0]\n */\n this.triangles.push([numberOfSlices, k, (k + 1) % numberOfSlices]);\n /* cell for the cone top are\n [N+1,0,1], [N+1,1,2], ... [N+1,N-2,N-1], [N+1,N-1,0]\n */\n this.triangles.push([numberOfSlices + 1, k, (k + 1) % numberOfSlices]);\n }\n }", "get normalized() {\n const [Q1, { x: Qx2, y: Qy2 }, { x: Qx, y: Qy }] = [\n { x: 0 + ((2 / 3) * (1 - 0)), y: 2 + ((2 / 3) * (0 - 2)) },\n { x: 2 + ((2 / 3) * (1 - 2)), y: 2 + ((2 / 3) * (0 - 2)) },\n { x: 2, y: 2 },\n ] // = commands.Q.normalized.points.slice(0, 3)\n const T1x2 = 4 > Qx ? 4 + (Qx - (4 - Qx2)) : 4 - (Qx - (4 - Qx2))\n const T1y2 = 2 > Qy ? 2 + (Qy - (4 - Qy2)) : 2 - (Qy - (4 - Qy2))\n const T2x2 = 6 + (4 - (8 - T1x2))\n const T2y2 = 2 - (2 - (4 - T1y2))\n\n return {\n points: [\n Q1, { x: Qx2, y: Qy2 }, { x: Qx, y: Qy },\n { x: 4 - Qx2, y: 4 - Qy2 }, { x: T1x2, y: T1y2 }, { x: 4, y: 2 },\n { x: 8 - T1x2, y: 4 - T1y2 }, { x: T2x2, y: T2y2 }, { x: 6, y: 2 },\n { x: 6, y: 2 }, { x: 0, y: 2 }, { x: 0, y: 2 },\n ],\n type: 'C',\n }\n }", "function getGeometryTriangleNormals(geo, ia, ib, ic, a, b, c) {\n var normals = geo.arrays.normals;\n var iax, ibx, icx;\n if (!normals) {\n a = a.set([0,0,0]);\n b = b.set([0,0,0]);\n c = c.set([0,0,0]);\n return false; // no normals exist\n }\n if (geo.compressedNormals) {\n\n var iax = ia * 2;\n var ibx = ib * 2;\n var icx = ic * 2;\n\n var encna = normals.subarray(iax, iax + 2);\n var encnb = normals.subarray(ibx, ibx + 2);\n var encnc = normals.subarray(icx, icx + 2);\n\n SceneJS_math_octDecodeVec2(normals.subarray(iax, iax + 2), a);\n SceneJS_math_octDecodeVec2(normals.subarray(ibx, ibx + 2), b);\n SceneJS_math_octDecodeVec2(normals.subarray(icx, icx + 2), c);\n\n } else {\n iax = ia*3;\n ibx = ib*3;\n icx = ic*3;\n a[0] = normals[iax];\n a[1] = normals[iax + 1];\n a[2] = normals[iax + 2];\n\n b[0] = normals[ibx];\n b[1] = normals[ibx + 1];\n b[2] = normals[ibx + 2];\n\n c[0] = normals[icx];\n c[1] = normals[icx + 1];\n c[2] = normals[icx + 2];\n\n }\n return true;\n }", "function calcVertices() {\n\tfor (var i = 0; i < rotationMasterArray[0].length - 1; i++) {\n \t\tfor (j = 0; j < rotationMasterArray.length - 1; j++) {\n\n \t\tvar index = (vertices.length / 3);\n\n \t\tvar currentLine = rotationMasterArray[j];\n \t\tvar nextLine = rotationMasterArray[j + 1];\n\n \t\tvertices.push(currentLine[i].x, currentLine[i].y, currentLine[i].z);\n \t\tvertices.push(currentLine[i + 1].x, currentLine[i + 1].y, currentLine[i + 1].z);\n \t\tvertices.push(nextLine[i + 1].x, nextLine[i + 1].y, nextLine[i + 1].z);\n \t\tvertices.push(nextLine[i].x, nextLine[i].y, nextLine[i].z);\n\n \t\tindexes.push(index, index + 1, index + 2);\n \t\tindexes.push(index, index + 2, index + 3);\n\t\t}\n\t}\n}" ]
[ "0.66545326", "0.6629677", "0.65941006", "0.6454413", "0.63554573", "0.6320616", "0.63141966", "0.6237331", "0.6221246", "0.62168425", "0.6184713", "0.6181636", "0.6141608", "0.6134165", "0.6118319", "0.6104997", "0.61049294", "0.6096802", "0.6061261", "0.6055501", "0.6039629", "0.60077524", "0.59845054", "0.59661734", "0.594923", "0.59400904", "0.59258085", "0.5898772", "0.5892636", "0.58897895", "0.58883494", "0.5874122", "0.5856301", "0.58415425", "0.58066106", "0.580583", "0.57956976", "0.57836276", "0.57630694", "0.5755653", "0.5753135", "0.5739692", "0.5727354", "0.57258064", "0.57242036", "0.572201", "0.57192904", "0.5697331", "0.56838137", "0.5676932", "0.56709564", "0.5670435", "0.5654805", "0.5652901", "0.5651064", "0.56371117", "0.5630861", "0.5628728", "0.5622943", "0.5617167", "0.56047976", "0.5602175", "0.5578822", "0.5574709", "0.55737823", "0.5567967", "0.5566253", "0.55649436", "0.55630046", "0.5559884", "0.5535104", "0.5526332", "0.5511889", "0.5509047", "0.5498327", "0.5498043", "0.5491243", "0.54903334", "0.54848063", "0.548037", "0.5470031", "0.546345", "0.54624856", "0.5449457", "0.5448708", "0.5446335", "0.54442644", "0.54257953", "0.54256123", "0.5416893", "0.53973156", "0.5393907", "0.5392194", "0.5391374", "0.53853923", "0.5382749", "0.53800726", "0.53747755", "0.53722924", "0.53715545", "0.5364668" ]
0.0
-1
Parse output that is formatted like this: uv loop at [0x559b65ed5770] has open handles: [0x7f2de0018430] timer (active) Close callback: 0x7f2df31de220 CloseCallback(uv_handle_s) [...] Data: 0x7f2df33df140 example_instance [...] (First field): 0x7f2df33dedc0 vtable for ExampleOwnerClass [...] [0x7f2de000b870] timer Close callback: 0x7f2df31de220 CloseCallback(uv_handle_s) [...] Data: (nil) [0x7f2de000b910] timer Close callback: 0x7f2df31de220 CloseCallback(uv_handle_s) [...] Data: 0x42 uv loop at [0x559b65ed5770] has 3 open handles in total
function isGlibc() { try { const lddOut = spawnSync('ldd', [process.execPath]).stdout; const libcInfo = lddOut.toString().split('\n').map( (line) => line.match(/libc\.so.+=>\s*(\S+)\s/)).filter((info) => info); if (libcInfo.length === 0) return false; const nmOut = spawnSync('nm', ['-D', libcInfo[0][1]]).stdout; if (/gnu_get_libc_version/.test(nmOut)) return true; } catch { return false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function ParseOutput() {\n this.lines = [ ];\n this.currentLine = [];\n this.currentLineListItemType = null;\n }", "function DebugProtocolParser(inputStream,\n protocolVersion,\n rawDumpFileName,\n textDumpFileName,\n textDumpFilePrefix,\n hexDumpConsolePrefix,\n textDumpConsolePrefix) {\n var _this = this;\n this.inputStream = inputStream;\n this.closed = false; // stream is closed/broken, don't parse anymore\n this.bytes = 0;\n this.dvalues = 0;\n this.messages = 0;\n this.requests = 0;\n this.prevBytes = 0;\n this.bytesPerSec = 0;\n this.statsTimer = null;\n this.readableNumberValue = true;\n\n events.EventEmitter.call(this);\n\n var buf = new Buffer(0); // accumulate data\n var msg = []; // accumulated message until EOM\n var versionIdentification;\n\n var statsInterval = 2000;\n var statsIntervalSec = statsInterval / 1000;\n this.statsTimer = setInterval(function () {\n _this.bytesPerSec = (_this.bytes - _this.prevBytes) / statsIntervalSec;\n _this.prevBytes = _this.bytes;\n _this.emit('stats-update');\n }, statsInterval);\n\n function consume(n) {\n var tmp = new Buffer(buf.length - n);\n buf.copy(tmp, 0, n);\n buf = tmp;\n }\n\n inputStream.on('data', function (data) {\n var i, n, x, v, gotValue, len, t, tmpbuf, verstr;\n var prettyMsg;\n\n if (_this.closed || !_this.inputStream) {\n console.log('Ignoring incoming data from closed input stream, len ' + data.length);\n return;\n }\n\n _this.bytes += data.length;\n if (rawDumpFileName) {\n fs.appendFileSync(rawDumpFileName, data);\n }\n if (hexDumpConsolePrefix) {\n console.log(hexDumpConsolePrefix + data.toString('hex'));\n }\n\n buf = Buffer.concat([ buf, data ]);\n\n // Protocol version handling. When dumping an output stream, the\n // caller gives a non-null protocolVersion so we don't read one here.\n if (protocolVersion == null) {\n if (buf.length > 1024) {\n _this.emit('transport-error', 'Parse error (version identification too long), dropping connection');\n _this.close();\n return;\n }\n\n for (i = 0, n = buf.length; i < n; i++) {\n if (buf[i] == 0x0a) {\n tmpbuf = new Buffer(i);\n buf.copy(tmpbuf, 0, 0, i);\n consume(i + 1);\n verstr = tmpbuf.toString('utf-8');\n t = verstr.split(' ');\n protocolVersion = Number(t[0]);\n versionIdentification = verstr;\n\n _this.emit('protocol-version', {\n protocolVersion: protocolVersion,\n versionIdentification: versionIdentification\n });\n break;\n }\n }\n\n if (protocolVersion == null) {\n // Still waiting for version identification to complete.\n return;\n }\n }\n\n // Parse complete dvalues (quite inefficient now) by trial parsing.\n // Consume a value only when it's fully present in 'buf'.\n // See doc/debugger.rst for format description.\n\n while (buf.length > 0) {\n x = buf[0];\n v = undefined;\n gotValue = false; // used to flag special values like undefined\n\n if (x >= 0xc0) {\n // 0xc0...0xff: integers 0-16383\n if (buf.length >= 2) {\n v = ((x - 0xc0) << 8) + buf[1];\n consume(2);\n }\n } else if (x >= 0x80) {\n // 0x80...0xbf: integers 0-63\n v = x - 0x80;\n consume(1);\n } else if (x >= 0x60) {\n // 0x60...0x7f: strings with length 0-31\n len = x - 0x60;\n if (buf.length >= 1 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 1, 1 + len);\n v = bufferToDebugString(v);\n consume(1 + len);\n }\n } else {\n switch (x) {\n case 0x00: v = DVAL_EOM; consume(1); break;\n case 0x01: v = DVAL_REQ; consume(1); break;\n case 0x02: v = DVAL_REP; consume(1); break;\n case 0x03: v = DVAL_ERR; consume(1); break;\n case 0x04: v = DVAL_NFY; consume(1); break;\n case 0x10: // 4-byte signed integer\n if (buf.length >= 5) {\n v = buf.readInt32BE(1);\n consume(5);\n }\n break;\n case 0x11: // 4-byte string\n if (buf.length >= 5) {\n len = buf.readUInt32BE(1);\n if (buf.length >= 5 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 5, 5 + len);\n v = bufferToDebugString(v);\n consume(5 + len);\n }\n }\n break;\n case 0x12: // 2-byte string\n if (buf.length >= 3) {\n len = buf.readUInt16BE(1);\n if (buf.length >= 3 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 3, 3 + len);\n v = bufferToDebugString(v);\n consume(3 + len);\n }\n }\n break;\n case 0x13: // 4-byte buffer\n if (buf.length >= 5) {\n len = buf.readUInt32BE(1);\n if (buf.length >= 5 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 5, 5 + len);\n v = { type: 'buffer', data: v.toString('hex') };\n consume(5 + len);\n // Value could be a Node.js buffer directly, but\n // we prefer all dvalues to be JSON compatible\n }\n }\n break;\n case 0x14: // 2-byte buffer\n if (buf.length >= 3) {\n len = buf.readUInt16BE(1);\n if (buf.length >= 3 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 3, 3 + len);\n v = { type: 'buffer', data: v.toString('hex') };\n consume(3 + len);\n // Value could be a Node.js buffer directly, but\n // we prefer all dvalues to be JSON compatible\n }\n }\n break;\n case 0x15: // unused/none\n v = { type: 'unused' };\n consume(1);\n break;\n case 0x16: // undefined\n v = { type: 'undefined' };\n gotValue = true; // indicate 'v' is actually set\n consume(1);\n break;\n case 0x17: // null\n v = null;\n gotValue = true; // indicate 'v' is actually set\n consume(1);\n break;\n case 0x18: // true\n v = true;\n consume(1);\n break;\n case 0x19: // false\n v = false;\n consume(1);\n break;\n case 0x1a: // number (IEEE double), big endian\n if (buf.length >= 9) {\n v = new Buffer(8);\n buf.copy(v, 0, 1, 9);\n v = { type: 'number', data: v.toString('hex') };\n\n if (_this.readableNumberValue) {\n // The value key should not be used programmatically,\n // it is just there to make the dumps more readable.\n v.value = buf.readDoubleBE(1);\n }\n consume(9);\n }\n break;\n case 0x1b: // object\n if (buf.length >= 3) {\n len = buf[2];\n if (buf.length >= 3 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 3, 3 + len);\n v = { type: 'object', 'class': buf[1], pointer: v.toString('hex') };\n consume(3 + len);\n }\n }\n break;\n case 0x1c: // pointer\n if (buf.length >= 2) {\n len = buf[1];\n if (buf.length >= 2 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 2, 2 + len);\n v = { type: 'pointer', pointer: v.toString('hex') };\n consume(2 + len);\n }\n }\n break;\n case 0x1d: // lightfunc\n if (buf.length >= 4) {\n len = buf[3];\n if (buf.length >= 4 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 4, 4 + len);\n v = { type: 'lightfunc', flags: buf.readUInt16BE(1), pointer: v.toString('hex') };\n consume(4 + len);\n }\n }\n break;\n case 0x1e: // heapptr\n if (buf.length >= 2) {\n len = buf[1];\n if (buf.length >= 2 + len) {\n v = new Buffer(len);\n buf.copy(v, 0, 2, 2 + len);\n v = { type: 'heapptr', pointer: v.toString('hex') };\n consume(2 + len);\n }\n }\n break;\n default:\n _this.emit('transport-error', 'Parse error, dropping connection');\n _this.close();\n }\n }\n\n if (typeof v === 'undefined' && !gotValue) {\n break;\n }\n msg.push(v);\n _this.dvalues++;\n\n // Could emit a 'debug-value' event here, but that's not necessary\n // because the receiver will just collect statistics which can also\n // be done using the finished message.\n\n if (v === DVAL_EOM) {\n _this.messages++;\n\n if (textDumpFileName || textDumpConsolePrefix) {\n prettyMsg = prettyDebugMessage(msg);\n if (textDumpFileName) {\n fs.appendFileSync(textDumpFileName, (textDumpFilePrefix || '') + prettyMsg + '\\n');\n }\n if (textDumpConsolePrefix) {\n console.log(textDumpConsolePrefix + prettyMsg);\n }\n }\n\n _this.emit('debug-message', msg);\n msg = []; // new object, old may be in circulation for a while\n }\n }\n });\n\n // Not all streams will emit this.\n inputStream.on('error', function (err) {\n _this.emit('transport-error', err);\n _this.close();\n });\n\n // Not all streams will emit this.\n inputStream.on('close', function () {\n _this.close();\n });\n}", "function createParser() {\n let buffer;\n let position; // current read position\n let fieldLength; // length of the `field` portion of the line\n let discardTrailingNewline = false;\n let message = { event: '', data: '' };\n let pending = [];\n const decoder = new TextDecoder();\n return function parse(chunk) {\n if (buffer === undefined) {\n buffer = chunk;\n position = 0;\n fieldLength = -1;\n }\n else {\n const concat = new Uint8Array(buffer.length + chunk.length);\n concat.set(buffer);\n concat.set(chunk, buffer.length);\n buffer = concat;\n }\n const bufLength = buffer.length;\n let lineStart = 0; // index where the current line starts\n while (position < bufLength) {\n if (discardTrailingNewline) {\n if (buffer[position] === ControlChars.NewLine) {\n lineStart = ++position; // skip to next char\n }\n discardTrailingNewline = false;\n }\n // look forward until the end of line\n let lineEnd = -1; // index of the \\r or \\n char\n for (; position < bufLength && lineEnd === -1; ++position) {\n switch (buffer[position]) {\n case ControlChars.Colon:\n if (fieldLength === -1) {\n // first colon in line\n fieldLength = position - lineStart;\n }\n break;\n // \\r case below should fallthrough to \\n:\n case ControlChars.CchunkiageReturn:\n discardTrailingNewline = true;\n // eslint-disable-next-line no-fallthrough\n case ControlChars.NewLine:\n lineEnd = position;\n break;\n }\n }\n if (lineEnd === -1) {\n // end of the buffer but the line hasn't ended\n break;\n }\n else if (lineStart === lineEnd) {\n // empty line denotes end of incoming message\n if (message.event || message.data) {\n // NOT a server ping (\":\\n\\n\")\n if (!message.event)\n throw new Error('Missing message event');\n const event = common_1.validateStreamEvent(message.event);\n const data = common_1.parseStreamData(event, message.data);\n pending.push({\n event,\n data,\n });\n message = { event: '', data: '' };\n }\n }\n else if (fieldLength > 0) {\n // end of line indicates message\n const line = buffer.subarray(lineStart, lineEnd);\n // exclude comments and lines with no values\n // line is of format \"<field>:<value>\" or \"<field>: <value>\"\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n const field = decoder.decode(line.subarray(0, fieldLength));\n const valueOffset = fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);\n const value = decoder.decode(line.subarray(valueOffset));\n switch (field) {\n case 'event':\n message.event = value;\n break;\n case 'data':\n // append the new value if the message has data\n message.data = message.data ? message.data + '\\n' + value : value;\n break;\n }\n }\n // next line\n lineStart = position;\n fieldLength = -1;\n }\n if (lineStart === bufLength) {\n // finished reading\n buffer = undefined;\n const messages = [...pending];\n pending = [];\n return messages;\n }\n else if (lineStart !== 0) {\n // create a new view into buffer beginning at lineStart so we don't\n // need to copy over the previous lines when we get the new chunk\n buffer = buffer.subarray(lineStart);\n position -= lineStart;\n }\n };\n}", "_onControlSocketData(chunk) {\n this.log(`< ${chunk}`);\n // This chunk might complete an earlier partial response.\n const completeResponse = this._partialResponse + chunk;\n const parsed = (0, parseControlResponse_1.parseControlResponse)(completeResponse);\n // Remember any incomplete remainder.\n this._partialResponse = parsed.rest;\n // Each response group is passed along individually.\n for (const message of parsed.messages) {\n const code = parseInt(message.substr(0, 3), 10);\n const response = { code, message };\n const err = code >= 400 ? new FTPError(response) : undefined;\n this._passToHandler(err ? err : response);\n }\n }", "function parse_out(data) {\n\tswitch (data.msg[0]) {\n\t\tcase 0x07 : { // PDC status (Sets off IKE gongs)\n\t\t\tdata = decode_pdc_status(data);\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault : {\n\t\t\tdata.command = 'unk';\n\t\t\tdata.value = Buffer.from(data.msg);\n\t\t}\n\t}\n\n\tlog.bus(data);\n}", "function TorrentParser() {\n ModelParser.call(this);\n\n this.on('string', function(string) {\n\t\tif (!this.infoHasher &&\n\t\t string.length == 4 && // avoid converting long buffers to strings\n\t\t string.toString() == 'info') {\n\t\t // Start infoHash\n\t\t this.infoStart = this.pos + 1;\n\t\t this.levels = 0;\n\t\t this.infoHasher = new crypto.createHash('sha1');\n\t\t}\n\t });\n this.on('list', function() {\n\t\tif (this.levels !== undefined)\n\t\t this.levels++;\n\t });\n this.on('dict', function() {\n\t\tif (this.levels !== undefined)\n\t\t this.levels++;\n\t });\n this.on('up', function() {\n\t\tif (this.levels !== undefined) {\n\t\t this.levels--;\n\n\t\t if (this.levels == 0) {\n\t\t\t// Finalize infoHash\n\t\t\tthis.infoHasher.update(this.currentBuffer.slice(this.infoStart, this.pos + 1));\n\t\t\tvar infoHex = this.infoHasher.digest('hex');\n\t\t\tthis.emit('infoHex', infoHex);\n\n\t\t\tdelete this.levels;\n\t\t\tdelete this.infoHasher;\n\t\t\tdelete this.infoStart;\n\t\t }\n\t\t}\n\t });\n this.on('parsed', function(pos) {\n\t\tthis.pos = pos;\n\t });\n}", "function parser(commandOutput, callback) {\n console.log(commandOutput);\n token = JSON.parse(commandOutput);\n}", "function parseStream(stream) {\n return __awaiter(this, void 0, void 0, function () {\n var reg, streaming;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n console.log(\"parsing stream\");\n reg = /\\B(\\$[a-zA-Z][a-zA-Z0-9]+\\b)(?!;)/gm;\n streaming = true;\n // listen to stream\n stream\n .on(\"data\", function (data) {\n // convert data (as buffer) to JSON tweet data\n var tweet = JSON.parse(Buffer.from(data).toString(\"utf-8\"));\n // store tweet text\n var text;\n // attempt to get the full tweet content\n try {\n if (tweet.extended_tweet)\n text = tweet.extended_tweet.full_text;\n else if (tweet.retweeted_status)\n text = tweet.retweeted_status.extended_tweet.full_text;\n }\n catch (error) {\n // TODO: figure out all types of tweet data\n return;\n }\n // exit if text doesn't match filter\n if (!text || !text.match(reg))\n return;\n // too many fake-looking tweets from whaleagent telegram\n if (text.indexOf(\"whaleagent\") > -1) {\n console.log(tweet);\n console.log(text.indexOf(\"whaleagent\"));\n return;\n }\n var tickerList = text.match(reg);\n for (var _i = 0, tickerList_1 = tickerList; _i < tickerList_1.length; _i++) {\n var ticker = tickerList_1[_i];\n frequencyList.add(ticker);\n }\n })\n .on(\"connection aborted\", function () {\n streaming = false;\n });\n _a.label = 1;\n case 1:\n if (!(streaming && !restarting)) return [3 /*break*/, 3];\n return [4 /*yield*/, wait(500)];\n case 2:\n _a.sent();\n return [3 /*break*/, 1];\n case 3:\n console.log(\"done streaming\");\n return [2 /*return*/];\n }\n });\n });\n}", "static *parse(/** !ArrayBuffer */ buf) {\n const reader = new Reader();\n const view = new DataView(buf);\n let /** number */ pos = 0;\n while (pos < buf.byteLength) {\n // Read the frame header\n const startMs = timeMs(view, pos);\n const len = view.getUint32(pos + 8, true);\n const endMs = pos + 12 + len < buf.byteLength\n ? timeMs(view, pos + 12 + len) : Infinity;\n const frame = new Frame();\n frame.startMs_ = startMs;\n frame.durationMs_ = endMs - startMs;\n reader.add(new DataView(buf, pos + 12, len));\n let cmd;\n while ((cmd = Command.parse(reader))) {\n if (cmd.keyframe) frame.keyframe_ = true;\n frame.commands_.push(cmd);\n }\n yield frame;\n pos += 12 + len;\n }\n }", "function decodePIDResponse(frame) {\n console.log(frame.ID.toUpperCase());\n console.log('PID:' + frame.BYTES[2].toUpperCase());\n if (0x0D == parseInt(frame.BYTES[2], 16)) {\n console.log('Speed: ' + parseInt(frame.BYTES[3], 16) + ' km/h')\n }\n else if (0xA6 == parseInt(frame.BYTES[2], 16)) {\n var sum = 0;\n\n sum += (parseInt(frame.BYTES[3], 16) * (2 ^ 24));\n sum += (parseInt(frame.BYTES[4], 16) * (2 ^ 16));\n sum += (parseInt(frame.BYTES[5], 16) * (2 ^ 8));\n sum += (parseInt(frame.BYTES[6], 16) * (2 ^ 1));\n\n console.log('Odometer: ' + sum + ' km')\n\n }\n else {\n console.log('Data0: ' + frame.BYTES[3] + 'h');\n console.log('Data1: ' + frame.BYTES[4] + 'h');\n console.log('Data2: ' + frame.BYTES[5] + 'h');\n console.log('Data3: ' + frame.BYTES[6] + 'h');\n }\n}", "function FrameStreamingParser (options) {\n Writable.call(this, options);\n //frames that are streaming, indexed by id\n this.frames = {};\n}", "async launch() {\n var proc = await this.worker.launch();\n\n // Proxy the exit event so we don't need to query .worker.\n this.worker.process.once('exit', this.emit.bind(this, 'exit'));\n\n // Process the output(s) to emit events based on the json streams.\n\n // stderr should not contain any useful logs so just pipe it...\n proc.stderr.pipe(process.stderr);\n\n // Parse stdout and emit non-json bits to stdout.\n proc.stdout.pipe(split(function(line) {\n try {\n var parsed = JSON.parse(line);\n debug('emit', parsed.type, parsed);\n this.emit(parsed.type, parsed);\n } catch (e) {\n // This is an intentional console log for any line which is not a\n // newline delimited json string.\n console.log(line);\n }\n }.bind(this)));\n\n // Wait for start event.\n await waitForEvent(this, 'start');\n }", "function Output(options) {\n options = options || {};\n this.command = options.command || '';\n this.args = options.args || {};\n this.typed = options.typed || '';\n this.canonical = options.canonical || '';\n this.hidden = options.hidden === true ? true : false;\n\n this.data = undefined;\n this.completed = false;\n this.error = false;\n this.start = new Date();\n\n this.onClose = util.createEvent('Output.onClose');\n this.onChange = util.createEvent('Output.onChange');\n}", "function _process($this) {\n \n // update the last message timestamp to the current timestamp\n $this.lastMessageTimestamp = new Date().getTime();\n var xhr = $this.activeXhr;\n\n var responseText = xhr.responseText;\n if (responseText.length >= STREAM_THRESHOLD) {\n if ($this.activeXhr == $this.mostRecentXhr) {\n //LOG.debug(\"RECONNECT!\");\n connect($this, false);\n }\n }\n\n // Check response text again!\n var progressText = responseText.slice(xhr.position);\n xhr.position = responseText.length;\n\n var buf = $this.buf;\n\n var bytes = Windows1252.toArray(progressText, $this.requiresEscaping);\n // handle fragmentation for escaped downstream\n if (bytes.hasRemainder) {\n // back up position by 1 to unread the escape char\n xhr.position--;\n }\n\n buf.position = buf.limit;\n buf.putBytes(bytes);\n buf.position = 0;\n buf.mark();\n\n parse:\n while(true) {\n if(!buf.hasRemaining()) {\n break;\n }\n\n var type = buf.getUnsigned();\n switch (type & 0x80) {\n case TEXT_FRAME_START:\n var endOfFrameAt = buf.indexOf(TEXT_FRAME_TERMINATOR);\n if (endOfFrameAt == -1) {\n // incomplete text frame\n break parse;\n }\n\n var dataBytes = buf.array.slice(buf.position, endOfFrameAt);\n var data = new $rootModule.ByteBuffer(dataBytes);\n\n // consume the payload bytes plus end of frame marker\n var numBytes = endOfFrameAt - buf.position;\n buf.skip(numBytes + 1);\n buf.mark();\n\n // handle command frames\n if (type == COMMAND_FRAME_START) {\n //LOG.debug(xhr.id+\": COMMAND FRAME: \"+data);\n handleCommandFrame($this, data);\n } else {\n //LOG.debug(xhr.id+\": DISPATCH TEXT\");\n dispatchText($this, data.getString(Charset.UTF8));\n }\n break;\n\n case BYTE_FRAME_START:\n case PRE_LENGTH_TEXT_FRAME_START:\n var length = 0;\n var lengthComplete = false;\n while (buf.hasRemaining()) {\n var b = buf.getUnsigned();\n\n length = length << 7;\n length |= (b & 0x7f);\n if ((b & 0x80) != 0x80) {\n lengthComplete = true;\n break;\n }\n }\n\n //LOG.debug(xhr.id+\": BYTE FRAME: \"+length);\n if (!lengthComplete) {\n //LOG.debug(\"incomplete length prefix\");\n break parse;\n }\n if (buf.remaining() < length) {\n //LOG.debug(\"incomplete payload: \"+buf.remaining()+\" < \"+length);\n break parse;\n }\n\n // extract binary payload\n var payloadData = buf.array.slice(buf.position, buf.position + length);\n var payload = new $rootModule.ByteBuffer(payloadData);\n\n // consume binary payload\n buf.skip(length)\n buf.mark()\n\n // dispatch byte frame\n\t // LOG.debug(xhr.id+\": DISPATCH BYTES: \"+payload.remaining());\n if (type == BYTE_FRAME_START) {\n \tdispatchBytes($this, payload);\n } \n else if (type == WSE_PING_FRAME_CODE) {\n dispatchPingReceived($this);\n } else {\n \t//LOG.debug(xhr.id+\": DISPATCH TEXT\");\n dispatchText($this, payload.getString(Charset.UTF8));\n }\n \n break;\n default:\n throw new Error(\"Emulation protocol error. Unknown frame type: \" + type);\n }\n }\n\n buf.reset();\n buf.compact();\n}", "function TTMLParser() {\n\n let context = this.context;\n let log = Debug(context).getInstance().log;\n\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n let instance,\n timingRegex,\n ttml, // contains the whole ttml document received\n ttmlStyling, // contains the styling information from the document (from head following EBU-TT-D)\n ttmlLayout, // contains the positioning information from the document (from head following EBU-TT-D)\n fontSize,\n lineHeight,\n linePadding,\n defaultLayoutProperties,\n defaultStyleProperties,\n fontFamilies,\n textAlign,\n multiRowAlign,\n wrapOption,\n unicodeBidi,\n displayAlign,\n writingMode,\n videoModel,\n converter;\n\n let cueCounter = 0; // Used to give every cue a unique ID.\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n }\n\n /**\n * Get the begin-end interval if present, or null otherwise.\n *\n * @param {Object} element - TTML element which may have begin and end attributes\n */\n function getInterval(element) {\n if (element.hasOwnProperty('begin') && element.hasOwnProperty('end')) {\n let beginTime = parseTimings(element.begin);\n let endTime = parseTimings(element.end);\n return [beginTime, endTime];\n } else {\n return null;\n }\n }\n\n function getCueID() {\n let id = 'cue_TTML_' + cueCounter;\n cueCounter++;\n return id;\n }\n\n /*\n * Create list of intervals where spans start and end. Empty list if no times.\n * Clip to interval using startInterval and endInterval and add these two times.\n * Also support case when startInterval/endInteval not given (sideloaded file)\n *\n * @param {Array} spans - array of span elements\n */\n function createSpanIntervalList(spans, startInterval, endInterval) {\n\n let spanChangeTimes = [];\n let spanChangeTimeStrings = [];\n let cue_intervals = [];\n\n function addSpanTime(span, name) {\n if (span.hasOwnProperty(name)) {\n let timeString = span[name];\n if (spanChangeTimeStrings.indexOf(timeString) < 0) {\n spanChangeTimeStrings.push(timeString);\n }\n }\n }\n\n for (let i = 0; i < spans.length; i++) {\n let span = spans[i];\n addSpanTime(span, 'begin');\n addSpanTime(span, 'end');\n }\n if (spanChangeTimeStrings.length === 0) {\n return cue_intervals; // No span timing so no intervals.\n }\n\n if (typeof startInterval !== 'undefined' && typeof endInterval !== 'undefined' ) {\n for (let i = 0; i < spanChangeTimeStrings.length; i++) {\n let changeTime = parseTimings(spanChangeTimeStrings[i]);\n if (startInterval < changeTime && changeTime < endInterval) {\n spanChangeTimes.push(changeTime);\n }\n }\n spanChangeTimes.push(startInterval);\n spanChangeTimes.push(endInterval);\n } else {\n for (let i = 0; i < spanChangeTimeStrings.length; i++) {\n spanChangeTimes.push(parseTimings(spanChangeTimeStrings[i]));\n }\n }\n spanChangeTimes.sort(function (a, b) { return a - b;});\n for (let i = 0; i < spanChangeTimes.length - 1; i++) {\n cue_intervals.push([spanChangeTimes[i], spanChangeTimes[i + 1]]);\n }\n return cue_intervals;\n }\n\n\n function clipStartTime(startTime, intervalStart) {\n if (typeof startInterval !== 'undefined') {\n if (startTime < intervalStart) {\n startTime = intervalStart;\n }\n }\n return startTime;\n }\n\n\n function clipEndTime(endTime, intervalEnd) {\n if (typeof intervalEnd !== 'undefined') {\n if (endTime > intervalEnd) {\n endTime = intervalEnd;\n }\n }\n return endTime;\n }\n\n /*\n * Get interval from entity that has begin and end properties.\n * If intervalStart and intervalEnd defined, use them to clip the interval.\n * Return null if no overlap with interval\n */\n function getClippedInterval(entity, intervalStart, intervalEnd) {\n let startTime = parseTimings(entity.begin);\n let endTime = parseTimings(entity.end);\n startTime = clipStartTime(startTime, intervalStart);\n endTime = clipEndTime(endTime, intervalEnd);\n if (typeof intervalStart !== 'undefined' && typeof intervalEnd !== 'undefined') {\n if (endTime < intervalStart || startTime > intervalEnd) {\n log('TTML: Cue ' + startTime + '-' + endTime + ' outside interval ' +\n intervalStart + '-' + intervalEnd);\n return null;\n }\n }\n return [startTime, endTime];\n }\n\n /*\n * Check if entity timing has some overlap with interval\n */\n function inIntervalOrNoTiming(entity, interval) {\n let inInterval = true;\n if (entity.hasOwnProperty('span')) {\n let entityInterval = getInterval(entity.span);\n if (entityInterval !== null) { //Timing\n inInterval = (entityInterval[0] < interval[1] && entityInterval[1] > interval[0]);\n }\n }\n return inInterval;\n }\n\n /**\n * Parse the raw data and process it to return the HTML element representing the cue.\n * Return the region to be processed and controlled (hide/show) by the caption controller.\n * @param {string} data - raw data received from the TextSourceBuffer\n * @param {number} intervalStart\n * @param {number} intervalEnd\n * @param {array} imageArray - images represented as binary strings\n */\n\n function parse(data, intervalStart, intervalEnd, imageArray) {\n let tt, // Top element\n head, // head in tt\n body, // body in tt\n ttExtent, // extent attribute of tt element\n type,\n i;\n\n var errorMsg = '';\n\n // Parse the TTML in a JSON object.\n ttml = converter.xml_str2json(data);\n\n if (!ttml) {\n throw new Error('TTML document could not be parsed');\n }\n\n if (videoModel.getTTMLRenderingDiv()) {\n type = 'html';\n }\n\n // Check the document and compare to the specification (TTML and EBU-TT-D).\n tt = ttml.tt;\n if (!tt) {\n throw new Error('TTML document lacks tt element');\n }\n\n // Get the namespace if there is one defined in the JSON object.\n var ttNS = getNamespacePrefix(tt, 'http://www.w3.org/ns/ttml');\n\n // Remove the namespace before each node if it exists:\n if (ttNS) {\n removeNamespacePrefix(tt, ttNS);\n }\n\n ttExtent = tt['tts:extent']; // Should check that tts is right namespace.\n\n head = tt.head;\n if (!head) {\n throw new Error('TTML document lacks head element');\n }\n if (head.layout) {\n ttmlLayout = head.layout.region_asArray; //Mandatory in EBU-TT-D\n }\n if (head.styling) {\n ttmlStyling = head.styling.style_asArray; // Mandatory in EBU-TT-D\n }\n\n let imageDataUrls = {};\n\n if (imageArray) {\n for (i = 0; i < imageArray.length; i++) {\n let key = 'urn:mpeg:14496-30:subs:' + (i + 1).toString();\n let dataUrl = 'data:image/png;base64,' + btoa(imageArray[i]);\n imageDataUrls[key] = dataUrl;\n }\n }\n\n if (head.metadata) {\n let embeddedImages = head.metadata.image_asArray; // Handle embedded images\n if (embeddedImages) {\n for (i = 0; i < embeddedImages.length; i++) {\n let key = '#' + embeddedImages[i]['xml:id'];\n let imageType = embeddedImages[i].imagetype.toLowerCase();\n let dataUrl = 'data:image/' + imageType + ';base64,' + embeddedImages[i].__text;\n imageDataUrls[key] = dataUrl;\n }\n }\n }\n\n body = tt.body;\n if (!body) {\n throw new Error('TTML document lacks body element');\n }\n\n // Extract the cellResolution information\n var cellResolution = getCellResolution();\n\n // Recover the video width and height displayed by the player.\n var videoWidth = videoModel.getElement().clientWidth;\n var videoHeight = videoModel.getElement().clientHeight;\n\n // Compute the CellResolution unit in order to process properties using sizing (fontSize, linePadding, etc).\n var cellUnit = [videoWidth / cellResolution[0], videoHeight / cellResolution[1]];\n defaultStyleProperties['font-size'] = cellUnit[1] + 'px;';\n\n var regions = [];\n if (ttmlLayout) {\n for (i = 0; i < ttmlLayout.length; i++) {\n regions.push(processRegion(JSON.parse(JSON.stringify(ttmlLayout[i])), cellUnit));\n }\n }\n\n // Get the namespace prefix.\n var nsttp = getNamespacePrefix(ttml.tt, 'http://www.w3.org/ns/ttml#parameter');\n\n // Set the framerate.\n if (tt.hasOwnProperty(nsttp + ':frameRate')) {\n tt.frameRate = parseInt(tt[nsttp + ':frameRate'], 10);\n }\n var captionArray = [];\n // Extract the div\n var divs = tt.body_asArray[0].__children;\n\n // Timing is either on div, paragraph or span level.\n\n for (let k = 0; k < divs.length; k++) {\n let div = divs[k].div;\n let divInterval = null; // This is mainly for image subtitles.\n\n if (null !== (divInterval = getInterval(div))) {\n // Timing on div level is not allowed by EBU-TT-D.\n // We only use it for SMPTE-TT image subtitle profile.\n\n // Layout should be defined by a region. Given early test material, we also support that it is on\n // div level\n let layout;\n if (div.region) {\n let region = findRegionFromID(ttmlLayout, div.region);\n layout = getRelativePositioning(region, ttExtent);\n }\n if (!layout) {\n layout = getRelativePositioning(div, ttExtent);\n }\n\n let imgKey = div['smpte:backgroundImage'];\n if (imgKey !== undefined && imageDataUrls[imgKey] !== undefined) {\n captionArray.push({\n start: divInterval[0],\n end: divInterval[1],\n id: getCueID(),\n data: imageDataUrls[imgKey],\n type: 'image',\n layout: layout\n });\n }\n continue; // Next div\n }\n\n let paragraphs = div.p_asArray;\n // Check if cues is not empty or undefined.\n if (divInterval === null && (!paragraphs || paragraphs.length === 0)) {\n errorMsg = 'TTML has div that contains no timing and no paragraphs.';\n log(errorMsg);\n return captionArray;\n }\n\n for (let j2 = 0; j2 < paragraphs.length; j2++) {\n let paragraph = paragraphs[j2];\n let spans = paragraph.span_asArray;\n let cueIntervals = [];\n // For timing, the overall goal is to find the intervals where there should be cues\n // The timing may either be on paragraph or span level.\n if (paragraph.hasOwnProperty('begin') && paragraph.hasOwnProperty('end')) {\n // Timing on paragraph level\n let clippedInterval = getClippedInterval(paragraph, intervalStart, intervalEnd);\n if (clippedInterval !== null) {\n cueIntervals.push(clippedInterval);\n }\n } else {\n // Timing must be on span level\n cueIntervals = createSpanIntervalList(spans, intervalStart, intervalEnd);\n }\n if (cueIntervals.length === 0) {\n errorMsg = 'TTML: Empty paragraph';\n continue; // Nothing in this paragraph\n }\n\n let paragraphChildren = paragraph.__children;\n\n for (let i2 = 0; i2 < cueIntervals.length; i2++) {\n let interval = cueIntervals[i2];\n let childrenInInterval = [];\n for (let k2 = 0; k2 < paragraphChildren.length; k2++) {\n let child = paragraphChildren[k2];\n if (inIntervalOrNoTiming(child, interval)) {\n childrenInInterval.push(child);\n }\n }\n if (childrenInInterval.length === 0) {\n continue; // No children to render\n }\n\n if (type === 'html') {\n lineHeight = {};\n linePadding = {};\n fontSize = {};\n\n /**\n * Find the region defined for the cue.\n */\n // properties to be put in the \"captionRegion\" HTML element.\n var cueRegionProperties = constructCueRegion(paragraph, div, cellUnit);\n\n /**\n * Find the style defined for the cue.\n */\n // properties to be put in the \"paragraph\" HTML element.\n var cueStyleProperties = constructCueStyle(paragraph, cellUnit);\n\n /**\n * /!\\ Create the cue HTML Element containing the whole cue.\n */\n var styleIDs = cueStyleProperties[1];\n cueStyleProperties = cueStyleProperties[0];\n\n // Final cue HTML element.\n var cueParagraph = document.createElement('div');\n cueParagraph.className = styleIDs;\n\n // Create a wrapper containing the cue information about unicodeBidi and direction\n // as they need to be defined on at this level.\n // We append to the wrapper the cue itself.\n var cueDirUniWrapper = constructCue(childrenInInterval, cellUnit);\n cueDirUniWrapper.className = 'cueDirUniWrapper';\n\n // If the style defines these two properties, we place them in cueContainer\n // and delete them from the cue style so it is not added afterwards to the final cue.\n if (arrayContains('unicode-bidi', cueStyleProperties)) {\n cueDirUniWrapper.style.cssText += getPropertyFromArray('unicode-bidi', cueStyleProperties);\n deletePropertyFromArray('unicode-bidi', cueStyleProperties);\n }\n if (arrayContains('direction', cueStyleProperties)) {\n cueDirUniWrapper.style.cssText += getPropertyFromArray('direction', cueStyleProperties);\n deletePropertyFromArray('direction', cueStyleProperties);\n }\n\n // Apply the linePadding property if it is specified in the cue style.\n if (arrayContains('padding-left', cueStyleProperties) && arrayContains('padding-right', cueStyleProperties)) {\n cueDirUniWrapper.innerHTML = applyLinePadding(cueDirUniWrapper, cueStyleProperties);\n }\n\n /**\n * Clean and set the style and region for the cue to be returned.\n */\n\n // Remove the line padding property from being added at the \"paragraph\" element level.\n if (arrayContains('padding-left', cueStyleProperties) && arrayContains('padding-right', cueStyleProperties)) {\n deletePropertyFromArray('padding-left', cueStyleProperties);\n deletePropertyFromArray('padding-right', cueStyleProperties);\n }\n\n // Remove the ID of the region from being added at the \"paragraph\" element level.\n var regionID = '';\n if (arrayContains('regionID', cueRegionProperties)) {\n var wholeRegionID = getPropertyFromArray('regionID', cueRegionProperties);\n regionID = wholeRegionID.slice(wholeRegionID.indexOf(':') + 1, wholeRegionID.length - 1);\n }\n\n // We link the p style to the finale cueParagraph element.\n if (cueStyleProperties) {\n cueParagraph.style.cssText = cueStyleProperties.join(' ') + 'display:flex;';\n }\n // We define the CSS style for the cue region.\n if (cueRegionProperties) {\n cueRegionProperties = cueRegionProperties.join(' ');\n }\n\n // We then place the cue wrapper inside the paragraph element.\n cueParagraph.appendChild(cueDirUniWrapper);\n\n // Final cue.\n var finalCue = document.createElement('div');\n finalCue.appendChild(cueParagraph);\n finalCue.id = getCueID();\n finalCue.style.cssText = 'position: absolute; margin: 0; display: flex; box-sizing: border-box; pointer-events: none;' + cueRegionProperties;\n\n if (Object.keys(fontSize).length === 0) {\n fontSize.defaultFontSize = '100';\n }\n\n // We add all the cue information in captionArray.\n captionArray.push({\n start: interval[0],\n end: interval[1],\n type: 'html',\n cueHTMLElement: finalCue,\n regions: regions,\n regionID: regionID,\n cueID: finalCue.id,\n videoHeight: videoHeight,\n videoWidth: videoWidth,\n cellResolution: cellResolution,\n fontSize: fontSize || {\n defaultFontSize: '100'\n },\n lineHeight: lineHeight,\n linePadding: linePadding\n });\n\n } else {\n var text = '';\n var textElements = childrenInInterval;\n if (textElements.length) {\n textElements.forEach(function (el) {\n if (el.hasOwnProperty('span')) {\n var spanElements = el.span.__children;\n spanElements.forEach(function (spanEl) {\n // If metadata is present, do not process.\n if (spanElements.hasOwnProperty('metadata')) {\n return;\n }\n // If the element is a string\n if (spanEl.hasOwnProperty('#text')) {\n text += spanEl['#text'].replace(/[\\r\\n]+/gm, ' ').trim();\n // If the element is a 'br' tag\n } else if ('br' in spanEl) {\n // Create a br element.\n text += '\\n';\n }\n });\n } else if (el.hasOwnProperty('br')) {\n text += '\\n';\n } else {\n text += el['#text'].replace(/[\\r\\n]+/gm, ' ').trim();\n }\n });\n }\n\n captionArray.push({\n start: interval[0],\n end: interval[1],\n data: text,\n type: 'text'\n });\n }\n }\n }\n }\n\n if (errorMsg !== '') {\n log(errorMsg);\n }\n\n if (captionArray.length > 0) {\n return captionArray;\n } else { // This seems too strong given that there are segments with no TTML subtitles\n throw new Error(errorMsg);\n }\n }\n\n function setup() {\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n timingRegex = /^([0-9][0-9]+):([0-5][0-9]):([0-5][0-9])|(60)(\\.([0-9])+)?$/; // Regex defining the time\n fontSize = {};\n lineHeight = {};\n linePadding = {};\n defaultLayoutProperties = {\n 'top': 'auto;',\n 'left': 'auto;',\n 'width': '90%;',\n 'height': '10%;',\n 'align-items': 'flex-start;',\n 'overflow': 'visible;',\n '-ms-writing-mode': 'lr-tb, horizontal-tb;',\n '-webkit-writing-mode': 'horizontal-tb;',\n '-moz-writing-mode': 'horizontal-tb;',\n 'writing-mode': 'horizontal-tb;'\n };\n defaultStyleProperties = {\n 'color': 'rgb(255,255,255);',\n 'direction': 'ltr;',\n 'font-family': 'monospace, sans-serif;',\n 'font-style': 'normal;',\n 'line-height': 'normal;',\n 'font-weight': 'normal;',\n 'text-align': 'start;',\n 'justify-content': 'flex-start;',\n 'text-decoration': 'none;',\n 'unicode-bidi': 'normal;',\n 'white-space': 'normal;',\n 'width': '100%;'\n };\n fontFamilies = {\n monospace: 'font-family: monospace;',\n sansSerif: 'font-family: sans-serif;',\n serif: 'font-family: serif;',\n monospaceSansSerif: 'font-family: monospace, sans-serif;',\n monospaceSerif: 'font-family: monospace, serif;',\n proportionalSansSerif: 'font-family: Arial;',\n proportionalSerif: 'font-family: Times New Roman;',\n 'default': 'font-family: monospace, sans-serif;'\n };\n textAlign = {\n right: ['justify-content: flex-end;', 'text-align: right;'],\n start: ['justify-content: flex-start;', 'text-align: start;'],\n center: ['justify-content: center;', 'text-align: center;'],\n end: ['justify-content: flex-end;', 'text-align: end;'],\n left: ['justify-content: flex-start;', 'text-align: left;']\n };\n multiRowAlign = {\n start: 'text-align: start;',\n center: 'text-align: center;',\n end: 'text-align: end;',\n auto: ''\n };\n wrapOption = {\n wrap: 'white-space: normal;',\n noWrap: 'white-space: nowrap;'\n };\n unicodeBidi = {\n normal: 'unicode-bidi: normal;',\n embed: 'unicode-bidi: embed;',\n bidiOverride: 'unicode-bidi: bidi-override;'\n };\n displayAlign = {\n before: 'align-items: flex-start;',\n center: 'align-items: center;',\n after: 'align-items: flex-end;'\n };\n writingMode = {\n lrtb: '-webkit-writing-mode: horizontal-tb;' +\n 'writing-mode: horizontal-tb;',\n rltb: '-webkit-writing-mode: horizontal-tb;' +\n 'writing-mode: horizontal-tb;' +\n 'direction: rtl;' +\n 'unicode-bidi: bidi-override;',\n tbrl: '-webkit-writing-mode: vertical-rl;' +\n 'writing-mode: vertical-rl;' +\n '-webkit-text-orientation: upright;' +\n 'text-orientation: upright;',\n tblr: '-webkit-writing-mode: vertical-lr;' +\n 'writing-mode: vertical-lr;' +\n '-webkit-text-orientation: upright;' +\n 'text-orientation: upright;',\n lr: '-webkit-writing-mode: horizontal-tb;' +\n 'writing-mode: horizontal-tb;',\n rl: '-webkit-writing-mode: horizontal-tb;' +\n 'writing-mode: horizontal-tb;' +\n 'direction: rtl;',\n tb: '-webkit-writing-mode: vertical-rl;' +\n 'writing-mode: vertical-rl;' +\n '-webkit-text-orientation: upright;' +\n 'text-orientation: upright;'\n };\n converter = new X2JS({\n escapeMode: false,\n attributePrefix: '',\n arrayAccessForm: 'property',\n emptyNodeForm: 'object',\n stripWhitespaces: false,\n enableToStringFunc: false,\n matchers: []\n });\n }\n\n function parseTimings(timingStr) {\n // Test if the time provided by the caption is valid.\n var test = timingRegex.test(timingStr);\n var timeParts,\n parsedTime,\n frameRate;\n\n if (!test) {\n // Return NaN so it will throw an exception at internalParse if the time is incorrect.\n return NaN;\n }\n\n timeParts = timingStr.split(':');\n\n // Process the timings by decomposing it and converting it in numbers.\n parsedTime = (parseFloat(timeParts[0]) * SECONDS_IN_HOUR +\n parseFloat(timeParts[1]) * SECONDS_IN_MIN +\n parseFloat(timeParts[2]));\n\n // In case a frameRate is provided, we adjust the parsed time.\n if (timeParts[3]) {\n frameRate = ttml.tt.frameRate;\n if (frameRate && !isNaN(frameRate)) {\n parsedTime += parseFloat(timeParts[3]) / frameRate;\n } else {\n return NaN;\n }\n }\n return parsedTime;\n }\n\n function getNamespacePrefix(json, ns) {\n // Obtain the namespace prefix.\n var r = Object.keys(json)\n .filter(function (k) {\n return (k.split(':')[0] === 'xmlns' || k.split(':')[1] === 'xmlns') && json[k] === ns;\n }).map(function (k) {\n return k.split(':')[2] || k.split(':')[1];\n });\n if (r.length != 1) {\n return null;\n }\n return r[0];\n }\n\n function removeNamespacePrefix(json, nsPrefix) {\n for (var key in json) {\n if (json.hasOwnProperty(key)) {\n if ((typeof json[key] === 'object' || json[key] instanceof Object) && !Array.isArray(json[key])) {\n removeNamespacePrefix(json[key], nsPrefix);\n } else if (Array.isArray(json[key])) {\n for (var i = 0; i < json[key].length; i++) {\n removeNamespacePrefix(json[key][i], nsPrefix);\n }\n }\n var fullNsPrefix = nsPrefix + ':';\n var nsPrefixPos = key.indexOf(fullNsPrefix);\n if (nsPrefixPos >= 0) {\n var newKey = key.slice(nsPrefixPos + fullNsPrefix.length);\n json[newKey] = json[key];\n delete json[key];\n }\n }\n }\n }\n\n // backgroundColor = background-color, convert from camelCase to dash.\n function camelCaseToDash(key) {\n return key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }\n\n // Convert an RGBA value written in Hex to rgba(v,v,v,a).\n function convertHexToRGBA(rgba) {\n // Get the hexadecimal value without the #.\n var hex = rgba.slice(1);\n // Separate the values in pairs.\n var hexMatrice = hex.match(/.{2}/g);\n // Convert the alpha value in decimal between 0 and 1.\n var alpha = parseFloat(parseInt((parseInt(hexMatrice[3], 16) / 255) * 1000, 10) / 1000);\n // Get the standard RGB value.\n var rgb = hexMatrice.slice(0, 3).map(function (i) {\n return parseInt(i, 16);\n });\n // Return the RGBA value for CSS.\n return 'rgba(' + rgb.join(',') + ',' + alpha + ');';\n }\n\n // Convert an RGBA value written in TTML rgba(v,v,v,a => 0 to 255) to CSS rgba(v,v,v,a => 0 to 1).\n function convertAlphaValue(rgbaTTML) {\n let rgba,\n alpha,\n resu;\n\n rgba = rgbaTTML.replace(/^(rgb|rgba)\\(/,'').replace(/\\)$/,'').replace(/\\s/g,'').split(',');\n alpha = parseInt(rgba[rgba.length - 1], 10) / 255;\n resu = 'rgba(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ',' + alpha + ');';\n\n return resu;\n }\n\n // Return whether or not an array contains a certain text\n function arrayContains(text, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].indexOf(text) > -1) {\n return true;\n }\n }\n return false;\n }\n\n // Return the whole value that contains \"text\"\n function getPropertyFromArray(text, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].indexOf(text) > -1) {\n return array[i];\n }\n }\n return null;\n }\n\n // Delete a a property from an array.\n function deletePropertyFromArray(property, array) {\n array.splice(array.indexOf(getPropertyFromArray(property, array)), 1);\n }\n\n function mergeArrays(primeArray, arrayToAdd) {\n for (var i = 0; i < primeArray.length; i++) {\n for (var j = 0; j < arrayToAdd.length; j++) {\n // Take only the name of the property\n if (primeArray[i]) {\n if (primeArray[i].split(':')[0].indexOf(arrayToAdd[j].split(':')[0]) > -1) {\n primeArray.splice(i, 1);\n }\n }\n }\n }\n return primeArray.concat(arrayToAdd);\n }\n\n function getSizeTypeAndDefinition(cueStyleElement) {\n let returnTab = new Array(2);\n let startRef = cueStyleElement.indexOf(':') === -1 ? 0 : cueStyleElement.indexOf(':');\n let endRef;\n if (cueStyleElement.indexOf('%') === -1) {\n if (cueStyleElement.indexOf('c') === -1) {\n if (cueStyleElement.indexOf('p') === -1) {\n returnTab[0] = returnTab[1] = null;\n } else {\n returnTab[0] = 'p';\n endRef = cueStyleElement.indexOf('p');\n }\n } else {\n returnTab[0] = 'c';\n endRef = cueStyleElement.indexOf('c');\n }\n } else {\n returnTab[0] = '%';\n endRef = cueStyleElement.indexOf('%');\n }\n returnTab [1] = cueStyleElement.slice(startRef, endRef);\n return returnTab;\n }\n\n /**\n * Processing of styling information:\n * - processStyle: return an array of strings with the cue style under a CSS style form.\n * - findStyleFromID: Return the unprocessed style from TTMLStyling corresponding to the ID researched.\n * - getProcessedStyle: Return the processed style(s) from the ID(s) received in entry.\n * **/\n\n\n // Compute the style properties to return an array with the cleaned properties.\n function processStyle(cueStyle, cellUnit, includeRegionStyles) {\n var properties = [];\n var valueFtSizeInPx,\n valueLHSizeInPx;\n\n // Clean up from the xml2json parsing:\n for (var key in cueStyle) {\n if (cueStyle.hasOwnProperty(key)) {\n //Clean the properties from the parsing.\n var newKey = key.replace('ebutts:', '');\n newKey = newKey.replace('xml:', '');\n newKey = newKey.replace('tts:', '');\n\n // Clean the properties' names.\n newKey = camelCaseToDash(newKey);\n cueStyle[newKey] = cueStyle[key];\n delete cueStyle[key];\n }\n }\n\n // Line padding is computed from the cellResolution.\n if ('line-padding' in cueStyle) {\n var valuePadding = parseFloat(cueStyle['line-padding'].slice(cueStyle['line-padding'].indexOf(':') + 1,\n cueStyle['line-padding'].indexOf('c')));\n if ('id' in cueStyle) {\n linePadding[cueStyle.id] = valuePadding;\n }\n var valuePaddingInPx = valuePadding * cellUnit[0] + 'px;';\n properties.push('padding-left:' + valuePaddingInPx);\n properties.push('padding-right:' + valuePaddingInPx);\n }\n // Font size is computed from the cellResolution.\n if ('font-size' in cueStyle) {\n var fontSizeTab = getSizeTypeAndDefinition(cueStyle['font-size']);\n var valueFtSize = parseFloat(fontSizeTab[1]);\n if ('id' in cueStyle) {\n fontSize[cueStyle.id] = fontSizeTab;\n }\n\n if (fontSizeTab[0] === '%') {\n valueFtSizeInPx = valueFtSize / 100 * cellUnit[1] + 'px;';\n } else if (fontSizeTab[0] === 'c') {\n valueFtSizeInPx = valueFtSize * cellUnit[1] + 'px;';\n }\n\n properties.push('font-size:' + valueFtSizeInPx);\n }\n // Line height is computed from the cellResolution.\n if ('line-height' in cueStyle) {\n if (cueStyle['line-height'] === 'normal') {\n properties.push('line-height: normal;');\n } else {\n var LineHeightTab = getSizeTypeAndDefinition(cueStyle['line-height']);\n var valueLHSize = parseFloat(LineHeightTab[1]);\n if ('id' in cueStyle) {\n lineHeight[cueStyle.id] = LineHeightTab;\n }\n\n if (LineHeightTab[0] === '%') {\n valueLHSizeInPx = valueLHSize / 100 * cellUnit[1] + 'px;';\n } else if (LineHeightTab[0] === 'c') {\n valueLHSizeInPx = valueLHSize * cellUnit[1] + 'px;';\n }\n\n properties.push('line-height:' + valueLHSizeInPx);\n }\n }\n // Font-family can be specified by a generic family name or a custom family name.\n if ('font-family' in cueStyle) {\n if (cueStyle['font-family'] in fontFamilies) {\n properties.push(fontFamilies[cueStyle['font-family']]);\n } else {\n properties.push('font-family:' + cueStyle['font-family'] + ';');\n }\n }\n // Text align needs to be set from two properties:\n // The standard text-align CSS property.\n // The justify-content property as we use flex boxes.\n if ('text-align' in cueStyle) {\n if (cueStyle['text-align'] in textAlign) {\n properties.push(textAlign[cueStyle['text-align']][0]);\n properties.push(textAlign[cueStyle['text-align']][1]);\n }\n }\n // Multi Row align is set only by the text-align property.\n // TODO: TO CHECK\n if ('multi-row-align' in cueStyle) {\n if (arrayContains('text-align', properties) && cueStyle['multi-row-align'] != 'auto') {\n deletePropertyFromArray('text-align', properties);\n }\n if (cueStyle['multi-row-align'] in multiRowAlign) {\n properties.push(multiRowAlign[cueStyle['multi-row-align']]);\n }\n }\n // Background color can be specified from hexadecimal (RGB or RGBA) value.\n var rgbaValue;\n if ('background-color' in cueStyle) {\n if (cueStyle['background-color'].indexOf('#') > -1 && (cueStyle['background-color'].length - 1) === 8) {\n rgbaValue = convertHexToRGBA(cueStyle['background-color']);\n } else if (cueStyle['background-color'].indexOf('rgba') > -1) {\n rgbaValue = convertAlphaValue(cueStyle['background-color']);\n } else {\n rgbaValue = cueStyle['background-color'] + ';';\n }\n properties.push('background-color: ' + rgbaValue);\n }\n // Color can be specified from hexadecimal (RGB or RGBA) value.\n if ('color' in cueStyle) {\n if (cueStyle.color.indexOf('#') > -1 && (cueStyle.color.length - 1) === 8) {\n rgbaValue = convertHexToRGBA(cueStyle.color);\n } else if (cueStyle.color.indexOf('rgba') > -1) {\n rgbaValue = convertAlphaValue(cueStyle.color);\n } else {\n rgbaValue = cueStyle.color + ';';\n }\n properties.push('color: ' + rgbaValue);\n }\n // Wrap option is determined by the white-space CSS property.\n if ('wrap-option' in cueStyle) {\n if (cueStyle['wrap-option'] in wrapOption) {\n properties.push(wrapOption[cueStyle['wrap-option']]);\n } else {\n properties.push('white-space:' + cueStyle['wrap-option']);\n }\n }\n // Unicode bidi is determined by the unicode-bidi CSS property.\n if ('unicode-bidi' in cueStyle) {\n if (cueStyle['unicode-bidi'] in unicodeBidi) {\n properties.push(unicodeBidi[cueStyle['unicode-bidi']]);\n } else {\n properties.push('unicode-bidi:' + cueStyle['unicode-bidi']);\n }\n }\n\n // Standard properties identical to CSS.\n\n if ('font-style' in cueStyle) {\n properties.push('font-style:' + cueStyle['font-style'] + ';');\n }\n if ('font-weight' in cueStyle) {\n properties.push('font-weight:' + cueStyle['font-weight'] + ';');\n }\n if ('direction' in cueStyle) {\n properties.push('direction:' + cueStyle.direction + ';');\n }\n if ('text-decoration' in cueStyle) {\n properties.push('text-decoration:' + cueStyle['text-decoration'] + ';');\n }\n\n if (includeRegionStyles) {\n properties = properties.concat(processRegion(cueStyle, cellUnit));\n }\n\n // Handle white-space preserve\n if (ttml.tt.hasOwnProperty('xml:space')) {\n if (ttml.tt['xml:space'] === 'preserve') {\n properties.push('white-space: pre;');\n }\n }\n\n return properties;\n }\n\n // Find the style set by comparing the style IDs available.\n // Return null if no style is found\n function findStyleFromID(ttmlStyling, cueStyleID) {\n // For every styles available, search the corresponding style in ttmlStyling.\n for (var j = 0; j < ttmlStyling.length; j++) {\n var currStyle = ttmlStyling[j];\n if (currStyle['xml:id'] === cueStyleID || currStyle.id === cueStyleID) {\n // Return the style corresponding to the ID in parameter.\n return currStyle;\n }\n }\n return null;\n }\n // Return the computed style from a certain ID.\n function getProcessedStyle(reference, cellUnit, includeRegionStyles) {\n var styles = [];\n var ids = reference.match(/\\S+/g);\n ids.forEach(function (id) {\n // Find the style for each id received.\n var cueStyle = findStyleFromID(ttmlStyling, id);\n if (cueStyle) {\n // Process the style for the cue in CSS form.\n // Send a copy of the style object, so it does not modify the original by cleaning it.\n var stylesFromId = processStyle(JSON.parse(JSON.stringify(cueStyle)), cellUnit, includeRegionStyles);\n styles = styles.concat(stylesFromId);\n }\n });\n return styles;\n }\n\n // Calculate relative left, top, width, height from extent and origin in percent.\n // Return object with {left, top, width, height} as numbers in percent or null.\n function getRelativePositioning(element, ttExtent) {\n\n let pairRe = /([\\d\\.]+)(%|px)\\s+([\\d\\.]+)(%|px)/;\n\n if (('tts:extent' in element) && ('tts:origin' in element) ) {\n let extentParts = pairRe.exec(element['tts:extent']);\n let originParts = pairRe.exec(element['tts:origin']);\n if (extentParts === null || originParts === null) {\n log('Bad extent or origin: ' + element['tts:extent'] + ' ' + element['tts:origin']);\n return null;\n }\n let width = parseFloat(extentParts[1]);\n let height = parseFloat(extentParts[3]);\n let left = parseFloat(originParts[1]);\n let top = parseFloat(originParts[3]);\n\n if (ttExtent) { // Should give overall scale in pixels\n let ttExtentParts = pairRe.exec(ttExtent);\n if (ttExtentParts === null || ttExtentParts[2] !== 'px' || ttExtentParts[4] !== 'px') {\n log('Bad tt.extent: ' + ttExtent);\n return null;\n }\n let exWidth = parseFloat(ttExtentParts[1]);\n let exHeight = parseFloat(ttExtentParts[3]);\n if (extentParts[2] === 'px') {\n width = width / exWidth * 100;\n }\n if (extentParts[4] === 'px') {\n height = height / exHeight * 100;\n }\n if (originParts[2] === 'px') {\n left = left / exWidth * 100;\n }\n if (originParts[4] === 'px') {\n top = top / exHeight * 100;\n }\n }\n return { 'left': left, 'top': top, 'width': width, 'height': height };\n } else {\n return null;\n }\n }\n\n /**\n * Processing of layout information:\n * - processRegion: return an array of strings with the cue region under a CSS style form.\n * - findRegionFromID: Return the unprocessed region from TTMLLayout corresponding to the ID researched.\n * - getProcessedRegion: Return the processed region(s) from the ID(s) received in entry.\n ***/\n\n // Compute the region properties to return an array with the cleaned properties.\n function processRegion(cueRegion, cellUnit) {\n var properties = [];\n\n // Clean up from the xml2json parsing:\n for (var key in cueRegion) {\n //Clean the properties from the parsing.\n var newKey = key.replace('tts:', '');\n newKey = newKey.replace('xml:', '');\n\n // Clean the properties' names.\n newKey = camelCaseToDash(newKey);\n cueRegion[newKey] = cueRegion[key];\n if (newKey !== key) {\n delete cueRegion[key];\n }\n }\n // Extent property corresponds to width and height\n if ('extent' in cueRegion) {\n var coordsExtent = cueRegion.extent.split(/\\s/);\n properties.push('width: ' + coordsExtent[0] + ';');\n properties.push('height: ' + coordsExtent[1] + ';');\n }\n // Origin property corresponds to top and left\n if ('origin' in cueRegion) {\n var coordsOrigin = cueRegion.origin.split(/\\s/);\n properties.push('left: ' + coordsOrigin[0] + ';');\n properties.push('top: ' + coordsOrigin[1] + ';');\n }\n // DisplayAlign property corresponds to vertical-align\n if ('display-align' in cueRegion) {\n properties.push(displayAlign[cueRegion['display-align']]);\n }\n // WritingMode is not yet implemented (for CSS3, to come)\n if ('writing-mode' in cueRegion) {\n properties.push(writingMode[cueRegion['writing-mode']]);\n }\n // Style will give to the region the style properties from the style selected\n if ('style' in cueRegion) {\n var styleFromID = getProcessedStyle(cueRegion.style, cellUnit, true);\n properties = properties.concat(styleFromID);\n }\n\n // Standard properties identical to CSS.\n\n if ('padding' in cueRegion) {\n properties.push('padding:' + cueRegion.padding + ';');\n }\n if ('overflow' in cueRegion) {\n properties.push('overflow:' + cueRegion.overflow + ';');\n }\n if ('show-background' in cueRegion) {\n properties.push('show-background:' + cueRegion['show-background'] + ';');\n }\n if ('id' in cueRegion) {\n properties.push('regionID:' + cueRegion.id + ';');\n }\n\n return properties;\n }\n\n // Find the region set by comparing the region IDs available.\n // Return null if no region is found\n function findRegionFromID(ttmlLayout, cueRegionID) {\n // For every region available, search the corresponding style in ttmlLayout.\n for (var j = 0; j < ttmlLayout.length; j++) {\n var currReg = ttmlLayout[j];\n if (currReg['xml:id'] === cueRegionID || currReg.id === cueRegionID) {\n // Return the region corresponding to the ID in parameter.\n return currReg;\n }\n }\n return null;\n }\n\n // Return the computed region from a certain ID.\n function getProcessedRegion(reference, cellUnit) {\n var regions = [];\n var ids = reference.match(/\\S+/g);\n ids.forEach(function (id) {\n // Find the region for each id received.\n var cueRegion = findRegionFromID(ttmlLayout, id);\n if (cueRegion) {\n // Process the region for the cue in CSS form.\n // Send a copy of the style object, so it does not modify the original by cleaning it.\n var regionsFromId = processRegion(JSON.parse(JSON.stringify(cueRegion)), cellUnit);\n regions = regions.concat(regionsFromId);\n }\n });\n return regions;\n }\n\n //Return the cellResolution defined by the TTML document.\n function getCellResolution() {\n var defaultCellResolution = [32, 15]; // Default cellResolution.\n if (ttml.tt.hasOwnProperty('ttp:cellResolution')) {\n return ttml.tt['ttp:cellResolution'].split(' ').map(parseFloat);\n } else {\n return defaultCellResolution;\n }\n }\n\n // Return the cue wrapped into a span specifying its linePadding.\n function applyLinePadding(cueHTML, cueStyle) {\n // Extract the linePadding property from cueStyleProperties.\n var linePaddingLeft = getPropertyFromArray('padding-left', cueStyle);\n var linePaddingRight = getPropertyFromArray('padding-right', cueStyle);\n var linePadding = linePaddingLeft.concat(' ' + linePaddingRight + ' ');\n\n // Declaration of the HTML elements to be used in the cue innerHTML construction.\n var outerHTMLBeforeBr = '';\n var outerHTMLAfterBr = '';\n var cueInnerHTML = '';\n\n // List all the nodes of the subtitle.\n var nodeList = Array.prototype.slice.call(cueHTML.children);\n // Take a br element as reference.\n var brElement = cueHTML.getElementsByClassName('lineBreak')[0];\n // First index of the first br element.\n var idx = nodeList.indexOf(brElement);\n // array of all the br element indices\n var indices = [];\n // Find all the indices of the br elements.\n while (idx != -1) {\n indices.push(idx);\n idx = nodeList.indexOf(brElement, idx + 1);\n }\n\n // Strings for the cue innerHTML construction.\n var spanStringEnd = '<\\/span>';\n var br = '<br>';\n var clonePropertyString = '<span' + ' class=\"spanPadding\" ' + 'style=\"-webkit-box-decoration-break: clone; box-decoration-break: clone; ';\n\n // If br elements are found:\n if (indices.length) {\n // For each index of a br element we compute the HTML coming before and/or after it.\n indices.forEach(function (i, index) {\n // If this is the first line break, we compute the HTML of the element coming before.\n if (index === 0) {\n var styleBefore = '';\n // for each element coming before the line break, we add its HTML.\n for (var j = 0; j < i; j++) {\n outerHTMLBeforeBr += nodeList[j].outerHTML;\n // If this is the first element, we add its style to the wrapper.\n if (j === 0) {\n styleBefore = linePadding.concat(nodeList[j].style.cssText);\n }\n }\n // The before element will comprises the clone property (for line wrapping), the style that\n // need to be applied (ex: background-color) and the rest og the HTML.\n outerHTMLBeforeBr = clonePropertyString + styleBefore + '\">' + outerHTMLBeforeBr;\n }\n // For every element of the list, we compute the element coming after the line break.s\n var styleAfter = '';\n // for each element coming after the line break, we add its HTML.\n for (var k = i + 1; k < nodeList.length; k++) {\n outerHTMLAfterBr += nodeList[k].outerHTML;\n // If this is the last element, we add its style to the wrapper.\n if (k === nodeList.length - 1) {\n styleAfter += linePadding.concat(nodeList[k].style.cssText);\n }\n }\n\n // The before element will comprises the clone property (for line wrapping), the style that\n // need to be applied (ex: background-color) and the rest og the HTML.\n outerHTMLAfterBr = clonePropertyString + styleAfter + '\">' + outerHTMLAfterBr;\n\n // For each line break we must add the before and/or after element to the final cue as well as\n // the line break when needed.\n if (outerHTMLBeforeBr && outerHTMLAfterBr && index === (indices.length - 1)) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd + br + outerHTMLAfterBr + spanStringEnd;\n } else if (outerHTMLBeforeBr && outerHTMLAfterBr && index !== (indices.length - 1)) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd + br + outerHTMLAfterBr + spanStringEnd + br;\n } else if (outerHTMLBeforeBr && !outerHTMLAfterBr) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd;\n } else if (!outerHTMLBeforeBr && outerHTMLAfterBr && index === (indices.length - 1)) {\n cueInnerHTML += outerHTMLAfterBr + spanStringEnd;\n } else if (!outerHTMLBeforeBr && outerHTMLAfterBr && index !== (indices.length - 1)) {\n cueInnerHTML += outerHTMLAfterBr + spanStringEnd + br;\n }\n });\n } else {\n // If there is no line break in the subtitle, we simply wrap cue in a span indicating the linePadding.\n var style = '';\n for (var k = 0; k < nodeList.length; k++) {\n style += nodeList[k].style.cssText;\n }\n cueInnerHTML = clonePropertyString + linePadding + style + '\">' + cueHTML.innerHTML + spanStringEnd;\n }\n return cueInnerHTML;\n }\n\n /*\n * Create the cue element\n * I. The cues are text only:\n * i) The cue contains a 'br' element\n * ii) The cue contains a span element\n * iii) The cue contains text\n */\n\n function constructCue(cueElements, cellUnit) {\n var cue = document.createElement('div');\n cueElements.forEach(function (el) {\n // If metadata is present, do not process.\n if (el.hasOwnProperty('metadata')) {\n return;\n }\n\n /**\n * If the p element contains spans: create the span elements.\n */\n if (el.hasOwnProperty('span')) {\n\n // Stock the span subtitles in an array (in case there are only one value).\n var spanElements = el.span.__children;\n\n // Create the span element.\n var spanHTMLElement = document.createElement('span');\n // Extract the style of the span.\n if (el.span.hasOwnProperty('style')) {\n var spanStyle = getProcessedStyle(el.span.style, cellUnit);\n spanHTMLElement.className = 'spanPadding ' + el.span.style;\n spanHTMLElement.style.cssText = spanStyle.join(' ');\n }\n\n\n // if the span has more than one element, we check for each of them their nature (br or text).\n spanElements.forEach(function (spanEl) {\n // If metadata is present, do not process.\n if (spanElements.hasOwnProperty('metadata')) {\n return;\n }\n // If the element is a string\n if (spanEl.hasOwnProperty('#text')) {\n var textNode = document.createTextNode(spanEl['#text']);\n spanHTMLElement.appendChild(textNode);\n // If the element is a 'br' tag\n } else if ('br' in spanEl) {\n // To handle br inside span we need to add the current span\n // to the cue and then create a br and add that the cue\n // then create a new span that we use for the next line of\n // text, that is a copy of the current span\n\n // Add the current span to the cue, only if it has childNodes (text)\n if (spanHTMLElement.hasChildNodes()) {\n cue.appendChild(spanHTMLElement);\n }\n\n // Create a br and add that to the cue\n var brEl = document.createElement('br');\n brEl.className = 'lineBreak';\n cue.appendChild(brEl);\n\n // Create an replacement span and copy the style and classname from the old one\n var newSpanHTMLElement = document.createElement('span');\n newSpanHTMLElement.className = spanHTMLElement.className;\n newSpanHTMLElement.style.cssText = spanHTMLElement.style.cssText;\n\n // Replace the current span with the one we just created\n spanHTMLElement = newSpanHTMLElement;\n }\n });\n // We append the element to the cue container.\n cue.appendChild(spanHTMLElement);\n }\n\n /**\n * Create a br element if there is one in the cue.\n */\n else if (el.hasOwnProperty('br')) {\n // We append the line break to the cue container.\n var brEl = document.createElement('br');\n brEl.className = 'lineBreak';\n cue.appendChild(brEl);\n }\n\n /**\n * Add the text that is not in any inline element\n */\n else if (el.hasOwnProperty('#text')) {\n // Add the text to an individual span element (to add line padding if it is defined).\n var textNode = document.createElement('span');\n textNode.textContent = el['#text'];\n\n // We append the element to the cue container.\n cue.appendChild(textNode);\n }\n });\n return cue;\n }\n\n function constructCueRegion(cue, div, cellUnit) {\n var cueRegionProperties = []; // properties to be put in the \"captionRegion\" HTML element\n // Obtain the region ID(s) assigned to the cue.\n var pRegionID = cue.region;\n // If div has a region.\n var divRegionID = div.region;\n\n var divRegion;\n var pRegion;\n\n // If the div element reference a region.\n if (divRegionID) {\n divRegion = getProcessedRegion(divRegionID, cellUnit);\n }\n // If the p element reference a region.\n if (pRegionID) {\n pRegion = cueRegionProperties.concat(getProcessedRegion(pRegionID, cellUnit));\n if (divRegion) {\n cueRegionProperties = mergeArrays(divRegion, pRegion);\n } else {\n cueRegionProperties = pRegion;\n }\n } else if (divRegion) {\n cueRegionProperties = divRegion;\n }\n\n // Add initial/default values to what's not defined in the layout:\n applyDefaultProperties(cueRegionProperties, defaultLayoutProperties);\n\n return cueRegionProperties;\n }\n\n function constructCueStyle(cue, cellUnit) {\n var cueStyleProperties = []; // properties to be put in the \"paragraph\" HTML element\n // Obtain the style ID(s) assigned to the cue.\n var pStyleID = cue.style;\n // If body has a style.\n var bodyStyleID = ttml.tt.body.style;\n // If div has a style.\n var divStyleID = ttml.tt.body.div.style;\n\n var bodyStyle;\n var divStyle;\n var pStyle;\n var styleIDs = '';\n\n // If the body element reference a style.\n if (bodyStyleID) {\n bodyStyle = getProcessedStyle(bodyStyleID, cellUnit);\n styleIDs = 'paragraph ' + bodyStyleID;\n }\n\n // If the div element reference a style.\n if (divStyleID) {\n divStyle = getProcessedStyle(divStyleID, cellUnit);\n if (bodyStyle) {\n divStyle = mergeArrays(bodyStyle, divStyle);\n styleIDs += ' ' + divStyleID;\n } else {\n styleIDs = 'paragraph ' + divStyleID;\n }\n }\n\n // If the p element reference a style.\n if (pStyleID) {\n pStyle = getProcessedStyle(pStyleID, cellUnit);\n if (bodyStyle && divStyle) {\n cueStyleProperties = mergeArrays(divStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else if (bodyStyle) {\n cueStyleProperties = mergeArrays(bodyStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else if (divStyle) {\n cueStyleProperties = mergeArrays(divStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else {\n cueStyleProperties = pStyle;\n styleIDs = 'paragraph ' + pStyleID;\n }\n } else if (bodyStyle && !divStyle) {\n cueStyleProperties = bodyStyle;\n } else if (!bodyStyle && divStyle) {\n cueStyleProperties = divStyle;\n }\n\n\n // Add initial/default values to what's not defined in the styling:\n applyDefaultProperties(cueStyleProperties, defaultStyleProperties);\n\n return [cueStyleProperties, styleIDs];\n }\n\n function applyDefaultProperties(array, defaultProperties) {\n for (var key in defaultProperties) {\n if (defaultProperties.hasOwnProperty(key)) {\n if (!arrayContains(key, array)) {\n array.push(key + ':' + defaultProperties[key]);\n }\n }\n }\n }\n\n instance = {\n parse: parse,\n setConfig: setConfig\n };\n\n setup();\n return instance;\n}", "parseStdOut(data) {\n const lines = data.split('\\n');\n lines.forEach(line => {\n debug(line);\n const match = REG_EXP.exec(colors.strip(line));\n if (match) {\n const summaryHashrate = parseFloat(match[1]);\n const acceptedShares = parseFloat(match[8]);\n const rejectedShares = parseFloat(match[9]);\n const faultShares = parseFloat(match[10]);\n this.setTotalHashrate(summaryHashrate);\n this.acceptPercent = 100 * acceptedShares / (acceptedShares + rejectedShares + faultShares);\n }\n });\n }", "function RawStream(str) {\n this.data = str;\n this.i = 0;\n this.symbols = new Stack(this.data.length);\n}", "_timeout() {\n this.log.debug('[Demux] Timeout reached');\n\n // The stream will eventually call _destroy which will properly handle the cleanup.\n this.end();\n }", "parse() {\n while (this.shouldContinue()) {\n const c = this.buffer.charCodeAt(this.index - this.offset);\n switch (this.state) {\n case Tokenizer_State.Text: {\n this.stateText(c);\n break;\n }\n case Tokenizer_State.SpecialStartSequence: {\n this.stateSpecialStartSequence(c);\n break;\n }\n case Tokenizer_State.InSpecialTag: {\n this.stateInSpecialTag(c);\n break;\n }\n case Tokenizer_State.CDATASequence: {\n this.stateCDATASequence(c);\n break;\n }\n case Tokenizer_State.InAttributeValueDq: {\n this.stateInAttributeValueDoubleQuotes(c);\n break;\n }\n case Tokenizer_State.InAttributeName: {\n this.stateInAttributeName(c);\n break;\n }\n case Tokenizer_State.InCommentLike: {\n this.stateInCommentLike(c);\n break;\n }\n case Tokenizer_State.InSpecialComment: {\n this.stateInSpecialComment(c);\n break;\n }\n case Tokenizer_State.BeforeAttributeName: {\n this.stateBeforeAttributeName(c);\n break;\n }\n case Tokenizer_State.InTagName: {\n this.stateInTagName(c);\n break;\n }\n case Tokenizer_State.InClosingTagName: {\n this.stateInClosingTagName(c);\n break;\n }\n case Tokenizer_State.BeforeTagName: {\n this.stateBeforeTagName(c);\n break;\n }\n case Tokenizer_State.AfterAttributeName: {\n this.stateAfterAttributeName(c);\n break;\n }\n case Tokenizer_State.InAttributeValueSq: {\n this.stateInAttributeValueSingleQuotes(c);\n break;\n }\n case Tokenizer_State.BeforeAttributeValue: {\n this.stateBeforeAttributeValue(c);\n break;\n }\n case Tokenizer_State.BeforeClosingTagName: {\n this.stateBeforeClosingTagName(c);\n break;\n }\n case Tokenizer_State.AfterClosingTagName: {\n this.stateAfterClosingTagName(c);\n break;\n }\n case Tokenizer_State.BeforeSpecialS: {\n this.stateBeforeSpecialS(c);\n break;\n }\n case Tokenizer_State.InAttributeValueNq: {\n this.stateInAttributeValueNoQuotes(c);\n break;\n }\n case Tokenizer_State.InSelfClosingTag: {\n this.stateInSelfClosingTag(c);\n break;\n }\n case Tokenizer_State.InDeclaration: {\n this.stateInDeclaration(c);\n break;\n }\n case Tokenizer_State.BeforeDeclaration: {\n this.stateBeforeDeclaration(c);\n break;\n }\n case Tokenizer_State.BeforeComment: {\n this.stateBeforeComment(c);\n break;\n }\n case Tokenizer_State.InProcessingInstruction: {\n this.stateInProcessingInstruction(c);\n break;\n }\n case Tokenizer_State.InNamedEntity: {\n this.stateInNamedEntity(c);\n break;\n }\n case Tokenizer_State.BeforeEntity: {\n this.stateBeforeEntity(c);\n break;\n }\n case Tokenizer_State.InHexEntity: {\n this.stateInHexEntity(c);\n break;\n }\n case Tokenizer_State.InNumericEntity: {\n this.stateInNumericEntity(c);\n break;\n }\n default: {\n // `this._state === State.BeforeNumericEntity`\n this.stateBeforeNumericEntity(c);\n }\n }\n this.index++;\n }\n this.cleanup();\n }", "function Parse(input) {\n // Decode an incoming message to an object of fields.\n var b = bytes(atob(input.data));\n // use TTN decoder:\n var decoded = Decoder(b, input.fPort);\n // Update values in device properties\n status_update_device(decoded);\n return decoded;\n}", "processLastChangeEvent(body)\r\n\t{\r\n\t\t//Si le body est null on ne fait rien\r\n if (body == null)\r\n {\r\n Logger.log(\"Empty body in processLastChangeEvent. Do nothing...\", LogType.DEBUG);\r\n return;\r\n }\r\n //Si c'est déjà un objet, on le traite, sinon on le parse puis on le traite\r\n\t\t//Il faut gérer plusieur cas, test OK sur TV LG et Freeplayer\r\n\t\tif (body.Event)\r\n\t\t{\r\n\t\t\tLogger.log(\"Body LastChange Event \" + JSON.stringify(body.Event), LogType.DEBUG);\r\n\t\t\tvar eventProperties = body.Event[0];\r\n\t\t\tif (!eventProperties)\r\n\t\t\t\teventProperties = body.Event;\r\n\t\t\tvar instance = eventProperties;\r\n if (eventProperties.InstanceID && eventProperties.InstanceID[0]) instance = eventProperties.InstanceID[0];\r\n\t\t\tfor (var prop in instance)\r\n\t\t\t{\r\n\t\t\t\tif (prop == '$')\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tLogger.log(\"Processing update propertie \" + JSON.stringify(prop) + \" with val \" + JSON.stringify(instance[prop][0]['$'].val), LogType.DEBUG);\r\n\t\t\t\tvar variable = this.getVariableByName(prop);\r\n\t\t\t\tif (variable)\r\n\t\t\t\t{\r\n\t\t\t\t\tvariable.Value = instance[prop][0]['$'].val;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t\tLogger.log(\"Unable to process LastChange propertie Event \" + prop + \" with value \" + instance[prop][0]['$'].val + \" of service \" + this.Device.UDN + \"::\" + this.ID, LogType.WARNING);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\txml2js.parseString(body, (err, data) => {\r\n\t\t\t\t//Manage Error\r\n\t\t\t\tif (err)\r\n\t\t\t\t{\r\n\t\t\t\t\tLogger.log(\"Error decoding LastChange Event : \" + this.Device.UDN + '::' + this.ID + \" ==> xml : \" + JSON.stringify(body) + \", err : \" + err, LogType.ERROR);\r\n\t\t\t\t\tthis.Device.emit('error', \"Error decoding LastChange Event : \" + this.Device.UDN + '::' + this.ID + \" ==> xml : \" + JSON.stringify(body) + \", err : \" + err);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t\tthis.processLastChangeEvent(data)\r\n\t\t\t});\r\n\t\t}\r\n\t}", "dataMessage () {\n if (this.fin) {\n const messageLength = this.messageLength;\n const fragments = this.fragments;\n\n this.totalPayloadLength = 0;\n this.messageLength = 0;\n this.fragmented = 0;\n this.fragments = [];\n\n if (this.opcode === 2) {\n var data;\n\n if (this.binaryType === 'nodebuffer') {\n data = toBuffer(fragments, messageLength);\n } else if (this.binaryType === 'arraybuffer') {\n data = toArrayBuffer(toBuffer(fragments, messageLength));\n } else {\n data = fragments;\n }\n\n this.onmessage(data, { masked: this.masked, binary: true });\n } else {\n const buf = toBuffer(fragments, messageLength);\n\n if (!isValidUTF8(buf)) {\n this.error(new Error('invalid utf8 sequence'), 1007);\n return;\n }\n\n this.onmessage(buf.toString(), { masked: this.masked });\n }\n }\n\n this.state = GET_INFO;\n }", "dataMessage () {\n if (this._fin) {\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n var data;\n\n if (this._binaryType === 'nodebuffer') {\n data = toBuffer(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(toBuffer(fragments, messageLength));\n } else {\n data = fragments;\n }\n\n this.onmessage(data);\n } else {\n const buf = toBuffer(fragments, messageLength);\n\n if (!Validation(buf)) {\n this.error(new Error('invalid utf8 sequence'), 1007);\n return;\n }\n\n this.onmessage(buf.toString());\n }\n }\n\n this._state = GET_INFO;\n }", "function parseControlResponse(text) {\n const lines = text.split(/\\r?\\n/).filter(isNotBlank);\n const messages = [];\n let startAt = 0;\n let tokenRegex;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n // No group has been opened.\n if (!tokenRegex) {\n if (isMultiline(line)) {\n // Open a group by setting an expected token.\n const token = line.substr(0, 3);\n tokenRegex = new RegExp(`^${token}(?:$| )`);\n startAt = i;\n }\n else if (isSingleLine(line)) {\n // Single lines can be grouped immediately.\n messages.push(line);\n }\n }\n // Group has been opened, expect closing token.\n else if (tokenRegex.test(line)) {\n tokenRegex = undefined;\n messages.push(lines.slice(startAt, i + 1).join(LF));\n }\n }\n // The last group might not have been closed, report it as a rest.\n const rest = tokenRegex ? lines.slice(startAt).join(LF) + LF : \"\";\n return { messages, rest };\n}", "out(out){\n this.emit(this.events.DATA,out.map((a) => {\n let al = a.length;\n a[0] = this.sanitize(a[0]);\n if(al === 2) a[2] = this.nowSec\n return {'name':a[0],'value':a[1],'time':a[2]};\n }));\n }", "function ready(response) {\n switch (args.named[\"--output\"]) {\n case \"stat\":\n console.log(response.status);\n break;\n case \"head\":\n console.log(response.statusLine);\n console.log(response.getHeaderString());\n break;\n case \"headers\":\n console.log(response.getHeaderString());\n break;\n case \"body\":\n if (response.data) console.log(response.data);\n break;\n case \"status\":\n console.log(response.statusLine);\n break;\n case \"full\":\n console.log(response.statusLine);\n console.log(response.getHeaderString());\n if (response.data) console.log(response.data);\n break;\n case \"auto\":\n case false:\n if (response.data) console.log(response.data);\n else {\n console.log(response.statusLine);\n console.log(response.getHeaderString());\n }\n break;\n default:\n throw new Error(\"unrecognized out format \" + args.named[\"-o\"]);\n }\n }", "onInstancesReceived(err, result) {\n if (this.timeoutId !== undefined) {\n clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n\n if (!err) {\n this.instances = result;\n this.setState({ instances: result });\n this.pingLoop = setInterval(this.pingAllInstances, 1000);\n this.postLoadState = STATE_OK;\n if (this.loadedMinTime) {\n this.setState({ state: STATE_OK });\n }\n } else {\n if (err === deepstream.CONSTANTS.EVENT.NO_RPC_PROVIDER) {\n this.error = 'Service is not responding';\n } else {\n this.error = err;\n }\n this.postLoadState = STATE_ERROR;\n if (this.loadedMinTime) {\n this.setState({ state: STATE_ERROR });\n }\n }\n }", "static handleOutput(evt){\n // response info includes response event object and output string \n IpcResponder.respond(GHCI_PROCESS.responseEvt, \"ghci\", {str: evt.str});\n }", "constructor() {\n this._output;\n }", "function parseStatusOutput(stdout) {\n const info = {};\n\n stdout.split('\\n').forEach((l) => {\n if ( l.trim().length ) {\n const spl = l.trim().split(': ', 2);\n if ( spl.length !== 2 ) {\n info.Description += l;\n } else {\n info[spl[0]] = spl[1];\n }\n }\n });\n\n return info;\n}", "function liveStreamCallback(historyData) {\n setHistoryTips();\n updateStats(historyData);\n}", "dataMessage () {\n\t if (this.fin) {\n\t const messageLength = this.messageLength;\n\t const fragments = this.fragments;\n\n\t this.totalPayloadLength = 0;\n\t this.messageLength = 0;\n\t this.fragmented = 0;\n\t this.fragments = [];\n\n\t if (this.opcode === 2) {\n\t var data;\n\n\t if (this.binaryType === 'nodebuffer') {\n\t data = toBuffer(fragments, messageLength);\n\t } else if (this.binaryType === 'arraybuffer') {\n\t data = toArrayBuffer(toBuffer(fragments, messageLength));\n\t } else {\n\t data = fragments;\n\t }\n\n\t this.onmessage(data, { masked: this.masked, binary: true });\n\t } else {\n\t const buf = toBuffer(fragments, messageLength);\n\n\t if (!isValidUTF8(buf)) {\n\t this.error(new Error('invalid utf8 sequence'), 1007);\n\t return;\n\t }\n\n\t this.onmessage(buf.toString(), { masked: this.masked });\n\t }\n\t }\n\n\t this.state = GET_INFO;\n\t }", "ohlcv() {\n const self = this\n const stream = new Transform({\n objectMode: true,\n transform(chunk, encoding, callback) {\n self.analyze(chunk, callback)\n }\n })\n return stream\n }", "function buildMainStream() {\n var mainStream = [];\n // runInstances\n mainStream.push(function (callback) {\n ec2.runInstances(params, function(error, result) {\n if (error) {\n log.error(\"Could not create instance\", error);\n return callback(error);\n }\n var instances = result.Instances;\n var response = instances.map(function (instance) {\n return {\n name: config.ESNameTag,\n id: instance.InstanceId,\n privateIp: instance.PrivateIpAddress\n };\n });\n return callback(null, response);\n });\n });\n // createTags\n mainStream.push(function (response, callback) {\n var instanceIds = response.map(function (instance) {\n return instance.id;\n });\n log.debug(\"Instances being created\", instanceIds, \"Tagging...\");\n var createTagsParams = {\n Resources: instanceIds,\n Tags: [\n {Key: \"Name\", Value: config.ESNameTag},\n {Key: \"Group\", Value: config.ESGroupTag}\n ]\n };\n ec2.createTags(createTagsParams, function(error) {\n if (error) {\n log.error(\"Could not tag instances \" + instanceIds + \". PLEASE DO IT MANUALLY. Add the following tags: {\\\"Name\\\":\\\"\" + config.ESNameTag + \"\\\"} and {\\\"Group\\\":\\\"\" + config.ESGroupTag + \"\\\"}\");\n }\n return callback(null, response);\n });\n });\n return mainStream;\n }", "setupDataHandlers() {\n this.dc.onmessage = (e) => {\n var msg = JSON.parse(e.data);\n console.log(\"received message over data channel:\" + msg);\n };\n this.dc.onclose = () => {\n this.remoteStream.getVideoTracks()[0].stop();\n console.log(\"The Data Channel is Closed\");\n };\n }", "dataMessage () {\n\t if (this._fin) {\n\t const messageLength = this._messageLength;\n\t const fragments = this._fragments;\n\n\t this._totalPayloadLength = 0;\n\t this._messageLength = 0;\n\t this._fragmented = 0;\n\t this._fragments = [];\n\n\t if (this._opcode === 2) {\n\t var data;\n\n\t if (this._binaryType === 'nodebuffer') {\n\t data = toBuffer(fragments, messageLength);\n\t } else if (this._binaryType === 'arraybuffer') {\n\t data = toArrayBuffer(toBuffer(fragments, messageLength));\n\t } else {\n\t data = fragments;\n\t }\n\n\t this.onmessage(data);\n\t } else {\n\t const buf = toBuffer(fragments, messageLength);\n\n\t if (!isValidUTF8(buf)) {\n\t this.error(new Error('invalid utf8 sequence'), 1007);\n\t return;\n\t }\n\n\t this.onmessage(buf.toString());\n\t }\n\t }\n\n\t this._state = GET_INFO;\n\t }", "function parse({ status, callbacks , isFirst = false, separator }) {\n logger(`browser-sdk :: chunkParser :: parse :: id = ${status.id}`);\n if ((isFirst || status.state == STATES.ERROR_UNPARSED) && !status.isOk) {\n // there has been an error in the initial http response\n processGenericError(status, callbacks);\n return;\n }\n\n const lastLineIndex = status.bufferString.lastIndexOf(separator);\n const lasLineIsComplete = lastLineIndex === status.bufferString.length;\n if(lastLineIndex >= 0){\n const lines = parseBufferStringJson(status, lastLineIndex, separator);\n if(!lasLineIsComplete){\n status.bufferString = status.bufferString.substring(lastLineIndex + 1);\n }else{\n status.bufferString = null;\n status.bufferString = '';\n }\n\n if(lines == null){\n processGenericError(status, callbacks);\n return;\n }\n\n while(lines.length > 0){\n try {\n const line = lines.shift();\n if (isData(line)) {\n addToPending(callbacks, 'processEvents', line.d);\n status.state = STATES.EVENT;\n } else if (isProgress(line)) {\n addToPending(callbacks, 'processProgress', line.p);\n status.state = STATES.EVENT;\n } else if (isMetadata(line)) {\n addToPending(callbacks, 'processMeta', line.metadata || line.m);\n status.state = STATES.METADATA;\n } else if (\n isErrorFormat1(line)\n || isErrorFormat2(line)\n || isErrorFormat3(line)\n ) {\n throw processErrorParsed(callbacks, status, line);\n } else {\n // this should never happen\n throw processGenericError(status, callbacks);\n }\n }\n catch (error) {\n if (error) {\n joinMsgsIfObjectHasStrings(error);\n logger(`browser-sdk :: chunksParser :: parse :: id = ${status.id} :: errorParsed = ${status.state}:: errorMsg = ${error.msg} :: bufferString = ${status.bufferString}`);\n const e = new Error();\n e.message = error.msg;\n throw e;\n }\n }\n }\n }\n}", "wait_HumanPlay_response() {\n if (this.lastResponse[0] != this.client.response[0]) {\n this.lastResponse = this.client.response;\n this.parseResponse(this.lastResponse[1]);\n this.state = 'WAIT_ANIMATION_END';\n }\n }", "dataMessage () {\n if (this._fin) {\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n var data;\n\n if (this._binaryType === 'nodebuffer') {\n data = toBuffer(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(toBuffer(fragments, messageLength));\n } else {\n data = fragments;\n }\n\n this.onmessage(data);\n } else {\n const buf = toBuffer(fragments, messageLength);\n\n if (!validation.isValidUTF8(buf)) {\n this.error(\n new Error('Invalid WebSocket frame: invalid UTF-8 sequence'),\n 1007\n );\n return;\n }\n\n this.onmessage(buf.toString());\n }\n }\n\n this._state = GET_INFO;\n }", "async fetchTimeframes() {\n const url = this.createUrlBuilder().build();\n return timeframes_1.parseTimeframesPage(await this.request(url, \"txt\" /* TEXT */));\n }", "function MetadataParser() {\n\n var cfg = new Config();\n\n ffmpeg.setFfmpegPath(cfg.ffmpegPath);\n ffmpeg.setFfprobePath(cfg.ffprobePath);\n\n this.metadata = \"\";\n}", "transform(chunk, encoding, callback) {\n output.NumberOfLines += chunk.toString().split('\\n').length;\n output.LengthInBytes += chunk.length;\n output.TimeElapsed = milliSeconds;\n this.push(output); // Pushes the calculated values into the object output\n callback(); // A function that needs to be called after we're done processing the data chunk\n }", "getChunkHandler() {\n var decoder = new TextDecoder();\n var partial = false;\n return (data) => {\n var currentTime = (new Date()).getTime();\n var elapsedMillis = currentTime - this.prevChunkRecvTime;\n this.prevChunkRecvTime = currentTime;\n\n if(data.done) {\n return true;\n }\n\n var chunk = decoder.decode(data.value || new Uint8Array, {stream: !data.done});\n var startIdx = 0, msg;\n if(partial) {\n var partialEnd = chunk.indexOf(\"}{\", startIdx);\n if(partialEnd == -1) {\n console.debug(\"Another partial received in entirety, skipping chunk\");\n startIdx = chunk.length;\n } else {\n console.debug(\"Partial dropped from the start of chunk\");\n startIdx = partialEnd + 1;\n }\n }\n\n if(startIdx < chunk.length) {\n if (chunk[startIdx] != '{') {\n throw new Error(\"Invalid chunk received, cannot process this request further\");\n }\n this.callback({type: \"stat_chunk\", msg: {elapsed: elapsedMillis}});\n \n while(true) {\n if(startIdx == chunk.length) {\n break;\n }\n var msgEnd = chunk.indexOf(\"}{\", startIdx);\n if(msgEnd == -1) {\n try {\n msg = JSON.parse(chunk.substring(startIdx));\n partial = false;\n this.callback({ type: \"data\", msg: this.transformer(msg)});\n } catch (err) {\n console.debug(\"Invalid JSON, partial received at the end. Dropping it\");\n partial = true;\n }\n startIdx = chunk.length;\n } else {\n try {\n msg = JSON.parse(chunk.substring(startIdx, msgEnd + 1));\n this.callback({ type: \"data\", msg: this.transformer(msg)});\n } catch (err) {\n throw new Error(\"Invalid JSON which was unexpected here: \" + err.message); \n }\n startIdx = msgEnd + 1;\n }\n }\n }\n return false;\n };\n }", "_parseComplete() {\n var callback = this._callback;\n this._callback = null;\n this._batchIndex = 0;\n callback.call(this, this.textures);\n }", "messageHandler(self, e) {\n let msg = ( (e.data).match(/^[0-9]+(\\[.+)$/) || [] )[1];\n if( msg != null ) {\n let msg_parsed = JSON.parse(msg);\n let [r, data] = msg_parsed;\n self.socketEventList.forEach(e=>e.run(self, msg_parsed))\n }\n }", "blockSessionParser(block) {\n block.protocol = null;\n block.originator = null;\n block.timeZone = null;\n block.sessionName = null;\n block.originator = null;\n block.protocol = null;\n block.uri = null;\n block.phoneNumber = null;\n block.email = null;\n block.timeDescription = null;\n block.timeRepeat = null;\n\n for (var j = 0; j < block.data.length; j++) {\n var res = block.data[j].split(\"=\");\n var key = res[0].replace(/ |\\n|\\r/g, \"\");\n var value = res[1];\n switch (key) {\n case \"v\":\n block.protocol = value;\n break;\n case \"o\":\n block.originator = this.parseOline(value);\n break;\n case \"s\":\n block.sessionName = value;\n break;\n case \"u\":\n block.uri = value;\n break;\n case \"e\":\n block.email = value;\n break;\n case \"p\":\n block.phoneNumber = value;\n break;\n case \"z\":\n block.timeZone = value;\n break;\n case \"a\":\n block.attributes.push(this.parseAline(value, block));\n break;\n case \"c\":\n block.connection = this.parseCline(value);\n break;\n case \"i\":\n block.information = value;\n break;\n case \"b\":\n block.bandwidths.push(value);\n break;\n case \"k\":\n block.encryption = value;\n break;\n // TIME DESCRIPTION\n case \"t\":\n block.timeDescription = this.parseTline(value);\n break;\n case \"r\":\n block.timeRepeat = this.parseRline(value);\n break;\n }\n }\n return block;\n }", "function GetInfo() {\n return __awaiter(this, void 0, void 0, function () {\n var response, _a, _b;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n _b = (_a = JSON).parse;\n return [4 /*yield*/, cmd({ cmd: \"getinfo\" })];\n case 1:\n response = _b.apply(_a, [_c.sent()]);\n return [2 /*return*/, response];\n }\n });\n });\n}", "function MyParser() {\n\tTransform.call(this);\n\n\t// buffer the first 8 bytes written\n\tthis._bytes(8 + 15, this.onheader);\n}", "function ParseStream (noRoot) {\n // call the parent constructor that needs a tokenizer as parameter\n Parser.call(this, new Tokenizer());\n\n this._object;\n this._noRoot = noRoot;\n var self = this;\n this.rootObjectPath = '$'\n\n /**\n * called when parsing the top level object of the JSON fragment\n * sets the internal reference to what is parsed\n * @param value the value at top level\n * @return JSONPath to the root element\n */\n function initialSet (value, dispose) {\n if(!noRoot) {\n self._object = value;\n }\n var handled = self.emitValue(self.rootObjectPath, value);\n if(!handled && typeof dispose == 'function') {\n dispose();\n }\n return self.rootObjectPath;\n }\n\n this.initialHandler(this.value(initialSet));\n // TODO set a default handler which is stricter than `ignore`\n this.defaultHandler(function(token, type, next) {\n if(type !== 'eof') {\n throw new SyntaxError(\"unexpected token \"+token+\". expected eof\");\n }\n });\n}", "function clarinet (eventBus) {\n 'use strict'\n\n // shortcut some events on the bus\n var emitSaxKey = eventBus(__WEBPACK_IMPORTED_MODULE_0__events__[\"j\" /* SAX_KEY */]).emit\n var emitValueOpen = eventBus(__WEBPACK_IMPORTED_MODULE_0__events__[\"l\" /* SAX_VALUE_OPEN */]).emit\n var emitValueClose = eventBus(__WEBPACK_IMPORTED_MODULE_0__events__[\"k\" /* SAX_VALUE_CLOSE */]).emit\n var emitFail = eventBus(__WEBPACK_IMPORTED_MODULE_0__events__[\"b\" /* FAIL_EVENT */]).emit\n\n var MAX_BUFFER_LENGTH = 64 * 1024\n var stringTokenPattern = /[\\\\\"\\n]/g\n var _n = 0\n\n // states\n var BEGIN = _n++\n var VALUE = _n++ // general stuff\n var OPEN_OBJECT = _n++ // {\n var CLOSE_OBJECT = _n++ // }\n var OPEN_ARRAY = _n++ // [\n var CLOSE_ARRAY = _n++ // ]\n var STRING = _n++ // \"\"\n var OPEN_KEY = _n++ // , \"a\"\n var CLOSE_KEY = _n++ // :\n var TRUE = _n++ // r\n var TRUE2 = _n++ // u\n var TRUE3 = _n++ // e\n var FALSE = _n++ // a\n var FALSE2 = _n++ // l\n var FALSE3 = _n++ // s\n var FALSE4 = _n++ // e\n var NULL = _n++ // u\n var NULL2 = _n++ // l\n var NULL3 = _n++ // l\n var NUMBER_DECIMAL_POINT = _n++ // .\n var NUMBER_DIGIT = _n // [0-9]\n\n // setup initial parser values\n var bufferCheckPosition = MAX_BUFFER_LENGTH\n var latestError\n var c\n var p\n var textNode\n var numberNode = ''\n var slashed = false\n var closed = false\n var state = BEGIN\n var stack = []\n var unicodeS = null\n var unicodeI = 0\n var depth = 0\n var position = 0\n var column = 0 // mostly for error reporting\n var line = 1\n\n function checkBufferLength () {\n var maxActual = 0\n\n if (textNode !== undefined && textNode.length > MAX_BUFFER_LENGTH) {\n emitError('Max buffer length exceeded: textNode')\n maxActual = Math.max(maxActual, textNode.length)\n }\n if (numberNode.length > MAX_BUFFER_LENGTH) {\n emitError('Max buffer length exceeded: numberNode')\n maxActual = Math.max(maxActual, numberNode.length)\n }\n\n bufferCheckPosition = (MAX_BUFFER_LENGTH - maxActual) +\n position\n }\n\n eventBus(__WEBPACK_IMPORTED_MODULE_0__events__[\"m\" /* STREAM_DATA */]).on(handleData)\n\n /* At the end of the http content close the clarinet\n This will provide an error if the total content provided was not\n valid json, ie if not all arrays, objects and Strings closed properly */\n eventBus(__WEBPACK_IMPORTED_MODULE_0__events__[\"n\" /* STREAM_END */]).on(handleStreamEnd)\n\n function emitError (errorString) {\n if (textNode !== undefined) {\n emitValueOpen(textNode)\n emitValueClose()\n textNode = undefined\n }\n\n latestError = Error(errorString + '\\nLn: ' + line +\n '\\nCol: ' + column +\n '\\nChr: ' + c)\n\n emitFail(Object(__WEBPACK_IMPORTED_MODULE_0__events__[\"o\" /* errorReport */])(undefined, undefined, latestError))\n }\n\n function handleStreamEnd () {\n if (state === BEGIN) {\n // Handle the case where the stream closes without ever receiving\n // any input. This isn't an error - response bodies can be blank,\n // particularly for 204 http responses\n\n // Because of how Oboe is currently implemented, we parse a\n // completely empty stream as containing an empty object.\n // This is because Oboe's done event is only fired when the\n // root object of the JSON stream closes.\n\n // This should be decoupled and attached instead to the input stream\n // from the http (or whatever) resource ending.\n // If this decoupling could happen the SAX parser could simply emit\n // zero events on a completely empty input.\n emitValueOpen({})\n emitValueClose()\n\n closed = true\n return\n }\n\n if (state !== VALUE || depth !== 0) { emitError('Unexpected end') }\n\n if (textNode !== undefined) {\n emitValueOpen(textNode)\n emitValueClose()\n textNode = undefined\n }\n\n closed = true\n }\n\n function whitespace (c) {\n return c === '\\r' || c === '\\n' || c === ' ' || c === '\\t'\n }\n\n function handleData (chunk) {\n // this used to throw the error but inside Oboe we will have already\n // gotten the error when it was emitted. The important thing is to\n // not continue with the parse.\n if (latestError) { return }\n\n if (closed) {\n return emitError('Cannot write after close')\n }\n\n var i = 0\n c = chunk[0]\n\n while (c) {\n if (i > 0) {\n p = c\n }\n c = chunk[i++]\n if (!c) break\n\n position++\n if (c === '\\n') {\n line++\n column = 0\n } else column++\n switch (state) {\n case BEGIN:\n if (c === '{') state = OPEN_OBJECT\n else if (c === '[') state = OPEN_ARRAY\n else if (!whitespace(c)) { return emitError('Non-whitespace before {[.') }\n continue\n\n case OPEN_KEY:\n case OPEN_OBJECT:\n if (whitespace(c)) continue\n if (state === OPEN_KEY) stack.push(CLOSE_KEY)\n else {\n if (c === '}') {\n emitValueOpen({})\n emitValueClose()\n state = stack.pop() || VALUE\n continue\n } else stack.push(CLOSE_OBJECT)\n }\n if (c === '\"') { state = STRING } else { return emitError('Malformed object key should start with \" ') }\n continue\n\n case CLOSE_KEY:\n case CLOSE_OBJECT:\n if (whitespace(c)) continue\n\n if (c === ':') {\n if (state === CLOSE_OBJECT) {\n stack.push(CLOSE_OBJECT)\n\n if (textNode !== undefined) {\n // was previously (in upstream Clarinet) one event\n // - object open came with the text of the first\n emitValueOpen({})\n emitSaxKey(textNode)\n textNode = undefined\n }\n depth++\n } else {\n if (textNode !== undefined) {\n emitSaxKey(textNode)\n textNode = undefined\n }\n }\n state = VALUE\n } else if (c === '}') {\n if (textNode !== undefined) {\n emitValueOpen(textNode)\n emitValueClose()\n textNode = undefined\n }\n emitValueClose()\n depth--\n state = stack.pop() || VALUE\n } else if (c === ',') {\n if (state === CLOSE_OBJECT) { stack.push(CLOSE_OBJECT) }\n if (textNode !== undefined) {\n emitValueOpen(textNode)\n emitValueClose()\n textNode = undefined\n }\n state = OPEN_KEY\n } else { return emitError('Bad object') }\n continue\n\n case OPEN_ARRAY: // after an array there always a value\n case VALUE:\n if (whitespace(c)) continue\n if (state === OPEN_ARRAY) {\n emitValueOpen([])\n depth++\n state = VALUE\n if (c === ']') {\n emitValueClose()\n depth--\n state = stack.pop() || VALUE\n continue\n } else {\n stack.push(CLOSE_ARRAY)\n }\n }\n if (c === '\"') state = STRING\n else if (c === '{') state = OPEN_OBJECT\n else if (c === '[') state = OPEN_ARRAY\n else if (c === 't') state = TRUE\n else if (c === 'f') state = FALSE\n else if (c === 'n') state = NULL\n else if (c === '-') { // keep and continue\n numberNode += c\n } else if (c === '0') {\n numberNode += c\n state = NUMBER_DIGIT\n } else if ('123456789'.indexOf(c) !== -1) {\n numberNode += c\n state = NUMBER_DIGIT\n } else { return emitError('Bad value') }\n continue\n\n case CLOSE_ARRAY:\n if (c === ',') {\n stack.push(CLOSE_ARRAY)\n if (textNode !== undefined) {\n emitValueOpen(textNode)\n emitValueClose()\n textNode = undefined\n }\n state = VALUE\n } else if (c === ']') {\n if (textNode !== undefined) {\n emitValueOpen(textNode)\n emitValueClose()\n textNode = undefined\n }\n emitValueClose()\n depth--\n state = stack.pop() || VALUE\n } else if (whitespace(c)) { continue } else { return emitError('Bad array') }\n continue\n\n case STRING:\n if (textNode === undefined) {\n textNode = ''\n }\n\n // thanks thejh, this is an about 50% performance improvement.\n var starti = i - 1\n\n // eslint-disable-next-line no-labels\n STRING_BIGLOOP: while (true) {\n // zero means \"no unicode active\". 1-4 mean \"parse some more\". end after 4.\n while (unicodeI > 0) {\n unicodeS += c\n c = chunk.charAt(i++)\n if (unicodeI === 4) {\n // TODO this might be slow? well, probably not used too often anyway\n textNode += String.fromCharCode(parseInt(unicodeS, 16))\n unicodeI = 0\n starti = i - 1\n } else {\n unicodeI++\n }\n // we can just break here: no stuff we skipped that still has to be sliced out or so\n // eslint-disable-next-line no-labels\n if (!c) break STRING_BIGLOOP\n }\n if (c === '\"' && !slashed) {\n state = stack.pop() || VALUE\n textNode += chunk.substring(starti, i - 1)\n break\n }\n if (c === '\\\\' && !slashed) {\n slashed = true\n textNode += chunk.substring(starti, i - 1)\n c = chunk.charAt(i++)\n if (!c) break\n }\n if (slashed) {\n slashed = false\n if (c === 'n') { textNode += '\\n' } else if (c === 'r') { textNode += '\\r' } else if (c === 't') { textNode += '\\t' } else if (c === 'f') { textNode += '\\f' } else if (c === 'b') { textNode += '\\b' } else if (c === 'u') {\n // \\uxxxx. meh!\n unicodeI = 1\n unicodeS = ''\n } else {\n textNode += c\n }\n c = chunk.charAt(i++)\n starti = i - 1\n if (!c) break\n else continue\n }\n\n stringTokenPattern.lastIndex = i\n var reResult = stringTokenPattern.exec(chunk)\n if (!reResult) {\n i = chunk.length + 1\n textNode += chunk.substring(starti, i - 1)\n break\n }\n i = reResult.index + 1\n c = chunk.charAt(reResult.index)\n if (!c) {\n textNode += chunk.substring(starti, i - 1)\n break\n }\n }\n continue\n\n case TRUE:\n if (!c) continue // strange buffers\n if (c === 'r') state = TRUE2\n else { return emitError('Invalid true started with t' + c) }\n continue\n\n case TRUE2:\n if (!c) continue\n if (c === 'u') state = TRUE3\n else { return emitError('Invalid true started with tr' + c) }\n continue\n\n case TRUE3:\n if (!c) continue\n if (c === 'e') {\n emitValueOpen(true)\n emitValueClose()\n state = stack.pop() || VALUE\n } else { return emitError('Invalid true started with tru' + c) }\n continue\n\n case FALSE:\n if (!c) continue\n if (c === 'a') state = FALSE2\n else { return emitError('Invalid false started with f' + c) }\n continue\n\n case FALSE2:\n if (!c) continue\n if (c === 'l') state = FALSE3\n else { return emitError('Invalid false started with fa' + c) }\n continue\n\n case FALSE3:\n if (!c) continue\n if (c === 's') state = FALSE4\n else { return emitError('Invalid false started with fal' + c) }\n continue\n\n case FALSE4:\n if (!c) continue\n if (c === 'e') {\n emitValueOpen(false)\n emitValueClose()\n state = stack.pop() || VALUE\n } else { return emitError('Invalid false started with fals' + c) }\n continue\n\n case NULL:\n if (!c) continue\n if (c === 'u') state = NULL2\n else { return emitError('Invalid null started with n' + c) }\n continue\n\n case NULL2:\n if (!c) continue\n if (c === 'l') state = NULL3\n else { return emitError('Invalid null started with nu' + c) }\n continue\n\n case NULL3:\n if (!c) continue\n if (c === 'l') {\n emitValueOpen(null)\n emitValueClose()\n state = stack.pop() || VALUE\n } else { return emitError('Invalid null started with nul' + c) }\n continue\n\n case NUMBER_DECIMAL_POINT:\n if (c === '.') {\n numberNode += c\n state = NUMBER_DIGIT\n } else { return emitError('Leading zero not followed by .') }\n continue\n\n case NUMBER_DIGIT:\n if ('0123456789'.indexOf(c) !== -1) numberNode += c\n else if (c === '.') {\n if (numberNode.indexOf('.') !== -1) { return emitError('Invalid number has two dots') }\n numberNode += c\n } else if (c === 'e' || c === 'E') {\n if (numberNode.indexOf('e') !== -1 ||\n numberNode.indexOf('E') !== -1) { return emitError('Invalid number has two exponential') }\n numberNode += c\n } else if (c === '+' || c === '-') {\n if (!(p === 'e' || p === 'E')) { return emitError('Invalid symbol in number') }\n numberNode += c\n } else {\n if (numberNode) {\n emitValueOpen(parseFloat(numberNode))\n emitValueClose()\n numberNode = ''\n }\n i-- // go back one\n state = stack.pop() || VALUE\n }\n continue\n\n default:\n return emitError('Unknown state: ' + state)\n }\n }\n if (position >= bufferCheckPosition) { checkBufferLength() }\n }\n}", "onLogDumpCreated(logDumpText) {\n const logDump = JSON.parse(logDumpText);\n\n logDump.constants.timeTickOffset = 0;\n logDump.events = [];\n\n const source = new NetInternalsTest.Source(1, EventSourceType.SOCKET);\n logDump.events.push(NetInternalsTest.createBeginEvent(\n source, EventType.SOCKET_ALIVE, this.startTime_, null));\n logDump.events.push(NetInternalsTest.createMatchingEndEvent(\n logDump.events[0], this.endTime_, null));\n logDumpText = JSON.stringify(logDump);\n\n assertEquals('Log loaded.', LogUtil.loadLogFile(logDumpText));\n\n endTime = this.endTime_;\n startTime = this.startTime_;\n if (startTime >= endTime) {\n --startTime;\n }\n\n sanityCheckWithTimeRange(false);\n\n this.onTaskDone();\n }", "async function handleStream() {\n const signal = controller.signal;\n for await (const chunk of ipfs.cat(image.cid, { signal })) {\n setImgBuffer((oldBuff) => [...oldBuff, chunk]);\n }\n\n if (mode === modeType.scanlation) {\n let textBuffer = [];\n //will only begin loading translation data if component isn't unloading\n for await (const chunk of ipfs.cat(data.cid, { signal })) {\n textBuffer = [...textBuffer, chunk];\n }\n setTranslation(JSON.parse(Buffer.concat(textBuffer).toString()));\n }\n }", "parse() {\n /**\n * The first two bytes are a bitmask which states which features are present in the mapFile\n * The second two bytes are.. something?\n */\n const featureFlags = this.take(2, \"featureFlags\").readUInt16LE(0);\n this.take(2, \"unknown01\");\n if (featureFlags & 0b000000000000001) {\n this.robotStatus = this.take(0x2C, \"robot status\");\n }\n\n\n if (featureFlags & 0b000000000000010) {\n this.mapHead = this.take(0x28, \"map head\");\n this.parseImg();\n }\n if (featureFlags & 0b000000000000100) {\n let head = asInts(this.take(12, \"history\"));\n this.history = [];\n for (let i = 0; i < head[2]; i++) {\n // Convert from ±meters to mm. UI assumes center is at 20m\n let position = this.readFloatPosition(this.buf, this.offset + 1);\n // first byte may be angle or whether robot is in taxi mode/cleaning\n //position.push(this.buf.readUInt8(this.offset)); //TODO\n this.history.push(position[0], position[1]);\n this.offset += 9;\n }\n }\n if (featureFlags & 0b000000000001000) {\n // TODO: Figure out charge station location from this.\n let chargeStation = this.take(16, \"charge station\");\n this.chargeStation = {\n position: this.readFloatPosition(chargeStation, 4),\n orientation: chargeStation.readFloatLE(12)\n };\n }\n if (featureFlags & 0b000000000010000) {\n let head = asInts(this.take(12, \"virtual wall\"));\n\n this.virtual_wall = [];\n this.no_go_area = [];\n\n let wall_num = head[2];\n\n for (let i = 0; i < wall_num; i++) {\n this.take(12, \"virtual wall prefix\");\n let body = asFloat(this.take(32, \"Virtual walls coords\"));\n\n if (body[0] === body[2] && body[1] === body[3] && body[4] === body[6] && body[5] === body[7]) {\n //is wall\n let x1 = Math.round(ViomiMapParser.convertFloat(body[0]));\n let y1 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[1]));\n let x2 = Math.round(ViomiMapParser.convertFloat(body[4]));\n let y2 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[5]));\n\n this.virtual_wall.push([x1, y1, x2, y2]);\n } else {\n //is zone\n let x1 = Math.round(ViomiMapParser.convertFloat(body[0]));\n let y1 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[1]));\n let x2 = Math.round(ViomiMapParser.convertFloat(body[2]));\n let y2 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[3]));\n let x3 = Math.round(ViomiMapParser.convertFloat(body[4]));\n let y3 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[5]));\n let x4 = Math.round(ViomiMapParser.convertFloat(body[6]));\n let y4 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[7]));\n\n this.no_go_area.push([x1, y1, x2, y2, x3, y3, x4, y4]);\n }\n\n this.take(48, \"unknown48\");\n }\n }\n if (featureFlags & 0b000000000100000) {\n let head = asInts(this.take(12, \"area head\"));\n let area_num = head[2];\n\n this.clean_area = [];\n\n for (let i = 0; i < area_num; i++) {\n this.take(12, \"area prefix\");\n let body = asFloat(this.take(32, \"area coords\"));\n\n let x1 = Math.round(ViomiMapParser.convertFloat(body[0]));\n let y1 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[1]));\n let x2 = Math.round(ViomiMapParser.convertFloat(body[2]));\n let y2 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[3]));\n let x3 = Math.round(ViomiMapParser.convertFloat(body[4]));\n let y3 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[5]));\n let x4 = Math.round(ViomiMapParser.convertFloat(body[6]));\n let y4 = Math.round(ViomiMapParser.MAX_MAP_HEIGHT - ViomiMapParser.convertFloat(body[7]));\n\n this.clean_area.push([x1, y1, x2, y2, x3, y3, x4, y4]);\n\n this.take(48, \"unknown48\");\n }\n }\n if (featureFlags & 0b000000001000000) {\n let navigateTarget = this.take(20, \"navigate\");\n this.navigateTarget = {position: this.readFloatPosition(navigateTarget, 8)};\n }\n if (featureFlags & 0b000000010000000) {\n let realtimePose = this.take(21, \"realtime\");\n this.realtimePose = {position: this.readFloatPosition(realtimePose, 9)};\n }\n\n if (featureFlags & 0b000100000000000) {\n //v6 example: 5b590f5f00000001\n //v7 example: e35a185e00000001\n this.take(8, \"unknown8\");\n this.parseRooms();\n // more stuff i don't understand\n this.take(50, \"unknown50\");\n this.take(5, \"unknown5\");\n this.points = [];\n try {\n this.parsePose();\n } catch (e) {\n Logger.warn(\"Unable to parse Pose\", e); //TODO\n }\n }\n this.take(this.buf.length - this.offset, \"trailing\");\n\n // TODO: one of them is just the room outline, not actual past navigation logic\n return this.convertToValetudoMap({\n image: this.img,\n zones: this.rooms,\n //TODO: at least according to all my sample files, this.points is never the path\n //Why is this here?\n //path: {points: this.points.length ? this.points : this.history},\n path: {points: this.history},\n goto_target: this.navigateTarget && this.navigateTarget.position,\n robot: this.realtimePose && this.realtimePose.position,\n charger: this.chargeStation && this.chargeStation.position,\n virtual_wall: this.virtual_wall,\n no_go_area: this.no_go_area,\n clean_area: this.clean_area\n });\n }", "function quick_and_dirty_vtt_or_srt_parser(vtt) {\n console.log('--quick_and_dirty_vtt_or_srt_parser--');\n\tlet lines = vtt.trim().replace('\\r\\n', '\\n').split(/[\\r\\n]/).map(function(line) {\n\t\treturn line.trim();\n });\n // console.log(lines);\n\tlet cues = [];\n\tlet start = null;\n\tlet end = null;\n\tlet payload = null;\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tif (lines[i].indexOf('-->') >= 0) {\n\t\t\tlet splitted = lines[i].split(/[ \\t]+-->[ \\t]+/);\n\t\t\tif (splitted.length != 2) {\n\t\t\t\tthrow 'Error when splitting \"-->\": ' + lines[i];\n\t\t\t}\n\n\t\t\t// Already ignoring anything past the \"end\" timestamp (i.e. cue settings).\n\t\t\tstart = parse_timestamp(splitted[0]);\n\t\t\tend = parse_timestamp(splitted[1]);\n\t\t} else if (lines[i] == '') {\n\t\t\tif (start && end) {\n\t\t\t\tlet cue = { 'start': start, 'end': end, 'text': payload };\n\t\t\t\tcues.push(cue);\n\t\t\t\tstart = null;\n\t\t\t\tend = null;\n\t\t\t\tpayload = null;\n\t\t\t}\n\t\t} else if(start && end) {\n\t\t\tif (payload == null) {\n\t\t\t\tpayload = lines[i];\n\t\t\t} else {\n\t\t\t\tpayload += '\\n' + lines[i];\n\t\t\t}\n\t\t}\n\t}\n\tif (start && end) {\n\t\tlet cue = { 'start': start, 'end': end, 'text': payload };\n\t\tcues.push(cue);\n }\n \n console.log(cues);\n\n\treturn cues;\n}", "function TTMLParser() {\n\n var context = this.context;\n var log = (0, _coreDebug2['default'])(context).getInstance().log;\n\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n var instance = undefined,\n timingRegex = undefined,\n ttml = undefined,\n // contains the whole ttml document received\n ttmlStyling = undefined,\n // contains the styling information from the document (from head following EBU-TT-D)\n ttmlLayout = undefined,\n // contains the positioning information from the document (from head following EBU-TT-D)\n fontSize = undefined,\n lineHeight = undefined,\n linePadding = undefined,\n defaultLayoutProperties = undefined,\n defaultStyleProperties = undefined,\n fontFamilies = undefined,\n textAlign = undefined,\n multiRowAlign = undefined,\n wrapOption = undefined,\n unicodeBidi = undefined,\n displayAlign = undefined,\n writingMode = undefined,\n videoModel = undefined,\n converter = undefined;\n\n var cueCounter = 0; // Used to give every cue a unique ID.\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n }\n\n /**\n * Get the begin-end interval if present, or null otherwise.\n *\n * @param {Object} element - TTML element which may have begin and end attributes\n */\n function getInterval(element) {\n if (element.hasOwnProperty('begin') && element.hasOwnProperty('end')) {\n var beginTime = parseTimings(element.begin);\n var endTime = parseTimings(element.end);\n return [beginTime, endTime];\n } else {\n return null;\n }\n }\n\n function getCueID() {\n var id = 'cue_TTML_' + cueCounter;\n cueCounter++;\n return id;\n }\n\n /*\n * Create list of intervals where spans start and end. Empty list if no times.\n * Clip to interval using startInterval and endInterval and add these two times.\n * Also support case when startInterval/endInteval not given (sideloaded file)\n *\n * @param {Array} spans - array of span elements\n */\n function createSpanIntervalList(spans, startInterval, endInterval) {\n\n var spanChangeTimes = [];\n var spanChangeTimeStrings = [];\n var cue_intervals = [];\n\n function addSpanTime(span, name) {\n if (span.hasOwnProperty(name)) {\n var timeString = span[name];\n if (spanChangeTimeStrings.indexOf(timeString) < 0) {\n spanChangeTimeStrings.push(timeString);\n }\n }\n }\n\n for (var i = 0; i < spans.length; i++) {\n var span = spans[i];\n addSpanTime(span, 'begin');\n addSpanTime(span, 'end');\n }\n if (spanChangeTimeStrings.length === 0) {\n return cue_intervals; // No span timing so no intervals.\n }\n\n if (typeof startInterval !== 'undefined' && typeof endInterval !== 'undefined') {\n for (var i = 0; i < spanChangeTimeStrings.length; i++) {\n var changeTime = parseTimings(spanChangeTimeStrings[i]);\n if (startInterval < changeTime && changeTime < endInterval) {\n spanChangeTimes.push(changeTime);\n }\n }\n spanChangeTimes.push(startInterval);\n spanChangeTimes.push(endInterval);\n } else {\n for (var i = 0; i < spanChangeTimeStrings.length; i++) {\n spanChangeTimes.push(parseTimings(spanChangeTimeStrings[i]));\n }\n }\n spanChangeTimes.sort(function (a, b) {\n return a - b;\n });\n for (var i = 0; i < spanChangeTimes.length - 1; i++) {\n cue_intervals.push([spanChangeTimes[i], spanChangeTimes[i + 1]]);\n }\n return cue_intervals;\n }\n\n function clipStartTime(startTime, intervalStart) {\n if (typeof startInterval !== 'undefined') {\n if (startTime < intervalStart) {\n startTime = intervalStart;\n }\n }\n return startTime;\n }\n\n function clipEndTime(endTime, intervalEnd) {\n if (typeof intervalEnd !== 'undefined') {\n if (endTime > intervalEnd) {\n endTime = intervalEnd;\n }\n }\n return endTime;\n }\n\n /*\n * Get interval from entity that has begin and end properties.\n * If intervalStart and intervalEnd defined, use them to clip the interval.\n * Return null if no overlap with interval\n */\n function getClippedInterval(entity, intervalStart, intervalEnd) {\n var startTime = parseTimings(entity.begin);\n var endTime = parseTimings(entity.end);\n startTime = clipStartTime(startTime, intervalStart);\n endTime = clipEndTime(endTime, intervalEnd);\n if (typeof intervalStart !== 'undefined' && typeof intervalEnd !== 'undefined') {\n if (endTime < intervalStart || startTime > intervalEnd) {\n log('TTML: Cue ' + startTime + '-' + endTime + ' outside interval ' + intervalStart + '-' + intervalEnd);\n return null;\n }\n }\n return [startTime, endTime];\n }\n\n /*\n * Check if entity timing has some overlap with interval\n */\n function inIntervalOrNoTiming(entity, interval) {\n var inInterval = true;\n if (entity.hasOwnProperty('span')) {\n var entityInterval = getInterval(entity.span);\n if (entityInterval !== null) {\n //Timing\n inInterval = entityInterval[0] < interval[1] && entityInterval[1] > interval[0];\n }\n }\n return inInterval;\n }\n\n /**\n * Parse the raw data and process it to return the HTML element representing the cue.\n * Return the region to be processed and controlled (hide/show) by the caption controller.\n * @param {string} data - raw data received from the TextSourceBuffer\n * @param {number} intervalStart\n * @param {number} intervalEnd\n * @param {array} imageArray - images represented as binary strings\n */\n\n function parse(data, intervalStart, intervalEnd, imageArray) {\n var tt = undefined,\n // Top element\n head = undefined,\n // head in tt\n body = undefined,\n // body in tt\n ttExtent = undefined,\n // extent attribute of tt element\n type = undefined,\n i = undefined;\n\n var errorMsg = '';\n\n // Parse the TTML in a JSON object.\n ttml = converter.xml_str2json(data);\n\n if (!ttml) {\n throw new Error('TTML document could not be parsed');\n }\n\n if (videoModel.getTTMLRenderingDiv()) {\n type = 'html';\n }\n\n // Check the document and compare to the specification (TTML and EBU-TT-D).\n tt = ttml.tt;\n if (!tt) {\n throw new Error('TTML document lacks tt element');\n }\n\n // Get the namespace if there is one defined in the JSON object.\n var ttNS = getNamespacePrefix(tt, 'http://www.w3.org/ns/ttml');\n\n // Remove the namespace before each node if it exists:\n if (ttNS) {\n removeNamespacePrefix(tt, ttNS);\n }\n\n ttExtent = tt['tts:extent']; // Should check that tts is right namespace.\n\n head = tt.head;\n if (!head) {\n throw new Error('TTML document lacks head element');\n }\n if (head.layout) {\n ttmlLayout = head.layout.region_asArray; //Mandatory in EBU-TT-D\n }\n if (head.styling) {\n ttmlStyling = head.styling.style_asArray; // Mandatory in EBU-TT-D\n }\n\n var imageDataUrls = {};\n\n if (imageArray) {\n for (i = 0; i < imageArray.length; i++) {\n var key = 'urn:mpeg:14496-30:subs:' + (i + 1).toString();\n var dataUrl = 'data:image/png;base64,' + btoa(imageArray[i]);\n imageDataUrls[key] = dataUrl;\n }\n }\n\n if (head.metadata) {\n var embeddedImages = head.metadata.image_asArray; // Handle embedded images\n if (embeddedImages) {\n for (i = 0; i < embeddedImages.length; i++) {\n var key = '#' + embeddedImages[i]['xml:id'];\n var imageType = embeddedImages[i].imagetype.toLowerCase();\n var dataUrl = 'data:image/' + imageType + ';base64,' + embeddedImages[i].__text;\n imageDataUrls[key] = dataUrl;\n }\n }\n }\n\n body = tt.body;\n if (!body) {\n throw new Error('TTML document lacks body element');\n }\n\n // Extract the cellResolution information\n var cellResolution = getCellResolution();\n\n // Recover the video width and height displayed by the player.\n var videoWidth = videoModel.getElement().clientWidth;\n var videoHeight = videoModel.getElement().clientHeight;\n\n // Compute the CellResolution unit in order to process properties using sizing (fontSize, linePadding, etc).\n var cellUnit = [videoWidth / cellResolution[0], videoHeight / cellResolution[1]];\n defaultStyleProperties['font-size'] = cellUnit[1] + 'px;';\n\n var regions = [];\n if (ttmlLayout) {\n for (i = 0; i < ttmlLayout.length; i++) {\n regions.push(processRegion(JSON.parse(JSON.stringify(ttmlLayout[i])), cellUnit));\n }\n }\n\n // Get the namespace prefix.\n var nsttp = getNamespacePrefix(ttml.tt, 'http://www.w3.org/ns/ttml#parameter');\n\n // Set the framerate.\n if (tt.hasOwnProperty(nsttp + ':frameRate')) {\n tt.frameRate = parseInt(tt[nsttp + ':frameRate'], 10);\n }\n var captionArray = [];\n // Extract the div\n var divs = tt.body_asArray[0].__children;\n\n // Timing is either on div, paragraph or span level.\n\n for (var k = 0; k < divs.length; k++) {\n var div = divs[k].div;\n var divInterval = null; // This is mainly for image subtitles.\n\n if (null !== (divInterval = getInterval(div))) {\n // Timing on div level is not allowed by EBU-TT-D.\n // We only use it for SMPTE-TT image subtitle profile.\n\n // Layout should be defined by a region. Given early test material, we also support that it is on\n // div level\n var layout = undefined;\n if (div.region) {\n var region = findRegionFromID(ttmlLayout, div.region);\n layout = getRelativePositioning(region, ttExtent);\n }\n if (!layout) {\n layout = getRelativePositioning(div, ttExtent);\n }\n\n var imgKey = div['smpte:backgroundImage'];\n if (imgKey !== undefined && imageDataUrls[imgKey] !== undefined) {\n captionArray.push({\n start: divInterval[0],\n end: divInterval[1],\n id: getCueID(),\n data: imageDataUrls[imgKey],\n type: 'image',\n layout: layout\n });\n }\n continue; // Next div\n }\n\n var paragraphs = div.p_asArray;\n // Check if cues is not empty or undefined.\n if (divInterval === null && (!paragraphs || paragraphs.length === 0)) {\n errorMsg = 'TTML has div that contains no timing and no paragraphs.';\n log(errorMsg);\n return captionArray;\n }\n\n for (var j2 = 0; j2 < paragraphs.length; j2++) {\n var paragraph = paragraphs[j2];\n var spans = paragraph.span_asArray;\n var cueIntervals = [];\n // For timing, the overall goal is to find the intervals where there should be cues\n // The timing may either be on paragraph or span level.\n if (paragraph.hasOwnProperty('begin') && paragraph.hasOwnProperty('end')) {\n // Timing on paragraph level\n var clippedInterval = getClippedInterval(paragraph, intervalStart, intervalEnd);\n if (clippedInterval !== null) {\n cueIntervals.push(clippedInterval);\n }\n } else {\n // Timing must be on span level\n cueIntervals = createSpanIntervalList(spans, intervalStart, intervalEnd);\n }\n if (cueIntervals.length === 0) {\n errorMsg = 'TTML: Empty paragraph';\n continue; // Nothing in this paragraph\n }\n\n var paragraphChildren = paragraph.__children;\n\n for (var i2 = 0; i2 < cueIntervals.length; i2++) {\n var interval = cueIntervals[i2];\n var childrenInInterval = [];\n for (var k2 = 0; k2 < paragraphChildren.length; k2++) {\n var child = paragraphChildren[k2];\n if (inIntervalOrNoTiming(child, interval)) {\n childrenInInterval.push(child);\n }\n }\n if (childrenInInterval.length === 0) {\n continue; // No children to render\n }\n\n if (type === 'html') {\n lineHeight = {};\n linePadding = {};\n fontSize = {};\n\n /**\n * Find the region defined for the cue.\n */\n // properties to be put in the \"captionRegion\" HTML element.\n var cueRegionProperties = constructCueRegion(paragraph, div, cellUnit);\n\n /**\n * Find the style defined for the cue.\n */\n // properties to be put in the \"paragraph\" HTML element.\n var cueStyleProperties = constructCueStyle(paragraph, cellUnit);\n\n /**\n * /!\\ Create the cue HTML Element containing the whole cue.\n */\n var styleIDs = cueStyleProperties[1];\n cueStyleProperties = cueStyleProperties[0];\n\n // Final cue HTML element.\n var cueParagraph = document.createElement('div');\n cueParagraph.className = styleIDs;\n\n // Create a wrapper containing the cue information about unicodeBidi and direction\n // as they need to be defined on at this level.\n // We append to the wrapper the cue itself.\n var cueDirUniWrapper = constructCue(childrenInInterval, cellUnit);\n cueDirUniWrapper.className = 'cueDirUniWrapper';\n\n // If the style defines these two properties, we place them in cueContainer\n // and delete them from the cue style so it is not added afterwards to the final cue.\n if (arrayContains('unicode-bidi', cueStyleProperties)) {\n cueDirUniWrapper.style.cssText += getPropertyFromArray('unicode-bidi', cueStyleProperties);\n deletePropertyFromArray('unicode-bidi', cueStyleProperties);\n }\n if (arrayContains('direction', cueStyleProperties)) {\n cueDirUniWrapper.style.cssText += getPropertyFromArray('direction', cueStyleProperties);\n deletePropertyFromArray('direction', cueStyleProperties);\n }\n\n // Apply the linePadding property if it is specified in the cue style.\n if (arrayContains('padding-left', cueStyleProperties) && arrayContains('padding-right', cueStyleProperties)) {\n cueDirUniWrapper.innerHTML = applyLinePadding(cueDirUniWrapper, cueStyleProperties);\n }\n\n /**\n * Clean and set the style and region for the cue to be returned.\n */\n\n // Remove the line padding property from being added at the \"paragraph\" element level.\n if (arrayContains('padding-left', cueStyleProperties) && arrayContains('padding-right', cueStyleProperties)) {\n deletePropertyFromArray('padding-left', cueStyleProperties);\n deletePropertyFromArray('padding-right', cueStyleProperties);\n }\n\n // Remove the ID of the region from being added at the \"paragraph\" element level.\n var regionID = '';\n if (arrayContains('regionID', cueRegionProperties)) {\n var wholeRegionID = getPropertyFromArray('regionID', cueRegionProperties);\n regionID = wholeRegionID.slice(wholeRegionID.indexOf(':') + 1, wholeRegionID.length - 1);\n }\n\n // We link the p style to the finale cueParagraph element.\n if (cueStyleProperties) {\n cueParagraph.style.cssText = cueStyleProperties.join(' ') + 'display:flex;';\n }\n // We define the CSS style for the cue region.\n if (cueRegionProperties) {\n cueRegionProperties = cueRegionProperties.join(' ');\n }\n\n // We then place the cue wrapper inside the paragraph element.\n cueParagraph.appendChild(cueDirUniWrapper);\n\n // Final cue.\n var finalCue = document.createElement('div');\n finalCue.appendChild(cueParagraph);\n finalCue.id = getCueID();\n finalCue.style.cssText = 'position: absolute; margin: 0; display: flex; box-sizing: border-box; pointer-events: none;' + cueRegionProperties;\n\n if (Object.keys(fontSize).length === 0) {\n fontSize.defaultFontSize = '100';\n }\n\n // We add all the cue information in captionArray.\n captionArray.push({\n start: interval[0],\n end: interval[1],\n type: 'html',\n cueHTMLElement: finalCue,\n regions: regions,\n regionID: regionID,\n cueID: finalCue.id,\n videoHeight: videoHeight,\n videoWidth: videoWidth,\n cellResolution: cellResolution,\n fontSize: fontSize || {\n defaultFontSize: '100'\n },\n lineHeight: lineHeight,\n linePadding: linePadding\n });\n } else {\n var text = '';\n var textElements = childrenInInterval;\n if (textElements.length) {\n textElements.forEach(function (el) {\n if (el.hasOwnProperty('span')) {\n var spanElements = el.span.__children;\n spanElements.forEach(function (spanEl) {\n // If metadata is present, do not process.\n if (spanElements.hasOwnProperty('metadata')) {\n return;\n }\n // If the element is a string\n if (spanEl.hasOwnProperty('#text')) {\n text += spanEl['#text'].replace(/[\\r\\n]+/gm, ' ').trim();\n // If the element is a 'br' tag\n } else if ('br' in spanEl) {\n // Create a br element.\n text += '\\n';\n }\n });\n } else if (el.hasOwnProperty('br')) {\n text += '\\n';\n } else {\n text += el['#text'].replace(/[\\r\\n]+/gm, ' ').trim();\n }\n });\n }\n\n captionArray.push({\n start: interval[0],\n end: interval[1],\n data: text,\n type: 'text'\n });\n }\n }\n }\n }\n\n if (errorMsg !== '') {\n log(errorMsg);\n }\n\n if (captionArray.length > 0) {\n return captionArray;\n } else {\n // This seems too strong given that there are segments with no TTML subtitles\n throw new Error(errorMsg);\n }\n }\n\n function setup() {\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n timingRegex = /^([0-9][0-9]+):([0-5][0-9]):([0-5][0-9])|(60)(\\.([0-9])+)?$/; // Regex defining the time\n fontSize = {};\n lineHeight = {};\n linePadding = {};\n defaultLayoutProperties = {\n 'top': 'auto;',\n 'left': 'auto;',\n 'width': '90%;',\n 'height': '10%;',\n 'align-items': 'flex-start;',\n 'overflow': 'visible;',\n '-ms-writing-mode': 'lr-tb, horizontal-tb;',\n '-webkit-writing-mode': 'horizontal-tb;',\n '-moz-writing-mode': 'horizontal-tb;',\n 'writing-mode': 'horizontal-tb;'\n };\n defaultStyleProperties = {\n 'color': 'rgb(255,255,255);',\n 'direction': 'ltr;',\n 'font-family': 'monospace, sans-serif;',\n 'font-style': 'normal;',\n 'line-height': 'normal;',\n 'font-weight': 'normal;',\n 'text-align': 'start;',\n 'justify-content': 'flex-start;',\n 'text-decoration': 'none;',\n 'unicode-bidi': 'normal;',\n 'white-space': 'normal;',\n 'width': '100%;'\n };\n fontFamilies = {\n monospace: 'font-family: monospace;',\n sansSerif: 'font-family: sans-serif;',\n serif: 'font-family: serif;',\n monospaceSansSerif: 'font-family: monospace, sans-serif;',\n monospaceSerif: 'font-family: monospace, serif;',\n proportionalSansSerif: 'font-family: Arial;',\n proportionalSerif: 'font-family: Times New Roman;',\n 'default': 'font-family: monospace, sans-serif;'\n };\n textAlign = {\n right: ['justify-content: flex-end;', 'text-align: right;'],\n start: ['justify-content: flex-start;', 'text-align: start;'],\n center: ['justify-content: center;', 'text-align: center;'],\n end: ['justify-content: flex-end;', 'text-align: end;'],\n left: ['justify-content: flex-start;', 'text-align: left;']\n };\n multiRowAlign = {\n start: 'text-align: start;',\n center: 'text-align: center;',\n end: 'text-align: end;',\n auto: ''\n };\n wrapOption = {\n wrap: 'white-space: normal;',\n noWrap: 'white-space: nowrap;'\n };\n unicodeBidi = {\n normal: 'unicode-bidi: normal;',\n embed: 'unicode-bidi: embed;',\n bidiOverride: 'unicode-bidi: bidi-override;'\n };\n displayAlign = {\n before: 'align-items: flex-start;',\n center: 'align-items: center;',\n after: 'align-items: flex-end;'\n };\n writingMode = {\n lrtb: '-webkit-writing-mode: horizontal-tb;' + 'writing-mode: horizontal-tb;',\n rltb: '-webkit-writing-mode: horizontal-tb;' + 'writing-mode: horizontal-tb;' + 'direction: rtl;' + 'unicode-bidi: bidi-override;',\n tbrl: '-webkit-writing-mode: vertical-rl;' + 'writing-mode: vertical-rl;' + '-webkit-text-orientation: upright;' + 'text-orientation: upright;',\n tblr: '-webkit-writing-mode: vertical-lr;' + 'writing-mode: vertical-lr;' + '-webkit-text-orientation: upright;' + 'text-orientation: upright;',\n lr: '-webkit-writing-mode: horizontal-tb;' + 'writing-mode: horizontal-tb;',\n rl: '-webkit-writing-mode: horizontal-tb;' + 'writing-mode: horizontal-tb;' + 'direction: rtl;',\n tb: '-webkit-writing-mode: vertical-rl;' + 'writing-mode: vertical-rl;' + '-webkit-text-orientation: upright;' + 'text-orientation: upright;'\n };\n converter = new _externalsXml2json2['default']({\n escapeMode: false,\n attributePrefix: '',\n arrayAccessForm: 'property',\n emptyNodeForm: 'object',\n stripWhitespaces: false,\n enableToStringFunc: false,\n matchers: []\n });\n }\n\n function parseTimings(timingStr) {\n // Test if the time provided by the caption is valid.\n var test = timingRegex.test(timingStr);\n var timeParts, parsedTime, frameRate;\n\n if (!test) {\n // Return NaN so it will throw an exception at internalParse if the time is incorrect.\n return NaN;\n }\n\n timeParts = timingStr.split(':');\n\n // Process the timings by decomposing it and converting it in numbers.\n parsedTime = parseFloat(timeParts[0]) * SECONDS_IN_HOUR + parseFloat(timeParts[1]) * SECONDS_IN_MIN + parseFloat(timeParts[2]);\n\n // In case a frameRate is provided, we adjust the parsed time.\n if (timeParts[3]) {\n frameRate = ttml.tt.frameRate;\n if (frameRate && !isNaN(frameRate)) {\n parsedTime += parseFloat(timeParts[3]) / frameRate;\n } else {\n return NaN;\n }\n }\n return parsedTime;\n }\n\n function getNamespacePrefix(json, ns) {\n // Obtain the namespace prefix.\n var r = Object.keys(json).filter(function (k) {\n return (k.split(':')[0] === 'xmlns' || k.split(':')[1] === 'xmlns') && json[k] === ns;\n }).map(function (k) {\n return k.split(':')[2] || k.split(':')[1];\n });\n if (r.length != 1) {\n return null;\n }\n return r[0];\n }\n\n function removeNamespacePrefix(json, nsPrefix) {\n for (var key in json) {\n if (json.hasOwnProperty(key)) {\n if ((typeof json[key] === 'object' || json[key] instanceof Object) && !Array.isArray(json[key])) {\n removeNamespacePrefix(json[key], nsPrefix);\n } else if (Array.isArray(json[key])) {\n for (var i = 0; i < json[key].length; i++) {\n removeNamespacePrefix(json[key][i], nsPrefix);\n }\n }\n var fullNsPrefix = nsPrefix + ':';\n var nsPrefixPos = key.indexOf(fullNsPrefix);\n if (nsPrefixPos >= 0) {\n var newKey = key.slice(nsPrefixPos + fullNsPrefix.length);\n json[newKey] = json[key];\n delete json[key];\n }\n }\n }\n }\n\n // backgroundColor = background-color, convert from camelCase to dash.\n function camelCaseToDash(key) {\n return key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }\n\n // Convert an RGBA value written in Hex to rgba(v,v,v,a).\n function convertHexToRGBA(rgba) {\n // Get the hexadecimal value without the #.\n var hex = rgba.slice(1);\n // Separate the values in pairs.\n var hexMatrice = hex.match(/.{2}/g);\n // Convert the alpha value in decimal between 0 and 1.\n var alpha = parseFloat(parseInt(parseInt(hexMatrice[3], 16) / 255 * 1000, 10) / 1000);\n // Get the standard RGB value.\n var rgb = hexMatrice.slice(0, 3).map(function (i) {\n return parseInt(i, 16);\n });\n // Return the RGBA value for CSS.\n return 'rgba(' + rgb.join(',') + ',' + alpha + ');';\n }\n\n // Convert an RGBA value written in TTML rgba(v,v,v,a => 0 to 255) to CSS rgba(v,v,v,a => 0 to 1).\n function convertAlphaValue(rgbaTTML) {\n var rgba = undefined,\n alpha = undefined,\n resu = undefined;\n\n rgba = rgbaTTML.replace(/^(rgb|rgba)\\(/, '').replace(/\\)$/, '').replace(/\\s/g, '').split(',');\n alpha = parseInt(rgba[rgba.length - 1], 10) / 255;\n resu = 'rgba(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ',' + alpha + ');';\n\n return resu;\n }\n\n // Return whether or not an array contains a certain text\n function arrayContains(text, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].indexOf(text) > -1) {\n return true;\n }\n }\n return false;\n }\n\n // Return the whole value that contains \"text\"\n function getPropertyFromArray(text, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].indexOf(text) > -1) {\n return array[i];\n }\n }\n return null;\n }\n\n // Delete a a property from an array.\n function deletePropertyFromArray(property, array) {\n array.splice(array.indexOf(getPropertyFromArray(property, array)), 1);\n }\n\n function mergeArrays(primeArray, arrayToAdd) {\n for (var i = 0; i < primeArray.length; i++) {\n for (var j = 0; j < arrayToAdd.length; j++) {\n // Take only the name of the property\n if (primeArray[i]) {\n if (primeArray[i].split(':')[0].indexOf(arrayToAdd[j].split(':')[0]) > -1) {\n primeArray.splice(i, 1);\n }\n }\n }\n }\n return primeArray.concat(arrayToAdd);\n }\n\n function getSizeTypeAndDefinition(cueStyleElement) {\n var returnTab = new Array(2);\n var startRef = cueStyleElement.indexOf(':') === -1 ? 0 : cueStyleElement.indexOf(':');\n var endRef = undefined;\n if (cueStyleElement.indexOf('%') === -1) {\n if (cueStyleElement.indexOf('c') === -1) {\n if (cueStyleElement.indexOf('p') === -1) {\n returnTab[0] = returnTab[1] = null;\n } else {\n returnTab[0] = 'p';\n endRef = cueStyleElement.indexOf('p');\n }\n } else {\n returnTab[0] = 'c';\n endRef = cueStyleElement.indexOf('c');\n }\n } else {\n returnTab[0] = '%';\n endRef = cueStyleElement.indexOf('%');\n }\n returnTab[1] = cueStyleElement.slice(startRef, endRef);\n return returnTab;\n }\n\n /**\n * Processing of styling information:\n * - processStyle: return an array of strings with the cue style under a CSS style form.\n * - findStyleFromID: Return the unprocessed style from TTMLStyling corresponding to the ID researched.\n * - getProcessedStyle: Return the processed style(s) from the ID(s) received in entry.\n * **/\n\n // Compute the style properties to return an array with the cleaned properties.\n function processStyle(cueStyle, cellUnit, includeRegionStyles) {\n var properties = [];\n var valueFtSizeInPx, valueLHSizeInPx;\n\n // Clean up from the xml2json parsing:\n for (var key in cueStyle) {\n if (cueStyle.hasOwnProperty(key)) {\n //Clean the properties from the parsing.\n var newKey = key.replace('ebutts:', '');\n newKey = newKey.replace('xml:', '');\n newKey = newKey.replace('tts:', '');\n\n // Clean the properties' names.\n newKey = camelCaseToDash(newKey);\n cueStyle[newKey] = cueStyle[key];\n delete cueStyle[key];\n }\n }\n\n // Line padding is computed from the cellResolution.\n if ('line-padding' in cueStyle) {\n var valuePadding = parseFloat(cueStyle['line-padding'].slice(cueStyle['line-padding'].indexOf(':') + 1, cueStyle['line-padding'].indexOf('c')));\n if ('id' in cueStyle) {\n linePadding[cueStyle.id] = valuePadding;\n }\n var valuePaddingInPx = valuePadding * cellUnit[0] + 'px;';\n properties.push('padding-left:' + valuePaddingInPx);\n properties.push('padding-right:' + valuePaddingInPx);\n }\n // Font size is computed from the cellResolution.\n if ('font-size' in cueStyle) {\n var fontSizeTab = getSizeTypeAndDefinition(cueStyle['font-size']);\n var valueFtSize = parseFloat(fontSizeTab[1]);\n if ('id' in cueStyle) {\n fontSize[cueStyle.id] = fontSizeTab;\n }\n\n if (fontSizeTab[0] === '%') {\n valueFtSizeInPx = valueFtSize / 100 * cellUnit[1] + 'px;';\n } else if (fontSizeTab[0] === 'c') {\n valueFtSizeInPx = valueFtSize * cellUnit[1] + 'px;';\n }\n\n properties.push('font-size:' + valueFtSizeInPx);\n }\n // Line height is computed from the cellResolution.\n if ('line-height' in cueStyle) {\n if (cueStyle['line-height'] === 'normal') {\n properties.push('line-height: normal;');\n } else {\n var LineHeightTab = getSizeTypeAndDefinition(cueStyle['line-height']);\n var valueLHSize = parseFloat(LineHeightTab[1]);\n if ('id' in cueStyle) {\n lineHeight[cueStyle.id] = LineHeightTab;\n }\n\n if (LineHeightTab[0] === '%') {\n valueLHSizeInPx = valueLHSize / 100 * cellUnit[1] + 'px;';\n } else if (LineHeightTab[0] === 'c') {\n valueLHSizeInPx = valueLHSize * cellUnit[1] + 'px;';\n }\n\n properties.push('line-height:' + valueLHSizeInPx);\n }\n }\n // Font-family can be specified by a generic family name or a custom family name.\n if ('font-family' in cueStyle) {\n if (cueStyle['font-family'] in fontFamilies) {\n properties.push(fontFamilies[cueStyle['font-family']]);\n } else {\n properties.push('font-family:' + cueStyle['font-family'] + ';');\n }\n }\n // Text align needs to be set from two properties:\n // The standard text-align CSS property.\n // The justify-content property as we use flex boxes.\n if ('text-align' in cueStyle) {\n if (cueStyle['text-align'] in textAlign) {\n properties.push(textAlign[cueStyle['text-align']][0]);\n properties.push(textAlign[cueStyle['text-align']][1]);\n }\n }\n // Multi Row align is set only by the text-align property.\n // TODO: TO CHECK\n if ('multi-row-align' in cueStyle) {\n if (arrayContains('text-align', properties) && cueStyle['multi-row-align'] != 'auto') {\n deletePropertyFromArray('text-align', properties);\n }\n if (cueStyle['multi-row-align'] in multiRowAlign) {\n properties.push(multiRowAlign[cueStyle['multi-row-align']]);\n }\n }\n // Background color can be specified from hexadecimal (RGB or RGBA) value.\n var rgbaValue;\n if ('background-color' in cueStyle) {\n if (cueStyle['background-color'].indexOf('#') > -1 && cueStyle['background-color'].length - 1 === 8) {\n rgbaValue = convertHexToRGBA(cueStyle['background-color']);\n } else if (cueStyle['background-color'].indexOf('rgba') > -1) {\n rgbaValue = convertAlphaValue(cueStyle['background-color']);\n } else {\n rgbaValue = cueStyle['background-color'] + ';';\n }\n properties.push('background-color: ' + rgbaValue);\n }\n // Color can be specified from hexadecimal (RGB or RGBA) value.\n if ('color' in cueStyle) {\n if (cueStyle.color.indexOf('#') > -1 && cueStyle.color.length - 1 === 8) {\n rgbaValue = convertHexToRGBA(cueStyle.color);\n } else if (cueStyle.color.indexOf('rgba') > -1) {\n rgbaValue = convertAlphaValue(cueStyle.color);\n } else {\n rgbaValue = cueStyle.color + ';';\n }\n properties.push('color: ' + rgbaValue);\n }\n // Wrap option is determined by the white-space CSS property.\n if ('wrap-option' in cueStyle) {\n if (cueStyle['wrap-option'] in wrapOption) {\n properties.push(wrapOption[cueStyle['wrap-option']]);\n } else {\n properties.push('white-space:' + cueStyle['wrap-option']);\n }\n }\n // Unicode bidi is determined by the unicode-bidi CSS property.\n if ('unicode-bidi' in cueStyle) {\n if (cueStyle['unicode-bidi'] in unicodeBidi) {\n properties.push(unicodeBidi[cueStyle['unicode-bidi']]);\n } else {\n properties.push('unicode-bidi:' + cueStyle['unicode-bidi']);\n }\n }\n\n // Standard properties identical to CSS.\n\n if ('font-style' in cueStyle) {\n properties.push('font-style:' + cueStyle['font-style'] + ';');\n }\n if ('font-weight' in cueStyle) {\n properties.push('font-weight:' + cueStyle['font-weight'] + ';');\n }\n if ('direction' in cueStyle) {\n properties.push('direction:' + cueStyle.direction + ';');\n }\n if ('text-decoration' in cueStyle) {\n properties.push('text-decoration:' + cueStyle['text-decoration'] + ';');\n }\n\n if (includeRegionStyles) {\n properties = properties.concat(processRegion(cueStyle, cellUnit));\n }\n\n // Handle white-space preserve\n if (ttml.tt.hasOwnProperty('xml:space')) {\n if (ttml.tt['xml:space'] === 'preserve') {\n properties.push('white-space: pre;');\n }\n }\n\n return properties;\n }\n\n // Find the style set by comparing the style IDs available.\n // Return null if no style is found\n function findStyleFromID(ttmlStyling, cueStyleID) {\n // For every styles available, search the corresponding style in ttmlStyling.\n for (var j = 0; j < ttmlStyling.length; j++) {\n var currStyle = ttmlStyling[j];\n if (currStyle['xml:id'] === cueStyleID || currStyle.id === cueStyleID) {\n // Return the style corresponding to the ID in parameter.\n return currStyle;\n }\n }\n return null;\n }\n // Return the computed style from a certain ID.\n function getProcessedStyle(reference, cellUnit, includeRegionStyles) {\n var styles = [];\n var ids = reference.match(/\\S+/g);\n ids.forEach(function (id) {\n // Find the style for each id received.\n var cueStyle = findStyleFromID(ttmlStyling, id);\n if (cueStyle) {\n // Process the style for the cue in CSS form.\n // Send a copy of the style object, so it does not modify the original by cleaning it.\n var stylesFromId = processStyle(JSON.parse(JSON.stringify(cueStyle)), cellUnit, includeRegionStyles);\n styles = styles.concat(stylesFromId);\n }\n });\n return styles;\n }\n\n // Calculate relative left, top, width, height from extent and origin in percent.\n // Return object with {left, top, width, height} as numbers in percent or null.\n function getRelativePositioning(element, ttExtent) {\n\n var pairRe = /([\\d\\.]+)(%|px)\\s+([\\d\\.]+)(%|px)/;\n\n if ('tts:extent' in element && 'tts:origin' in element) {\n var extentParts = pairRe.exec(element['tts:extent']);\n var originParts = pairRe.exec(element['tts:origin']);\n if (extentParts === null || originParts === null) {\n log('Bad extent or origin: ' + element['tts:extent'] + ' ' + element['tts:origin']);\n return null;\n }\n var width = parseFloat(extentParts[1]);\n var height = parseFloat(extentParts[3]);\n var left = parseFloat(originParts[1]);\n var _top = parseFloat(originParts[3]);\n\n if (ttExtent) {\n // Should give overall scale in pixels\n var ttExtentParts = pairRe.exec(ttExtent);\n if (ttExtentParts === null || ttExtentParts[2] !== 'px' || ttExtentParts[4] !== 'px') {\n log('Bad tt.extent: ' + ttExtent);\n return null;\n }\n var exWidth = parseFloat(ttExtentParts[1]);\n var exHeight = parseFloat(ttExtentParts[3]);\n if (extentParts[2] === 'px') {\n width = width / exWidth * 100;\n }\n if (extentParts[4] === 'px') {\n height = height / exHeight * 100;\n }\n if (originParts[2] === 'px') {\n left = left / exWidth * 100;\n }\n if (originParts[4] === 'px') {\n _top = _top / exHeight * 100;\n }\n }\n return { 'left': left, 'top': _top, 'width': width, 'height': height };\n } else {\n return null;\n }\n }\n\n /**\n * Processing of layout information:\n * - processRegion: return an array of strings with the cue region under a CSS style form.\n * - findRegionFromID: Return the unprocessed region from TTMLLayout corresponding to the ID researched.\n * - getProcessedRegion: Return the processed region(s) from the ID(s) received in entry.\n ***/\n\n // Compute the region properties to return an array with the cleaned properties.\n function processRegion(cueRegion, cellUnit) {\n var properties = [];\n\n // Clean up from the xml2json parsing:\n for (var key in cueRegion) {\n //Clean the properties from the parsing.\n var newKey = key.replace('tts:', '');\n newKey = newKey.replace('xml:', '');\n\n // Clean the properties' names.\n newKey = camelCaseToDash(newKey);\n cueRegion[newKey] = cueRegion[key];\n if (newKey !== key) {\n delete cueRegion[key];\n }\n }\n // Extent property corresponds to width and height\n if ('extent' in cueRegion) {\n var coordsExtent = cueRegion.extent.split(/\\s/);\n properties.push('width: ' + coordsExtent[0] + ';');\n properties.push('height: ' + coordsExtent[1] + ';');\n }\n // Origin property corresponds to top and left\n if ('origin' in cueRegion) {\n var coordsOrigin = cueRegion.origin.split(/\\s/);\n properties.push('left: ' + coordsOrigin[0] + ';');\n properties.push('top: ' + coordsOrigin[1] + ';');\n }\n // DisplayAlign property corresponds to vertical-align\n if ('display-align' in cueRegion) {\n properties.push(displayAlign[cueRegion['display-align']]);\n }\n // WritingMode is not yet implemented (for CSS3, to come)\n if ('writing-mode' in cueRegion) {\n properties.push(writingMode[cueRegion['writing-mode']]);\n }\n // Style will give to the region the style properties from the style selected\n if ('style' in cueRegion) {\n var styleFromID = getProcessedStyle(cueRegion.style, cellUnit, true);\n properties = properties.concat(styleFromID);\n }\n\n // Standard properties identical to CSS.\n\n if ('padding' in cueRegion) {\n properties.push('padding:' + cueRegion.padding + ';');\n }\n if ('overflow' in cueRegion) {\n properties.push('overflow:' + cueRegion.overflow + ';');\n }\n if ('show-background' in cueRegion) {\n properties.push('show-background:' + cueRegion['show-background'] + ';');\n }\n if ('id' in cueRegion) {\n properties.push('regionID:' + cueRegion.id + ';');\n }\n\n return properties;\n }\n\n // Find the region set by comparing the region IDs available.\n // Return null if no region is found\n function findRegionFromID(ttmlLayout, cueRegionID) {\n // For every region available, search the corresponding style in ttmlLayout.\n for (var j = 0; j < ttmlLayout.length; j++) {\n var currReg = ttmlLayout[j];\n if (currReg['xml:id'] === cueRegionID || currReg.id === cueRegionID) {\n // Return the region corresponding to the ID in parameter.\n return currReg;\n }\n }\n return null;\n }\n\n // Return the computed region from a certain ID.\n function getProcessedRegion(reference, cellUnit) {\n var regions = [];\n var ids = reference.match(/\\S+/g);\n ids.forEach(function (id) {\n // Find the region for each id received.\n var cueRegion = findRegionFromID(ttmlLayout, id);\n if (cueRegion) {\n // Process the region for the cue in CSS form.\n // Send a copy of the style object, so it does not modify the original by cleaning it.\n var regionsFromId = processRegion(JSON.parse(JSON.stringify(cueRegion)), cellUnit);\n regions = regions.concat(regionsFromId);\n }\n });\n return regions;\n }\n\n //Return the cellResolution defined by the TTML document.\n function getCellResolution() {\n var defaultCellResolution = [32, 15]; // Default cellResolution.\n if (ttml.tt.hasOwnProperty('ttp:cellResolution')) {\n return ttml.tt['ttp:cellResolution'].split(' ').map(parseFloat);\n } else {\n return defaultCellResolution;\n }\n }\n\n // Return the cue wrapped into a span specifying its linePadding.\n function applyLinePadding(cueHTML, cueStyle) {\n // Extract the linePadding property from cueStyleProperties.\n var linePaddingLeft = getPropertyFromArray('padding-left', cueStyle);\n var linePaddingRight = getPropertyFromArray('padding-right', cueStyle);\n var linePadding = linePaddingLeft.concat(' ' + linePaddingRight + ' ');\n\n // Declaration of the HTML elements to be used in the cue innerHTML construction.\n var outerHTMLBeforeBr = '';\n var outerHTMLAfterBr = '';\n var cueInnerHTML = '';\n\n // List all the nodes of the subtitle.\n var nodeList = Array.prototype.slice.call(cueHTML.children);\n // Take a br element as reference.\n var brElement = cueHTML.getElementsByClassName('lineBreak')[0];\n // First index of the first br element.\n var idx = nodeList.indexOf(brElement);\n // array of all the br element indices\n var indices = [];\n // Find all the indices of the br elements.\n while (idx != -1) {\n indices.push(idx);\n idx = nodeList.indexOf(brElement, idx + 1);\n }\n\n // Strings for the cue innerHTML construction.\n var spanStringEnd = '<\\/span>';\n var br = '<br>';\n var clonePropertyString = '<span' + ' class=\"spanPadding\" ' + 'style=\"-webkit-box-decoration-break: clone; box-decoration-break: clone; ';\n\n // If br elements are found:\n if (indices.length) {\n // For each index of a br element we compute the HTML coming before and/or after it.\n indices.forEach(function (i, index) {\n // If this is the first line break, we compute the HTML of the element coming before.\n if (index === 0) {\n var styleBefore = '';\n // for each element coming before the line break, we add its HTML.\n for (var j = 0; j < i; j++) {\n outerHTMLBeforeBr += nodeList[j].outerHTML;\n // If this is the first element, we add its style to the wrapper.\n if (j === 0) {\n styleBefore = linePadding.concat(nodeList[j].style.cssText);\n }\n }\n // The before element will comprises the clone property (for line wrapping), the style that\n // need to be applied (ex: background-color) and the rest og the HTML.\n outerHTMLBeforeBr = clonePropertyString + styleBefore + '\">' + outerHTMLBeforeBr;\n }\n // For every element of the list, we compute the element coming after the line break.s\n var styleAfter = '';\n // for each element coming after the line break, we add its HTML.\n for (var k = i + 1; k < nodeList.length; k++) {\n outerHTMLAfterBr += nodeList[k].outerHTML;\n // If this is the last element, we add its style to the wrapper.\n if (k === nodeList.length - 1) {\n styleAfter += linePadding.concat(nodeList[k].style.cssText);\n }\n }\n\n // The before element will comprises the clone property (for line wrapping), the style that\n // need to be applied (ex: background-color) and the rest og the HTML.\n outerHTMLAfterBr = clonePropertyString + styleAfter + '\">' + outerHTMLAfterBr;\n\n // For each line break we must add the before and/or after element to the final cue as well as\n // the line break when needed.\n if (outerHTMLBeforeBr && outerHTMLAfterBr && index === indices.length - 1) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd + br + outerHTMLAfterBr + spanStringEnd;\n } else if (outerHTMLBeforeBr && outerHTMLAfterBr && index !== indices.length - 1) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd + br + outerHTMLAfterBr + spanStringEnd + br;\n } else if (outerHTMLBeforeBr && !outerHTMLAfterBr) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd;\n } else if (!outerHTMLBeforeBr && outerHTMLAfterBr && index === indices.length - 1) {\n cueInnerHTML += outerHTMLAfterBr + spanStringEnd;\n } else if (!outerHTMLBeforeBr && outerHTMLAfterBr && index !== indices.length - 1) {\n cueInnerHTML += outerHTMLAfterBr + spanStringEnd + br;\n }\n });\n } else {\n // If there is no line break in the subtitle, we simply wrap cue in a span indicating the linePadding.\n var style = '';\n for (var k = 0; k < nodeList.length; k++) {\n style += nodeList[k].style.cssText;\n }\n cueInnerHTML = clonePropertyString + linePadding + style + '\">' + cueHTML.innerHTML + spanStringEnd;\n }\n return cueInnerHTML;\n }\n\n /*\n * Create the cue element\n * I. The cues are text only:\n * i) The cue contains a 'br' element\n * ii) The cue contains a span element\n * iii) The cue contains text\n */\n\n function constructCue(cueElements, cellUnit) {\n var cue = document.createElement('div');\n cueElements.forEach(function (el) {\n // If metadata is present, do not process.\n if (el.hasOwnProperty('metadata')) {\n return;\n }\n\n /**\n * If the p element contains spans: create the span elements.\n */\n if (el.hasOwnProperty('span')) {\n\n // Stock the span subtitles in an array (in case there are only one value).\n var spanElements = el.span.__children;\n\n // Create the span element.\n var spanHTMLElement = document.createElement('span');\n // Extract the style of the span.\n if (el.span.hasOwnProperty('style')) {\n var spanStyle = getProcessedStyle(el.span.style, cellUnit);\n spanHTMLElement.className = 'spanPadding ' + el.span.style;\n spanHTMLElement.style.cssText = spanStyle.join(' ');\n }\n\n // if the span has more than one element, we check for each of them their nature (br or text).\n spanElements.forEach(function (spanEl) {\n // If metadata is present, do not process.\n if (spanElements.hasOwnProperty('metadata')) {\n return;\n }\n // If the element is a string\n if (spanEl.hasOwnProperty('#text')) {\n var textNode = document.createTextNode(spanEl['#text']);\n spanHTMLElement.appendChild(textNode);\n // If the element is a 'br' tag\n } else if ('br' in spanEl) {\n // To handle br inside span we need to add the current span\n // to the cue and then create a br and add that the cue\n // then create a new span that we use for the next line of\n // text, that is a copy of the current span\n\n // Add the current span to the cue, only if it has childNodes (text)\n if (spanHTMLElement.hasChildNodes()) {\n cue.appendChild(spanHTMLElement);\n }\n\n // Create a br and add that to the cue\n var brEl = document.createElement('br');\n brEl.className = 'lineBreak';\n cue.appendChild(brEl);\n\n // Create an replacement span and copy the style and classname from the old one\n var newSpanHTMLElement = document.createElement('span');\n newSpanHTMLElement.className = spanHTMLElement.className;\n newSpanHTMLElement.style.cssText = spanHTMLElement.style.cssText;\n\n // Replace the current span with the one we just created\n spanHTMLElement = newSpanHTMLElement;\n }\n });\n // We append the element to the cue container.\n cue.appendChild(spanHTMLElement);\n }\n\n /**\n * Create a br element if there is one in the cue.\n */\n else if (el.hasOwnProperty('br')) {\n // We append the line break to the cue container.\n var brEl = document.createElement('br');\n brEl.className = 'lineBreak';\n cue.appendChild(brEl);\n }\n\n /**\n * Add the text that is not in any inline element\n */\n else if (el.hasOwnProperty('#text')) {\n // Add the text to an individual span element (to add line padding if it is defined).\n var textNode = document.createElement('span');\n textNode.textContent = el['#text'];\n\n // We append the element to the cue container.\n cue.appendChild(textNode);\n }\n });\n return cue;\n }\n\n function constructCueRegion(cue, div, cellUnit) {\n var cueRegionProperties = []; // properties to be put in the \"captionRegion\" HTML element\n // Obtain the region ID(s) assigned to the cue.\n var pRegionID = cue.region;\n // If div has a region.\n var divRegionID = div.region;\n\n var divRegion;\n var pRegion;\n\n // If the div element reference a region.\n if (divRegionID) {\n divRegion = getProcessedRegion(divRegionID, cellUnit);\n }\n // If the p element reference a region.\n if (pRegionID) {\n pRegion = cueRegionProperties.concat(getProcessedRegion(pRegionID, cellUnit));\n if (divRegion) {\n cueRegionProperties = mergeArrays(divRegion, pRegion);\n } else {\n cueRegionProperties = pRegion;\n }\n } else if (divRegion) {\n cueRegionProperties = divRegion;\n }\n\n // Add initial/default values to what's not defined in the layout:\n applyDefaultProperties(cueRegionProperties, defaultLayoutProperties);\n\n return cueRegionProperties;\n }\n\n function constructCueStyle(cue, cellUnit) {\n var cueStyleProperties = []; // properties to be put in the \"paragraph\" HTML element\n // Obtain the style ID(s) assigned to the cue.\n var pStyleID = cue.style;\n // If body has a style.\n var bodyStyleID = ttml.tt.body.style;\n // If div has a style.\n var divStyleID = ttml.tt.body.div.style;\n\n var bodyStyle;\n var divStyle;\n var pStyle;\n var styleIDs = '';\n\n // If the body element reference a style.\n if (bodyStyleID) {\n bodyStyle = getProcessedStyle(bodyStyleID, cellUnit);\n styleIDs = 'paragraph ' + bodyStyleID;\n }\n\n // If the div element reference a style.\n if (divStyleID) {\n divStyle = getProcessedStyle(divStyleID, cellUnit);\n if (bodyStyle) {\n divStyle = mergeArrays(bodyStyle, divStyle);\n styleIDs += ' ' + divStyleID;\n } else {\n styleIDs = 'paragraph ' + divStyleID;\n }\n }\n\n // If the p element reference a style.\n if (pStyleID) {\n pStyle = getProcessedStyle(pStyleID, cellUnit);\n if (bodyStyle && divStyle) {\n cueStyleProperties = mergeArrays(divStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else if (bodyStyle) {\n cueStyleProperties = mergeArrays(bodyStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else if (divStyle) {\n cueStyleProperties = mergeArrays(divStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else {\n cueStyleProperties = pStyle;\n styleIDs = 'paragraph ' + pStyleID;\n }\n } else if (bodyStyle && !divStyle) {\n cueStyleProperties = bodyStyle;\n } else if (!bodyStyle && divStyle) {\n cueStyleProperties = divStyle;\n }\n\n // Add initial/default values to what's not defined in the styling:\n applyDefaultProperties(cueStyleProperties, defaultStyleProperties);\n\n return [cueStyleProperties, styleIDs];\n }\n\n function applyDefaultProperties(array, defaultProperties) {\n for (var key in defaultProperties) {\n if (defaultProperties.hasOwnProperty(key)) {\n if (!arrayContains(key, array)) {\n array.push(key + ':' + defaultProperties[key]);\n }\n }\n }\n }\n\n instance = {\n parse: parse,\n setConfig: setConfig\n };\n\n setup();\n return instance;\n}", "async parse(args, state) {\n const context = await this._parse(args, state);\n return context.toResult();\n }", "streamInfo() {\n return {\n comment: parsePrelude(this.prelude).comment,\n directives: this.directives,\n errors: this.errors,\n warnings: this.warnings\n };\n }", "streamInfo() {\n return {\n comment: parsePrelude(this.prelude).comment,\n directives: this.directives,\n errors: this.errors,\n warnings: this.warnings\n };\n }", "function parseBody(input) {\n\tfor (var i = 0 ; i < input.length ; i++) {\n\t\tvar obj = input[i]\n\t\tswitch(obj.type) {\n\t\t\tcase 'message':\n\t\t\t\tswitch(obj.message.type) {\n\t\t\t\t\tcase 'text':\n\t\t\t\t\t\tmyLog('[' + obj.timestamp + '] ' + chalk.green(obj.source.userId) + chalk.cyan(' said: ') + chalk.blue(obj.message.text))\n\t\t\t\t\t\tbreak\n case 'location':\n myLog('[' + obj.timestamp + '] ' + chalk.green(obj.source.userId) + chalk.cyan(' sent a ') + chalk.blue(obj.message.type))\n break\n\t\t\t\t\tdefault:\n myLog('[' + obj.timestamp + '] ' + chalk.green(obj.source.userId) + chalk.cyan(' sent a ') + chalk.blue(obj.message.type))\n\t\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'follow':\n\t\t\t\tmyLog('[' + obj.timestamp + '] ' + chalk.green(obj.source.userId) + chalk.cyan(' joined the channel'))\n\t\t\t\tbreak\n\t\t\tcase 'unfollow':\n\t\t\t\tmyLog('[' + obj.timestamp + '] ' + chalk.green(obj.source.userId) + chalk.red(' left the channel'))\n\t\t\t\tbreak\n\t\t\tcase 'join':\n\t\t\t\tmyLog('[' + obj.timestamp + '] ' + chalk.cyan('Joined ') + chalk.green(obj.source.groupId))\n\t\t\t\tchannel = obj.source.groupId\n\t\t\t\tline.sendText(channel, '大家好!我是退治報時機器人OwO')\n\t\t\t\tbreak\n default:\n myLog('[' + obj.timestamp + '] ' + chalk.green(obj.source.userId) + chalk.cyan(' made a ') + chalk.blue(obj.type) + chalk.cyan(' event'))\n\t\t}\n\t}\n}", "function callback(data) {\n parseData = JSON.parse(data)\n console.log(\"name: \", parseData.dataset)\n // console.log(\"print - \", JSON.stringify(JSON.parse(data), null, '\\t'))\n}", "function YCurrentLoopOutput_nextCurrentLoopOutput()\n { var resolve = YAPI.resolveFunction(this._className, this._func);\n if(resolve.errorType != YAPI_SUCCESS) return null;\n var next_hwid = YAPI.getNextHardwareId(this._className, resolve.result);\n if(next_hwid == null) return null;\n return YCurrentLoopOutput.FindCurrentLoopOutput(next_hwid);\n }", "constructor(stream) {\n\n /** call super() to invoke extended class's constructor */\n super();\n\n /** capture incoming data */\n let buffer = '';\n\n /** handle the incoming data events */\n stream.on('data', data => {\n /**\n * append raw data to end of buffer then, starting from\n * the front backwards, look for complete messages\n */\n buffer += data;\n let boundary = buffer.indexOf('\\n');\n /**\n * JSON.parse each message string and emit as message\n * event by LDJclient via this.emit\n */\n while (boundary !== -1) {\n const input = buffer.substring(0, boundary);\n buffer = buffer.substring(boundary + 1);\n this.emit('message', JSON.parse(input));\n boundary = buffer.indexOf('\\n');\n }\n });\n }", "gotInfo (err, data, cb) {\n if (err) return cb(err)\n if (!data) data = []\n\n const lastUpdate = Date.now() / 1000\n\n // refill our instances cache\n for (let datum of data) {\n const id = datum.meta.id\n const found = this.instances.has(id)\n const instance = found ? this.instances.get(id) : {}\n\n instance.lastUpdate = lastUpdate\n\n if (found) continue\n\n instance.app = util.normalizeName(datum.meta.app)\n\n let tags = datum.reply.tags || []\n tags = tags.map(tag => util.normalizeName(tag))\n instance.tags = tags.join(',')\n\n this.instances.set(id, instance)\n }\n\n cb(null, data)\n }", "load(data) {\n super.load(data);\n const videoInfo = _1.BaseVideo.parseRawData(data);\n this.watchingCount = +videoInfo.viewCount.videoViewCountRenderer.viewCount.runs\n .map((r) => r.text)\n .join(\" \")\n .replace(/[^0-9]/g, \"\");\n this.chatContinuation =\n data[3].response.contents.twoColumnWatchNextResults.conversationBar.liveChatRenderer.continuations[0].reloadContinuationData.continuation;\n return this;\n }", "init() {\n this._child = fork('./routes/src/worker/parser.js');\n this._child.on('message', (data) => {\n this._bk_data[0] = data.data[0];\n this._bk_data[1] = data.data[1];\n this._bk_data[2] = data.data[2];\n this._bk_data[3] = data.data[3];\n this._bk_data[4] = data.data[4];\n this._bk_data[5] = data.data[5];\n this._bk_data[6] = data.data[6];\n this._bk_data[7] = data.data[7];\n });\n }", "stream(track) {\n const _opts = {\n method: \"post\",\n url: this._stream,\n qs: {\n track,\n language: \"en\",\n stall_warnings: true\n }\n };\n // create initial request with auth & options\n this.activeStream = this._request(_opts);\n this.activeStream.on(\"response\", response => {\n let buffer = \"\";\n \n if(response.statusCode !== 200) {\n this.events.emit(\"twitter:stream:error\", { type: \"STATUS\", err: response });\n }\n \n response.on(\"data\", data => {\n let index, json;\n buffer += data.toString(\"utf8\");\n \n // loop over the stream while there is an indexOf new line characters\n while ((index = buffer.indexOf(\"\\r\\n\")) > -1) {\n json = buffer.slice(0, index); // grab the json to the first end of line\n buffer = buffer.slice(index + 2); // set the next buffer content\n if (json.length) { // if the json has length try to parse and emit a success/error event\n try {\n this.events.emit(\"twitter:stream:success\", JSON.parse(json));\n }\n catch(err) {\n this.events.emit(\"twitter:stream:error\", { type: 'JSON', err });\n }\n }\n }\n }).on(\"error\", err => {\n // response error\n this.events.emit(\"twitter:stream:error\", {type: \"RESPONSE\", err});\n this.activeStream.abort();\n }).on(\"end\", () => {\n // response end\n this.events.emit(\"twitter:stream:end\");\n });\n \n }).on(\"error\", err => {\n // request error\n this.events.emit(\"twitter:stream:error\", {type: \"REQUEST\", err})\n this.activeStream.abort();\n });\n\n this.activeStream.end();\n }", "static parseUDPFrame(data) {\n const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);\n buff.readOffset = 2;\n const frameNumber = buff.readUInt8();\n const hostType = buff.readUInt8();\n let remoteHost;\n if (hostType === constants_1.Socks5HostType.IPv4) {\n remoteHost = ip.fromLong(buff.readUInt32BE());\n }\n else if (hostType === constants_1.Socks5HostType.IPv6) {\n remoteHost = ip.toString(buff.readBuffer(16));\n }\n else {\n remoteHost = buff.readString(buff.readUInt8());\n }\n const remotePort = buff.readUInt16BE();\n return {\n frameNumber,\n remoteHost: {\n host: remoteHost,\n port: remotePort\n },\n data: buff.readBuffer()\n };\n }", "function Debugger() {\n events.EventEmitter.call(this);\n\n this.web = null; // web UI singleton\n this.targetStream = null; // transport connection to target\n this.outputPassThroughStream = null; // dummy passthrough for message dumping\n this.inputParser = null; // parser for incoming debug messages\n this.outputParser = null; // parser for outgoing debug messages (stats, dumping)\n this.protocolVersion = null;\n this.dukVersion = null;\n this.dukGitDescribe = null;\n this.targetInfo = null;\n this.attached = false;\n this.handshook = false;\n this.reqQueue = null;\n this.stats = { // stats for current debug connection\n rxBytes: 0, rxDvalues: 0, rxMessages: 0, rxBytesPerSec: 0,\n txBytes: 0, txDvalues: 0, txMessages: 0, txBytesPerSec: 0\n };\n this.execStatus = {\n attached: false,\n state: 'detached',\n fileName: '',\n funcName: '',\n line: 0,\n pc: 0\n };\n this.breakpoints = [];\n this.callstack = [];\n this.locals = [];\n this.messageLines = [];\n this.messageScrollBack = 100;\n}", "function OnStreams(e = null){\n\tif (HasValidResponse()){ \n\t\tBuildStreamUI(RawResponse['streams']);\n\t}\n}", "playback(playbackBlocks){\n let pbIndex = this.state.pbIndex\n let rIndex = this.state.rIndex\n let mIndex = this.state.mIndex\n let tsIndex = this.state.tsIndex\n let songLength = this.state.playbackBlocks.length\n let namePB, repeatPB, measurePB, timeSigPB, bpmPB, color\n\n while (pbIndex < songLength) {\n let playbackBlock = playbackBlocks[pbIndex]\n namePB = playbackBlock.name\n bpmPB = playbackBlock.msPerBeat\n color = playbackBlock.color\n while (rIndex < playbackBlock.repeat) {\n repeatPB = rIndex + 1\n while (mIndex < playbackBlock.measure) {\n measurePB = mIndex + 1\n while (tsIndex < playbackBlock.timeSig){\n timeSigPB = tsIndex + 1\n tsIndex++\n if (tsIndex == playbackBlock.timeSig) {\n tsIndex = 0\n mIndex++\n if (mIndex == playbackBlock.measure) {\n tsIndex = 0\n mIndex =0\n rIndex++\n if (rIndex == playbackBlock.repeat) {\n tsIndex = 0\n mIndex =0\n rIndex = 0\n pbIndex++\n }\n }\n }\n break\n }\n break\n }\n break\n }\n break\n }\n this.setState({\n name: namePB,\n repeat: repeatPB,\n measure: measurePB,\n timeSig: timeSigPB,\n color: color,\n pbIndex: pbIndex,\n rIndex: rIndex,\n mIndex: mIndex,\n tsIndex: tsIndex\n })\n return bpmPB\n }", "ondecoded(packet) {\n // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a \"parse error\"\n nextTick(() => {\n this.emitReserved(\"packet\", packet);\n }, this.setTimeoutFn);\n }", "onOutput () {}", "function FrameParser (options) {\n Transform.call(this, options);\n this.frames = {};\n this.ignoredFrames = {};\n}", "parse(eventObject) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t// method definition\n\t\tlet {name, time} = eventObject;\t\t\t\t\t\t\t\t\t\t\t// let keyword, destructuring\n\t\treturn `Received event ${name} at time ${time}`;\t\t\t\t\t\t// template string\n\t}", "message() {\n let msg = null;\n if (this._message) {\n return this._message;\n }\n\n let data = this._data;\n switch (this._dataFormat) {\n case XVIZ_FORMAT.BINARY_GLB:\n if (data instanceof Buffer) {\n data = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);\n }\n msg = parseBinaryXVIZ(data);\n break;\n case XVIZ_FORMAT.JSON_BUFFER:\n let jsonString = null;\n if (data instanceof Buffer) {\n // Default to utf8 encoding\n jsonString = data.toString();\n } else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {\n data = new Uint8Array(data);\n\n // This is slow\n jsonString = new TextDecoder('utf8').decode(data);\n }\n\n msg = JSON.parse(jsonString);\n break;\n case XVIZ_FORMAT.JSON_STRING:\n msg = JSON.parse(data);\n break;\n case XVIZ_FORMAT.OBJECT:\n // TODO: what is the recursive case?\n // see parse-stream-data-message.js\n msg = data;\n break;\n default:\n throw new Error(`Unsupported format ${this._dataFormat}`);\n }\n\n this._message = new XVIZMessage(msg);\n return this._message;\n }", "create() {\n\n //establish socket connection with server\n this.socket = io(this.serverURL, {reconnection: false});\n\n //initialize a group to later be used to store every player EXCEPT the one currently playing\n this.otherPlayers = this.add.group();\n\n this.pipes = this.add.group();\n this.pipes.setDepth(100);\n\n this.waitingText = this.add.text(225,150, \"WAITING FOR PLAYERS...\", { font: \"bold 32px Arial\", fill: \"#fff\", boundsAlignH: \"center\", boundsAlignV: \"middle\", stroke: '#000000', strokeThickness: 6});\n this.waitingText.alpha = 0.0;\n this.waitingText.setDepth(2);\n\n this.countDownText = this.add.text(225,150, \"\", { font: \"bold 32px Arial\", fill: \"#ff0000\", boundsAlignH: \"center\", boundsAlignV: \"middle\", stroke: '#000000', strokeThickness: 6});\n this.countDownText.alpha = 0.0;\n this.countDownText.setDepth(3);\n\n this.gameEndText = this.add.text(225,150, \"\", { font: \"bold 18px Arial\", fill: \"#f6f413\", boundsAlignH: \"center\", boundsAlignV: \"middle\", stroke: '#000000', strokeThickness: 4});\n this.gameEndText.alpha = 0.0;\n this.gameEndText.setDepth(3);\n\n this.highScoreText = this.add.text(750,10, \"\", { font: \"15px Arial\", fill: \"#ffffff\", stroke: '#000000', strokeThickness: 2});\n this.highScoreText.setDepth(4);\n\n this.highScoreAlertText = this.add.text(10, 10, \"\", { font: \"32px Arial\", fill: \"#ffffff\", stroke: '#000000', strokeThickness: 6});\n this.highScoreAlertText.alpha = 0.0;\n this.highScoreAlertText.setDepth(5);\n\n this.disconnectedText = this.add.text(225,400, \"You were disconnected from the server, please refresh page.\", { font: \"bold 20px Arial\", fill: \"#ff0000\", boundsAlignH: \"center\", boundsAlignV: \"middle\", stroke: '#000000', strokeThickness: 6});\n this.disconnectedText.alpha = 0.0;\n this.disconnectedText.setDepth(6);\n\n\n\n\n initializeSocketOnEvents(this);\n\n this.spacebar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);\n\n this.input.on('pointerdown', pointer => {\n if(this.player) {\n if(this.player.isActive) {\n this.player.setVelocity(0, -420);\n }\n }\n });\n }", "constructor(stream) {\n this._stream = stream;\n this._parser = null;\n }", "function Parser () {\n var self = this;\n self.client = new ParserStream();\n self.peer = new ParserStream();\n self.client.peer = self.peer;\n self.peer.peer = self.client;\n self.definitions = definitions;\n self.client.on('handshake', function () {\n self.client.handshake.sent();\n self.changeParsers();\n });\n self.peer.on('handshake', function () {\n self.peer.handshake.sent();\n self.changeParsers();\n });\n}", "function parse_613(data) {\n\tlet parse = {\n\t\tvehicle : {\n\t\t\todometer : {\n\t\t\t\tkm : ((data.msg[1] << 8) + data.msg[0]) * 10,\n\t\t\t\tmi : null,\n\t\t\t},\n\n\t\t\trunning_clock : ((data.msg[4] << 8) + data.msg[3]),\n\t\t},\n\n\t\t// Looks bad, I should feel bad\n\t\tfuel : {\n\t\t\tlevel : null,\n\t\t\tliters : (data.msg[2] >= 0x80) && data.msg[2] - 0x80 || data.msg[2],\n\t\t},\n\t};\n\n\tparse.fuel.level = Math.floor((parse.fuel.liters / config.fuel.liters_max) * 100);\n\tif (parse.fuel.level < 0) parse.fuel.level = 0;\n\tif (parse.fuel.level > 100) parse.fuel.level = 100;\n\n\tupdate.status('fuel.level', parse.fuel.level, false);\n\tupdate.status('fuel.liters', parse.fuel.liters);\n\n\tparse.vehicle.odometer.mi = Math.floor(convert(parse.vehicle.odometer.km).from('kilometre').to('us mile'));\n\n\tupdate.status('vehicle.odometer.km', parse.vehicle.odometer.km);\n\tupdate.status('vehicle.odometer.mi', parse.vehicle.odometer.mi, false);\n\n\tupdate.status('vehicle.running_clock', parse.vehicle.running_clock, false);\n}", "function handleCallback(data) {\n console.log(data);\n }", "function printFinishedTelnetOutput(outputRecordManager) {\n var nicOutputRecords = outputRecordManager.getOutputRecords();\n for (var j = 0; j < nicOutputRecords.length; j++) {\n ndebug.AppGuiManager.printOutputToScreenConsole(\n nicOutputRecords[j].getMessage(),\n nicOutputRecords[j].getLevel(),\n nicOutputRecords[j].getTimestamp());\n }\n}", "async interpret() {\n const byteCode = await this.emitRawStream();\n await new Promise((resolve, reject) => {\n let lli = spawn('lli', [], {\n stdio: ['pipe', 'inherit', 'inherit']\n });\n\n byteCode.pipe(lli.stdin);\n\n lli.on('error', reject);\n lli.on('exit', resolve);\n });\n }", "async function parseStatus() {\n let trackingInfo = {};\n let status, sender, receiver, eta;\n let additionalFilesInfo = [];\n\n // Iterate over every tracking number\n for (let elem of trackingNumArray) {\n for (let s of surnameArray) {\n try {\n let results = await databases.findStatusInfo(elem, s);\n trackingInfo[elem] = results[\"containerLine\"][0];\n trackingInfo[elem].overseasAccess = results[\"overseasAccess\"];\n\n // console.log(trackingInfo[elem]); // for testing\n\n sender = trackingInfo[elem].sender.firstName + \" \" \n + trackingInfo[elem].sender.middleName + \" \"\n + trackingInfo[elem].sender.lastName;\n\n receiver = trackingInfo[elem].receiver.firstName + \" \" \n + trackingInfo[elem].receiver.middleName + \" \"\n + trackingInfo[elem].receiver.lastName;\n\n status = trackingInfo[elem].status.stage;\n eta = trackingInfo[elem].status.estPortArrivalDate;\n\n const additionalFilesArray = trackingInfo[elem].status.additionalFiles;\n\n for (let file of additionalFilesArray) {\n additionalFilesInfo.push({\n containerId : results._id.toString(),\n fileId: file._id.toString(),\n fileName: file.name\n });\n }\n\n break; // breaks out pf surnameArray loop to move on searching with next tracking number\n\n } catch(err) {\n trackingInfo[elem] = err;\n continue;\n }\n }\n }\n\n res.render(\"tracking/cargoflex-results\", {\n trackingInfo: trackingInfo, \n trackingNumber: req.body.trackingNumber,\n trackingSurname: req.body.surname,\n additionalFilesInfo: additionalFilesInfo,\n sender: sender,\n receiver: receiver,\n status: status,\n eta: eta,\n user: user\n });\n }", "function parse_twitch_stream(c, channel_name, numViewers) {\n\n var minute = 0;\n var past_minuteJSON;\n minute_parser();\n var hourJSON = init_hourJSON(channel_name, numViewers);\n var emoteKeys;\n\n\n //for 60 times\n //return minuteJSON after a minute, then call minute_parser() again\n\n function minute_parser() {\n //each minute\n //emotes used\n // - # of uses\n // - list of who used that emote\n\n //intialize data structure\n var minuteJSON = require('./global.json');\n delete minuteJSON.meta;\n delete minuteJSON.template;\n //console.log(util.inspect(minuteJSON.emotes, {depth:null}))\n emoteKeys = Object.keys(minuteJSON.emotes);\n\n //initialize userSet property as an Object to imitate a set\n for (var i = 0; i < emoteKeys.length; i++) {\n minuteJSON.emotes[emoteKeys[i]].userSet = {};\n minuteJSON.emotes[emoteKeys[i]].ocurrences = 0;\n }\n //console.log(util.inspect(emoteKeys, {depth:null}))\n\n if(minute == 0) {\n c.addListener('raw', function (message) {\n //console.log(util.inspect(message, {depth: null}));\n //console.log(message.args[1]);\n\n var userName = message.nick;\n\n //search for emotes\n for (var i = 0; i < emoteKeys.length; i++) {\n //console.log(emoteKeys[i]);\n\n var ocurrences = countOcurrences(message.args[1], emoteKeys[i]);\n if (ocurrences > 0) {\n //console.log(emoteKeys[i] + \" : \" + ocurrences);\n //check to see if userName already present\n //if not, add to list\n if (!(userName in minuteJSON.emotes[emoteKeys[i]].userSet)) {\n minuteJSON.emotes[emoteKeys[i]].userSet[userName] = true;\n //console.log(\"added \"+userName+\" for \"+emoteKeys[i]);\n }\n\n //add ocurrences to json\n minuteJSON.emotes[emoteKeys[i]].ocurrences += ocurrences;\n\n }\n }\n });\n }\n\n //return minuteJSON after 1 minute\n setTimeout(function(){\n minuteJSON;\n minute++;\n //console.log(util.inspect(minuteJSON, {depth: null}));\n parse_minute_into_hour(minuteJSON);\n //return true;\n }, 60000);\n }\n\n function init_hourJSON(streamName, numViewers){\n var hourJSON = new Object();\n\n hourJSON.streamName = streamName;\n hourJSON.timestamp = Date.now();\n hourJSON.numViewers = numViewers;\n hourJSON.minutes = {};\n\n return hourJSON;\n }\n\n function parse_minute_into_hour(minuteJSON){\n //clone minuteJSON\n var minuteCLONE = JSON.parse(JSON.stringify(minuteJSON));\n\n console.log(\"parse_minute_into_hour()\");\n //var minuteInHour = {};\n //var highestEmoticon = \"Kappa\";\n //var highestQuantity = 0;\n //var numUsers = 0;\n\n //iterate through emoticons\n //find which emoticon has the highest quantity in the minute\n\n //console.log(\"MINUTEJSON: \");\n //console.log(util.inspect(minuteJSON, {depth:null}));\n //console.log(\"for loop has \"+minuteJSON.emotes.length+ \" emotes to check\");\n\n //for(var i = 0; i < emoteKeys.length; i++){\n //if(minuteJSON.emotes[emoteKeys[i]].ocurrences > highestQuantity){\n // highestQuantity = minuteJSON.emotes[emoteKeys[i]].ocurrences;\n // highestEmoticon = emoteKeys[i];\n // numUsers = Object.keys(minuteJSON.emotes[emoteKeys[i]].userSet).length;\n //}\n //}\n //console.log(\"reached end of for loop\");\n\n\n for(var i = 0; i < emoteKeys.length; i++){\n if(minuteCLONE.emotes[emoteKeys[i]].ocurrences == 0){\n delete minuteCLONE.emotes[emoteKeys[i]];\n }\n else{\n delete minuteCLONE.emotes[emoteKeys[i]].description;\n delete minuteCLONE.emotes[emoteKeys[i]].image_id;\n }\n }\n\n //tweet?\n emotes2 = minuteCLONE.emotes;\n //console.log(util.inspect(emotes));\n\n var emoteArray = [];\n\n //count number of emotes\n var totalEmotes = 0;\n var emoteKeys2 = Object.keys(emotes2);\n for (var i = 0; i < emoteKeys2.length; i++) {\n //totalEmotes += emotes[emoteKeys[i]].ocurrences;\n for (var j = 0; j < emotes2[emoteKeys2[i]].ocurrences; j++) {\n emoteArray.push(emoteKeys2[i]);\n }\n }\n console.log(emoteArray);\n\n translate_to_emoji(emoteArray);\n\n\n\n //add to minuteInHour:\n // - emoticon name\n // - # of uses\n // - # of users\n\n //minuteInHour.emoteName = highestEmoticon;\n //minuteInHour.ocurrences = highestQuantity;\n //minuteInHour.numUsers = numUsers;\n\n //add to hourJSON\n //console.log(\"set minute in hourJSON\");\n //hourJSON.minutes[minute] = minuteInHour;\n hourJSON.minutes[minute] = minuteCLONE;\n console.log(\"log hourJSON\");\n //console.log(util.inspect(hourJSON, {depth: null}));\n console.log(minute);\n\n var filename = \"./twitch_logs_by_minute/\"+hourJSON.timestamp+\"-\"+hourJSON.streamName+\".json\";\n fs.writeFileSync(filename, JSON.stringify(hourJSON, null, 4, function(err){\n if(err){\n console.log(err);\n }\n else {\n console.log(\"JSON saved to \" + filename);\n\n }\n\n }));\n\n\n if(minute < 60){\n console.log(\"starting minute \"+minute);\n minute_parser();\n }\n else{\n //pass filename\n //render and tweet\n //close\n }\n }\n}", "async function parse(parser, source, opts) {\n if (!connectionOptions) {\n const spawnedServer = await spawnServer(opts);\n connectionOptions = spawnedServer.connectionOptions;\n }\n\n return new Promise((resolve, reject) => {\n const socket = new net.Socket();\n let chunks = \"\";\n\n socket.on(\"error\", (error) => {\n reject(error);\n });\n\n socket.on(\"data\", (data) => {\n chunks += data.toString(\"utf-8\");\n });\n\n socket.on(\"end\", () => {\n const response = JSON.parse(chunks);\n\n if (response.error) {\n const error = new Error(response.error);\n if (response.loc) {\n error.loc = response.loc;\n }\n\n reject(error);\n }\n\n resolve(response);\n });\n\n socket.connect(connectionOptions, () => {\n socket.end(\n JSON.stringify({\n parser,\n source,\n maxwidth: opts.printWidth,\n tabwidth: opts.tabWidth\n })\n );\n });\n });\n}", "function statStream() {\n if (!(this instanceof statStream)) {\n return new statStream();\n }\n\n options = {\n objectMode: true\n };\n Transform.call(this, options);\n\n // State to keep between data events\n this._linecount = 0;\n this._keys = {};\n this._cur = null;\n this._allowedPops = {\n \"prochloro\": true,\n \"synecho\": true,\n \"picoeuk\": true,\n \"beads\": true\n };\n}", "async completeTracing () {\n const traceDuration = Date.now() - this.traceStart\n log.info(`Tracing completed after ${traceDuration}ms, capturing performance data for frame ${this.frameId}`)\n\n /**\n * download all tracing data\n * in case it fails, continue without capturing any data\n */\n try {\n const traceBuffer = await this.page.tracing.stop()\n const traceEvents = JSON.parse(traceBuffer.toString('utf8'))\n\n /**\n * modify pid of renderer frame to be the same as where tracing was started\n * possibly related to https://github.com/GoogleChrome/lighthouse/issues/6968\n */\n const startedInBrowserEvt = traceEvents.traceEvents.find(e => e.name === 'TracingStartedInBrowser')\n const mainFrame = (\n startedInBrowserEvt &&\n startedInBrowserEvt.args &&\n startedInBrowserEvt.args.data.frames &&\n startedInBrowserEvt.args.data.frames.find(frame => !frame.parent)\n )\n if (mainFrame && mainFrame.processId) {\n const threadNameEvt = traceEvents.traceEvents.find(e => e.ph === 'R' &&\n e.cat === 'blink.user_timing' && e.name === 'navigationStart' && e.args.data.isLoadingMainFrame)\n if (threadNameEvt) {\n log.info(`Replace mainFrame process id ${mainFrame.processId} with actual thread process id ${threadNameEvt.pid}`)\n mainFrame.processId = threadNameEvt.pid\n } else {\n log.info(`Couldn't replace mainFrame process id ${mainFrame.processId} with actual thread process id`)\n }\n }\n\n this.trace = {\n ...traceEvents,\n frameId: this.frameId,\n loaderId: this.loaderId,\n pageUrl: this.pageUrl,\n traceStart: this.traceStart,\n traceEnd: Date.now()\n }\n this.emit('tracingComplete', this.trace)\n this.finishTracing()\n } catch (err) {\n log.error(`Error capturing tracing logs: ${err.stack}`)\n this.emit('tracingError', err)\n return this.finishTracing()\n }\n }", "function parseEvent(response) {\n if(!response)\n return;\n for (const key in response.args) {\n const arg = response.args[key];\n if (typeof arg === 'object') {\n if (arg.constructor !== Array)\n response.args[key] = arg.toNumber();\n }\n else if(!isAddress(arg))\n response.args[key] = toUtf8(arg);\n }\n}", "async fetchAndOutputTestRunStatus() {\n\t\t\n\t\t// Get the persistent data\n\t\t//----------------------------\n\n\t\t// Variable initialization safety\n\t\tif(\n\t\t\tthis.testID == null || \n\t\t\tthis.processedTestRunSteps == null ||\n\t\t\tthis.jsonOutputObj == null\n\t\t) {\n\t\t\tthrow \"Unable to fetch and output test run status : testID is not set\"\n\t\t}\n\n\t\t// The persistent data objects\n\t\tlet processedTestRunSteps = this.processedTestRunSteps;\n\t\tlet jsonOutputObj = this.jsonOutputObj;\n\n\t\t// Get the test response\n\t\t//----------------------------\n\n\t\t// Get the test response\n\t\tlet testResponse = await SpaceAndProjectApi.getTestRunResult(this.testID);\n\n\t\t// Unwrap the data - where possible\n\t\tlet testRunResult = testResponse.result\n\t\t// Check and skip result object, return null\n\t\tif( testRunResult == null ) {\n\t\t\treturn null\n\t\t}\n\n\t\t// Get the test steps\n\t\tlet testRunSteps = testRunResult.steps\n\n\t\t// Remember where to print out the steps after each loop\n\t\tlet startFromIndex = 0;\n\t\tif (processedTestRunSteps.length === 0) {\n\t\t\tstartFromIndex = 0\n\t\t} else {\n\t\t\tstartFromIndex = processedTestRunSteps.length\n\t\t}\n\t\n\t\t// Printing out all the result from the startFromIndex\n\t\tfor (let index = startFromIndex; index < testRunSteps.length; index++) {\n\t\t\t// Get the test run step\n\t\t\tlet step = testRunSteps[index]\n\t\t\tif (\n\t\t\t\tstep.status === \"success\" || \n\t\t\t\tstep.status === \"error\" || \n\t\t\t\tstep.status === \"failure\" || \n\t\t\t\tstep.status === \"terminated\" || \n\t\t\t\tstep.status === \"system_error\" \n\t\t\t) {\n\t\t\t\t// Lets log the first step timing\n\t\t\t\tif(index >= 0 && this._firstStepTimeMS == null) {\n\t\t\t\t\tthis._firstStepTimeMS = Date.now();\n\t\t\t\t\tthis._firstStepTimeTakenMS = this._firstStepTimeMS - this._startTimeMS;\n\t\t\t\t}\n\n\t\t\t\t// Lets log the output, and pushed it into the processed step list\n\t\t\t\tprocessedTestRunSteps.push(formatAndOutputStepObject(step));\n\t\t\t} else {\n\t\t\t\t// Minor additional delay for \"pending\" steps\n\t\t\t\tif( index <= 5 ) {\n\t\t\t\t\t// For first 5 steps, lets, reduce the the \"wait\" between steps\n\t\t\t\t\t// await sleep(100+Math.random()*50)\n\t\t\t\t\tawait sleep(10)\n\t\t\t\t} else {\n\t\t\t\t\t// 1s awaits min\n\t\t\t\t\tawait sleep(1000+Math.random()*150)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Minimum 10 ms delay between step - makes outputs more readable\n\t\t\t// bottle neck would have been in the test steps anyway\n\t\t\tawait sleep(10);\n\t\t}\n\n\t\t// Lets see if test is fully completed\n\t\t// if so return and break the loop\n\t\tlet testRunStatus = testRunResult.status\n\t\tif (\n\t\t\ttestRunStatus === \"success\" || \n\t\t\ttestRunStatus === \"error\" || \n\t\t\ttestRunStatus === \"failure\" || \n\t\t\ttestRunStatus === \"terminated\" || \n\t\t\ttestRunStatus === \"system_error\" \n\t\t) {\n\t\t\t// Update the JSON object\n\t\t\tjsonOutputObj.status = testRunStatus;\n\t\t\tjsonOutputObj.steps = processedTestRunSteps;\n\n\t\t\t// Return test status\n\t\t\treturn testRunStatus\n\t\t}\n\n\t\t// Pending status\n\t\tif(\n\t\t\ttestRunStatus === \"init\" ||\n\t\t\ttestRunStatus === \"created\" ||\n\t\t\ttestRunStatus === \"pending\"\n\t\t) {\n\t\t\t// No final status, return nothing\n\t\t\treturn null\n\t\t}\n\n\t\t// Unknown / Invalid status\n\t\tOutputHandler.standardRed(`> Unexpected test status (will treat it as system_error) : ${testRunStatus}`)\n\t\treturn \"system_error\"\n\t}", "parseString (idx) {\n let str = \"\";\n const len = this.size;\n const uson = this.input;\n const regex = USON.pattern.string;\n\n while (true) {\n /* Recalibrate the pattern */\n regex.lastIndex = idx;\n\n /* Get to the next stop-character */\n const match = regex.exec (uson);\n\n if (match === null) {\n /* At least the closing double quote must be present */\n return this.parseError (USON.error.unexpectedEnd, len);\n }\n\n /* Assemble the string */\n const end = match.index;\n str += uson.substring (idx, end);\n idx = end;\n\n /* See what kind of stop-character it is */\n const chr = uson[idx];\n\n if (chr === '\"') {\n /* End of string */\n this.pos = idx + 1;\n return str;\n } else if (chr === '\\\\') {\n /* Escape sequence */\n const seq = this.parseStringEscape (idx + 1);\n\n if (seq === undefined) {\n /* Bubble the error up */\n return;\n }\n\n str += seq;\n } else if (chr === '\\x7f') {\n /* JSON compatibility */\n ++idx;\n str += '\\x7f';\n continue;\n } else {\n /* Control character */\n return this.parseError (USON.error.string, idx);\n }\n\n idx = this.pos;\n }\n}", "async postParsingAnalysis () {\n var mapped = Object.keys(this.results).map(addr => {return { addr: addr, count: this.results[addr] }})\n var sortedByCount = this.sortEntriesByCount(mapped)\n var topNentries = this.getTopN(sortedByCount, N)\n\n var fileName = `${this.baseOutPath}-${analysisName}.json`\n var fileContent = {\n // Signal and format to visualize as piechart\n piechart: {\n datasets: [{\n backgroundColor: ['#D33F49', '#77BA99', '#23FFD9', '#27B299', '#831A49'],\n data: this.formatData(topNentries)\n }],\n labels: await this.formatLabelsForPieChart(topNentries)\n },\n hint: 'The labels of this chart have been computed using temporally sensitive data'\n }\n var summary = {\n fileName: fileName,\n attackCategory: 'Network State',\n analysisName: `Top ${N} sources by traffic`,\n supportedDiagrams: ['PieChart']\n }\n return await this.storeAndReturnResult(fileName, fileContent, summary)\n }", "async loop () {\n while (true) {\n const events = await this.getMessages()\n this.processQueue()\n\n events.forEach(element => {\n try {\n const parsedElement = JSON.parse(element.payload.body)\n this.emit(`message:${parsedElement.recipe}`, parsedElement)\n this.emit('message', parsedElement)\n } catch (_e) {\n console.log(_e)\n this.emit('warning', 'element unknown')\n }\n })\n }\n }", "function parseCommandOutput(output) {\n return output.replace(/.+:([\\d]{4}).+/, '$1').trim();\n}", "function onData(chunk) {\n try {\n parse(chunk);\n } catch (err) {\n self.emit(\"error\", err);\n }\n }", "destroy() {\n this._clearListeners();\n this._pending = [];\n this._targetStream.complete();\n }", "function parseReceivedData(receivedData) {\n var data = receivedData.toString();\n console.log(\"Command received: \" + data);\n\n var data_parts = data.split(\" \");\n\n return {\n command: data_parts[0],\n args: data_parts[1]\n }\n}", "function Handler(res, client, clientCookie, Command) {\n\n // Send request to WinCC Unified RunTime \n // \n client.write(Command);\n\n console.log('Already send the ReadTag command. ' + (new Date()));\n console.log(\"CilentCookie: \" + clientCookie);\n\n const rl = readline.createInterface({\n input: client,\n crlfDelay: Infinity\n });\n\n // Listen for event \"line\"\n // \n rl.on('line', (line) => {\n\n // Convert the WinCC Unified Runtime response to JSON Format\n // Send to the Cilent\n // \n let obj = JSON.parse(line); \n res.send(obj);\n \n var endDateTime = GetCurrentTime();\n console.log(\"The result is sent to the client \" + endDateTime + \"\\r\\n\" + 'Listening on port 4000...' + \"\\r\\n\");\n\n res.end();\n });\n}", "function buildDataFn(data, result, childProcess) {\n let localMatch = data.toString('utf-8').match(/Time: (.*)ms/);\n if (localMatch) { result.match = Number(stripAnsi(localMatch[1])) };\n}", "function parseData() {\n let current;\n\n while (true) {\n current = input[i++];\n if (!current) {\n break;\n }\n\n parser.pos_++;\n\n switch (parser.state_) {\n case State.INIT:\n if (current === '{') {\n parser.state_ = State.OBJECT_OPEN;\n } else if (current === '[') {\n parser.state_ = State.ARRAY_OPEN;\n } else if (!utils.isJsonWhitespace(current)) {\n parser.error_(input, i);\n }\n continue;\n\n case State.KEY_START:\n case State.OBJECT_OPEN:\n if (utils.isJsonWhitespace(current)) {\n continue;\n }\n if (parser.state_ === State.KEY_START) {\n stack.push(State.KEY_END);\n } else {\n if (current === '}') {\n addMessage('{}');\n parser.state_ = nextState();\n continue;\n } else {\n stack.push(State.OBJECT_END);\n }\n }\n if (current === '\"') {\n parser.state_ = State.STRING;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n\n case State.KEY_END:\n case State.OBJECT_END:\n if (utils.isJsonWhitespace(current)) {\n continue;\n }\n if (current === ':') {\n if (parser.state_ === State.OBJECT_END) {\n stack.push(State.OBJECT_END);\n parser.depth_++;\n }\n parser.state_ = State.VALUE;\n } else if (current === '}') {\n parser.depth_--;\n addMessage();\n parser.state_ = nextState();\n } else if (current === ',') {\n if (parser.state_ === State.OBJECT_END) {\n stack.push(State.OBJECT_END);\n }\n parser.state_ = State.KEY_START;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.ARRAY_OPEN:\n case State.VALUE:\n if (utils.isJsonWhitespace(current)) {\n continue;\n }\n if (parser.state_ === State.ARRAY_OPEN) {\n parser.depth_++;\n parser.state_ = State.VALUE;\n if (current === ']') {\n parser.depth_--;\n if (parser.depth_ === 0) {\n parser.state_ = State.ARRAY_END;\n return;\n }\n\n addMessage('[]');\n\n parser.state_ = nextState();\n continue;\n } else {\n stack.push(State.ARRAY_END);\n }\n }\n if (current === '\"')\n parser.state_ = State.STRING;\n else if (current === '{')\n parser.state_ = State.OBJECT_OPEN;\n else if (current === '[')\n parser.state_ = State.ARRAY_OPEN;\n else if (current === 't')\n parser.state_ = State.TRUE1;\n else if (current === 'f')\n parser.state_ = State.FALSE1;\n else if (current === 'n')\n parser.state_ = State.NULL1;\n else if (current === '-') {\n // continue\n } else if ('0123456789'.indexOf(current) !== -1) {\n parser.state_ = State.NUM_DIGIT;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.ARRAY_END:\n if (current === ',') {\n stack.push(State.ARRAY_END);\n parser.state_ = State.VALUE;\n\n if (parser.depth_ === 1) {\n msgStart = i; // skip ',', including a leading one\n }\n } else if (current === ']') {\n parser.depth_--;\n if (parser.depth_ === 0) {\n return;\n }\n\n addMessage();\n parser.state_ = nextState();\n } else if (utils.isJsonWhitespace(current)) {\n continue;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.STRING:\n const old = i;\n\n STRING_LOOP: while (true) {\n while (parser.unicodeCount_ > 0) {\n current = input[i++];\n if (parser.unicodeCount_ === 4) {\n parser.unicodeCount_ = 0;\n } else {\n parser.unicodeCount_++;\n }\n if (!current) {\n break STRING_LOOP;\n }\n }\n\n if (current === '\"' && !parser.slashed_) {\n parser.state_ = nextState();\n break;\n }\n if (current === '\\\\' && !parser.slashed_) {\n parser.slashed_ = true;\n current = input[i++];\n if (!current) {\n break;\n }\n }\n if (parser.slashed_) {\n parser.slashed_ = false;\n if (current === 'u') {\n parser.unicodeCount_ = 1;\n }\n current = input[i++];\n if (!current) {\n break;\n } else {\n continue;\n }\n }\n\n pattern.lastIndex = i;\n const patternResult = pattern.exec(input);\n if (!patternResult) {\n i = input.length + 1;\n break;\n }\n i = patternResult.index + 1;\n current = input[patternResult.index];\n if (!current) {\n break;\n }\n }\n\n parser.pos_ += (i - old);\n\n continue;\n\n case State.TRUE1:\n if (!current) {\n continue;\n }\n if (current === 'r') {\n parser.state_ = State.TRUE2;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.TRUE2:\n if (!current) {\n continue;\n }\n if (current === 'u') {\n parser.state_ = State.TRUE3;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.TRUE3:\n if (!current) {\n continue;\n }\n if (current === 'e') {\n parser.state_ = nextState();\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.FALSE1:\n if (!current) {\n continue;\n }\n if (current === 'a') {\n parser.state_ = State.FALSE2;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.FALSE2:\n if (!current) {\n continue;\n }\n if (current === 'l') {\n parser.state_ = State.FALSE3;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.FALSE3:\n if (!current) {\n continue;\n }\n if (current === 's') {\n parser.state_ = State.FALSE4;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.FALSE4:\n if (!current) {\n continue;\n }\n if (current === 'e') {\n parser.state_ = nextState();\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.NULL1:\n if (!current) {\n continue;\n }\n if (current === 'u') {\n parser.state_ = State.NULL2;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.NULL2:\n if (!current) {\n continue;\n }\n if (current === 'l') {\n parser.state_ = State.NULL3;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.NULL3:\n if (!current) {\n continue;\n }\n if (current === 'l') {\n parser.state_ = nextState();\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.NUM_DECIMAL_POINT:\n if (current === '.') {\n parser.state_ = State.NUM_DIGIT;\n } else {\n parser.error_(input, i);\n }\n continue;\n\n case State.NUM_DIGIT: // no need for a full validation here\n if ('0123456789.eE+-'.indexOf(current) !== -1) {\n continue;\n } else {\n i--;\n parser.pos_--;\n parser.state_ = nextState();\n }\n continue;\n\n default:\n parser.error_(input, i);\n }\n }\n }", "function YCurrentLoopOutput_FirstCurrentLoopOutput()\n {\n var next_hwid = YAPI.getFirstHardwareId('CurrentLoopOutput');\n if(next_hwid == null) return null;\n return YCurrentLoopOutput.FindCurrentLoopOutput(next_hwid);\n }", "function processBuffer(self) {\n var messages = self.buffer.split('\\n');\n self.buffer = \"\";\n _.each(messages, function(message){\n if (message.length > 0) {\n var parsed = JSON.parse(message);\n processMessage(self, parsed);\n }\n });\n}" ]
[ "0.51066655", "0.49225134", "0.47151554", "0.4628691", "0.45853758", "0.45621577", "0.452999", "0.45146808", "0.4505238", "0.44953865", "0.44395724", "0.44302842", "0.44075388", "0.4406428", "0.44035548", "0.43800867", "0.436657", "0.43453223", "0.43328992", "0.43203926", "0.42931458", "0.42863065", "0.4285078", "0.4276424", "0.4275382", "0.4267101", "0.42640528", "0.42581695", "0.42567286", "0.42246002", "0.42102063", "0.41876012", "0.41850442", "0.417875", "0.41774878", "0.4167179", "0.41605514", "0.41561818", "0.41501838", "0.414928", "0.41344005", "0.41342503", "0.41332322", "0.4130415", "0.4127285", "0.41266695", "0.4124764", "0.41225448", "0.41149887", "0.4113203", "0.4111182", "0.41064352", "0.41044784", "0.40962562", "0.40942264", "0.4091894", "0.4075742", "0.40755418", "0.4069461", "0.40597546", "0.40461493", "0.4041521", "0.4040206", "0.40393075", "0.4037568", "0.40235844", "0.40167797", "0.40125328", "0.40072578", "0.398817", "0.39877766", "0.39840713", "0.3983324", "0.39786148", "0.397822", "0.3969849", "0.39661217", "0.3965139", "0.3964495", "0.39628175", "0.39618945", "0.3956359", "0.3954615", "0.39528584", "0.39502478", "0.39501262", "0.39376497", "0.3937361", "0.3936365", "0.39302978", "0.3925908", "0.39215302", "0.3918493", "0.39125293", "0.39119744", "0.39112988", "0.39101368", "0.39086327", "0.39039725", "0.39016315", "0.38938445" ]
0.0
-1
Funciones Insertar valores en la tabla
function ins_dato(filtro) { $.get("data-1.json",function (datos,status,xhr) { switch (xhr.status) { case 200: var tabla = $("#tabdatos"); for (var i = 0; i < filtro.length; i++) { datos.forEach(function (valor,indice,array) { if (filtro[i] == valor.Id) { $(tabla).append("<tr> <td> <p> <img src= 'img/home.jpg' width='400' height='300' align='middle'></p></td>"+ "<td><strong> <p> Dirección: </strong>" + valor.Direccion + "<br>"+ "<strong>Ciudad: </strong>" + valor.Ciudad + "<br>"+ "<strong>Teléfono: </strong>" + valor.Telefono + "<br>"+ "<strong>Código postal: </strong>" + valor.Codigo_Postal + "<br>"+ "<strong>Precio: </strong>" + valor.Precio + "<br>"+ "<strong>Tipo: </strong>" + valor.Tipo + "</p><br> </td> </tr>"); } }); } break; case 404: console.log("Error"); break; default: console.log("Error"); break; } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function insertValueTable(id, name, username) {\n\n var table = document.getElementById(\"tabela\");\n var row = table.insertRow(-1);\n var cell1 = row.insertCell(0);\n var cell2 = row.insertCell(1);\n var cell3 = row.insertCell(2);\n\n cell1.innerHTML = id;\n cell2.innerHTML = name;\n cell3.innerHTML = username;\n}", "function crearTablaPuertasValoresIniciales(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_iniciales (k_codusuario,k_codinspeccion,n_cliente,n_equipo,n_empresamto,o_desc_puerta,o_tipo_puerta,o_motorizacion,o_acceso,o_accionamiento,o_operador,o_hoja,o_transmision,o_identificacion,f_fecha,v_ancho,v_alto,v_codigo,o_consecutivoinsp,ultimo_mto,inicio_servicio,ultima_inspeccion,h_hora,o_tipo_informe)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores iniciales...Espere\");\n console.log('transaction creada ok');\n });\n}", "function insertTableValues(dynamicTableValues)\r\n{\r\n\tdb.transaction(function(transaction){ insertvalues(transaction, dynamicTableValues);}, errorCB, successCB);\r\n}", "function crearTablaAscensorValoresIniciales(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_iniciales (k_codusuario,k_codinspeccion,n_cliente,n_equipo,n_empresamto,o_tipoaccion,v_capacperson,v_capacpeso,v_paradas,f_fecha,v_codigo,o_consecutivoinsp,ultimo_mto,inicio_servicio,ultima_inspeccion,h_hora,o_tipo_informe)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores iniciales...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaEscalerasValoresIniciales(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE escaleras_valores_iniciales (k_codusuario,k_codinspeccion,n_cliente,n_equipo,n_empresamto,v_velocidad,o_tipo_equipo,v_inclinacion,v_ancho_paso,f_fecha,ultimo_mto,inicio_servicio,ultima_inspeccion,v_codigo,o_consecutivoinsp,h_hora,o_tipo_informe)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores iniciales...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaPuertasValoresOtras(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_otras (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores otras...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaPuertasValoresElementos(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_elementos (k_codusuario,k_codinspeccion,k_coditem,o_descripcion,v_selecion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores elementos...Espere\");\n console.log('transaction creada ok');\n });\n}", "function User_Insert_Types_d_attribut_Liste_des_types_d_attribut_de_personne0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 30;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 31;\ncomplexe\nNbr Jointure: 1;\n Joint n° 0 = categorie,ta_numero,ta_numero\n\n******************\n*/\n\n var Table=\"typeattribut\";\n var CleMaitre = TAB_COMPO_PPTES[28].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ta_nom=GetValAt(30);\n if (!ValiderChampsObligatoire(Table,\"ta_nom\",TAB_GLOBAL_COMPO[30],ta_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ta_nom\",TAB_GLOBAL_COMPO[30],ta_nom))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",ta_nom\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(ta_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(ta_nom)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "insertOne(cols, values, cb) {\n console.log(\"burgervals \" + values);\n orm.insertOne('burgers', cols, values, (res) => cb(res));\n }", "function crearTablaPuertasValoresElectrica(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_electrica (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores electrica...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaAscensorValoresElementos(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_elementos (k_codusuario,k_codinspeccion,k_coditem,o_descripcion,v_selecion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores elementos...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaEscalerasValoresElementos(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE escaleras_valores_elementos (k_codusuario,k_codinspeccion,k_coditem,o_descripcion,v_selecion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores elementos...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaPuertasValoresProteccion(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_proteccion (k_codusuario,k_codinspeccion,k_coditem,v_sele_inspector,v_sele_empresa,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores protección...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaAscensorValoresProteccion(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_proteccion (k_codusuario,k_codinspeccion,k_coditem,v_sele_inspector,v_sele_empresa,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores protección...Espere\");\n console.log('transaction creada ok');\n });\n}", "function User_Insert_Villes_Liste_des_villes0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 126;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 127;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = canton,ct_numero,ct_numero\n\n******************\n*/\n\n var Table=\"ville\";\n var CleMaitre = TAB_COMPO_PPTES[123].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var vi_nom=GetValAt(126);\n if (!ValiderChampsObligatoire(Table,\"vi_nom\",TAB_GLOBAL_COMPO[126],vi_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"vi_nom\",TAB_GLOBAL_COMPO[126],vi_nom))\n \treturn -1;\n var ct_numero=GetValAt(127);\n if (ct_numero==\"-1\")\n ct_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"ct_numero\",TAB_GLOBAL_COMPO[127],ct_numero,true))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",vi_nom,ct_numero\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(vi_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(vi_nom)+\"'\" )+\",\"+ct_numero+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function crearTablaEscalerasValoresProteccion(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE escaleras_valores_proteccion (k_codusuario,k_codinspeccion,k_coditem,v_sele_inspector,v_sele_empresa,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores protección...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaPuertasValoresMotorizacion(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_motorizacion (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores motorizacion...Espere\");\n console.log('transaction creada ok');\n });\n}", "function insere(){\n\t//SE EU ALTEREI ALGUM REGISTRO\n\tif(!Verifica_Alteracao(DIV_TABELA)){\n\t\tselecionaLinha(DIV_TABELA,$('#position').val(),2);\n\t\treturn;\n\t}\n\n\tif(empty(objTabela)){\n\t\tobjTabela = {};\n\t\tobjTabela.registros = [];\n\t\tobjTabela.total = 0;\n\t}\n\n\tvar novaPosicao = {};\n\tnovaPosicao.fa_number = '';\n\tnovaPosicao.fa_nome = '';\n\tnovaPosicao.pt_classfisc = '';\n\tnovaPosicao.ce_cest = '';\n\tnovaPosicao.fa_ipi = '0,00';\n\tnovaPosicao.fa_comiss = '0,000';\n\tnovaPosicao.fa_cstpis = '01';\n\tnovaPosicao.fa_pis = '0,00';\n\tnovaPosicao.fa_cofins = '0,00';\n\tnovaPosicao.fa_imposto = '0,00';\n\tnovaPosicao.fa_redicm7 = '0,00';\n\tnovaPosicao.fa_redicm12 = '0,00';\n\n\tobjTabela.registros.push(novaPosicao);\n\tobjTabela.total += 1;\n\n\tvar actpos = objTabela.total > 0 ? (objTabela.total - 1) : 0;\n\n\tpagination((Math.ceil(objTabela.total / LIMITE_REGISTROS)),function(){\n\t\tpintaLinha($(DIV_TABELA + \" tr[actipos=\"+actpos+\"]\"));\n\t\tsetStatus(actpos,'+',DIV_TABELA);\n\t\tBloqueia_Linhas(actpos,DIV_TABELA);\n\t\t$('#records').val(objTabela.total);\n\t\tselecionaLinha(DIV_TABELA,actpos,2);\n\t});\n}", "insertOne(table,cols,vals,cb) {\n let query = `INSERT INTO ${table}`;\n query += ` (${cols.toString()}) `;\n query += ` VALUES (${printQuestionMarks(vals.length)})`;\n \n connection.query(query,vals,(err,result) =>{\n if(err) throw err;\n cb(result);\n });\n }", "function User_Insert_Etats_de_personne_Liste_des_états_de_personne0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 1\n\nId dans le tab: 52;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"etatpersonne\";\n var CleMaitre = TAB_COMPO_PPTES[50].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ep_libelle=GetValAt(52);\n if (!ValiderChampsObligatoire(Table,\"ep_libelle\",TAB_GLOBAL_COMPO[52],ep_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ep_libelle\",TAB_GLOBAL_COMPO[52],ep_libelle))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",ep_libelle\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(ep_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(ep_libelle)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function insertvalues(tx,dynamicTableValues) {\r\n \r\n\tvar query = 'INSERT INTO ' + dynamicTableValues[0] +' VALUES(';\r\n \r\n for(var i = 1; i < dynamicTableValues.length; i++)\r\n {\r\n \t//query = query + \"'\" + dynamicTableValues[i] + \"'\" ;\r\n \tquery = query + '\"' + dynamicTableValues[i] + '\"' ; \r\n \t\r\n \tif(i != (dynamicTableValues.length - 1 ))\r\n \t\tquery = query + ',';\r\n }\r\n query = query + ')';\r\n \r\n console.log(query);\r\n \r\n tx.executeSql( query );\r\n}", "function crearTablaAscensorValoresFoso(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_foso (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores foso...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaAscensorValoresPozo(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_pozo (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores pozo...Espere\");\n console.log('transaction creada ok');\n });\n}", "function User_Insert_Types_de_journaux_Liste_des_types_de_journaux0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 1\n\nId dans le tab: 201;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typejournal\";\n var CleMaitre = TAB_COMPO_PPTES[199].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tj_libelle=GetValAt(201);\n if (!ValiderChampsObligatoire(Table,\"tj_libelle\",TAB_GLOBAL_COMPO[201],tj_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tj_libelle\",TAB_GLOBAL_COMPO[201],tj_libelle))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tj_libelle\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(tj_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(tj_libelle)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function fillUpTable() {\r\n\tgetInstantValues();\r\n}", "function pet_insert_db(tx) {\n\n\tvar nome = $(\"#pet_nome\").val();\n var qtd = $(\"#pet_qtd\").val();\n var preco = $(\"#pet_preco\").val();\n\n //converter \n qtd = parseInt(qtd); \n preco = parseFloat(preco);\n\n //parar a inserção chama validação do forms jquery\n if(nome.length < 3 || qtd <=0 || preco <=0 ){\n return false;\n }\n if(nome =='' || qtd =='' || preco ==''){\n return false;\n }\n \n\n //-------------------------------------------------\n tx.executeSql('INSERT INTO Pet (nome, qtd, preco) VALUES (\"' + nome.toUpperCase() + '\", \"' + qtd + '\", \"' + preco + '\")');\n \n cadastrado();\n\n\tpet_view();\n}", "insert(tableName, data){\n\t\t\tif(this.hasTable(tableName)){\n\t\t\t\tdata.id = typeof data.id === 'undefined' ? this.tableNextId[tableName] : data.id;\n\n\t\t\t\ttry {\n\t\t\t\t\tlet fieldData = this.generateFieldData(tableName, data);\n\t\t\t\t\tthis.tableData[tableName].push(fieldData);\n\t\t\t\t\tthis.tableNextId[tableName]++;\n\n\t\t\t\t\treturn {code: 'code005', content: '添加成功!'};\n\t\t\t\t}catch(e){\n\t\t\t\t\tlet matches = e.toString().match(/^Error: (code\\d+):(.*)$/);\n\t\t\t\t\treturn {code: matches[1], content: matches[2]};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {code: 'code006', content: '添加失败!'};\n\t\t}", "function User_Insert_Types_de_lien_Liste_des_types_de_lien_entre_personne0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 45;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 46;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typelien\";\n var CleMaitre = TAB_COMPO_PPTES[43].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tl_libelle=GetValAt(45);\n if (!ValiderChampsObligatoire(Table,\"tl_libelle\",TAB_GLOBAL_COMPO[45],tl_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tl_libelle\",TAB_GLOBAL_COMPO[45],tl_libelle))\n \treturn -1;\n var tl_description=GetValAt(46);\n if (!ValiderChampsObligatoire(Table,\"tl_description\",TAB_GLOBAL_COMPO[46],tl_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tl_description\",TAB_GLOBAL_COMPO[46],tl_description))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tl_libelle,tl_description\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(tl_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(tl_libelle)+\"'\" )+\",\"+(tl_description==\"\" ? \"null\" : \"'\"+ValiderChaine(tl_description)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function agenda_insert_db(tx) {\n\tvar nome = $(\"#agenda_nome\").val();\n\tvar tel = $(\"#agenda_telefone\").val();\n\ttx.executeSql('INSERT INTO Agenda (nome, tel) VALUES (\"' + nome + '\", \"' + tel + '\")');\n\tagenda_view();\n}", "function InsertRow(tr) {\n var newTr = {};\n var isValid = true;\n //validate form\n if (tr.find('input[id*=__MaThuoc]').val().trim() == \"\") {\n tr.find('input[id*=__MaThuoc]').addClass('input-validation-error');\n isValid = false;\n }\n if (tr.find('input[id*=__TenThuoc]').val().trim() == \"\") {\n tr.find('input[id*=__TenThuoc]').addClass('input-validation-error');\n isValid = false;\n }\n if (tr.find('input[id*=__MaDonViTinh]').val() <= 0) {\n tr.find('input[id*=__MaDonViTinh]').addClass('input-validation-error');\n isValid = false;\n }\n\n if (tr.find('input[id*=__SoLuong]').val() <= 0) {\n tr.find('input[id*=__SoLuong]').addClass('input-validation-error');\n isValid = false;\n }\n if (tr.find('input[id*=__GiaNhap]').val() < 0) {\n tr.find('input[id*=__GiaNhap]').addClass('input-validation-error');\n isValid = false;\n }\n if (tr.find('input[id*=__GiaBan]').val() < 0) {\n tr.find('input[id*=__GiaBan]').addClass('input-validation-error');\n isValid = false;\n }\n if (!isValid) {\n tr.find('input.input-validation-error:first').focus();\n return;\n }\n // Chi them khi chua co' ma hang trong bang\n //var maThuoc = tr.find('input[id*=__MaThuoc]').val().trim(); \n //if (jQuery('#tblCt').find('tbody input[value=' + maThuoc + ']').size()) {\n // var soluong1 = \n // //return false;\n //}\n\n // them doan nay de tinh toan them row hoac update so luong\n\n var flag = false;\n var maThuoc = tr.find('input[id*=__MaThuoc]').val().trim();\n jQuery.each(jQuery('#tblCt').find('tbody input[value=' + maThuoc + ']'), function () {\n if ($(this).attr(\"type\") == \"text\") {\n var thisTr = $(this).closest(\"tr\");\n var oldqty = parseFloat(thisTr.find('input[id*=__SoLuong]').val());\n var oldUnit = thisTr.find('select[id*=__MaDonViTinh]').val();\n var oldDiscount = thisTr.find('input[id*=__ChietKhau]').val();\n var oldPrice = thisTr.find('input[id*=__GiaNhap]').val();\n var oldPriceOut = thisTr.find('input[id*=__GiaBan]').val();\n\n var newqty = parseFloat(tr.find('input[id*=__SoLuong]').val());\n var newUnit = tr.find('select[id*=__MaDonViTinh]').val();\n var newDiscount = tr.find('input[id*=__ChietKhau]').val();\n var newPrice = tr.find('input[id*=__GiaNhap]').val();\n var newPriceOut = tr.find('input[id*=__GiaBan]').val();\n\n if (oldPrice == newPrice && oldUnit == newUnit && oldDiscount == newDiscount) {\n var total = (oldqty + newqty) * oldPrice;\n var actualTotal = total;\n\n if (oldDiscount != null) {\n var actualTotal = total - oldDiscount * total / 100;\n }\n var quantity = round(oldqty + newqty, 2);\n var refNum = $.number(quantity, 2, '.', ',');\n if (Math.floor(quantity) == quantity) {\n refNum = $.number(quantity, 0, '.', ',');\n }\n thisTr.find('input[id*=__SoLuong]').val(quantity);\n thisTr.find('span[id*=__SoLuong]').text(refNum);\n refNum = $.number(actualTotal, 0, '.', ',');\n thisTr.find('b[name=miniSum]').text(refNum);\n flag = true;\n }\n }\n });\n if (flag) {\n ClearTr(tr);\n $('.dataTables_scrollHeadInner tr:eq(1) input[id*=_TenThuoc]').focus();\n return false;\n }\n\n //copy current value to attribute\n tr.find(\"input[type=text],[type=number],[type=hidden]\").each(function () {\n $(this).attr(\"value\", $(this).val());\n });\n var slVal = tr.find(\"select[id*='MaDonViTinh']\").val();\n $(tr.find(\"select\").find(\".delete-thuoc\")).show();\n //Clone the row\n newTr = tr.clone().prop('outerHTML');\n\n ClearTr(tr);\n var row = $(\"table#tblCt\").find(\"tr:last\");\n var currentNum = 0;\n if (row.find(\"td\")[1] != undefined)\n currentNum = parseInt(row.find(\".stt\").text());\n if (isNaN(currentNum))\n currentNum = 0;\n //Replace and insert the row\n newTr = newTr.replace(/_-1__/g, \"_\" + currentNum + \"__\").replace(/\\[-1\\]/g, \"[\" + currentNum + \"]\");\n\n //$(newTr).insertAfter($(\"table#tblCt tbody tr\").eq(0));\n var addRow = [];\n $($(newTr).find(\"td\")).each(function () {\n var col = $(this).html();\n addRow.push(col);\n });\n tbl.row.add(addRow).draw();\n //Compile it to bind it with angular\n AngularHelper.Compile($(\"#create-receipt-note\"));\n\n var fTr = $(\"table#tblCt tr:last\");\n\n fTr.find(\"select[id*='MaDonViTinh']\").val(slVal);\n fTr.find(\".delete-thuoc\").show();\n\n InitEdit();\n RecalculateSTT();\n SaveRow(fTr, fTr.attr(\"id\") == 0);\n fTr.find('.edit-mode, .display-mode').toggle();\n // dont allow to edit mathuoc, tenthuoc\n fTr.find('td:eq(2),td:eq(3)').children().removeClass('edit-mode display-mode');\n if (loaiPhieu == 1) {\n fTr.find('td:eq(6),td:eq(7)').attr('align', 'right');\n } else {\n fTr.find('td:eq(6)').attr('align', 'right');\n }\n // enable input mask\n fTr.find(\":input,span\").inputmask();\n //tr.find(\"input[type=text]\").eq(0).focus();\n $('.dataTables_scrollHeadInner tr:eq(1) input[id*=_TenThuoc]').focus();\n\n}", "function crearTablaAscensorValoresMaquinas(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_maquinas (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores maquinas...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaInforme(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE informe (k_codinforme,v_consecutivoinforme,k_codusuario,f_informe)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores informe...Espere\");\n console.log('transaction creada ok');\n });\n}", "function User_Insert_Cantons_Liste_des_cantons0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 140;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 141;\ncomplexe\nNbr Jointure: 1;\n Joint n° 0 = ville,ct_numero,ct_numero\n\n******************\n*/\n\n var Table=\"canton\";\n var CleMaitre = TAB_COMPO_PPTES[137].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var ct_nom=GetValAt(140);\n if (!ValiderChampsObligatoire(Table,\"ct_nom\",TAB_GLOBAL_COMPO[140],ct_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ct_nom\",TAB_GLOBAL_COMPO[140],ct_nom))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",ct_nom\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(ct_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(ct_nom)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function User_Insert_Types_de_personne_Liste_des_types_de_personne0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 1\n\nId dans le tab: 49;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typepersonne\";\n var CleMaitre = TAB_COMPO_PPTES[47].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tp_type=GetValAt(49);\n if (!ValiderChampsObligatoire(Table,\"tp_type\",TAB_GLOBAL_COMPO[49],tp_type,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tp_type\",TAB_GLOBAL_COMPO[49],tp_type))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tp_type\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(tp_type==\"\" ? \"null\" : \"'\"+ValiderChaine(tp_type)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function User_Insert_Groupe_de_tables_Liste_des_groupes_de_tables0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 102;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 103;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"groupetable\";\n var CleMaitre = TAB_COMPO_PPTES[99].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var gt_libelle=GetValAt(102);\n if (!ValiderChampsObligatoire(Table,\"gt_libelle\",TAB_GLOBAL_COMPO[102],gt_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"gt_libelle\",TAB_GLOBAL_COMPO[102],gt_libelle))\n \treturn -1;\n var gt_tables=GetValAt(103);\n if (!ValiderChampsObligatoire(Table,\"gt_tables\",TAB_GLOBAL_COMPO[103],gt_tables,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"gt_tables\",TAB_GLOBAL_COMPO[103],gt_tables))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",gt_libelle,gt_tables\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(gt_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(gt_libelle)+\"'\" )+\",\"+(gt_tables==\"\" ? \"null\" : \"'\"+ValiderChaine(gt_tables)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function crearTablaPuertasValoresManiobras(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_maniobras (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores maniobras...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaPuertasValoresPreliminar(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_preliminar (k_codusuario,k_codinspeccion,k_coditem_preli,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores preliminares...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaPuertasValoresObservacionFinal(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_finales (k_codusuario,k_codinspeccion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores finales...Espere\");\n console.log('transaction creada ok');\n });\n}", "function insertSQL(table, obj) {\r\n // your code here\r\n let tableColumns = '(';\r\n let values = '(';\r\n for(var key in obj){\r\n tableColumns += String(key) + ',';\r\n values += String(obj[key]) + ',';\r\n }\r\n tableColumns -= ',';\r\n values -= ',';\r\n let statement = 'insert into ' + table + tableColumns +') values' + values + ')' ;\r\n statement += table;\r\n return statement;\r\n}", "function crearTablaAscensorValoresObservacionFinal(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_finales (k_codusuario,k_codinspeccion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores finales...Espere\");\n console.log('transaction creada ok');\n });\n}", "function appendTableData(id, data){\r\n\r\nlet newRow = id.insertRow();\r\n//Check column doesn't contain the data\r\nfor(let i=0; i<id.rows.item(0).cells.length; i++){\r\n let cell = newRow.insertCell();\r\n if(i < data.length){\r\n cell.innerHTML = data[i];\r\n }\r\n}\r\n\r\n}", "function crearTablaAscensorValoresPreliminar(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_preliminar (k_codusuario,k_codinspeccion,k_coditem_preli,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores preliminares...Espere\");\n console.log('transaction creada ok');\n });\n}", "function addData(question,answer,option1,option2,option3,table){ \n\tvar createSql=\"create table if not exists \"+table+\"(question text,answer text,option1 text,option2 text,option3 text)\";\n\tvar insertSql=\"insert into \"+table+\" values(?,?,?,?,?)\";\n\n db.transaction(function(tx)\n\t{ \t\n\t \ttx.executeSql(createSql,[])\n\t\ttx.executeSql(insertSql,[question,answer,option1,option2,option3],onSuccess,onError)\t\t\n }); \n}", "function User_Insert_Produits_Prix_5(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 5\n\nId dans le tab: 170;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 171;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 172;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = tva,tv_numero,tv_numero\n\nId dans le tab: 173;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 174;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"prix\";\n var CleMaitre = TAB_COMPO_PPTES[165].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */\n var px_tarifht=GetValAt(170);\n if (!ValiderChampsObligatoire(Table,\"px_tarifht\",TAB_GLOBAL_COMPO[170],px_tarifht,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"px_tarifht\",TAB_GLOBAL_COMPO[170],px_tarifht))\n \treturn -1;\n var px_tarifttc=GetValAt(171);\n if (!ValiderChampsObligatoire(Table,\"px_tarifttc\",TAB_GLOBAL_COMPO[171],px_tarifttc,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"px_tarifttc\",TAB_GLOBAL_COMPO[171],px_tarifttc))\n \treturn -1;\n var tv_numero=GetValAt(172);\n if (tv_numero==\"-1\")\n tv_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"tv_numero\",TAB_GLOBAL_COMPO[172],tv_numero,true))\n \treturn -1;\n var px_datedebut=GetValAt(173);\n if (!ValiderChampsObligatoire(Table,\"px_datedebut\",TAB_GLOBAL_COMPO[173],px_datedebut,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"px_datedebut\",TAB_GLOBAL_COMPO[173],px_datedebut))\n \treturn -1;\n var px_actif=GetValAt(174);\n if (!ValiderChampsObligatoire(Table,\"px_actif\",TAB_GLOBAL_COMPO[174],px_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"px_actif\",TAB_GLOBAL_COMPO[174],px_actif))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",pd_numero,px_tarifht,px_tarifttc,tv_numero,px_datedebut,px_actif\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+TAB_COMPO_PPTES[158].NewCle+\",\"+(px_tarifht==\"\" ? \"null\" : \"'\"+ValiderChaine(px_tarifht)+\"'\" )+\",\"+(px_tarifttc==\"\" ? \"null\" : \"'\"+ValiderChaine(px_tarifttc)+\"'\" )+\",\"+tv_numero+\",\"+(px_datedebut==\"\" ? \"null\" : \"'\"+ValiderChaine(px_datedebut)+\"'\" )+\",\"+(px_actif==\"true\" ? \"true\" : \"false\")+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function crearTablaEscalerasValoresPreliminar(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE escaleras_valores_preliminar (k_codusuario,k_codinspeccion,k_coditem_preli,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores preliminares...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaEscalerasValoresDefectos(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE escaleras_valores_defectos (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores defectos...Espere\");\n console.log('transaction creada ok');\n });\n}", "function insert_to_db(table, row){\n var schema = db.model(table);\n var data = new schema(row);\n schema.findOne({sensID: row.sensID, teamID: row.teamID}).exec(function (err, result) {\n if (err){\n console.log(err);\n } else {\n if (result == null) {\n data.save(function(err, result){\n if (err){\n console.log(err);\n } else {\n console.log('add Data');\n }\n });\n }\n }\n })\n\n}", "function crearTablaPuertasValoresAudios(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_audios (k_codusuario,k_codinspeccion,n_audio,n_directorio,o_estado_envio)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction creada ok');\n });\n}", "function crearTablaEscalerasValoresObservacionFinal(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE escaleras_valores_finales (k_codusuario,k_codinspeccion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores finales...Espere\");\n console.log('transaction creada ok');\n });\n}", "insertOne(table, cols, vals, cb) {\n const search = `INSERT INTO ${table} (${cols.toString()}) VALUES (${printQuestionMarks(vals.length)})`;\n console.log(\"the search is \" + search);\n console.log('values ' + vals);\n connection.query(search,vals, (err, results) => {\n if (err) throw err;\n cb(results);\n })\n }", "function crearTablaPuertasValoresMecanicos(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_mecanicos (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores mecanicos...Espere\");\n console.log('transaction creada ok');\n });\n}", "function crearTablaPuertasValoresFotografias(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE puertas_valores_fotografias (k_codusuario,k_codinspeccion,k_coditem,n_fotografia,n_directorio,o_estado_envio)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction creada ok');\n });\n}", "function insertdata() {\n getData.getAllData().then(function() {});\n }", "function crearTablaInformeValoresAudios(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE informe_valores_audios (k_codusuario,k_codinforme,n_audio,n_directorio,o_estado_envio)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction creada ok');\n });\n}", "function insertarDatosTablaMenaje(posicion) {\n var fila;\n if (posicion % 2 == 0) {\n fila = \"<tr class='danger'>\";\n } else {\n fila = \"<tr class='warning'>\";\n }\n\n var foto = arrayPadreMenaje[posicion][0];\n fila += \"<td><img src='http://www.vetusplas.com/images/webcli/peque/\" + foto + \".png' onclick='imagengrandeMenaje(\" + posicion + \")' id='foto\" + posicion + \"'></td>\";\n fila += \"<td>\" + arrayPadreMenaje[posicion][0] + \"</td>\";\n fila += \"<td>\" + arrayPadreMenaje[posicion][1] + \"</td>\";\n fila += \"<td>\" + arrayPadreMenaje[posicion][2] + \"</td>\";\n fila += \"<td>\" + arrayPadreMenaje[posicion][3] + \"</td>\";\n fila += \"<td><input type='number' id='cajasMenaje\" + posicion + \"' min='0' oninput='calculoTotalMenaje(\" + posicion + \")'></td>\";\n fila += \"<td><input type='number' disabled id='totalMenaje\" + posicion + \"'></td>\";\n fila += \"</tr>\";\n //Cada vez que hago un fila no borre la anterior\n document.getElementById(\"tbodyMenaje\").innerHTML += fila;\n\n}", "function crearTablaAscensorValoresFotografias(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_fotografias (k_codusuario,k_codinspeccion,k_coditem,n_fotografia,n_directorio,o_estado_envio)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction creada ok');\n });\n}", "function _insert(\n\ttableName,\n\trowData={}\n) {\n\tthis.validateTableExistance(tableName);\n\t\n\tconst table = this.tables[tableName];\n\treturn table.insert(rowData);\n}", "insertarPersona (persona) {\n let valores = `${ persona.getNombre() }, ${ persona.getApellido() }, ${ persona.getDireccion() }, ${ persona.getEdad() }, ${ persona.getTelefono() }, ${ persona.getCorreo() }`;\n let r = this.db.push(valores);\n if (r) {\n console.log( \"PERSONA_INSERTADA\" );\n } else {\n console.log( \"ERROR_PERSONA_INSERTADA\" );\n }\n }", "function createTable(conn) {\r\n\r\n const sql = \"CREATE TABLE IF NOT EXISTS Alunos \" +\r\n \"(ID int NOT NULL AUTO_INCREMENT, \" +\r\n \"Nome varchar(150) NOT NULL, \" +\r\n \"Curso varchar(150) NOT NULL, \" +\r\n \"Inicio varchar(150) NOT NULL, \" +\r\n \"Final varchar(150) NOT NULL, \" +\r\n \"Horas int NOT NULL, \" +\r\n \"Cidade varchar(150) NOT NULL, \" +\r\n \"Dia int NOT NULL, \" +\r\n \"Mes varchar(150) NOT NULL, \" +\r\n \"Ano varchar(150) NOT NULL, PRIMARY KEY (ID));\";\r\n\r\n conn.query(sql, function (error, results, fields) {\r\n if (error) return console.log(error);\r\n console.log('Tabela criada!');\r\n adicionaGente(conn);\r\n\r\n///////////////////////////////////////////////////////////////////////////////////////\r\n\r\n //Popula a tabela:\r\n function adicionaGente(conn) {\r\n const sql = \"INSERT INTO Alunos(Nome,Curso,Inicio,Final,Horas,Cidade,Dia,Mes,Ano) VALUES ?\";\r\n const values = [\r\n ['Laurindo Schwaltz Jr', 'Análise e Desenvolvimento de Sistemas','15/10/2016','20/12/2020',948,'Porto Alegre',15,'janeiro',2020],\r\n ['Estrogildo Olegário Santos', 'Pós Graduação em Culinária','12/03/2010','20/10/2018',845,'Viamão',16,'março',2020],\r\n ['Hermengarda Belicosa Filha', 'Geografia e Ciências Políticas','03/06/2019','11/03/2020',324,'Cambará do Sul',12,'abril',2020],\r\n ['Leovesgaldina da Silva', 'Artes e Literatura Avançado','12/08/1996','15/11/2017',265,'Gravataí',19,'maio',2017],\r\n ['Asperinilson Laos Claos', 'Bacharelado em Consultoria Sutil','08/04/2015','16/08/2020',120,'São Leopoldo',03,'agosto',2019],\r\n ];\r\n conn.query(sql, [values], function (error, results, fields) {\r\n if (error) return console.log(error);\r\n console.log('Registros inseridos na tabela!');\r\n conn.end();\r\n });\r\n }\r\n });\r\n}", "static create(table, data, callback) {\n if (table.length === 0 || data.length === 0) {\n return;\n }\n\n let options = [table];\n\n let sql = 'INSERT INTO ?? (';\n\n let sets = [];\n let setValues = [];\n\n if (!Array.isArray(data)) {\n data = [data];\n }\n\n let allValueKeys = [];\n let allValues = [];\n\n for (let row of data) {\n let values = [];\n\n for (let key in row) {\n if (row.hasOwnProperty(key) && typeof row[key] !== 'undefined') {\n if (setValues.indexOf(key) === -1) {\n sets.push('??');\n setValues.push(key);\n }\n\n values.push('?');\n allValues.push(row[key]);\n }\n }\n\n allValueKeys.push(values);\n }\n sql += sets.join(', ');\n sql += ') VALUES ';\n let vals = [];\n for (let row of allValueKeys) {\n vals.push('(' + row.join(', ') + ')');\n }\n sql += vals.join(', ');\n\n options = options.concat(setValues);\n options = options.concat(allValues);\n\n return con.query(sql, options, (err,rows) => {\n if(err || rows.length > 0) {\n callback(err, null);\n } else {\n callback(null, rows);\n }\n });\n }", "function insereValoresTabela(vectorvalues){\n var tableFront = $('#table-automaton');\n tableFront.html('');\n var tr = $(document.createElement('tr'));\n var th = $(document.createElement('th'));\n th.html('');\n tr.append(th);\n var first = 'a';\n var last = 'z';\n for (var j = first.charCodeAt(0); j <= last.charCodeAt(0); j++) {\n var th = $( document.createElement('th') );\n th.html(String.fromCharCode(j));\n tr.append(th);\n }\n tableFront.append(tr);\n\n for(var i = 0; i < vectorvalues.length; i++){\n var tr = $(document.createElement('tr'));\n var td = $(document.createElement('td'));\n \n if(vectorvalues[i]['final']){\n td.html('q' + vectorvalues[i]['estado'] + '*');\n } else {\n td.html('q' + vectorvalues[i]['estado']);\n }\n tr.append(td);\n tr.addClass('state_'+vectorvalues[i]['estado']);\n var first = 'a';\n var last = 'z';\n for (var j = first.charCodeAt(0); j <= last.charCodeAt(0); j++) {\n var letter = String.fromCharCode(j);\n var td = $( document.createElement('td') );\n td.addClass('letter_'+letter);\n if(vectorvalues[i][letter] != '-'){\n td.html('q' + vectorvalues[i][letter]);\n } else {\n td.html('-');\n }\n tr.append(td);\n }\n tableFront.append(tr);\n }\n}", "function crearTablaEscalerasValoresFotografias(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE escaleras_valores_fotografias (k_codusuario,k_codinspeccion,k_coditem,n_fotografia,n_directorio,o_estado_envio)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction creada ok');\n });\n}", "function insertTemp(x) {\n //code Insertando avances fisicos\n \n \n \n if (APTI && x >= APTI.length) {\n //code\n console.log(\"Cargando datos espere un momento vamos a insertar avances temporales de Obra::: X=\" + x );\n \n insertarTempAvancesObras();\n }\n \n else if (APTI && APTI.length > 0) {\n console.log(\"Cargando datos espere un momento ::: 4 X=\" + x + \" Avances: \"+ APTI.length);\n \n \n \n db.transaction(function(tx) {\n \n tx.executeSql('INSERT INTO TempAvanceProyectos(idAvanceFinanciero, idAvanceFisico, idProyecto)' +\n ' VALUES (?, ?, ?)',\n [APTI.item(x).idAvanceFinanciero, APTI.item(x).idAvanceFisico, APTI.item(x).idProyectoFisico]);\n console.log(\"Avance Temp en Proyectos: \" + APTI.item(x).idProyectoFisico);\n \n \n }, errorCB, function (){\n console.log(\"Se inserto correctamente el avance temporal: \" + APTI.item(x).idProyectoFisico);\n \n x++;\n insertTemp(x);\n \n }); \n \n } else {\n console.log(\"No hay avances temporales de proyecto :::::::::::::::::::::::\");\n // insertarAvanceFinancieroProyectos(0);\n }\n}", "function crearTablaAscensorValoresCabina(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_cabina (k_codusuario,k_codinspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n $('#texto_carga').text(\"Creando valores cabina...Espere\");\n console.log('transaction creada ok');\n });\n}", "function User_Insert_Produits_Comptes_généraux_11(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 178;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = comptegen,cg_numero,cg_numero\n\nId dans le tab: 179;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"compteproduit\";\n var CleMaitre = TAB_COMPO_PPTES[175].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */\n var cg_numero=GetValAt(178);\n if (cg_numero==\"-1\")\n cg_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"cg_numero\",TAB_GLOBAL_COMPO[178],cg_numero,true))\n \treturn -1;\n var ci_actif=GetValAt(179);\n if (!ValiderChampsObligatoire(Table,\"ci_actif\",TAB_GLOBAL_COMPO[179],ci_actif,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ci_actif\",TAB_GLOBAL_COMPO[179],ci_actif))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",pd_numero,cg_numero,ci_actif\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+TAB_COMPO_PPTES[158].NewCle+\",\"+cg_numero+\",\"+(ci_actif==\"true\" ? \"true\" : \"false\")+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function save(table, column, value, callback) {\n // check if object with value already exists\n getIdByValue(table, column, value, function(resultId) {\n if (resultId == null) {\n var post = {};\n post[column] = value;\n\n var query = db.query('INSERT INTO ' + table + ' SET ?', post, function(err, result) {\n if (err) {\n db.rollback(function() {\n if (err) {\n console.log(err.message);\n }\n });\n return callback(err);\n } else {\n console.log('Inserted ID ' + result.insertId + ' into ' + table);\n return callback(err, result.insertId);\n }\n });\n console.log(query.sql);\n } else {\n return callback(err, resultId);\n }\n });\n}", "function addItemsPuertasItemsElectrica(k_coditem_electrica,o_descripcion,v_clasificacion) {\n db.transaction(function (tx) {\n var query = \"INSERT INTO puertas_items_electrica (k_coditem_electrica, o_descripcion, v_clasificacion) VALUES (?,?,?)\";\n tx.executeSql(query, [k_coditem_electrica,o_descripcion,v_clasificacion], function(tx, res) {\n console.log(\"insertId: \" + res.insertId + \" -- probably 1\");\n console.log(\"rowsAffected: \" + res.rowsAffected + \" -- should be 1\");\n },\n function(tx, error) {\n console.log('INSERT error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n $('#texto_carga').text(\"Creando items eléctrica...Espere\");\n });\n}", "insert(item) {\n const valuesArray = Object.values(item)\n let paramsString = valuesArray.map((value, index) => `$${index + 1}`).join(', ')\n let columnsString = Object.values(this.TABLE.COLUMNS).join(', ')\n const queryString = `\n INSERT INTO ${this.TABLE.TABLE_NAME}(${columnsString}) \n VALUES(${paramsString})\n RETURNING *;\n `\n return sendRequest(queryString, valuesArray)\n\n }", "insertInfo(){\n var self = this;\n var str = \"\",\n length = self.column.length,\n table = self.table,\n last = self.column.length - 1;\n for(let x = 0; x < length ; x++){\n if( x === last){\n str += self.column[x];\n continue;\n }\n str += self.column[x]+\",\";\n }\n\n self.insert = `INSERT INTO ${table} (${str}) VALUES \\n`;\n\n}", "function addTableEntry(id,fname,lname,role,salary,tableID)\n{\n var table = document.getElementById(tableID);\n var row = table.insertRow(table.rows.length);\n \n for(i = 0; i < 5; i++)\n {\n var tmpCell = row.insertCell(i)\n switch(i)\n {\n case 0:\n tmpCell.innerHTML = id;\n break;\n case 1:\n tmpCell.innerHTML = fname;\n break;\n case 2:\n tmpCell.innerHTML = lname;\n break;\n case 3:\n tmpCell.innerHTML = role;\n break;\n case 4:\n tmpCell.innerHTML = salary;\n break;\n } \n }\n}", "function crearTablaAscensorValoresAudios(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE ascensor_valores_audios (k_codusuario,k_codinspeccion,n_audio,n_directorio,o_estado_envio)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction creada ok');\n });\n}", "function criarItensTabala(dados) {\n\n const linha = tabela.insertRow();\n\n const colunaId = linha.insertCell(0)\n const colunaNome = linha.insertCell(1)\n const colunaValor = linha.insertCell(2)\n const colunaAcoes = linha.insertCell(3)\n\n const itemId = document.createTextNode(dados.id)\n const itemNome = document.createTextNode(dados.nome)\n const itemValor = document.createTextNode(dados.valor)\n\n colunaId.appendChild(itemId)\n colunaNome.appendChild(itemNome)\n colunaValor.appendChild(itemValor)\n\n criarBotoesTabela(colunaAcoes, dados)\n ordemCrescente()\n}", "function insertQuery() {\n var interesse = $('#query-input').val();\n\n databaseManager\n .query(\"INSERT INTO interesses (INTERESSE) VALUES (?)\", [interesse])\n .done(function () {\n alert(\"Interesse is in de database toegevoegd!\");\n loadController(CONTROLLER_ADMIN_HOME);\n })\n .fail(function () {\n alert(\"Interesse is in de database toegevoegd!\")\n });\n }", "function crearTablaEscalerasValoresAudios(){\n db.transaction(function (tx) {\n tx.executeSql('CREATE TABLE escaleras_valores_audios (k_codusuario,k_codinspeccion,n_audio,n_directorio,o_estado_envio)');\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction creada ok');\n });\n}", "create(cols, vals, cb) {\n orm.insertOne(\n 'burgers',\n cols, vals, (res) => cb(res)\n );\n }", "function creq()\r\n{\r\n\tvar tabla = document.getElementById('tabla_eq');\r\n\tvar oRow = tabla.insertRow(-1);\r\n\tvar oCell = oRow.insertCell(-1);\r\n\tvar oCell.innerHTML = 'funciona';\r\n}", "function acutalizarCantidad() {\n table.updateData([{ id: $idarticulo, cant: $('#codcantstk').val() }]);\n}", "function eventInsertOne(e){\n\t\te.preventDefault();\n\t\tlet container = document.querySelector(\"tbody\"); \n\t\tlet colTr = insertarFilaVacia(null, 0, 1);\n\t\tcontainer.appendChild(colTr);\n\t}", "function GuardarFondoPagina(){\n\n var Pagina;\n\n $('.actual').each(function () {\n var id = $(this)[0].id.split('_')[1];\n Pagina = {ID:parseInt($(this)[0].id.split('_')[1]),CuentoID:parseInt(CuentoActual.ID.split('_')[1]), Fondo:parseInt(getFondo($(this)[0].id).split('_')[1])};\n });\n\n db.transaction(InsertFondo,errorinsertFondo, successinsertFondo);\n\n var sql = \"INSERT OR REPLACE INTO `Fondos`(`ID_Cuento`, `ID_Paginas`, `Tipo_Fondo`)\";\n sql += \" VALUES (\" + Pagina.CuentoID + \",\" + Pagina.ID + \",\" + Pagina.Fondo + \") \";\n \n function InsertFondo(tx) {\n tx.executeSql(sql);\n }\n\n function errorinsertFondo(tx, err) {\n alert(\"Error al guardar fondo: \"+err);\n }\n\n function successinsertFondo() {\n }\n}", "function insertInto() {\n // create database connection\n let db = createConnection();\n\n // AUTO POPULATE DATABASE USING FAKER LIBRARY\n let data = [];\n let i;\n for (i = 1; i <= 3; i++) {\n data.push([\n faker.address.streetAddress(),\n faker.address.city(),\n faker.address.state(),\n faker.address.zipCode(),\n getRandomInt(500, 1000), // price\n getRandomInt(300, 1200), // size\n getRandomInt(1, 5), // room\n getRandomInt(1, 3), // bathroom\n faker.image.city(), // fake city image\n \"house\",\n getRandomInt(1, 10)\n ]);\n } // end for loop\n\n // Database query\n let sql =\n \"INSERT INTO property (address, city, state, zipcode, price, size, room, bathroom, img, type, distance) VALUES ?\";\n db.query(sql, [data], function(err, result, field) {\n if (err) throw err;\n console.log(\"Values inserted into table successfully...\");\n }); // end query\n} // end inserInto()", "function insertFieldValues(lyr, fieldName, values) {\n var size = getFeatureCount(lyr) || values.length,\n table = lyr.data = (lyr.data || new DataTable(size)),\n records = table.getRecords(),\n rec, val;\n\n for (var i=0, n=records.length; i<n; i++) {\n rec = records[i];\n val = values[i];\n if (!rec) rec = records[i] = {};\n rec[fieldName] = val === undefined ? null : val;\n }\n }", "function addVeiculo(dados, usuario){\n return new Promise((resolve,reject) => {\n let stm = db.prepare(\"INSERT INTO tbInfoVeiculo (usuarioCadastro, idmontadora, nomemodelo,anofabricacao,cores,tipoChassi,suspensaodianteira,suspensaotraseira,pneusdianteiro,pneutraseiro,freiodianteiro,freiotraseiro,tipodofreio,qtdcilindros,diametro,curso,cilindrada,potenciamaxima,torquemaximo,sistemadepartida,tipodealimentacao,combustivel,sistemadetransmissao,cambio,bateria,taxadecompessao,comprimento,largura,altura,distanciaentreeixos,distanciadosolo,alturadoassento,tanquedecombustivel,peso,arqFoto) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\")\n let p = dados;\n stm.run([usuario, p.montadora,p.nomeModelo,p.anoFabricacao,p.cores,p.tipoChassi,p.suspDianteira,p.suspTraseira,p.pnDianteiro,p.pnTraseiro,p.frDianteiro,p.frTraseiro,p.tpFreio,p.qtdCilindros,p.diametro,p.curso,p.cilindrada,p.potMax,p.tqMax,p.stPartida,p.tpAlimentacao,p.combustivel,p.stTransmissao,p.cambio,p.bateria,p.txCompress,p.comprimento,p.largura,p.altura,p.distEixos,p.distSolo,p.altAs,p.tqComb,p.peso,p.arqFoto], (err) => {\n if(err) {\n reject(err);\n }\n resolve(p.nomeModelo);//Confirmar veiculos\n })\n })\n}", "function addRow(data) {\n let insertQuery = \"INSERT INTO ?? (??,??) VALUES (?,?)\";\n let query = mysql.format(insertQuery, [\n \"todo\",\n \"user\",\n \"notes\",\n data.user,\n data.value,\n ]);\n pool.query(query, (err, response) => {\n if (err) {\n console.error(err);\n return;\n }\n // rows added\n console.log(response.insertId);\n });\n}", "function addRow(data) {\n let insertQuery = 'INSERT INTO ?? (??,??) VALUES (?,?)';\n let query = mysql.format(insertQuery, [\n 'todo',\n 'user',\n 'notes',\n data.user,\n data.value\n ]);\n pool.query(query, (err, response) => {\n if (err) {\n console.error(err);\n return;\n }\n // rows added\n console.log(response.insertId);\n });\n}", "function insertRecord(tableName,tableColumnNames, values, callback) {\n var insertSql = 'Insert into ' + tableName +\n ' ( ' + stringUtils.getDelimitedStringFromArray(tableColumnNames,',') +' ) VALUES ( ' +\n stringUtils.getDelimitedRepeatString('?',',',tableColumnNames.length) + ' ) ' ;\n\n runQueryWithParams( insertSql, values, function(err,results){\n if(err) {\n console.error(\"Error in insertRecord to \"+tableName+\";\"+err);\n callback(err,null);\n return;\n }\n callback(null,results);\n });\n}", "function addTable(posit) {\n var query = connection.query('insert into Position set ?', posit, function(err, result) {\n if (err) {\n console.error(err);\n return false;\n } else {\n console.log(query.sql)\n return true;\n }\n })\n}", "function insertTempObra(x) {\n //code Insertando avances fisicos\n \n if (AOTI && x >= AOTI.length) {\n //code\n console.log(\"Todas las inserciones terminadas:::::::::::::::::::::::::::::::::\");\n location.href=\"mapa_proyectos.html\";\n // insertarAvanceFinancieroProyectos(0);\n }\n \n else if (AOTI && AOTI.length > 0) {\n console.log(\"Cargando datos espere un momento ::: 4 X=\" + x + \" Avances: \"+ AOTI.length);\n \n \n \n db.transaction(function(tx) {\n \n tx.executeSql('INSERT INTO TempAvanceObras(idAvanceFinanciero, idAvanceFisico, idObra)' +\n ' VALUES (?, ?, ?)',\n [AOTI.item(x).idAvanceFinanciero, AOTI.item(x).idAvanceFisico, AOTI.item(x).idObraFisico]);\n console.log(\"Avance Temp en Proyectos: \" + AOTI.item(x).idObraFisico);\n \n \n }, errorCB, function (){\n console.log(\"Se inserto correctamente el avance temporal: \" + AOTI.item(x).idObraFisico);\n \n x++;\n insertTempObra(x);\n \n }); \n \n } else {\n console.log(\"No hay avances temporales de obra :::::::::::::::::::::::\");\n // insertarAvanceFinancieroProyectos(0);\n }\n}", "function User_Insert_Profils_de_droits_Liste_des_profils_de_droits0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 90;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 91;\ncomplexe\nNbr Jointure: 1;\n Joint n° 0 = droit,dp_numero,dp_numero\n\n******************\n*/\n\n var Table=\"droitprofil\";\n var CleMaitre = TAB_COMPO_PPTES[88].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var dp_libelle=GetValAt(90);\n if (!ValiderChampsObligatoire(Table,\"dp_libelle\",TAB_GLOBAL_COMPO[90],dp_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"dp_libelle\",TAB_GLOBAL_COMPO[90],dp_libelle))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",dp_libelle\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(dp_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(dp_libelle)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function GuardarPagina(numpage){\n\n db.transaction(InsertPage,errorinsertPage, successinsertPage);\n\n var sql = \"INSERT INTO Paginas (ID_Paginas,ID_Cuento) \";\n sql += \"VALUES ('\"+ numpage +\"', '\"+ CuentoActual.ID.split('_')[1] +\"')\";\n function InsertPage(tx) {\n tx.executeSql(sql);\n }\n\n function errorinsertPage(tx, err) {\n alert(\"Error al guardar página: \"+err);\n }\n\n function successinsertPage() {\n }\n}", "function insertAnuncio(anuncio) {\n\n // Calcula novo Id a partir do último código existente no array para novo cadastro. Se edição, retorna valor salvo\n if (edicao != 1) {\n novoId = (dados.livros.length)+1;\n }\n else {\n novoId = idAtual;\n }\n \n // Organiza os dados na forma do registro\n let novoAnuncio = {\n \"user_id\": usuario_logado,\n \"id\": novoId,\n \"fotAn\": anuncio.fotAn,\n \"titAn\": anuncio.titAn,\n \"descAn\": anuncio.descAn,\n \"locAn\": anuncio.locAn,\n \"contAn\": anuncio.contAn\n };\n\n // Insere o novo objeto no array para novos cadastros, ou atualiza em caso de edição\n if (edicao != 1) {\n dados.livros.push(novoAnuncio);\n displayMessage(\"Anuncio inserido com sucesso!\");\n }\n else {\n dados.livros[novoId-1] = novoAnuncio;\n displayMessage(\"Anuncio atualizado com sucesso!\");\n }\n\n // Atualiza os dados no Local Storage\n localStorage.setItem('dados', JSON.stringify(dados));\n\n // Altera \"edicao\" para diferente de 1, considerando que a próxima tarefa seja novo cadastro\n edicao = 0;\n}", "function addDataToTable(companyUser, costNumber, discountUser) \n{\n let table = document.getElementById('t01');\n let rows = document.getElementById('t01').getElementsByTagName('tr').length;\n let row = table.insertRow(rows);\n let cell1 = row.insertCell(0);\n let cell2 = row.insertCell(1);\n let cell3 = row.insertCell(2);\n let cell4 = row.insertCell(3);\n let totalCost = costNumber - costNumber * (discountUser / 100);\n \n //Adding values into each cell\n cell1.innerText = companyUser;\n cell2.innerText = new Intl.NumberFormat('pl-PL', { style: 'currency', currency: 'PLN' }).format(costNumber);\n cell3.innerText = discountUser + \" %\";\n cell4.innerText = new Intl.NumberFormat('pl-PL', { style: 'currency', currency: 'PLN' }).format(totalCost);\n \n //Unselecting elements and cleaning form valueFromInvoice\n document.getElementById('companyName').getElementsByTagName('option')[0].selected = 'selected';\n document.getElementById('valueFromInvoice').value = \"\";\n document.getElementById('discountValue').getElementsByTagName('option')[0].selected = 'selected';\n\n //Putting empty values\n cell1 = 0;\n cell2 = 0;\n cell3 = 0;\n cell4 = 0;\n}", "Insert() {\n\n }", "function addRowsToTable(bars, tx) {\r\n\tfor(var i=0;i<bars.length;i++){\r\n\t\tvar bar = bars[i];\r\n\t\tbarVarString = [bar['pk'], bar['name'], bar['slug'], bar['location'], bar['address'], bar['destination'], bar['destination_slug'], bar['phone'], bar['city'], bar['state'], bar['statekey'], bar['website']];\r\n\t\ttx.executeSql('INSERT INTO bars (id, name, slug, location, address, destination, destination_slug, phone, city, state, statekey, website) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', barVarString);\r\n\t}\r\n}", "function User_Insert_Types_d_attribut_Catégories_2(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 33;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 34;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"categorie\";\n var CleMaitre = TAB_COMPO_PPTES[31].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */\n var cr_libelle=GetValAt(33);\n if (!ValiderChampsObligatoire(Table,\"cr_libelle\",TAB_GLOBAL_COMPO[33],cr_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cr_libelle\",TAB_GLOBAL_COMPO[33],cr_libelle))\n \treturn -1;\n var cr_description=GetValAt(34);\n if (!ValiderChampsObligatoire(Table,\"cr_description\",TAB_GLOBAL_COMPO[34],cr_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cr_description\",TAB_GLOBAL_COMPO[34],cr_description))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",ta_numero,cr_libelle,cr_description\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+TAB_COMPO_PPTES[28].NewCle+\",\"+(cr_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(cr_libelle)+\"'\" )+\",\"+(cr_description==\"\" ? \"null\" : \"'\"+ValiderChaine(cr_description)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function InsertarCuentos(Cuentos) {\n\n db.transaction(InsertCuentos, errorinsertCuentos, successinsertCuentos);\n\n var sql = \"INSERT OR REPLACE INTO Cuentos (NombreCuento,ID_Colecciones) \";\n sql += \"VALUES ('\" + Cuentos.Nombre + \"', '\" + Cuentos.Coleccion + \"')\";\n function InsertCuentos(tx) {\n tx.executeSql(sql);\n }\n\n function errorinsertCuentos(tx, err) {\n alert(\"Error al Insertar cuentos: \" + err);\n }\n\n function successinsertCuentos() {\n // alert(\"success_hecho!\");\n }\n\n}", "function details_sql_generate(mytable,mytable_sql){\n\t\tsql = \"INSERT INTO \"+mytable_sql+\"(\";\n\t\ttam_col_temp=0;\n\t\t//creamos la primera concatenacion la cual es los campos a evaluar\n\t\tmytable.find(\"tr:eq(1) td\").each(function(i){\n\t\t\tif(jQuery(this).find(\">\").attr(\"colbd\")){\n\t\t\t\tcolbd = jQuery(this).find(\">\").attr(\"colbd\");\n\t\t\t\ttam_col_temp++;\n\t\t\t\tif(tam_col_temp==1){\n\t\t\t\t\tsql+=colbd;\n\t\t\t\t}else{\n\t\t\t\t\tsql+=\",\"+colbd;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tsql+=\")\";\n\t\t\n\n\t\tmytable.find(\"tr\").each(function(j){\n\t\t\t//este if se debe por que en la transaccion esta la cabecera y la fila a \n\t\t\tif(j>=2){\n\t\t\t\tif(j<3){\n\t\t\t\t\tsql+=\"VALUES(\";\n\t\t\t\t}else{\n\t\t\t\t\tsql+=\",VALUES(\"\n\t\t\t\t}\n\t\t\t\tjQuery(this).find('td').each(function(k){\n\t\t\t\t\tif(jQuery(this).find(\">\").attr(\"colbd\")){\n\t\t\t\t\t\tif(k==0){\n\t\t\t\t\t\t\tsql+=\"'\"+jQuery(this).find('>').val()+\"'\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tsql+=\",'\"+jQuery(this).find('>').val()+\"'\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tsql+=\")\";\n\t\t\t\tsql+\"\\n\";\n\t\t\t}\n\t\t});\n\t\talert(sql);\n\t\t//ahora guardaremos los valores\n\n\t}", "AgregaInsumo() {\n //insumo.UltPro = insumo.codigo;\n var rowNode =\n t //t es la tabla de insumos\n .row.add([insumo.id, insumo.codigo, insumo.nombre, insumo.esVenta || -1, \"Precio Unitario\", \"0\", \"0\", \"0\", \"0\", \"0\"])\n .draw() //dibuja la tabla con el nuevo insumo\n .node();\n //\n $('td:eq(3) input', rowNode).attr({\n id: (\"prec_\" + insumo.codigo),\n max: \"9999999999\",\n min: \"0\",\n step: \"1\",\n value: \"1\"\n }).change(function () {\n ordenCompra.CalcImporte($(this).parents('tr').find('td:eq(0)').html());\n });\n //\n $('td:eq(4) input', rowNode).attr({\n id: (\"cantBueno_\" + insumo.codigo),\n max: \"9999999999\",\n min: \"1\",\n step: \"1\",\n value: \"1\"\n }).change(function () {\n ordenCompra.CalcImporte($(this).parents('tr').find('td:eq(0)').html());\n });\n\n //$('td:eq(5)', rowNode).attr({id: (\"cantMalo_\"+insumo.codigo)});\n $('td:eq(5) input', rowNode).attr({\n id: (\"cantMalo_\" + insumo.codigo),\n max: \"9999999999\",\n min: \"0\",\n step: \"1\",\n value: \"0\"\n }).change(function () {\n ordenCompra.CalcImporte($(this).parents('tr').find('td:eq(0)').html());\n });\n //\n $('td:eq(6) input.valor', rowNode).attr({\n id: (\"valorBueno_v\" + insumo.codigo),\n style: \"display:none\"\n });\n $('td:eq(6) input.display', rowNode).attr({\n id: (\"valorBueno_d\" + insumo.codigo)\n });\n $('td:eq(7) input.valor', rowNode).attr({\n id: (\"valorMalo_v\" + insumo.codigo),\n style: \"display:none\"\n });\n $('td:eq(7) input.display', rowNode).attr({\n id: (\"valorMalo_d\" + insumo.codigo)\n });\n $('td:eq(8) input.valor', rowNode).attr({\n id: (\"subtotal_v\" + insumo.codigo),\n style: \"display:none\"\n });\n $('td:eq(8) input.display', rowNode).attr({\n id: (\"subtotal_d\" + insumo.codigo)\n });\n //t.order([0, 'desc']).draw();\n t.columns.adjust().draw();\n ordenCompra.CalcImporte(insumo.codigo);\n //calcTotal();\n //$('#open_modal_fac').attr(\"disabled\", false);\n }", "function insertToDB(firstName, lastName, email, education, opleidingsInstelling, know, jeBericht, ervaring, date) {\r\n // open database\r\n var db = new sqlite3.Database('admissions.db', (err) => {\r\n if (err) {\r\n return console.error(err.message);\r\n }\r\n });\r\n\r\n // create table for storage\r\n db.run('CREATE TABLE IF NOT EXISTS test (firstName TEXT, lastName TEXT, email TEXT, education TEXT, opleidingsInstelling TEXT, know TEXT, jeBericht TEXT, ervaring TEXT, date TEXT)');\r\n\r\n // insert one row into the test table\r\n db.run(`INSERT INTO test (firstName, lastName, email, education, opleidingsInstelling, know, jeBericht, ervaring, date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [firstName, lastName, email, education, opleidingsInstelling, know, jeBericht, ervaring, date], function(err) {\r\n if (err) {\r\n return console.log(err.message);\r\n }\r\n });\r\n\r\n\r\n // close database\r\n db.close((err) => {\r\n if (err) {\r\n return console.error(err.message);\r\n }\r\n });\r\n}", "async function insertTableValue(mail, pwd){\n try{\n await knex('users')\n .insert(\n [{'mail':mail, 'pwd':pwd}]\n );\n }\n catch(err){\n console.error('Erreur dans l\\'insertion d\\' élément de la table'); \n }\n}", "function addItemsPuertasItemsMotorizacion(k_coditem_motorizacion,o_descripcion,v_clasificacion) {\n db.transaction(function (tx) {\n var query = \"INSERT INTO puertas_items_motorizacion (k_coditem_motorizacion, o_descripcion, v_clasificacion) VALUES (?,?,?)\";\n tx.executeSql(query, [k_coditem_motorizacion,o_descripcion,v_clasificacion], function(tx, res) {\n console.log(\"insertId: \" + res.insertId + \" -- probably 1\");\n console.log(\"rowsAffected: \" + res.rowsAffected + \" -- should be 1\");\n },\n function(tx, error) {\n console.log('INSERT error: ' + error.message);\n });\n }, function(error) {\n console.log('transaction error: ' + error.message);\n }, function() {\n console.log('transaction ok');\n $('#texto_carga').text(\"Creando items motorización...Espere\");\n });\n}", "function User_Insert_Groupes_de_cantons_Liste_des_groupes_de_cantons0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 37;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 41;\ncomplexe\nNbr Jointure: 2;\n Joint n° 0 = appartienta,gc_numero,gc_numero\n Joint n° 1 = canton,ct_numero,ct_numero\n\n******************\n*/\n\n var Table=\"groupecanton\";\n var CleMaitre = TAB_COMPO_PPTES[35].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var gc_nom=GetValAt(37);\n if (!ValiderChampsObligatoire(Table,\"gc_nom\",TAB_GLOBAL_COMPO[37],gc_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"gc_nom\",TAB_GLOBAL_COMPO[37],gc_nom))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",gc_nom\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(gc_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(gc_nom)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\n\n/* table canton*/\nLstDouble_Exec_Req(GetSQLCompoAt(41),CleMaitre);\nreturn CleMaitre;\n\n}" ]
[ "0.71134865", "0.6548284", "0.6496309", "0.649352", "0.6492645", "0.6464312", "0.6452731", "0.6428112", "0.64233875", "0.64076793", "0.6399971", "0.6398232", "0.6395614", "0.63947076", "0.63866067", "0.6376183", "0.6363089", "0.63600975", "0.6348873", "0.63228047", "0.6321852", "0.63215995", "0.6296098", "0.62761205", "0.6274277", "0.6256081", "0.6251753", "0.6246972", "0.62246555", "0.62222886", "0.6220999", "0.62124705", "0.6210277", "0.6205268", "0.6203117", "0.61787164", "0.61753756", "0.61729145", "0.6164938", "0.61631787", "0.61591804", "0.61500376", "0.6139489", "0.61294454", "0.6128034", "0.6122099", "0.6120553", "0.61083657", "0.61065483", "0.6101904", "0.6101874", "0.60846794", "0.6083399", "0.6077262", "0.60714763", "0.60668325", "0.60592484", "0.60564697", "0.60448307", "0.604331", "0.6041934", "0.60366344", "0.60310197", "0.6023427", "0.6012335", "0.60001326", "0.59962595", "0.5995805", "0.59932387", "0.59928465", "0.59800196", "0.5975109", "0.5956823", "0.5946132", "0.5942229", "0.5929593", "0.59263825", "0.5922121", "0.5905072", "0.5894195", "0.589311", "0.5889412", "0.5885392", "0.58849156", "0.58791655", "0.5870492", "0.5869121", "0.58639634", "0.5861319", "0.5858983", "0.58580464", "0.5843064", "0.5829974", "0.581816", "0.5805604", "0.5804302", "0.5796346", "0.57927144", "0.5791223", "0.5790084", "0.5781857" ]
0.0
-1
does the keyup match any letter in the phrase create a boolean, an HTMLCollection with 0 length/which is true, return false. Read more about this in the unit04 thread
checkLetter(letter) { //works const boolean = document.getElementsByClassName(letter).length === 0; return !boolean; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "checkLetter(letter) {\r\n let keyboard = document.getElementById('qwerty');\r\n //check if button is clicked\r\n if (this.phrase.includes(letter)) {\r\n return true;\r\n // console.log(true)\r\n // this.showMatchedLetter(letter)\r\n } else {\r\n return false;\r\n }\r\n }", "checkLetter(keyClicked) {\r\n if (this.phrase.includes(keyClicked)) {\r\n console.log('Yeah bitch');\r\n return true;\r\n } else {\r\n console.log('No Bitch');\r\n return false;\r\n }\r\n }", "checkLetter(letter) {\r\r // Loop through the phrase text and if the letter matches\r // the phrase text at index j, return true\r for (let j = 0; j < this.phrase.length; j++){\r\r\n if (this.phrase[j] == letter)\r\n return true;\r\n }\r\r // No match, return false\r return false;\r }", "checkLetter(letter){\r\n if( this.phrase.indexOf(letter) > -1 ){\r\n this.showMatchedLetter(letter);\r\n return true; \r\n }\r\n }", "checkLetter(e){\n const phraseJoin = this.phrase.join('');\n return phraseJoin.includes(e.toLowerCase()) ? true : false;\n }", "checkLetter(letter){\r\n if(this.phrase.includes(letter)){\r\n return true;\r\n }else {\r\n return false;\r\n }\r\n\r\n }", "checkLetter(target){\n if (this.phrase.includes(target)) {\n return true;\n } else {\n return false;\n }\n }", "checkLetter(letter) {\n return this.phrase.includes(letter.textContent);\n }", "checkLetter(letter) {\n console.log(this.phrase);\n if (this.phrase.includes(letter)) {\n return true;\n } else {\n return false;\n }\n }", "checkLetter(letter) {\n\n let letterContained = false;\n\n for (let i = 0; i < this.phrase.length; i++) {\n if (this.phrase[i] === letter) {\n letterContained = true;\n }\n }\n\n return letterContained;\n }", "checkLetter(letter) {\n if (this.phrase.includes(letter)) { //the includes() method was used from https://www.w3schools.com/Jsref/jsref_includes.asp\n return true;\n } else {\n return false;\n }\n}", "function isPartialMatch() {\r\n // if (wordInput.value === currentWord.innerHTML) {\r\n // message.innerHTML = \"CORRECT!!!!!\";\r\n // return true;\r\n // } else {\r\n // message.innerHTML = \"\";\r\n\r\n for (let i = 0; i < wordInput.value.length; i++) {\r\n if (wordInput.value.charAt(i) === currentWord.innerText.charAt(i)) {\r\n } else {\r\n message1.innerHTML = \"\";\r\n return false;\r\n }\r\n }\r\n return true;\r\n}", "checkLetter(letter) { \n if (this.phrase.includes(letter)) {\n return true; \n }\n }", "checkLetter(){\n /** will correctly match if letter is on the current phrase**/\n let matched = this;\n let phraseLi = document.getElementById(\"phrase\").getElementsByTagName(\"li\");\n $('.keyrow button').bind('click', function(){\n for (var i = 0; i < phraseLi.length; i++) {\n if ($(this).text() === phraseLi[i].innerHTML) {\n $(this).addClass(\"phraseLetters\");\n phraseLi[i].classList.add(\"correct\");\n matched.showMatchedLetter();\n }\n }\n })\n }", "checkLetter(letter) {\r\n const phrase = this.phrase;\r\n if (phrase.includes(letter)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "checkLetter(letter) {\n let hasMatch = false;\n //loop through each phrase letter\n for (let i = 0; i < this.phrase.length; i++){\n if (this.phrase[i] === letter) {\n this.showMatchedLetter(letter);\n hasMatch = true;\n }\n }\n return hasMatch;\n }", "checkLetter(letter)\r\n {\r\n // get the index of the letter in the phrase (-1 if not found)\r\n\r\n let foundIndex = this.phrase.indexOf(letter);\r\n\r\n // if not found\r\n\r\n if (foundIndex === -1) \r\n {\r\n // return false\r\n\r\n return false;\r\n } \r\n else \r\n {\r\n // if found show the letters on the phrase area and return true\r\n //this.showMatchedLetter(letter);\r\n return true;\r\n }\r\n\r\n }", "checkLetter(letter) {\r\n // return true/false if passed letter, matches letter in phrase\r\n return this.phrase.includes(letter) ? true : false;\r\n }", "checkLetter(letter) {\n if ( this.phrase.includes(letter) ) {\n return true;\n }\n else {\n return false;\n }\n }", "function checkLetter(button) {\n let phraseElements = document.querySelectorAll('li.letter');\n let match = false;\n for(let i = 0; i < phraseElements.length; i++) {\n if (phraseElements[i].textContent.toUpperCase() === button.textContent.toUpperCase()) {\n phraseElements[i].classList.add('show');\n match = true;\n }\n }\n return match;\n}", "checkLetter(letter){\n return this.phrase.includes(letter);\n }", "checkLetter(letter) { \n const phrase = this.phrase.toLowerCase();\n return phrase.includes(letter) ? true : false;\n }", "checkForWin(){\r\n revealedLetters = document.querySelectorAll('.show')\r\n let phraseNoSpaces = splitPhraseArray.filter( char => char !== ' ')\r\n if(revealedLetters.length === phraseNoSpaces.length){\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}", "checkLetter(letter) {\n if (this.phrase.includes(letter)) {\n return true;\n }\n return false;\n }", "checkLetter(selectedLetter){\n const lis = document.getElementById('phrase').querySelector('ul').children;\n let isCorrect = false;\n for(let i = 0; i < lis.length; i++){\n if(lis[i].textContent === selectedLetter){\n this.showMatchedLetter(lis[i]);\n isCorrect = true;\n }\n }\n return isCorrect;\n }", "checkLetter(letter) {\r\n // console.log(`in checkLetter()`);\r\n // console.log(`letter clicked: ${letter.textContent}`);\r\n // console.log(`phrase is: ${this.phrase}`);\r\n const selectedPhrase = this.phrase;\r\n // console.log(`selected phrase is: ${selectedPhrase}`);\r\n let selectedLetter = letter.textContent;\r\n // console.log(`letteris: ${selectedLetter}`);\r\n\r\n //check to see if letter is included in the phrase\r\n // console.log(`checkLetter: ${selectedPhrase.includes(selectedLetter)}`);\r\n return selectedPhrase.includes(selectedLetter);\r\n }", "checkLetter(letter) {\n return this.phrase.includes(letter);\n }", "checkLetter(letter) {\n return this.phrase.includes(letter);\n }", "checkLetter(letter) {\r\n //return matching letters\r\n return this.phrase.includes(letter);\r\n}", "checkLetter(letter) {\n let phrase = this.phrase\n if (phrase.includes(letter)) {\n return true;\n } else {\n return false;\n }\n }", "checkLetter(e) {\n\t\tthis.letterGuess = e.toLowerCase();\n\t\tthis.regexText = /[A-Za-z]/.test(this.letterGuess);\n\t\tif (this.regexText) {\n\t \t\tlet thisPhrase = this.phrase.toString();\n\n\t\t\t//Append letters to Letter CheckArray\n\t\t\tif (this.letterGuesses.includes(this.letterGuess)) {\n\t\t\t\talert(\"You've already used that letter!\")\n\t\t\t} else {\n\t\t\tthis.letterGuesses.push(this.letterGuess);\n\t\t\t}\n\n\t\t\tif (this.phrase.includes(this.letterGuess)) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\talert(\"Please only use letters!\");\n\n\t\t}\n\t}", "checkLetter(letter) {\r\n if ([...this.phrase].indexOf(letter) !== -1) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "checkLetter(letter) {\n\t\tfor (let i = 0; i < this.phrase.length; i += 1) {\n\t\t\tif (this.phrase[i] === letter) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "checkLetter(letter) {\r\n return this.phrase.includes(letter)\r\n }", "checkLetter(letter) {\n if (this.phrase.includes(letter)) {\n return true;\n } else {\n return false;\n }\n }", "function matchWords() {\n if (wordInput.value === currentWord.innerHTML)\n return true;\n else \n return false;\n}", "checkLetter(letter) {\n if(this.phrase.includes(letter)) {\n return true\n } else {\n return false;\n }\n }", "checkLetter(letter) {\n let status = false;\n for (let i = 0; i < this.phrase.length; i++) {\n if (letter === this.phrase[i].toLowerCase()) {\n status = true;\n }\n }\n return status;\n }", "checkLetter(letter) { //Checks to see if the letter selected by the player matches a letter in the phrase.\r\n console.log('in checkLetter method'); \r\n console.log(letter);\r\n console.log(\"in the phrase.checkLetter method\");\r\n let phraseCharactersArray = this.phrase.split(''); //converts phrase to array\r\n console.log(phraseCharactersArray);\r\n return phraseCharactersArray.includes(letter);\r\n \r\n // phraseCharactersArray.forEach(character => {\r\n // if (character === letter) {\r\n // return true;\r\n // } else {\r\n // return false;\r\n // }\r\n // });\r\n }", "checkLetter(letter) {\n return this.phrase.includes(letter);\n }", "checkLetter(letter) {\r\n return this.phrase.includes(letter);\r\n }", "checkLetter(letterToCheck) {\n\n let checkForMatch = 0;\n\n for (let i = 0; i < this.phrase.length; i++) {\n if (letterToCheck === this.phrase[i].toLowerCase()) {\n checkForMatch++\n }\n }\n if (checkForMatch > 0) {\n return true;\n } else {\n return false;\n }\n }", "checkIfWordHasLetter(letter) {\r\n return this.text.includes(letter);\r\n }", "function checkLetter(choice) {\n const liWithLetters = phraseUl.getElementsByTagName('li');\n let match = false;\n for (i = 0; i < liWithLetters.length; i++) {\n const li = liWithLetters[i];\n const letterInPhrase = li.textContent;\n if (choice === letterInPhrase) {\n li.classList.add('show');\n match = true;\n }\n }\n return match;\n}", "function matchWords(){\r\n if(wordInPut.value === currentWord.innerHTML){\r\n message.innerHTML = 'Correct!!!'\r\n return true;\r\n } else {\r\n message.innerHTML = '';\r\n return false;\r\n }\r\n\r\n}", "checkLetter(letter) {\n if ( this.phrase.includes(letter.toLowerCase()) ) {\n return true;\n } else {\n return false;\n }\n }", "checkLetter(e) {\n let lettersInDom = document.getElementsByClassName(\"letter\")\n console.log(e.target.innerText)\n for (i = 0; i < lettersInDom.length; i++) {\n if (lettersInDom[i].innerText === e.target.innerText) {\n return true\n };\n // else{\n // return false\n // }\n };\n\n }", "checkLetter(letter) {\r\n return this.phrase.toLowerCase().includes(letter);\r\n }", "function matchWords(){\r\n\tif (wordInput.value===currentWord.innerHTML) \r\n\t{\r\n\t\tmessage.innerHTML='Correct!!!';\r\n\t\treturn true;\r\n\t}else{\r\n\t\tmessage.innerHTML='';\r\n\t\treturn false;\r\n\t}\r\n}", "checkLetter(guess) {\n if (this.phrase.includes(guess.toLowerCase())) {\n return true;\n } else {\n return false;\n }\n }", "function matchWord(){\r\n\tif (wordInput.value === currentWord.innerHTML) {\r\n\t \tmessage.innerHTML = 'correct!!!!!';\r\n\t \treturn true;\r\n\r\n\t}\r\n\telse{\r\n\t\tmessage,innerHTML = '';\r\n\t\treturn false;\r\n\t}\r\n}", "checkLetter(letter, phrase){\r\n let letterMatchFilter = new RegExp(letter)\r\n let matched = letterMatchFilter.test(phrase)\r\n return matched\r\n }", "checkForWin() {\n const letters = document.getElementById('phrase').querySelector('ul').querySelectorAll('li');\n let result = true;\n for (let i = 0; i < letters.length; i++) {\n if (!letters[i].classList.contains(\"matched\") && !letters[i].classList.contains(\"space\")) {\n result = false;\n }\n }\n return result;\n }", "checkLetter(letter) {\r\n return !(this.phrase.indexOf(letter) == -1);\r\n }", "function letterTest () {\n\t\t\n var userLetter = String.fromCharCode(event.keyCode).toLowerCase();\n console.log(userLetter);\n\n for (var i = 0; i < lettersOfWord.length; i++);\n\n if (userLetter === lettersOfWord[i]){\n \tconsole.log(userLetter + \" is present in this word\")\n }\n\n\n /* for( var i = 0; i< lettersOfWord.length; i++){\n \t\n \tif(userLetter.indexOf(lettersOfWord [i]))\n \tconsole.log(userLetter + \"is present in this word\");\n \t\t}*/\n }", "function checkLetter(guess) {\n\tmatch = null;\n\tlet letters = document.querySelectorAll('.letter'); //unrevealed letters collection\n\tfor (i = 0; i < letters.length; i++) {\n\t\tif (guess.textContent == letters[i].textContent) {\n\t\t\tletters[i].classList.add('show');\n\t\t\tmatch = true;\n\t\t}\n\t}\n\treturn match;\n}", "checkLetter(letterToCheck) {\n if(this.phrase.split(\"\").includes(letterToCheck)) {\n return true;\n }\n else {\n return false;\n }\n }", "function matchWords(){\r\n if(wordInput.value === currentWord.innerHTML) {\r\n message.innerHTML = 'Correct!';\r\n return true;\r\n } else {\r\n message.innerHTML = \"\";\r\n return false;\r\n }\r\n }", "checkLetter(letter) {\n return this.phrase.includes(letter);\n }", "checkLetter(letter) {\n return this.phrase.includes(letter);\n }", "function matchwords(){\n if(wordinput.value === currentword.innerHTML){\n message.innerHTML= 'WOhOOOOO!!!';\n return true;\n }\n else{\n message.innerHTML = '';\n return false;\n }\n}", "function checkLetter (guess){\n\t\tconst letter = document.getElementsByClassName(\"letter\");\n\t\tlet foundMatch = null;\n\t\tfor (let i = 0; i < letter.length; i++) {\n\t\t\tif (guess === letter[i].textContent.toLowerCase()) {\n letter[i].classList.add('show');\n foundMatch = letter[i].textContent;\n } \n }\n return foundMatch\n }", "function matchWords(){\n if(wordInput.value === currentWord.innerHTML){\n message.innerHTML='correct!!!!';\n return true;\n }else{\n message.innerHTML='';\n return false;\n }\n\n \n}", "checkLetter(button, selectedLetter) {\n let isChosen = true;\n //iterates through phrase and adds 'chosen' class if there is a match\n if (this.phrase.indexOf(selectedLetter) >= 0) {\n $(button).addClass('chosen');\n //displays letter to user if they guessed right\n this.showMatchedLetter(selectedLetter)\n isChosen = true;\n //iterates through phrase and adds 'wrong' class if there is no match\n } else if ($(button).attr('class') === 'key') {\n $(button).addClass('wrong');\n isChosen = false;\n } \n return isChosen\n }", "function matchWords() {\n if(wordInput.value === currentWord.innerHTML) {\n message.innerHTML = 'Correct!!!'\n return true;\n } else {\n message.innerHTML = '';\n return false;\n }\n }", "showMatchedLetter(letter) {\n const phraseLis = document.getElementById('phrase').children[0].children;\n\n for(let i = 0; i < phraseLis.length; i++) {\n if(phraseLis[i].textContent.includes(letter)) {\n phraseLis[i].className = 'show';\n }\n }\n }", "checkLetter(guess) {\n for (let i = 0; i < this.phrase.length; i++) {\n if (this.phrase.charAt(i) === guess) {\n return true;\n }\n }\n }", "function matchWord() {\r\n if (wordInput.value == currentWord.innerHTML) {\r\n message.innerHTML = 'Correct';\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}", "function checkLetter(arr) { \n let buttonClicked = arr;\n let phraseLetters = document.getElementsByClassName('letter');\n let letterMatched = null;\n\n for (let i = 0; i < phraseLetters.length; i += 1) {\n if (buttonClicked.toUpperCase() === phraseLetters[i].textContent.toUpperCase()) { \n phraseLetters[i].className += ' show';\n letterMatched = buttonClicked;\n }\n }\n\n return letterMatched;\n}", "checkLetter(letter) {\n const arr = this.phrase.split('');\n const phrase = this.phrase;\n //console.log(phrase);\n const guessedLetter = letter;\n const regex = new RegExp(guessedLetter);\n return regex.test(phrase);\n\n }", "showMatchedLetter(letter){\n const correctPhrase = document.querySelectorAll('#phrase ul li ');\n for(let i = 0; i<correctPhrase.length;i++){\n if(correctPhrase[i].innerHTML === letter) {\n correctPhrase[i].className = 'show'; \n }\n }\n }", "function matchWords(){\r\n if(wordInput.value===currentWord.innerHTML){\r\n message.innerHTML='Correct!!!';\r\n return true;\r\n }\r\n else{\r\n message.innerHTML='';\r\n return false;\r\n }\r\n}", "function checkLetter(button) {\nlet letterMatch = null;\n\n for (var i = 0; i < document.querySelectorAll('.letter').length; i++) {\n if (button.innerText.toLowerCase() === document.querySelectorAll('.letter')[i].innerText.toLowerCase()) {\n document.querySelectorAll('.letter')[i].classList.add(\"show\");\n letterMatch = \"match\";\n } \n}\nreturn letterMatch\n}", "function wordGuess(){\r\n var w = document.getElementById('Gword').value.toUpperCase();\r\n if (w == key)\r\n resultingText(true);\r\n else\r\n resultingText(false);\r\n}", "showMatchedLetter(inputLetter) {\r\n const gameLetterElements = document.querySelectorAll('#phrase li');\r\n console.log(gameLetterElements)\r\n gameLetterElements.forEach(current => {\r\n console.log(`Current phrase letter: ${current.innerText}`);\r\n console.log(`keyed letter: ${inputLetter}`);\r\n if (current.innerText.toLowerCase() == inputLetter) {\r\n current.classList.remove(\"hide\");\r\n current.classList.add(\"show\");\r\n }\r\n })\r\n }", "checkForWin(){\n let unguessedLetters = 0; \n for(let c = 0; c < this.activePhrase.phrase.length; c++){\n if(phraseSection.firstElementChild.children[c].classList.contains('hide')){\n unguessedLetters ++;\n } \n } \n if(unguessedLetters === 0){\n return true;\n } \n }", "function checkLetter(button) {\n const ListLI = phrase.getElementsByTagName('li');\n let match = null;\n for (let i = 0; i<ListLI.length; i++) {\n //if button text === letter li text\n if (ListLI[i].className===\"letter\" && button.textContent === ListLI[i].textContent) {\n //when match is found, letter li gets \"show\" class & match = letter\n ListLI[i].classList.add(\"show\");\n ListLI[i].style.transition = \"all .5s\";\n match = button.textContent;\n } \n }\n //if no match found, return match = null, exit function\n return match;\n}", "checkLetter(guessedletter) {\r\n let activePhr = game.activePhrase.toLowerCase();\r\n const phraseLetterArray = activePhr.split(\"\").filter(i => i != \" \");\r\n let letterWasCheacked = phraseLetterArray.includes(guessedletter);\r\n return letterWasCheacked;\r\n }", "function matchWords() {\n if (wordInput.value === currentWord.innerHTML) {\n message.innerHTML = 'Correct!!!';\n return true;\n } else {\n message.innerHTML = '';\n return false;\n }\n}", "function matchWords(){\n if(wordInput.value === currentWord.innerHTML){\n message.innerHTML = 'Prawidłowo!';\n message.style.color = \"green\";\n return true;\n }else{\n message.innerHTML = '';\n return false;\n }\n}", "checkForWin() {\r\n const activeLetters = this.activePhrase.phrase.split('');\r\n const selectedLetter = document.querySelectorAll(`li.show.letter`);\r\n\r\n for (let i = 0; i < activeLetters.length; i++) {\r\n if (activeLetters[i] === ' ') {\r\n activeLetters.pop(activeLetters[i]);\r\n }\r\n }\r\n\r\n for (let i = 0; i < activeLetters.length; i++) {\r\n if (selectedLetter.length === activeLetters.length) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n }", "function matchWords() {\n if (wordInput.value === currentWord.innerHTML) {\n message.innerHTML = \"Correct!!!\";\n return true;\n } else {\n message.innerHTML = \"\";\n return false;\n }\n}", "function testWin() {\n var hasLetters = false;\n\n for (var i = 0; i < guitarist.length; i++) {\n\n if (goodGuess.includes(guitarist.toLowerCase().charAt(i)) || (guitarist.charAt(i) === \" \")) {\n hasLetters = true;\n } else {\n hasLetters = false;\n }\n\n if (hasLetters === false) {\n if (numGuess === 0) {\n displayMessage('You lose, click \"Start\" to try again :(');\n document.querySelector(\"#wordLetters\").innerHTML = guitarist;\n return true;\n }\n return false;\n } \n\n }\n \n if (hasLetters === true) {\n displayMessage('You win!, click \"Start\" to play again :)');\n return true;\n }\n\n\n}", "function checkLetter(button) {\n const letter = $(button)[0].textContent;\n let letterFound = null;\n\n $.each($('.letter'), function(index, value) {\n\n if (value.textContent.toLowerCase() === letter) {\n $(value).addClass('show');\n letterFound = letter;\n }\n }); // end of each\n\n return letterFound;\n} // end of checkLetter", "checkLetter(letter) {\n return this.phrase.match(letter);\n }", "function Check_char(ct){\n\tf=document.forms[0];\n\tel=f.elements;\n\n\tif (el[ct].value.length > 1){\n\t\tel[ct].value = trim(el[ct].value);\n\t\t\n\t\treg_ex = /^([a-zàèéìòù]+['\\s]?){1,}[a-zàèéìòù]$/ig\n\t\t\n\t\tstringa = el[ct].value;\n\t\t\n\t\tif( stringa.match(reg_ex))\n\t\t\treturn true;\n\t\telse {\n\t\t\talert(\"Attenzione!\\nCarattere non ammesso nel campo \"+ct+\"\\n\\nSono consentiti solo lettere, spazi e apostrofi. Non sono ammessi:\\n - numeri\\n - caratteri speciali (es ?,@,_,*,+,-,/)\\n - spazi prima e dopo gli apostrofi\\n - doppio spazio o doppio apostrofo\\n - apostrofo finale\\n - spazi iniziali e finali\");\n\t\t\tel[ct].focus();\n\t\t\treturn false;\n\t\t}\n\t}\n\n}", "function checkLetter(button) {\n const letters = document.querySelectorAll('.letter');\n let match = null;\n let chosenLetter = button.textContent.toUpperCase();\n\n for (let i = 0; i < letters.length; i++) {\n if (chosenLetter === letters[i].textContent) {\n letters[i].className += ' show';\n match = letters[i].textContent;\n }\n }\n return match;\n}", "function checkLetter(button) {\n let letters = document.querySelectorAll(\".letter\");\n let match = null;\n for (i = 0; i < letters.length; i++) {\n if (button === letters[i].textContent) {\n letters[i].classList.add(\"show\");\n match = true;\n }\n }\n return match;\n}", "showMatchedLetter(letter){\r\n const phraseLi = document.querySelectorAll('#phrase > ul > li');\r\n \r\n if(this.checkLetter(letter) === true){\r\n for(let i =0; i < phraseLi.length; i++){\r\n if(phraseLi[i].textContent === letter ){\r\n phraseLi[i].classList.remove('hide');\r\n phraseLi[i].classList.add('show');\r\n \r\n }\r\n }\r\n \r\n\r\n }\r\n \r\n \r\n }", "isTyping() {\n return this._pressedLetters.length > 0;\n }", "function checkLetter(clickedButton) {\n let match = null;\n document.querySelectorAll('.letter').forEach( (letter) => {\n if (clickedButton === letter.textContent.toLowerCase() ) {\n letter.classList.add('show');\n match = clickedButton;\n }\n });\n return match;\n}", "function checkLetter(event) {\n let char = document.querySelectorAll('.letter');\n let result = null;\n\n for (let i = 0; i < char.length; i++) {\n if (char[i].textContent == event.textContent) {\n\n char[i].classList.add(\"show\");\n \tchar[i].style.boxShadow = '5px 4px 10px 0px #9e9e9e';\n \tchar[i].style.transition = 'ease 0.5s';\n\n result = event;\n }\n }\n return result;\n}", "function checkLetter (qwertyButton){\n // select all elements with class letter\n let li = document.getElementsByClassName('letter');\n // declare a match and set it to null\n let match = null;\n // loop through all elements with class letter\n for (let i = 0; i < li.length; i += 1) {\n // if the letter and the button clicked(text cont) are a match, add show\n if (li[i].textContent === qwertyButton.textContent) {\n li[i].classList.add('show');\n // store the letter that matched in variable\n match = li[i].textContent;\n } else{\n // else, the letter is marked null\n li[i].classList.add('null');\n }\n }\n // once the letter is checked, retuned the match\n return match;\n}", "showMatchedLetter(letter) {\n const letterCollection = document.getElementById('phrase').firstElementChild.children;\n for (let i = 0; i < letterCollection.length; i++) {\n if (letterCollection[i].textContent.toLowerCase() === letter) {\n letterCollection[i].className = 'show letter ' + letter;\n }\n }\n }", "function checkLetter(clickedButton) {\n const letterMatch = document.querySelectorAll(\".letter\");\n let match = null;\n for (let i = 0; i < letterMatch.length; i++) {\n if (letterMatch[i].innerHTML.toLowerCase() === clickedButton) {\n find = clickedButton;\n letterMatch[i].classList.add(\"show\");\n match = true;\n }\n }\n return match;\n}", "function isKeyInWord() {\n var isinword = false;\n\n // Compare the KEYINPUT with the characters of the word\n for (var i = 0; i < word.length; i++) {\n if (keyinput == word[i]) {\n isinword = true;\n // Replace the guessed character in GUESS\n guess[i] = keyinput;\n }\n }\n\n // If KEYINPT is not a match increase a bad guess and remove a life\n if (!isinword) {\n $(\".audioDoh\").trigger('play');\n lives--;\n badguess++;\n if (lives < 1) {\n matchesLost++;\n gamedone = true;\n }\n }\n\n // Update the labels\n updateGame();\n }", "showMatchedLetter(letter) {\r\n const phrase = document.querySelectorAll(\".letter\");\r\n phrase.forEach((char) => {\r\n if (char.textContent === letter) {\r\n char.classList.add(\"show\");\r\n char.classList.remove(\"hide\");\r\n }\r\n });\r\n }", "showMatchedLetter(letter) {\n\n const lis = document.getElementById('phrase').firstElementChild.children;\n for (let i = 0; i < lis.length; i++) {\n if (lis[i].textContent.toLowerCase() === letter) {\n lis[i].classList.add('show');\n lis[i].classList.remove('hide');\n }\n }\n }", "function checkLetter(button) {\r\n const fontClicked = button.innerHTML;\r\n var letterFound = null;\r\n\r\n for (let i = 0; i < letter.length; i++){\r\n if (fontClicked === letter[i].innerHTML.toLowerCase()) {\r\n letter[i].classList.add('show');\r\n letterFound = true;\r\n letterFound = fontClicked;\r\n }\r\n }\r\n return letterFound;\r\n}", "function checkMatches() {\n\tif (selectedChars[0]==selectedChars[1] && selectedChars[0] ==selectedChars[2]) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "checkForWin(){\n const $hidenLetters = $('#phrase .hide');\n if($hidenLetters.length === 0){\n return true;\n }\n return false;\n }" ]
[ "0.75248915", "0.7459201", "0.7458474", "0.7324257", "0.729602", "0.7289679", "0.725142", "0.72349733", "0.72045887", "0.71802545", "0.71492594", "0.71322864", "0.71143013", "0.7110448", "0.71099216", "0.7088287", "0.7062099", "0.70554143", "0.7037041", "0.7028106", "0.700277", "0.69961447", "0.6987331", "0.6974984", "0.6969484", "0.6968241", "0.69620955", "0.6946131", "0.6937845", "0.69366866", "0.6901282", "0.6890191", "0.6880431", "0.68594617", "0.68590266", "0.68553144", "0.6853844", "0.6852124", "0.6847109", "0.6844442", "0.6833323", "0.6829678", "0.6801468", "0.67995876", "0.67890793", "0.6780659", "0.6751122", "0.6746872", "0.6745648", "0.673992", "0.6724098", "0.6713293", "0.671076", "0.67051125", "0.6701688", "0.6700456", "0.6670729", "0.66696715", "0.6667298", "0.6667298", "0.66645426", "0.6654748", "0.66350603", "0.66334444", "0.6633073", "0.66307235", "0.6624191", "0.66117597", "0.6596489", "0.6593993", "0.6590505", "0.6590443", "0.65856636", "0.65800506", "0.65737826", "0.65603626", "0.6559736", "0.65547115", "0.65470856", "0.65403175", "0.65329003", "0.6508427", "0.65069264", "0.6495159", "0.6477491", "0.6477298", "0.64702106", "0.64564705", "0.64537007", "0.64435273", "0.6435963", "0.6431606", "0.6415504", "0.6402447", "0.639297", "0.63911486", "0.6386025", "0.63724446", "0.63699514", "0.63636327", "0.6352204" ]
0.0
-1
Handler for authenticating the SocketIO connection
function authenticate(socket, data, callback) { // Set the Authorization header using the provided token socket.request.headers.authorization = 'JWT ' + data.token; // Use Passport to populate the user details passport.authenticate('jwt', { session: false }, function (err, user) { if (err) { return callback(new Error(err)); } if (!user) { return callback(new Error('User not found')); } // Set the socket user socket.request.user = user; return callback(null, true); })(socket.request, socket.request.res, callback); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function authenticate() {\n socket.emit(\"authenticate\", {auth: auth_key, player_id: user_id, username: username});\n socket.emit(\"game/connect\", {game_id: game_id, player_id: user_id, chat: false});\n}", "authenticate() { \n this.socket = io(this.protocol + '://' + this.host + ':' + this.port, {\n\t\t\tquery: querystring.stringify({\n\t\t\t\taccess_token: this.token\n\t\t\t}) \n });\n //use minimal resources to run io socket for live rates\n //this.liveRatesSocket = io('/live')\n //this.tablesSocket = io('/tables')\n\n //console.log(this.liveRatesSocket)\n }", "onopen() {\n debug(\"transport is open - connecting\");\n\n if (typeof this.auth == \"function\") {\n this.auth(data => {\n this.packet({\n type: socket_io_parser_1.PacketType.CONNECT,\n data\n });\n });\n } else {\n this.packet({\n type: socket_io_parser_1.PacketType.CONNECT,\n data: this.auth\n });\n }\n }", "function on_auth_success(socket, accept) {\n console.log(\"Auth success\");\n /**\n * Accepts the connection\n * A message may be sent to client via accept\n */\n accept();\n }", "onopen() {\n debug(\"transport is open - connecting\");\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data });\n });\n }\n else {\n this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: this.auth });\n }\n }", "onopen() {\n debug(\"transport is open - connecting\");\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data });\n });\n }\n else {\n this.packet({ type: socket_io_parser_1.PacketType.CONNECT, data: this.auth });\n }\n }", "connect () {\n if (this.state == this.states.connected && this.socket.readyState == 'open')\n return\n\n if (!this.hasAuth())\n return this.fail('No auth parameters')\n\n this.state = this.states.connecting\n\n // To prevent duplicate messages\n this.clearSocketListeners()\n if (this.socket)\n this.socket.close()\n\n const url = this._buildUrl()\n this.socket = eio(url, this.options)\n this.socket.removeAllListeners('open')\n this.socket.removeAllListeners('error')\n this.socket.once('open', this.onOpen.bind(this))\n this.socket.once('error', (err) => {\n if (console && typeof(console.trace) == 'function') // eslint-disable-line\n console.trace(err) // eslint-disable-line\n\n if (err && err.type == 'TransportError') {\n this.fail(err)\n this._setupReconnect()\n }\n })\n }", "onopen() {\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this.packet({ type: PacketType.CONNECT, data });\n });\n }\n else {\n this.packet({ type: PacketType.CONNECT, data: this.auth });\n }\n }", "function login() {\n socket.emit('controllogin');\n}", "function _init(socketio) {\n // Require authentication here:\n socketio.use(require('socketio-jwt').authorize({\n secret: config.secrets.session,\n handshake: true\n }));\n\n socketio.on('connection', function (socket) {\n socket.address = socket.handshake.address + \":\" + config.port;\n\n socket.connectedAt = new Date();\n\n // Call _onDisconnect.\n socket.on('disconnect', function () {\n _onDisconnect(socket);\n //socket.on('user:off');\n console.info('[%s] DISCONNECTED', socket.address);\n });\n\n // Call _onConnect.\n _onConnect(socket, socketio);\n console.info('[%s] CONNECTED', socket.address);\n });\n}", "function onAuthorizeSuccess(data, accept){\n console.log('');\n console.log('successful connection to socket.io');\n console.log('data.user =');\n console.log(data.user);\n \n if(isRobot(data) || isOperator(data)) {\n console.log('connection authorized!');\n accept();\n } else {\n console.log('connection attempt from unauthorized source!');\n // reject connection (for whatever reason)\n accept(new Error('not authorized'));\n }\n}", "login(state, data) {\n socket.emit('login', data);\n }", "onopen() {\n debug(\"transport is open - connecting\");\n if (typeof this.auth == \"function\") {\n this.auth((data) => {\n this.packet({ type: dist.PacketType.CONNECT, data });\n });\n }\n else {\n this.packet({ type: dist.PacketType.CONNECT, data: this.auth });\n }\n }", "function authenticateSocket(options, socket, method) {\n\t return new Promise(function (resolve, reject) {\n\t socket.once('unauthorized', reject);\n\t socket.once('authenticated', resolve);\n\t\n\t socket[method]('authenticate', options);\n\t });\n\t}", "_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {\n const username = credentials.username;\n const password = credentials.password;\n const payload = new Binary(`\\x00${username}\\x00${password}`);\n const command = {\n saslStart: 1,\n mechanism: 'PLAIN',\n payload: payload,\n autoAuthorize: 1\n };\n\n sendAuthCommand(connection, '$external.$cmd', command, callback);\n }", "function authenticateSocket(options, socket, method) {\n\t return new Promise(function (resolve, reject) {\n\t socket.once('unauthorized', reject);\n\t socket.once('authenticated', resolve);\n\n\t socket[method]('authenticate', options);\n\t });\n\t}", "function auth(method) {\n\t\t\tvar socket = this// socket\n\t\t\t\t, args = Array.prototype.slice.call(arguments, 1);\n\n\t\t\t//TODO: authentification\n\n\t\t\t// call method\n\t\t\tioMethods[method].apply(socket, args);\n\t\t}", "function receivedAuthentication(event) {\n messageHandler.receivedAuthentication(event);\n }", "constructor(socket, cleanup) {\n this.socket = null;\n this.cleanup = null;\n this.authenticationTimeout = null;\n this.handshake = null;\n\n this.handshake = crypto.randomBytes(16).toString('base64')\n\n this.socket = socket;\n this.cleanup = cleanup;\n\n // client gets 500 ms to authenticate\n this.authenticationTimeout = setTimeout(() => { this.destroy(); }, 500);\n\n // here we ensure only our SSE servers will connect to this socket before sending data.\n this.socket.emit(protocolTopics.authenticationRequest, this.handshake, (reply) => {\n if (this.authenticate(reply) === false) { this.destroy(); return; }\n clearTimeout(this.authenticationTimeout);\n\n // add to the list of sockets that can process SSE's\n this.socket.join(EVENT_ROOM_NAME, (err) => {\n if (err) { return this.destroy(); }\n });\n\n // check if an accesstoken is valid.\n this.socket.on(protocolTopics.requestForAccessTokenCheck, (token, callback) => {\n this.handleAccessTokenRequest(token, callback);\n })\n // check if an accesstoken is valid.\n this.socket.on(protocolTopics.requestForOauthTokenCheck, (token, callback) => {\n this.handleOauthTokenRequest(token, callback);\n })\n });\n\n this.socket.on(\"disconnect\", () => { this.destroy(); });\n }", "__broker_auth(client, username, password, callback) {\n console.log('[HubManager MQTT] AUTH : ' + client.id + ' using ' + username + ':' + password);\n if (that.authConnCallback != null) {\n callback(null, that.authConnCallback(client, username, password));\n } else {\n callback(null, false); // block every auth if no callback defined\n }\n }", "function socket_connect() {\n socket = io('localhost:3000/');\n socket_emitUsername();\n socket_initSocketEventHandlers();\n}", "function authenticateSocket(options, socket, method) {\n return new Promise(function (resolve, reject) {\n socket.once('unauthorized', reject);\n socket.once('authenticated', resolve);\n\n socket[method]('authenticate', options);\n });\n}", "function startClientListener() {\n socketIO.on(\"connection\",(socket)=>{\n console.log(\"New connection. Waiting for device authentication...\");\n\n socket.on(\"device\",(data)=>{\n let type = data.type;\n console.log(\"Device authenticated as \"+type);\n\n switch(type) {\n case \"python\": pythonModule = socket; initializePythonModule(); break;\n case \"esp\": espModules.push(socket); break;\n default: console.log(\"Unknown device type...\");\n }\n });\n });\n}", "async onUpgrade(request, socket, head) {\n const { websocketAuth, websocketAuthTimeoutMs } = this.config;\n\n // Create client ID and pendingRequest.\n const clientId = makeId();\n const pendingRequest = (this._pendingAuthRequests[clientId] = {\n clientId,\n request,\n socket,\n head\n });\n\n // Toothless mode for WebSockets.\n if (!websocketAuth) {\n log.debug(`WebSocket for client ${clientId} authorized.`);\n return this.authorizeWebsocket(clientId);\n }\n\n // WebSocket authentication enabled.\n\n // Create ws_auth_request\n try {\n const wsAuthRequest = (pendingRequest.wsAuthRequest = makeWsAuthRequest(\n request,\n clientId\n ));\n log.debug(\n `Authenticating WebSocket client ${clientId} from ${\n wsAuthRequest.remoteIp\n }`\n );\n } catch (wsAuthError) {\n log.warn(`Cannot authenticate WebSocket client: ${wsAuthError}`);\n return this.rejectWebsocket(clientId, wsAuthError);\n }\n\n // Set authorization timeout handler.\n const startTimeMs = Date.now();\n pendingRequest.timeout = setTimeout(() => {\n const error = new Error(`WebSocket authentication timed out.`);\n error.code = 503;\n const deltaMs = Date.now() - startTimeMs;\n log.warn(`Socket auth check timed out after ${deltaMs} ms: ${error}`);\n this.rejectWebsocket(clientId, error);\n }, Math.max(MIN_WS_AUTH_TIMEOUT_MS, websocketAuthTimeoutMs));\n\n // Decouple response handling by emitting an event.\n log.debug(\"Emitting ws_auth_request\");\n this.emit(\"ws_auth_request\", pendingRequest.wsAuthRequest);\n }", "checkAuthenticated() {\n const { token, endpoint, sessionID } = this.authentication;\n\n if (token && endpoint && sessionID) {\n this.client.clearTimeout(this.connectTimeout);\n this.status = Constants.VoiceStatus.CONNECTING;\n /**\n * Emitted when we successfully initiate a voice connection.\n * @event VoiceConnection#authenticated\n */\n this.emit('authenticated');\n this.connect();\n }\n }", "handleInitialSocks5AuthenticationHandshakeResponse() {\n this.state = constants_1.SocksClientState.ReceivedAuthenticationResponse;\n const data = this._receiveBuffer.get(2);\n if (data[1] !== 0x00) {\n this._closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed);\n }\n else {\n this.sendSocks5CommandRequest();\n }\n }", "initSocket(callback, idhandler, userhandler) {\n this.io.on('assignment', idhandler);\n this.io.on('questionAsked', callback);\n this.io.on('newUser', userhandler);\n }", "async function auth() {\r\nclient.logger.level = 'warn'\r\nconsole.log(banner.string)\r\nclient.on('qr', qr => {\r\n console.log(color(time,\"white\"),color('[','white'),color('∆','red'),color(']','white'),color('Subscribete','white'),color('YOU','red'),color('TUBE','white'),color('Confu_Mods','yellow'))\r\n})\r\n\r\nfs.existsSync('./session.json') && client.loadAuthInfo('./session.json')\r\nclient.on('connecting', () => {\r\n\tconsole.log(color(time,\"white\"),color(\"[ESTADO]\",\"green\"), \"Conectando xd...\")\r\n})\r\nclient.on('open', () => {\r\n\tconsole.log(color(time,\"white\"),color(\"[ESTADO]\", \"green\"), \"Conectado :3\")\r\n})\r\nawait client.connect({timeoutMs: 30*1000})\r\nfs.writeFileSync('./session.json', JSON.stringify(client.base64EncodedAuthInfo(), null, '\\t'))\r\n}", "_onClientConnection(socket) {\n\t\tlogger.debug(\"Socketio connection\");\n\n\t\tsocket.emit('your_id');\n\n\t\t//socket.on('pincodeGenerated', _.bind(this.onCodeGenerated, this, socket))\n\t\tsocket.on(\"pincodeHeard\", this._onClientCodeHeard.bind(this, socket));\n\n\t\tsocket.on(\"idmobile\", this._onClientIdMobile.bind(this, socket));\n\n\t\tsocket.on(\"okToClose\", function () {\n\t\t\tsocket.disconnect();\n\t\t});\n\n\t\t//socket.on('disconnect', this.onDisconnect.bind(this, socket));\n\n\t}", "_authenticateSingleConnection(/*sendAuthCommand, connection, credentials, callback*/) {\n throw new Error('_authenticateSingleConnection must be overridden');\n }", "checkAuthenticated() {\n const { token, endpoint, sessionID } = this.authentication;\n\n if (token && endpoint && sessionID) {\n clearTimeout(this.connectTimeout);\n this.status = Constants.VoiceStatus.CONNECTING;\n /**\n * Emitted when we successfully initiate a voice connection.\n * @event VoiceConnection#authenticated\n */\n this.emit('authenticated');\n this.connect();\n }\n }", "function onSocketSecureConnect() {\n let data = _data.get(this);\n\n data.error = null;\n data.connected = true;\n\n _data.set(this, data);\n\n setImmediate(this.emit.bind(this, 'connected'));\n}", "function onConnect(socket) {\n // When the client emits 'info', this listens and executes\n socket.on('info', data => {\n socket.log(JSON.stringify(data, null, 2));\n });\n\n var id=socket.decoded_token;\n\n //Join own room\n socket.join(id._id);\n\n // Insert sockets below\n require('../api/room/room.socket').register(socket,id);\n require('../api/thing/thing.socket').register(socket);\n\n}", "function connect() {\n console.log(sock);\n\n var user = document.getElementById(\"pseudo\").value.trim();\n if (! user) return;\n document.getElementById(\"radio2\").check = true;\n id = user;\n sock.emit(\"login\", user);\n }", "async _handleAuthChallenge() {\n\n if (this._challengeResponseSent) {\n // Challenge response already sent. Checking result.\n\n if (this._socketBuffer.readUInt32BE() === 0) {\n // Auth success\n this._log('Authenticated successfully', true);\n this._authenticated = true;\n this.emit('authenticated');\n this._expectingChallenge = false;\n this._sendClientInit();\n } else {\n // Auth fail\n this._log('Authentication failed', true);\n this.emit('authError');\n this.resetState();\n }\n\n } else {\n\n this._log('Challenge received.', true);\n await this._socketBuffer.waitBytes(16, 'Auth challenge');\n\n const key = new Buffer(8);\n key.fill(0);\n key.write(this._password.slice(0, 8));\n\n this.reverseBits(key);\n\n const des1 = crypto.createCipheriv('des', key, new Buffer(8));\n const des2 = crypto.createCipheriv('des', key, new Buffer(8));\n\n const response = new Buffer(16);\n\n response.fill(des1.update(this._socketBuffer.buffer.slice(0, 8)), 0, 8);\n response.fill(des2.update(this._socketBuffer.buffer.slice(8, 16)), 8, 16);\n\n this._log('Sending response: ' + response.toString(), true, 2);\n\n this.sendData(response);\n this._challengeResponseSent = true;\n\n }\n\n }", "_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {\n const username = credentials.username;\n const password = credentials.password;\n const source = credentials.source;\n\n sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => {\n let nonce = null;\n let key = null;\n\n // Get nonce\n if (err == null) {\n nonce = r.nonce;\n // Use node md5 generator\n let md5 = crypto.createHash('md5');\n // Generate keys used for authentication\n md5.update(username + ':mongo:' + password, 'utf8');\n const hash_password = md5.digest('hex');\n // Final key\n md5 = crypto.createHash('md5');\n md5.update(nonce + username + hash_password, 'utf8');\n key = md5.digest('hex');\n }\n\n const authenticateCommand = {\n authenticate: 1,\n user: username,\n nonce,\n key\n };\n\n sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback);\n });\n }", "isAuthenticated(socket) {\n if (!socket.user.accountSK) {\n console.log('Unauthenticated socket request.');\n socket.emit('generalError', {error: 'Must be logged in.'});\n }\n\n return socket.user.accountSK;\n }", "login() {\n let _self = this;\n this._checkInit();\n let resolved = false;\n return new Promise((resolve, reject) => {\n this.on(eventTypes.LOGIN, data => {\n if(_self.onLogin) _self.onLogin(data);\n resolved = true;\n resolve(data)\n });\n // this.socket.on(eventTypes.ERROR, err => {\n // if(_self.onError) _self.onError(err);\n // if(resolved === false) {\n // reject(err);\n // }\n // })\n this.emit('login', { token: this.options.token });\n });\n }", "connect() {\n if(!this.username || !this.password) {\n return;\n }\n slsk.connect({\n user: this.username,\n pass: this.password,\n }, (err, client) => this.onConnected(err, client));\n }", "function onConnection(socket){\n console.log('connected...');\n}", "function logIntoServer()\n{\n socket.emit('logIntoServer',{id:currentServer.id,pass:loginServerPasswordInput.val()});\n}", "OnAuthenticated(string, string) {\n\n }", "@action\n authOnClient() {\n // get cookie from browser or jwt if already exist\n const token = this.jwt || cookie.get(this.cookieName);\n // force logout if token not present\n if (!token) return this.logout();\n // authorize apis on client side\n return this.jwtAuth({ token })\n .catch(err => console.error('Auth', err));\n }", "_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {\n // Create a random nonce\n crypto.randomBytes(24, (err, buff) => {\n if (err) {\n return callback(err, null);\n }\n\n return this._executeScram(\n sendAuthCommand,\n connection,\n credentials,\n buff.toString('base64'),\n callback\n );\n });\n }", "_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {\n // TODO: Destructure this\n const username = credentials.username;\n const password = credentials.password;\n const mechanismProperties = credentials.mechanismProperties;\n const gssapiServiceName =\n mechanismProperties['gssapiservicename'] ||\n mechanismProperties['gssapiServiceName'] ||\n 'mongodb';\n\n SSIPAuthenticate(\n this,\n kerberos.processes.MongoAuthProcess,\n username,\n password,\n gssapiServiceName,\n sendAuthCommand,\n connection,\n mechanismProperties,\n callback\n );\n }", "_onConnecting() {\n this.emit(\"connecting\");\n }", "_onRegisterClientConnection(socket) {\n\t\tlogger.debug(\"Register Socketio connection\");\n\n\t\tsocket.emit('your_id');\n\n\t\tsocket.on(\"pincode\", this._onRegisterClientPincode.bind(this, socket));\n\n\t\tsocket.on(\"idmobile\", this._onRegisterClientIdMobile.bind(this, socket));\n\n\t\tsocket.on(\"okToClose\", () => {\n\t\t\tsocket.disconnect();\n\t\t});\n\n\n\t}", "_handleSocketConnected() {\n this.sendClientHandshake();\n this._bsClientBush.postConnect();\n }", "onConnect() {\n this.state = constants_1.SocksClientState.Connected;\n // Send initial handshake.\n if (this._options.proxy.type === 4) {\n this.sendSocks4InitialHandshake();\n }\n else {\n this.sendSocks5InitialHandshake();\n }\n this.state = constants_1.SocksClientState.SentInitialHandshake;\n }", "function onLogin(userName, passWord, socket) {\n try{\n\n } catch(err) {\n console.error(err);\n }\n}", "function _onConnect(socket, io) {\n // When the client emits 'info', this listens and executes\n socket.on('info', function (data) {\n console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2));\n });\n\n // Insert sockets below\n require('../api/message/message.socket').register(socket, io);\n require('../api/user/user.socket').register(socket, io);\n}", "handleLogin() {\n this.authenticate();\n }", "function identify(request, response) {\n let { socket_id, channel_name } = request.body;\n\n var auth = pusher.authenticate(socket_id, channel_name, {\n // request.user.token comes from sonos-oauth.authenticated\n user_id: encrypt(request.user.token)\n });\n\n response.send(auth);\n\n // For the reconnect case, start subscribing to the related channel. If a\n // user is reconnecting, we need to subscribe again\n subscribe(channel_name, request.user.token);\n}", "startSocketHandling() {\n this.userNamespace.on('connection', (socket) => {\n logger.debug(`New socket connected to namespace ${this.userNamespace.name} + ${socket.id}`);\n\n // Register socket functions\n socket.on('getQuestions', this.getQuestions(socket));\n socket.on('answerQuestion', this.answerQuestion(socket));\n socket.on('answerOpenQuestion', this.answerOpenQuestion(socket));\n });\n }", "authorize(data, callback){ // all connecting sockets will need to authorize before doing anything else.\n // the callback is expecting some kind of user object as the second argument.\n users.findOne({ token: data.token }, callback);\n\n }", "onUnauthorized() {\n this.emit('unauthorized')\n this.disconnect()\n }", "function addHanldeOnAuthenticated(rtm, handler) {\n rtm.on(\"authenticated\", handler);\n}", "onConnect() {\n this.attempts = 1;\n this.connected = true;\n this.emit('connect');\n this.ws.on('message', msg => {\n msg = JSON.parse(msg);\n this.onMessage(msg);\n });\n }", "connect() {\n const protocol = this.config.ssl ? 'wss' : 'ws';\n const url = `${protocol}://${this.config.ip}:${this.config.port}`;\n\n log.debug('Socket - connect()', url);\n\n this.connection = null;\n\n this.connection = io(url, {\n forceNew: true,\n reconnection: false,\n upgrade: false,\n transports: ['websocket'],\n });\n\n // listens for server side errors\n this.connection.on('error', (error) => {\n log.debug('Socket - connect() - error', error);\n });\n\n // listens for websocket connection errors (ie db errors, server down, timeouts)\n this.connection.on('connect_error', (error) => {\n log.debug('Socket - connect() - server connection error', this.config.ip);\n log.error(error);\n\n this.listening = false;\n\n this.game.app.toggleLogin(false);\n this.game.app.sendError(null, 'Could not connect to the game server.');\n });\n\n // listens for socket connection attempts\n this.connection.on('connect', () => {\n log.debug('Socket - connect() - connecting to server', this.config.ip);\n this.listening = true;\n\n this.game.app.updateLoader('Preparing handshake...');\n this.connection.emit('client', {\n gVer: this.config.version,\n cType: 'HTML5',\n });\n });\n\n // listens for server side messages\n this.connection.on('message', (message) => {\n log.debug('Socket - connect() - message', message);\n this.receive(message);\n });\n\n // listens for a disconnect\n this.connection.on('disconnect', () => {\n log.debug('Socket - connect() - disconnecting');\n this.game.handleDisconnection();\n });\n }", "function socketCallback(socket) {\n\n /////////////////////////////////////////////////////////////////////////////\n // place client in a room, removing them from all other rooms\n // note: client can only join a room they are authorized to be in\n // requires:\n // payload.roomId : the room to join\n // emits to socket:\n // \"joinResponse\" of either `joined room ${payload.roomId}` or \"failed\"\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"join\", function(payload) {\n let rooms = Object.keys(socket.rooms);\n rooms.forEach( room => {\n if(room.match(/room \\d+/)) {\n socket.leave(room);\n }\n });\n verifyAuthCookie(socket, userId => {\n UserRoom.UserRoom.findAll({where: {userId: userId, roomId: payload.roomId}})\n .then( userRooms => {\n if(userRooms.length > 0) {\n socket.join(`room ${payload.roomId}`);\n socket.emit(\"joinResponse\",`joined room ${payload.roomId}`);\n } else {\n socket.emit(\"joinResponse\",\"failed\");\n }\n }).catch( () => socket.emit(\"joinResponse\",\"failed\") );\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // remove client from a room\n // requires:\n // payload.roomId : the room to leave\n // emits: nothing\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"leave\", function(payload) {\n socket.leave(`room ${payload.roomId}`);\n });\n\n\n /////////////////////////////////////////////////////////////////////////////\n // check whether client is logged in - this should only be fired\n // AFTER a successful reconnection\n // emits:\n // \"loggedInResponse\" either \"logged in\" or \"not logged in\"\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"loggedInReconnectEvent\",function(payload) {\n verifyAuthCookie(socket,\n () => socket.emit(\"loggedInReconnectEventResponse\",\"logged in\"),\n () => socket.emit(\"loggedInReconnectEventResponse\",\"not logged in\")\n );\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // user requests a lock on furniture item (no authorization here, for speed,\n // but note that furniture ID is a uuid hence effectively impossible to guess,\n // and even if guessed, all you obtain is a lock, not creation, deletion or update).\n // payload:\n // payload.furnishingId: the ID (uuid) of furnishing to lock\n // emits to socket:\n // \"lockResponse\" of either \"approved\" or \"denied\"\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"lockRequest\", function(payload) {\n verifyAuthCookie(socket, (userId,username) => {\n if(username === \"dummy\") {\n socket.emit(\"lockResponse\",\"approved\");\n } else {\n redis.get(payload.furnishingId)\n .then( result => {\n if(!result) {\n redis.set(payload.furnishingId, userId, 'PX', 2500);\n socket.emit(\"lockResponse\",\"approved\");\n } else {\n socket.emit(\"lockResponse\",\"denied\");\n }\n }).catch( () => socket.emit(\"lockResponse\",\"denied\") );\n }\n }, () => {\n socket.emit(\"lockResponse\",\"denied\");\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // notify every client to push the room to the undo stack\n // emits to room:\n // \"pushRoomToUndoStack\" passing on the payload\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"pushRoomToUndoStack\",function(payload) {\n verifyAuthCookie(socket, userId => {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n socket.to(`room ${roomId}`).emit(\"pushRoomToUndoStack\",payload);\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // notify every client to push the room to the redo stack\n // emits to room:\n // \"pushRoomToRedoStack\" passing on the payload\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"pushRoomToRedoStack\",function(payload) {\n verifyAuthCookie(socket, userId => {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n socket.to(`room ${roomId}`).emit(\"pushRoomToRedoStack\",payload);\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // notify every client to undo and persist payload to the room in DB\n // payload:\n // payload.room: the new room in object representation to persist to DB\n // emits to room:\n // \"undo\" passing on the payload\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"undo\",function(payload) {\n verifyAuthCookie(socket, userId => {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1]);\n Furnishing.Furnishing.findAll({\n where: { roomId: roomId }\n }).then( furnishings => {\n let furnishingIds = furnishings.map(furnishing => furnishing.id);\n redis.mget(furnishingIds)\n .then( result => {\n if(!result.find( val => !!val ) ) {\n persistRoom(roomId,payload.room);\n socket.to(`room ${roomId}`).emit(\"undo\",payload);\n socket.emit(\"undo\",payload);\n }\n }).catch( () => { } );\n }).catch( () => {} );\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // notify every client to redo and persist payload to the room in DB\n // payload:\n // payload.room: the new room in object representation to persist to DB\n // emits to room:\n // \"redo\" passing on the payload\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"redo\",function(payload) {\n verifyAuthCookie(socket, userId => {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1]);\n Furnishing.Furnishing.findAll({\n where: { roomId: roomId }\n }).then( furnishings => {\n let furnishingIds = furnishings.map(furnishing => furnishing.id);\n redis.mget(furnishingIds)\n .then( result => {\n if(!result.find( val => !!val ) ) {\n persistRoom(roomId,payload.room);\n socket.to(`room ${roomId}`).emit(\"redo\",payload);\n socket.emit(\"redo\",payload);\n }\n }).catch( () => { } );\n }).catch( () => {} );\n }\n });\n });\n\n\n /////////////////////////////////////////////////////////////////////////////\n // notify every client to clear the undo stack\n // emits to room:\n // \"clearUndoStack\" passing on the payload\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"clearUndoStack\",function(payload) {\n verifyAuthCookie(socket, userId => {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n socket.to(`room ${roomId}`).emit(\"clearUndoStack\",payload);\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // notify every client to clear the redo stack\n // emits to room:\n // \"clearRedoStack\" passing on the payload\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"clearRedoStack\",function(payload) {\n verifyAuthCookie(socket, userId => {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n socket.to(`room ${roomId}`).emit(\"clearRedoStack\",payload);\n }\n });\n });\n\n\n /////////////////////////////////////////////////////////////////////////////\n // user moves mouse while locked onto furniture item (does not persist!)\n // emits to room:\n // \"mouseMoved\" event passing the payload along.\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"mouseMoved\", function(payload) {\n verifyAuthCookie(socket, userId => {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n socket.to(`room ${roomId}`).emit(\"mouseMoved\",payload);\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // user refreshes timestamp on lock\n // emits to socket:\n // \"lockRefreshResponse\" of either \"approved\" or \"denied\"\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"lockRefresh\", function(payload) {\n verifyAuthCookie(socket, (userId,username) => {\n if(username === \"dummy\") {\n socket.emit(\"lockRefreshResponse\",\"approved\");\n } else {\n redis.get(payload.furnishingId)\n .then( result => {\n if(parseInt(result) === parseInt(userId)) {\n redis.set(payload.furnishingId, userId, 'PX', 2500);\n socket.emit(\"lockRefreshResponse\",\"approved\");\n } else {\n socket.emit(\"lockRefreshResponse\",\"denied\");\n }\n }).catch( () => socket.emit(\"lockRefreshResponse\",\"denied\") );\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // user releases lock on furniture item\n // payload:\n // payload.furnishing : new furnishing properties\n // emits to room:\n // \"update\" passing the payload along\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"lockRelease\", function(payload) {\n verifyAuthCookie(socket, userId => {\n if(payload && payload.furnishing) {\n redis.del(payload.furnishing.id);\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n Furnishing.Furnishing.update({...payload.furnishing, roomId: roomId},\n {where: {id:payload.furnishing.id,roomId:roomId} });\n socket.to(`room ${roomId}`).emit(\"update\",payload);\n }\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // user update color of furniture item -- update the DB and notify other users\n // payload:\n // payload.furnishingId : the ID (uuid) of the furnishing to update\n // payload.colorName : the new color name from the Color table\n // emits to room:\n // \"colorUpdate\" passing the payload along\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"updateColor\", function(payload) {\n verifyAuthCookie(socket, userId => {\n if(payload && payload.furnishingId && payload.colorName) {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n redis.get(payload.furnishingId)\n .then( result => {\n if(!result) {\n Furnishing.Furnishing.update({colorName:payload.colorName},\n {where:{id:payload.furnishingId, roomId:roomId}} );\n socket.to(`room ${roomId}`).emit(\"colorUpdate\",payload);\n socket.emit(\"colorUpdate\",payload);\n }\n }).catch(() => { } );\n }\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // room is deleted by the owner, signal other clients (does nothing to DB)\n // emits to room:\n // \"roomDeleted\"\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"roomDeleted\",function() {\n verifyAuthCookie(socket, userId => {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n socket.to(`room ${roomId}`).emit(\"roomDeleted\");\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // return client's available rooms to view\n // emits to socket:\n // \"availableRooms\" an object {availableRooms: rooms}\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"getAvailableRooms\",function(payload) {\n verifyAuthCookie(socket, userId => {\n User.User.findAll({where:{id:userId}})\n .then( users => {\n if(users.length > 0) {\n var user = users[0];\n user.getRooms().then( rooms => {\n socket.emit(\"availableRooms\",{availableRooms:rooms})\n })\n .catch( () => { } );\n }\n })\n .catch( () => { } );\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // user creates a furniture item -- persist the item to DB and notify other users\n // payload:\n // payload.furnishing an object representation of the new furnishing\n // emits to room:\n // \"create\" passing payload along\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"createFurnishing\", function(payload) {\n verifyAuthCookie(socket, userId => {\n if(payload && payload.furnishing) {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n Furnishing.Furnishing.create( {...payload.furnishing,roomId:roomId} )\n socket.to(`room ${roomId}`).emit(\"create\",payload);\n }\n }\n });\n });\n\n /////////////////////////////////////////////////////////////////////////////\n // remove client from all rooms\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"removeFromAllRooms\", function(payload) {\n let rooms = Object.keys(socket.rooms);\n rooms.forEach( room => {\n if(room.match(/room \\d+/)) {\n socket.leave(room);\n }\n });\n });\n\n\n /////////////////////////////////////////////////////////////////////////////\n // user deletes a furniture item -- delete from the database and notify other users\n // payload:\n // payload.furnishingId\n // emits to room:\n // \"delete\" passing along the payload\n /////////////////////////////////////////////////////////////////////////////\n socket.on(\"deleteFurnishing\", function(payload) {\n verifyAuthCookie(socket, userId => {\n if(payload && payload.furnishingId) {\n let rooms = Object.keys(socket.rooms);\n let roomStr = rooms.find( room => room.match(/room \\d+/))\n if(roomStr) {\n let roomId = parseInt(roomStr.split(\" \")[1])\n\n redis.get(payload.furnishingId)\n .then( result => {\n if(!result) {\n Furnishing.Furnishing.findAll( { where: { id: payload.furnishingId, roomId: roomId } } )\n .then( furnishings => {\n if(furnishings.length > 0) {\n let furnishing = furnishings[0];\n furnishing.destroy({force:true})\n }\n }).catch( () => { } )\n socket.to(`room ${roomId}`).emit(\"delete\",payload);\n socket.emit(\"delete\",payload);\n }\n }).catch( () => { } );\n }\n }\n });\n });\n}", "function handleConnection(socket, redis) {\n utils.setUserIdFromSocketId(redis, '#', socket.id).then(() => {\n console.log(`User connected from socket ${socket.id}`);\n }).catch((error) => {\n console.error('Could not create connection in cache', error);\n });\n}", "function login() {\r\n hashPassword = hash(document.getElementById(\"password01\").value);\r\n socket.emit(\"login\" , document.getElementById(\"username01\").value , hashPassword);\r\n}", "_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {\n const source = credentials.source;\n const username = credentials.username;\n const password = credentials.password;\n const mechanismProperties = credentials.mechanismProperties;\n const gssapiServiceName =\n mechanismProperties['gssapiservicename'] ||\n mechanismProperties['gssapiServiceName'] ||\n 'mongodb';\n\n GSSAPIInitialize(\n this,\n kerberos.processes.MongoAuthProcess,\n source,\n username,\n password,\n source,\n gssapiServiceName,\n sendAuthCommand,\n connection,\n mechanismProperties,\n callback\n );\n }", "function clientAuthenticate( ctx ) {\n\n /** Reject if we are not what we are looking for */\n if ( ctx.method !== \"publickey\" ||\n ctx.key.algo !== pubKey.fulltype ||\n !buffersEqual( ctx.key.data, pubKey.public )\n ) { return ctx.reject(); }\n\n /** Accept if we don't have signature */\n if ( !ctx.signature ) { return ctx.accept(); }\n\n /** Authenticate */\n const verifier = crypto.createVerify( ctx.sigAlgo );\n\n verifier.update( ctx.blob );\n\n if ( verifier.verify( pubKey.publicOrig, ctx.signature, 'binary' ) ) {\n ctx.accept();\n } else {\n ctx.reject();\n }\n\n }", "async connect(){}", "handler_AUTH(command, callback) {\n let args = command.toString().trim().split(/\\s+/);\n let method;\n let handler;\n\n args.shift(); // remove AUTH\n method = (args.shift() || '').toString().toUpperCase(); // get METHOD and keep additional arguments in the array\n handler = sasl['SASL_' + method];\n handler = handler ? handler.bind(this) : handler;\n\n if (!this.secure && this._isSupported('STARTTLS') && !this._server.options.hideSTARTTLS && !this._server.options.allowInsecureAuth) {\n this.send(538, 'Error: Must issue a STARTTLS command first');\n return callback();\n }\n\n if (this.session.user) {\n this.send(503, 'Error: No identity changes permitted');\n return callback();\n }\n\n if (!this._server.options.authMethods.includes(method) || typeof handler !== 'function') {\n this.send(504, 'Error: Unrecognized authentication type');\n return callback();\n }\n\n handler(args, callback);\n }", "handleAuthentication () {\n this.auth0.parseHash((err, authResult) => {\n console.log(authResult)\n if (authResult && authResult.accessToken && authResult.idToken) {\n this.setSession(authResult)\n } else if (err) {\n router.replace('/')\n console.log(err)\n }\n })\n }", "emitNewConnection() {\n // Get token from cookie.\n const token = localStorage.getItem('token');\n this.socket.emit('new-connection', { token });\n }", "function signInSuper() {\n\tsocket.emit('SignInSuperRequest',\"\");\n}", "requestAuth(callback) {\n callback(auth.sessionID)\n }", "init(app, server) {\n require('express-ws')(app, server);\n const utils = require('../components/utils');\n app.ws('/api/socket', function (ws, req) {\n const jwtToken = utils.getBackendToken(req);\n if (!jwtToken) {\n ws.close();\n } else {\n try {\n const userToken = jsonwebtoken.verify(jwtToken, config.get('oidc:publicKey'));\n if (userToken['realm_access'] && userToken['realm_access'].roles\n && (userToken['realm_access'].roles['includes'](config.get('server:penRequest:roleAdmin'))\n || userToken['realm_access'].roles['includes'](config.get('server:studentRequest:roleAdmin')))) {\n connectedClients.push(ws);\n } else {\n ws.close();\n }\n } catch (e) {\n log.error('error is from verify', e);\n ws.close();\n }\n }\n });\n\n }", "onAuth(client, options, request) {\n return true;\n }", "function initSocket() {\n\tg_socket = io.connect(g_server_address, {secure: true});\n}", "_authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {\n const username = credentials.username;\n const command = { authenticate: 1, mechanism: 'MONGODB-X509' };\n if (username) {\n command.user = username;\n }\n\n sendAuthCommand(connection, '$external.$cmd', command, callback);\n }", "function handleAuthRoute(state) {\n if (state.req.method === \"GET\" || state.req.method === \"HEAD\") {\n if (state.path.length === 4 && state.path[3] === \"login.html\") {\n server_types_1.serveFile(state, \"login.html\", path.join(state.settings.__assetsDir, \"authenticate\"));\n }\n else if (state.path.length === 4 && state.path[3] === \"transfer.html\") {\n server_types_1.serveFile(state, \"transfer.html\", path.join(state.settings.__assetsDir, \"authenticate\"));\n }\n else {\n state.throw(404);\n }\n return;\n }\n //state.path[3]: \"sendkey\" | \"recievekey\" | \"login\" | \"logout\" | \"pendingpin\"\n if (state.req.method !== \"POST\")\n return state.throw(405);\n if (state.path[3] === \"transfer\") {\n handleTransfer(state);\n }\n else if (state.path[3] === \"pendingpin\") {\n if (Object.keys(pko).length > 1000)\n return state.throwReason(509, \"Too many transfer requests in progress\");\n else\n state.respond(200).json({ pendingPin: getRandomPin() });\n }\n else if (state.path[3] === \"login\") {\n state.recieveBody(true).then(() => {\n if (state.body.length && !state.json)\n return; //recieve body sent a response already\n if (!state.body.length)\n return state.throwReason(400, \"Empty request body\");\n /** [username, type, timestamp, hash, sig] */\n let json = exports.parseAuthCookie(state.json.setCookie);\n if (json.length !== 5)\n return state.throwReason(400, \"Bad cookie format\");\n let { registerNotice } = state.settings.bindInfo.hostLevelPermissions[state.hostLevelPermissionsKey];\n let username = exports.validateCookie(json, registerNotice && [\n \" login attempted with unknown public key\",\n \" \" + state.json.publicKey,\n \" username: \" + json[1],\n \" timestamp: \" + json[2]\n ].join(\"\\n\"));\n if (username) {\n state.setHeader(\"Set-Cookie\", getSetCookie(\"TiddlyServerAuth\", state.json.setCookie, false, state.settings.authCookieAge));\n state.respond(200).empty();\n }\n else {\n state.throwReason(400, \"INVALID_CREDENTIALS\");\n }\n });\n }\n else if (state.path[3] === \"logout\") {\n state.setHeader(\"Set-Cookie\", getSetCookie(\"TiddlyServerAuth\", \"\", false, 0));\n state.respond(200).empty();\n }\n return;\n /* Create cookie for authentication. Can only be secured with HTTPS, otherwise anyone can \"borrow\" it */ {\n const { crypto_generichash_BYTES, crypto_sign_keypair, crypto_sign_detached, crypto_sign_verify_detached, crypto_generichash, from_base64 } = bundled_lib_1.libsodium;\n let keys = crypto_sign_keypair(\"uint8array\");\n // Never use the public key included in a message to check its signature.\n let publicHash = crypto_generichash(crypto_generichash_BYTES, keys.publicKey, undefined, \"base64\");\n let cookie = [\"key\", \"my username\", new Date().toISOString(), publicHash];\n let signed = crypto_sign_detached(cookie[0] + cookie[1] + cookie[2], keys.privateKey, \"base64\");\n cookie.push(signed);\n let request = {\n setCookie: JSON.stringify(signed),\n publicKey: keys.publicKey\n };\n //check the cookie on the server to make sure it is valid\n let valid = crypto_sign_verify_detached(from_base64(signed), cookie[0] + cookie[1] + cookie[2], keys.publicKey);\n }\n /* create secure channel for transferring private key */ {\n const { crypto_kx_client_session_keys, crypto_kx_server_session_keys, crypto_kx_keypair, from_base64, to_base64, randombytes_buf, crypto_secretbox_easy } = bundled_lib_1.libsodium;\n let clientKeys = crypto_kx_keypair(\"uint8array\");\n let clientPublicKey = to_base64(clientKeys.publicKey);\n let senderKeys = crypto_kx_keypair(\"uint8array\");\n let senderPublicKey = to_base64(senderKeys.publicKey);\n //exchange the public keys here\n let clientSession = crypto_kx_client_session_keys(clientKeys.publicKey, clientKeys.privateKey, from_base64(senderPublicKey), \"uint8array\");\n let clientCheck = bundled_lib_1.libsodium.crypto_generichash(Math.max(bundled_lib_1.libsodium.crypto_generichash_BYTES_MIN, 8), \n //server_to_client + client_to_server\n to_base64(clientSession.sharedRx) + to_base64(clientSession.sharedTx), undefined, \"uint8array\");\n let senderSession = crypto_kx_server_session_keys(senderKeys.publicKey, senderKeys.privateKey, from_base64(clientPublicKey), \"uint8array\");\n let senderCheck = bundled_lib_1.libsodium.crypto_generichash(Math.max(bundled_lib_1.libsodium.crypto_generichash_BYTES_MIN, 8), \n //server_to_client + client_to_server\n to_base64(senderSession.sharedTx) + to_base64(senderSession.sharedRx), undefined, \"uint8array\");\n // compare the two checks, they should be exactly the same\n if (senderCheck !== clientCheck)\n throw \"aghhhh!! someone messed with our key!!\";\n //encrypt the auth key on the sender\n let nonce = randombytes_buf(16);\n let encryptedKey = crypto_secretbox_easy(\"KEY PAIR OBJECT JSON\", nonce, senderSession.sharedTx, \"base64\");\n //decrypt on the client\n let decryptedKey = bundled_lib_1.libsodium.crypto_secretbox_open_easy(encryptedKey, nonce, clientSession.sharedRx);\n }\n}", "_onConnect() {\n clearTimeout(this._connectionTimeout);\n\n this.logger.info(\n {\n tnx: 'network',\n localAddress: this._socket.localAddress,\n localPort: this._socket.localPort,\n remoteAddress: this._socket.remoteAddress,\n remotePort: this._socket.remotePort\n },\n '%s established to %s:%s',\n this.secure ? 'Secure connection' : 'Connection',\n this._socket.remoteAddress,\n this._socket.remotePort\n );\n\n if (this._destroyed) {\n // Connection was established after we already had canceled it\n this.close();\n return;\n }\n\n this.stage = 'connected';\n\n // clear existing listeners for the socket\n this._socket.removeListener('data', this._onSocketData);\n this._socket.removeListener('timeout', this._onSocketTimeout);\n this._socket.removeListener('close', this._onSocketClose);\n this._socket.removeListener('end', this._onSocketEnd);\n\n this._socket.on('data', this._onSocketData);\n this._socket.once('close', this._onSocketClose);\n this._socket.once('end', this._onSocketEnd);\n\n this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT);\n this._socket.on('timeout', this._onSocketTimeout);\n\n this._greetingTimeout = setTimeout(() => {\n // if still waiting for greeting, give up\n if (this._socket && !this._destroyed && this._responseActions[0] === this._actionGreeting) {\n this._onError('Greeting never received', 'ETIMEDOUT', false, 'CONN');\n }\n }, this.options.greetingTimeout || GREETING_TIMEOUT);\n\n this._responseActions.push(this._actionGreeting);\n\n // we have a 'data' listener set up so resume socket if it was paused\n this._socket.resume();\n }", "_onConnect() {\n clearTimeout(this._connectionTimeout);\n\n this.logger.info(\n {\n tnx: 'network',\n localAddress: this._socket.localAddress,\n localPort: this._socket.localPort,\n remoteAddress: this._socket.remoteAddress,\n remotePort: this._socket.remotePort\n },\n '%s established to %s:%s',\n this.secure ? 'Secure connection' : 'Connection',\n this._socket.remoteAddress,\n this._socket.remotePort\n );\n\n if (this._destroyed) {\n // Connection was established after we already had canceled it\n this.close();\n return;\n }\n\n this.stage = 'connected';\n\n // clear existing listeners for the socket\n this._socket.removeListener('data', this._onSocketData);\n this._socket.removeListener('timeout', this._onSocketTimeout);\n this._socket.removeListener('close', this._onSocketClose);\n this._socket.removeListener('end', this._onSocketEnd);\n\n this._socket.on('data', this._onSocketData);\n this._socket.once('close', this._onSocketClose);\n this._socket.once('end', this._onSocketEnd);\n\n this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT);\n this._socket.on('timeout', this._onSocketTimeout);\n\n this._greetingTimeout = setTimeout(() => {\n // if still waiting for greeting, give up\n if (this._socket && !this._destroyed && this._responseActions[0] === this._actionGreeting) {\n this._onError('Greeting never received', 'ETIMEDOUT', false, 'CONN');\n }\n }, this.options.greetingTimeout || GREETING_TIMEOUT);\n\n this._responseActions.push(this._actionGreeting);\n\n // we have a 'data' listener set up so resume socket if it was paused\n this._socket.resume();\n }", "_onConnect() {\n clearTimeout(this._connectionTimeout);\n\n this.logger.info(\n {\n tnx: 'network',\n localAddress: this._socket.localAddress,\n localPort: this._socket.localPort,\n remoteAddress: this._socket.remoteAddress,\n remotePort: this._socket.remotePort\n },\n '%s established to %s:%s',\n this.secure ? 'Secure connection' : 'Connection',\n this._socket.remoteAddress,\n this._socket.remotePort\n );\n\n if (this._destroyed) {\n // Connection was established after we already had canceled it\n this.close();\n return;\n }\n\n this.stage = 'connected';\n\n // clear existing listeners for the socket\n this._socket.removeListener('data', this._onSocketData);\n this._socket.removeListener('timeout', this._onSocketTimeout);\n this._socket.removeListener('close', this._onSocketClose);\n this._socket.removeListener('end', this._onSocketEnd);\n\n this._socket.on('data', this._onSocketData);\n this._socket.once('close', this._onSocketClose);\n this._socket.once('end', this._onSocketEnd);\n\n this._socket.setTimeout(this.options.socketTimeout || SOCKET_TIMEOUT);\n this._socket.on('timeout', this._onSocketTimeout);\n\n this._greetingTimeout = setTimeout(() => {\n // if still waiting for greeting, give up\n if (this._socket && !this._destroyed && this._responseActions[0] === this._actionGreeting) {\n this._onError('Greeting never received', 'ETIMEDOUT', false, 'CONN');\n }\n }, this.options.greetingTimeout || GREETING_TIMEOUT);\n\n this._responseActions.push(this._actionGreeting);\n\n // we have a 'data' listener set up so resume socket if it was paused\n this._socket.resume();\n }", "connect() { socket_connect(this) }", "setupSocket() {\n this.socket = io('/gameroom');\n this.socket.on('connect', () => {\n this.socket.emit('setup_client')\n });\n this.socket.on('packet', this.handleSocketMessages)\n }", "initialize() {\n debug(\"Initializing ChatServer\");\n const io = this.io;\n io.use(this._userMiddleware());\n io.on(events.connection, (socket) => {\n this._handleNewUser(socket);\n socket.on(events.disconnect, this._handleDisconnect(socket));\n socket.on(events.messageSent, this._handleMessageSent(socket));\n });\n }", "onConnect(socket) {\r\n\t\t\r\n\t\t// Log to the console\r\n\t\tconsole.log(\"Socket \" + socket.id + \" connected\");\r\n\t\t\r\n\t\t// Create a new user\r\n\t\tlet user = new ServerUser(socket, this);\r\n\t\tthis.users[user.id] = user;\r\n\t\t\r\n\t}", "onConnect(socket) {\n // When the client emits 'info', this listens and executes\n socket.on('info', data => {\n socket.log(JSON.stringify(data, null, 2));\n });\n\n // Insert sockets below\n require('../api/thing/thing.socket').register(socket);\n }", "function configureSocketIO(io) {\n io.use(function (socket, next) {\n sessionMiddleware(socket.request, {}, next);\n }).on(\"connection\", socket => {\n let passportJSON = socket.request.session.passport;\n if (connectionsEnabled && passportJSON && passportJSON.user) {\n console.log(\"passportJSON:\", passportJSON);\n const user = User_1.getUserById(passportJSON.user);\n socket.emit(\"user\", user.toJSON());\n user.appendClient(new todoListClientSocketIO_1.TodoListClientSocketIO(socket));\n }\n else {\n if (connectionsEnabled) {\n console.log(\"Closing socket.io connection: no passport information.\");\n }\n else {\n console.log(\"Closing connection to simulate offline mode\");\n }\n socket.disconnect();\n }\n });\n}", "function socketIOinit(io)\n{\n console.log(\"running on port\");\n //python client connects\n io.on('connection',function(socket){\n // socketListeners\n // call this immediately on PC client\n socket.on('registerListener',function(data){\n console.log(\"uid: \" + data['UID']);\n var uuid = data['UID'];\n if (!socketListeners[uuid]) {\n socketListeners[uuid] = [];\n }\n socketListeners[uuid].push(socket);\n });\n\n socket.on('reqFiles',function(data){\n var client = data[\"client\"];\n var dir = data[\"dir\"];\n var file = data[\"file\"];\n console.log(\"req files\");\n requestFilesFromClient(file, dir, client, socket);\n });\n\n socket.on(\"reqEncrypt\",function(data){\n var client = data[\"client\"];\n console.log(\"req encrypt\");\n encrypt(client);\n });\n\n socket.on(\"reqDecrypt\",function(data){\n var client = data[\"client\"];\n console.log(\"req decrypt\");\n decrypt(client);\n });\n\n socket.on(\"reqKeylog\",function(data){\n var client = data[\"client\"];\n console.log(\"req keylog\");\n keylog(client,socket);\n });\n\n socket.on(\"reqWebcam\",function(data){\n var client = data[\"client\"];\n console.log(\"req webcam\");\n webcam(client,socket);\n });\n\n socket.on(\"reqScreenshot\",function(data){\n var client = data[\"client\"];\n console.log(\"req screenshot\");\n screenshot(client,socket);\n });\n\n socket.on(\"reqTTS\",function(data){\n var client = data[\"client\"];\n var text = data[\"text\"];\n console.log(\"req tts\");\n tts(client,text);\n });\n\n });\n}", "function rawSocketConnect() {\n that.debugOut('Raw socket connected');\n that.emit('raw socket connected', (that.socket.socket || that.socket));\n }", "authorizeClientConnection(callback) {\n this.authConnCallback = callback;\n }", "_initialize () {\n this.socket.on('data', data => this._sessionProtocol.chuck(data))\n this.socket.once('close', () => this.disconnect())\n }", "_onConnect() {\n console.log(\"connected\")\n }", "function loginHandler(response) {\n signInObject = JSON.parse(response);\n var email = document.getElementById(\"email1\").value;\n console.log(\"called loginHandler with email:\" + email);\n if(!signInObject.success) {\n var email1 = document.getElementById(\"email1\");\n email1.setCustomValidity(\"User doesn't exist!\");\n } else {\n //Save the token in the browser...\n sessionStorage.token = signInObject.data;\n sessionStorage.email = email; // For HMAC.\n // Initiate socket connection here...\n tsocket = new TwiddlerSocket(email, sessionStorage.token);\n console.log(\"Now waiting for socket response...\");\n /*The current view after this should be the home view */\n currentView = showHome;\n displayView();\n }\n}", "function handler(req, res){\n\n var remoteAddress = req.socket.remoteAddress;\n\n // Only process IPs in our authorised list\n if(authorisedIPs.indexOf(remoteAddress) >= 0) {\n\n try{\n if(req.method == 'POST'){\n var body = '';\n\n req.on('error',function(){\n res.writeHead(500, {\"Content-Type\": \"text/plain\"});\n res.end(\"Error\");\n });\n\n req.on('data',function(data){\n body += data;\n\n // Kill the connection if it's too large to handle\n if(body.length > 1e6){\n response.writeHead(413, {'Content-Type': 'text/plain'});\n req.connection.destroy();\n }\n });\n\n req.on('end',function(){\n var parsedBody = qs.parse(body);\n var json = JSON.stringify(parsedBody);\n\n // Emit a socket.io message to all current clients\n clients.forEach(function(client) {\n client.emit('data', json);\n });\n });\n }\n\n res.writeHead(200, {\"Content-Type\": \"text/plain\"});\n res.end(\"Ok\");\n }\n catch(error){\n res.writeHead(500, {\"Content-Type\": \"text/plain\"});\n res.end(\"Error\");\n }\n }\n else{\n res.writeHead(401, {\"Content-Type\": \"text/plain\"});\n res.end(\"Unauthorised\");\n }\n}", "function onConnect(socket) {\n // When the client emits 'info', this listens and executes\n socket.on('info', function (data) {\n console.info('[%s] %s', socket.address, JSON.stringify(data, null, 2));\n });\n\n //When the document is delete(active status is changed) 'Document:Delete' is emitted\n socket.on('Document:Delete', function (data) {\n socket.broadcast.emit('Document:Delete', data);\n});\n\n socket.on('onDisconnect', function (data) {\n socket.disconnect();\n });\n require('../api/photo/photo.socket').register(socket);\n require('../api/stamp/stamp.socket').register(socket);\n require('../api/signature/signature.socket').register(socket);\n require('../api/mobilelink/mobilelink.socket').register(socket);\n require('../api/links/links.socket').register(socket);\n require('../api/department/department.socket').register(socket);\n require('../api/otp/otp.socket').register(socket);\n require('../api/folder/folder.socket').register(socket);\n require('../api/document/document.socket').register(socket);\n require('../api/sharingpeople/sharingpeople.socket').register(socket);\n require('../api/notification/notification.socket').register(socket);\n require('../api/chat/chat.socket').register(socket);\n require('../api/onlineuser/onlineuser.socket').register(socket);\n require('../api/comment/comment.socket').register(socket);\n require('../api/fieldvalue/fieldvalue.socket').register(socket);\n require('../api/fieldoption/fieldoption.socket').register(socket);\n require('../api/documentlogs/documentlogs.socket').register(socket);\n require('../api/user/user.socket').register(socket);\n require('../api/favorite/favorite.socket').register(socket);\n}", "handleAuthentication() {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.auth0.parseHash((err, authResult) => {\n\t\t\t\tif (err) return reject(err);\n\t\t\t\tif (!authResult || !authResult.idToken) {\n\t\t\t\t\treturn reject(err);\n\t\t\t\t}\n\t\t\t\tthis.setSession(authResult);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}", "async authorizeWebsocket(clientId) {\n assert(\n isString(clientId) && clientId,\n `Client ID must be provided as a string.`\n );\n const { _wsServer: wsServer } = this;\n const pendingRequest = this._pendingAuthRequests[clientId];\n if (pendingRequest) {\n const { socket, request, head, timeout } = pendingRequest;\n clearTimeout(timeout);\n delete this._pendingAuthRequests[clientId];\n wsServer.handleUpgrade(request, socket, head, ws => {\n wsServer.emit(\"connection\", ws, request);\n });\n } else {\n log.warn(\n `Cannot authorize unknown WebSocket client \"${clientId}\", ignoring authorizeWebsocket() call.`\n );\n return;\n }\n }", "submit() {\n let data = {\n username : this.state.username,\n password : this.state.password\n };\n this.props.socket.emit('login', data);\n }", "onConnect(fn) {\n\n this.eventEmitter.on(settings.socket.connect, (data) => {\n\n fn(data)\n });\n }", "function onsocketConnected () {\n\tconsole.log(\"connected to server\"); \n}", "function connect() {\n console.log(\"connecting (csrf: \"+csrf+\")...\");\n var socket = new SockJS('/trio-websocket');\n stompClient = Stomp.over(socket);\n stompClient.debug = null;\n stompClient.connect({\"X-CSRF-TOKEN\": csrf}, function (frame) {\n console.log('... connected: ' + frame);\n stompClient.subscribe('/down/games/'+gameId, handleEvent);\n });\n}", "onAuthentication(func) {\n this._onAuthCallbacks.push(func);\n }", "init() {\n this.io.on('connection', function (socket) {\n /**\n * Triggered when a socket disconnects\n */\n socket.on('disconnect', function () {\n console.log(`[SOCKET] Client disconnected! ID: ${socket.id}`);\n });\n\n console.log(`[SOCKET] New client connected! ID: ${socket.id}`);\n });\n\n /**\n * Start listening on the right port/host for the Socket.IO server\n */\n console.log('[SYSTEM] Socket.IO started !');\n }" ]
[ "0.70052505", "0.6896481", "0.68397284", "0.6716324", "0.66483927", "0.66483927", "0.6579648", "0.6517444", "0.64907813", "0.637823", "0.6366447", "0.63660526", "0.6283011", "0.62652594", "0.6247861", "0.62061334", "0.6205211", "0.61438215", "0.6136378", "0.6128855", "0.61188793", "0.611195", "0.6107336", "0.61042076", "0.6063947", "0.60533553", "0.6052933", "0.60353523", "0.60076237", "0.5978945", "0.5971084", "0.59603137", "0.5953535", "0.5951594", "0.5944026", "0.59258974", "0.5861341", "0.58565766", "0.58477765", "0.58290136", "0.5824054", "0.5813869", "0.5808691", "0.5787496", "0.57863015", "0.57651645", "0.57632434", "0.5758106", "0.574829", "0.57478136", "0.5745415", "0.5739567", "0.5698364", "0.56951725", "0.5680939", "0.5652041", "0.5647536", "0.56454915", "0.56434655", "0.56386036", "0.5638209", "0.56326336", "0.5629869", "0.5624582", "0.56184596", "0.5616369", "0.5610097", "0.56002736", "0.5599796", "0.55828404", "0.558045", "0.5576819", "0.5574963", "0.5569967", "0.55663896", "0.5566324", "0.5566324", "0.5566324", "0.5557862", "0.5544194", "0.55426943", "0.5539161", "0.5535193", "0.55345577", "0.55266863", "0.5526462", "0.5522386", "0.5518089", "0.5515873", "0.55068415", "0.5498392", "0.54950714", "0.54905456", "0.5481003", "0.5478196", "0.54717886", "0.54669577", "0.5465328", "0.54601026", "0.5454647" ]
0.6358342
12
Utility function to parse an oldstyle tiddler DIV in a .tid file. It looks like this: The text of the tiddler (without the expected HTML encoding). Note that the field attributes are HTML encoded, but that the body of the tag is not encoded. When these tiddler DIVs are encountered within a TiddlyWiki HTML file then the body is encoded in the usual way.
function parseTiddlerDiv(text /* [,fields] */) { // Slot together the default results var result = {}; if(arguments.length > 1) { for(var f=1; f<arguments.length; f++) { var fields = arguments[f]; for(var t in fields) { result[t] = fields[t]; } } } // Parse the DIV body var startRegExp = /^\s*<div\s+([^>]*)>(\s*<pre>)?/gi, endRegExp, match = startRegExp.exec(text); if(match) { // Old-style DIVs don't have the <pre> tag if(match[2]) { endRegExp = /<\/pre>\s*<\/div>\s*$/gi; } else { endRegExp = /<\/div>\s*$/gi; } var endMatch = endRegExp.exec(text); if(endMatch) { // Extract the text result.text = text.substring(match.index + match[0].length,endMatch.index); // Process the attributes var attrRegExp = /\s*([^=\s]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi, attrMatch; do { attrMatch = attrRegExp.exec(match[1]); if(attrMatch) { var name = attrMatch[1]; var value = attrMatch[2] !== undefined ? attrMatch[2] : attrMatch[3]; result[name] = value; } } while(attrMatch); return result; } } return undefined; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function loadDiv(div, body) {\n//\ttry {\n\t\tvar divs = $(div), ts, te;\n if (!body) {\n var head = divs.find('head');\n var ty = '', st = '', t;\n if (head.length > 0) {\n var note = $(head[0]).find('note');\n // console.log(note);\n for (var n=0; n<note.length; n++) {\n // console.log(note[n]);\n if ($(note[n]).attr(\"type\") === 'start') ts = checknumber(timelineRef($(note[n]).text()));\n if ($(note[n]).attr(\"type\") === 'end') te = checknumber(timelineRef($(note[n]).text()));\n if ($(note[n]).attr(\"type\") === 'air_date') st = $(note[n]).text();\n if ($(note[n]).attr(\"type\") === 'program') ty = $(note[n]).text();\n }\n } else {\n ts = '';\n te = '';\n }\n t = trjs.utils.notnull(divs.attr(\"type\"));\n if (ty !== '' && t !== '')\n ty = t + ' ' + ty;\n else if (ty === '')\n ty = t;\n t = trjs.utils.notnull(divs.attr(\"subtype\"));\n if (t !== '') {\n if (trjs.data.textDesc != null)\n t = findTextOf(t);\n }\n if (st !== '' && t !== '')\n st = t + ' ' + ty;\n else if (st === '')\n st = t;\n loadTrans.push({loc: \"+div+\", ts: ts, te: te, tx: ty, stx: st, type: 'div'});\n }\n\t\tvar elts = divs.children();\n\t\t// copy the data from XML to container\n\t\tfor (var i = 0; i < elts.length; i++) {\n\t\t\t//console.log(\"TagName \" + \"[\" + i + \"]\" + elts[i].tagName);\n\t\t\t//console.log(\"NodeName \" + \"[\" + i + \"]\" + elts[i].nodeName); // ok pour elt et #text pour text\n\t\t\t//console.log(\"LocaName \" + \"[\" + i + \"]\" + elts[i].localName);\n\t\t\t//console.log(\"Type \" + \"[\" + i + \"]\" + elts[i].nodeType); // 1 pour elt et 3 pour text\n\t\t\t//console.log(\"Text \" + \"[\" + i + \"]\" + $(elts[i]).html());\n\t\t\tif (elts[i].nodeName === 'div')\n\t\t\t\tloadDiv(elts[i]);\n\t\t\telse if (elts[i].nodeName === 'annotationGrp' || elts[i].nodeName === 'annotationBlock')\n\t\t\t\tloadannotationBlock(elts[i]);\n\t\t\telse if (elts[i].nodeName === 'u')\n\t\t\t\tloadUIsolated(elts[i]);\n\t\t\telse if (elts[i].nodeName === 'incident') {\n\t \t\t// e += ' ' + $(elts[i]).text();\n\t\t\t\tvar e = loadIncidentContent(elts[i]);\n ts = checknumber(timelineRef($(elts[i]).attr(\"start\")));\n te = checknumber(timelineRef($(elts[i]).attr(\"end\")));\n\t\t\t\taddLineOfTranscript('+incident+', ts, te, e, 'note');\n\t\t\t} else if (elts[i].nodeName === 'pause') {\n var elt = '';\n\t\t\t\tif ($(elts[i]).attr('type') === 'short') {\n\t\t\t \telt += ' (.)';\n\t\t\t\t} else if ($(elts[i]).attr('type') === 'long') {\n\t\t\t \telt += ' (..)';\n\t\t\t\t} else if ($(elts[i]).attr('type') === 'verylong') {\n\t\t\t \telt += ' (...)';\n\t\t\t\t} else if ($(elts[i]).attr('type') === 'chrono') {\n\t\t\t\t\tvar dur = $(elts[i]).attr('dur');\n\t\t\t\t\tif (dur)\n\t\t\t\t \telt += ' (' + dur + ')';\n\t\t\t\t else\n\t\t\t\t \telt += ' (.)';\n\t\t\t\t} else {\n\t\t\t \telt += ' (.)';\n\t\t\t\t}\n ts = checknumber(timelineRef($(elts[i]).attr(\"start\")));\n te = checknumber(timelineRef($(elts[i]).attr(\"end\")));\n\t\t\t\taddLineOfTranscript('+pause+', ts, te, elt, 'note');\n\t\t\t} else if (elts[i].nodeName !== 'head') {\n\t\t\t\ttrjs.log.alert('loadDiv: unknown nodeName: ' + elts[i].nodeName);\n\t\t\t}\n\t\t}\n if (!body)\n\t loadTrans.push({loc: \"-div-\", ts: \"\", te: \"\", tx: \"\", stx: \"\", type: 'div'});\n/*\t} catch(e) {\n\t\ttrjs.log.alert('catched error ' + e.toString());\n\t\tconsole.log('catched error ' + e.toString());\n\t}\n*/\n}", "function Tiddler(nTitle, nTags, nText, nCreateTime) {\n var title, tags, createTime, text;\n\n // constructor\n\n title = nTitle;\n tags = nTags;\n text = nText;\n\n if (nCreateTime)\n createTime = nCreateTime;\n else\n createTime = new Date();\n\n // public functions\n\n this.toHtml = toHtml;\n this.getTitle = getTitle;\n this.getTags = getTags;\n this.getText = getText;\n this.containsMacro = containsMacro;\n\n // implementation\n\n function getTitle() {\n return title;\n }\n\n function getTags() {\n return tags;\n }\n\n function getText() {\n return text;\n }\n\n function containsMacro(name) {\n return (text.indexOf('<<' + name) != -1);\n }\n\n function toHtml() {\n var output = '<div tiddler=\"' + Tiddler.encodeText(title);\n\n output += '\" tags=\"';\n\n if (tags.length)\n for (var i = 0; i < tags.length; i++)\n output += Tiddler.encodeText(tags[i]) + ' ';\n\n output = output.trim();\n\n output += '\" modifier=\"' + 'twee' + '\"';\n\n output += ' created =\"' + Tiddler.encodeDate(createTime) + '\"';\n output += ' twine-position =\"' + Math.floor(Math.random() * 9999 + 1) + \",\" + Math.floor(Math.random() * 9999 + 1) + '\"';\n\n output += '>' + Tiddler.encodeText(text).trim() + '</div>';\n\n return output;\n }\n}", "function TML2HTML() {\n \n /* Constants */\n var startww = \"(^|\\\\s|\\\\()\";\n var endww = \"($|(?=[\\\\s\\\\,\\\\.\\\\;\\\\:\\\\!\\\\?\\\\)]))\";\n var PLINGWW =\n new RegExp(startww+\"!([\\\\w*=])\", \"gm\");\n var TWIKIVAR =\n new RegExp(\"^%(<nop(?:result| *\\\\/)?>)?([A-Z0-9_:]+)({.*})?$\", \"\");\n var MARKER =\n new RegExp(\"\\u0001([0-9]+)\\u0001\", \"\");\n var protocol = \"(file|ftp|gopher|https|http|irc|news|nntp|telnet|mailto)\";\n var ISLINK =\n new RegExp(\"^\"+protocol+\":|/\");\n var HEADINGDA =\n new RegExp('^---+(\\\\++|#+)(.*)$', \"m\");\n var HEADINGHT =\n new RegExp('^<h([1-6])>(.+?)</h\\\\1>', \"i\");\n var HEADINGNOTOC =\n new RegExp('(!!+|%NOTOC%)');\n var wikiword = \"[A-Z]+[a-z0-9]+[A-Z]+[a-zA-Z0-9]*\";\n var WIKIWORD =\n new RegExp(wikiword);\n var webname = \"[A-Z]+[A-Za-z0-9_]*(?:(?:[\\\\./][A-Z]+[A-Za-z0-9_]*)+)*\";\n var WEBNAME =\n new RegExp(webname);\n var anchor = \"#[A-Za-z_]+\";\n var ANCHOR =\n new RegExp(anchor);\n var abbrev = \"[A-Z]{3,}s?\\\\b\";\n var ABBREV =\n new RegExp(abbrev);\n var ISWIKILINK =\n new RegExp( \"^(?:(\"+webname+\")\\\\.)?(\"+wikiword+\")(\"+anchor+\")?\");\n var WW =\n new RegExp(startww+\"((?:(\"+webname+\")\\\\.)?(\"+wikiword+\"))\", \"gm\");\n var ITALICODE =\n new RegExp(startww+\"==(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)==\"+endww, \"gm\");\n var BOLDI =\n new RegExp(startww+\"__(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)__\"+endww, \"gm\");\n var CODE =\n new RegExp(startww+\"\\\\=(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)\\\\=\"+endww, \"gm\");\n var ITALIC =\n new RegExp(startww+\"\\\\_(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)\\\\_\"+endww, \"gm\");\n var BOLD =\n new RegExp(startww+\"\\\\*(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)\\\\*\"+endww, \"gm\");\n var NOPWW =\n new RegExp(\"<nop(?: *\\/)?>(\"+wikiword+\"|\"+abbrev+\")\", \"g\");\n var URI =\n new RegExp(\"(^|[-*\\\\s(])(\"+protocol+\":([^\\\\s<>\\\"]+[^\\s*.,!?;:)<]))\");\n\n /*\n * Main entry point, and only external function. 'options' is an object\n * that must provide the following method:\n * getViewUrl(web,topic) -> url (where topic may include an anchor)\n * and may optionally provide\n * expandVarsInURL(url, options) -> url\n * getViewUrl must generate a URL for the given web and topic.\n * expandVarsinURL gives an opportunity for a caller to expand selected\n * Macros embedded in URLs\n */\n this.convert = function(content, options) {\n this.opts = options;\n\n content = content.replace(/\\\\\\n/g, \" \");\n \n content = content.replace(/\\u0000/g, \"!\");\t\n content = content.replace(/\\u0001/g, \"!\");\t\n content = content.replace(/\\u0002/g, \"!\");\t\n \n this.refs = new Array();\n\n // Render TML constructs to tagged HTML\n return this._getRenderedVersion(content);\n };\n \n this._liftOut = function(text) {\n index = '\\u0001' + this.refs.length + '\\u0001';\n this.refs.push(text);\n return index;\n }\n \n this._dropBack = function(text) {\n var match;\n \n while (match = MARKER.exec(text)) {\n var newtext = this.refs[match[1]];\n if (newtext != match[0]) {\n var i = match.index;\n var l = match[0].length;\n text = text.substr(0, match.index) +\n newtext +\n text.substr(match.index + match[0].length);\n }\n MARKER.lastIndex = 0;\n }\n return text;\n };\n \n // Parse twiki variables.\n //for InlineEdit, would like to not nest them, and to surround entire html entities where needed\n this._processTags = function(text) {\n \n var queue = text.split(/%/);\n var stack = new Array();\n var stackTop = '';\n var prev = '';\n \n while (queue.length) {\n var token = queue.shift();\n if (stackTop.substring(-1) == '}') {\n while (stack.length && !TWIKIVAR.match(stackTop)) {\n stackTop = stack.pop() + stackTop;\n }\n }\n \n var match = TWIKIVAR.exec(stackTop);\n if (match) {\n var nop = match[1];\n var args = match[3];\n if (!args)\n args = '';\n // You can always replace the %'s here with a construct e.g.\n // html spans; however be very careful of variables that are\n // used in the context of parameters to HTML tags e.g.\n // <img src=\"%ATTACHURL%...\">\n var tag = '%' + match[2] + args + '%';\n if (nop) {\n nop = nop.replace(/[<>]/g, '');\n tag = \"<span class='TML'\"+nop+\">\"+tag+\"</span>\";\n }\n stackTop = stack.pop() + this._liftOut(tag) + token;\n } else {\n stack.push(stackTop);\n stackTop = prev + token;\n }\n prev = '%';\n }\n // Run out of input. Gather up everything in the stack.\n while (stack.length) {\n stackTop = stack.pop(stack) + stackTop;\n }\n \n return stackTop;\n };\n \n this._makeLink = function(url, text) {\n if (!text || text == '')\n text = url;\n url = this._liftOut(url);\n return \"<a href='\"+url+\"'>\" + text + \"</a>\";\n };\n \n this._expandRef = function(ref) {\n if (this.opts['expandVarsInURL']) {\n var origtxt = this.refs[ref];\n var newtxt = this.opts['expandVarsInURL'](origtxt, this.opts);\n if (newTxt != origTxt)\n return newtxt;\n }\n return '\\u0001'+ref+'\\u0001';\n };\n \n this._expandURL = function(url) {\n if (this.opts['expandVarsInURL'])\n return this.opts['expandVarsInURL'](url, this.opts);\n return url;\n };\n \n this._makeSquab = function(url, text) {\n url = _sg(MARKER, url, function(match) {\n this._expandRef(match[1]);\n }, this);\n \n if (url.test(/[<>\\\"\\x00-\\x1f]/)) {\n // we didn't manage to expand some variables in the url\n // path. Give up.\n // If we can't completely expand the URL, then don't expand\n // *any* of it (hence save)\n return text ? \"[[save][text]]\" : \"[[save]]\";\n }\n \n if (!text) {\n // forced link [[Word]] or [[url]]\n text = url;\n if (url.test(ISLINK)) {\n var wurl = url;\n wurl.replace(/(^|)(.)/g,$2.toUpperCase());\n var match = wurl.exec(ISWEB);\n if (match) {\n url = this.opts['getViewUrl'](match[1], match[2] + match[3]);\n } else {\n url = this.opts['getViewUrl'](null, wurl);\n }\n }\n } else if (match = url.exec(ISWIKILINK)) {\n // Valid wikiword expression\n url = this.optsgetViewUrl(match[1], match[2]) + match[3];\n }\n \n text.replace(WW, \"$1<nop>$2\");\n \n return this._makeLink(url, text);\n };\n \n // Lifted straight out of DevelopBranch Render.pm\n this._getRenderedVersion = function(text, refs) {\n if (!text)\n return '';\n \n this.LIST = new Array();\n this.refs = new Array();\n \n // Initial cleanup\n text = text.replace(/\\r/g, \"\");\n text = text.replace(/^\\n+/, \"\");\n text = text.replace(/\\n+$/, \"\");\n\n var removed = new BlockSafe();\n \n text = removed.takeOut(text, 'verbatim', true);\n\n // Remove PRE to prevent TML interpretation of text inside it\n text = removed.takeOut(text, 'pre', false);\n \n // change !%XXX to %<nop>XXX\n text = text.replace(/!%([A-Za-z_]+(\\{|%))/g, \"%<nop>$1\");\n\n // change <nop>%XXX to %<nopresult>XXX. A nop before th % indicates\n // that the result of the tag expansion is to be nopped\n text = text.replace(/<nop>%(?=[A-Z]+(\\{|%))/g, \"%<nopresult>\");\n \n // Pull comments\n text = _sg(/(<!--.*?-->)/, text,\n function(match) {\n this._liftOut(match[1]);\n }, this);\n \n // Remove TML pseudo-tags so they don't get protected like HTML tags\n text = text.replace(/<(.?(noautolink|nop|nopresult).*?)>/gi,\n \"\\u0001($1)\\u0001\");\n \n // Expand selected TWiki variables in IMG tags so that images appear in the\n // editor as images\n text = _sg(/(<img [^>]*src=)([\\\"\\'])(.*?)\\2/i, text,\n function(match) {\n return match[1]+match[2]+this._expandURL(match[3])+match[2];\n }, this);\n \n // protect HTML tags by pulling them out\n text = _sg(/(<\\/?[a-z]+(\\s[^>]*)?>)/i, text,\n function(match) {\n return this._liftOut(match[1]);\n }, this);\n \n var pseud = new RegExp(\"\\u0001\\((.*?)\\)\\u0001\", \"g\");\n // Replace TML pseudo-tags\n text = text.replace(pseud, \"<$1>\");\n \n // Convert TWiki tags to spans outside parameters\n text = this._processTags(text);\n \n // Change ' !AnyWord' to ' <nop>AnyWord',\n text = text.replace(PLINGWW, \"$1<nop>$2\");\n \n text = text.replace(/\\\\\\n/g, \"\"); // Join lines ending in '\\'\n \n // Blockquoted email (indented with '> ')\n text = text.replace(/^>(.*?)/gm,\n '&gt;<cite class=TMLcite>$1<br /></cite>');\n \n // locate isolated < and > and translate to entities\n // Protect isolated <!-- and -->\n text = text.replace(/<!--/g, \"\\u0000{!--\");\n text = text.replace(/-->/g, \"--}\\u0000\");\n // SMELL: this next fragment is a frightful hack, to handle the\n // case where simple HTML tags (i.e. without values) are embedded\n // in the values provided to other tags. The only way to do this\n // correctly (i.e. handle HTML tags with values as well) is to\n // parse the HTML (bleagh!)\n text = text.replace(/<(\\/[A-Za-z]+)>/g, \"{\\u0000$1}\\u0000\");\n text = text.replace(/<([A-Za-z]+(\\s+\\/)?)>/g, \"{\\u0000$1}\\u0000\");\n text = text.replace(/<(\\S.*?)>/g, \"{\\u0000$1}\\u0000\");\n // entitify lone < and >, praying that we haven't screwed up :-(\n text = text.replace(/</g, \"&lt;\");\n text = text.replace(/>/g, \"&gt;\");\n text = text.replace(/{\\u0000/g, \"<\");\n text = text.replace(/}\\u0000/g, \">\");\n \n // standard URI\n text = _sg(URI, text,\n function(match) {\n return match[1] + this._makeLink(match[2],match[2]);\n }, this);\n \n // Headings\n // '----+++++++' rule\n text = _sg(HEADINGDA, text, function(match) {\n return this._makeHeading(match[2],match[1].length);\n }, this);\n \n // Horizontal rule\n var hr = \"<hr class='TMLhr' />\";\n text = text.replace(/^---+/gm, hr);\n \n // Now we really _do_ need a line loop, to process TML\n // line-oriented stuff.\n var isList = false;\t\t// True when within a list\n var insideTABLE = false;\n this.result = new Array();\n\n var lines = text.split(/\\n/);\n for (var i in lines) {\n var line = lines[i];\n // Table: | cell | cell |\n // allow trailing white space after the last |\n if (line.match(/^(\\s*\\|.*\\|\\s*)/)) {\n if (!insideTABLE) {\n result.push(\"<table border=1 cellpadding=0 cellspacing=1>\");\n }\n result.push(this._emitTR(match[1]));\n insideTABLE = true;\n continue;\n } else if (insideTABLE) {\n result.push(\"</table>\");\n insideTABLE = false;\n }\n // Lists and paragraphs\n if (line.match(/^\\s*$/)) {\n isList = false;\n line = \"<p />\";\n }\n else if (line.match(/^\\S+?/)) {\n isList = false;\n }\n else if (line.match(/^(\\t| )+\\S/)) {\n var match;\n if (match = line.match(/^((\\t| )+)\\$\\s(([^:]+|:[^\\s]+)+?):\\s(.*)$/)) {\n // Definition list\n line = \"<dt> \"+match[3]+\" </dt><dd> \"+match[5];\n this._addListItem('dl', 'dd', match[1]);\n isList = true;\n }\n else if (match = line.match(/^((\\t| )+)(\\S+?):\\s(.*)$/)) {\n // Definition list\n line = \"<dt> \"+match[3]+\" </dt><dd> \"+match[4];\n this._addListItem('dl', 'dd', match[1]);\n isList = true;\n }\n else if (match = line.match(/^((\\t| )+)\\* (.*)$/)) {\n // Unnumbered list\n line = \"<li> \"+match[3];\n this._addListItem('ul', 'li', match[1]);\n isList = true;\n }\n else if (match = line.match(/^((\\t| )+)([1AaIi]\\.|\\d+\\.?) ?/)) {\n // Numbered list\n var ot = $3;\n ot = ot.replace(/^(.).*/, \"$1\");\n if (!ot.match(/^\\d/)) {\n ot = ' type=\"'+ot+'\"';\n } else {\n ot = '';\n }\n line.replace(/^((\\t| )+)([1AaIi]\\.|\\d+\\.?) ?/,\n \"<li\"+ot+\"> \");\n this._addListItem('ol', 'li', match[1]);\n isList = true;\n }\n } else {\n isList = false;\n }\n \n // Finish the list\n if (!isList) {\n this._addListItem('', '', '');\n }\n \n this.result.push(line);\n }\n \n if (insideTABLE) {\n this.result.push('</table>');\n }\n this._addListItem('', '', '');\n \n text = this.result.join(\"\\n\");\n text = text.replace(ITALICODE, \"$1<b><code>$2</code></b>\")\n text = text.replace(BOLDI, \"$1<b><i>$2</i></b>\");\n text = text.replace(BOLD, \"$1<b>$2</b>\")\n text = text.replace(ITALIC, \"$1<i>$2</i>\")\n text = text.replace(CODE, \"$1<code>$2</code>\");\n \n // Handle [[][] and [[]] links\n text = text.replace(/(^|\\s)\\!\\[\\[/gm, \"$1[<nop>[\");\n \n // We _not_ support [[http://link text]] syntax\n \n // detect and escape nopped [[][]]\n text = text.replace(/\\[<nop(?: *\\/)?>(\\[.*?\\](?:\\[.*?\\])?)\\]/g,\n '[<span class=\"TMLnop\">$1</span>]');\n text.replace(/!\\[(\\[.*?\\])(\\[.*?\\])?\\]/g,\n '[<span class=\"TMLnop\">$1$2</span>]');\n \n // Spaced-out Wiki words with alternative link text\n // i.e. [[1][3]]\n\n text = _sg(/\\[\\[([^\\]]*)\\](?:\\[([^\\]]+)\\])?\\]/, text,\n function(match) {\n return this._makeSquab(match[1],match[2]);\n }, this);\n \n // Handle WikiWords\n text = removed.takeOut(text, 'noautolink', true);\n \n text = text.replace(NOPWW, '<span class=\"TMLnop\">$1</span>');\n \n text = _sg(WW, text,\n function(match) {\n var url = this.opts['getViewUrl'](match[3], match[4]);\n if (match[5])\n url += match[5];\n return match[1]+this._makeLink(url, match[2]);\n }, this);\n\n text = removed.putBack(text, 'noautolink', 'div');\n \n text = removed.putBack(text, 'pre');\n \n // replace verbatim with pre in the final output\n text = removed.putBack(text, 'verbatim', 'pre',\n function(text) {\n // use escape to URL encode, then JS encode\n return HTMLEncode(text);\n });\n \n // There shouldn't be any lingering <nopresult>s, but just\n // in case there are, convert them to <nop>s so they get removed.\n text = text.replace(/<nopresult>/g, \"<nop>\");\n \n return this._dropBack(text);\n }\n \n // Make the html for a heading\n this._makeHeading = function(heading, level) {\n var notoc = '';\n if (heading.match(HEADINGNOTOC)) {\n heading = heading.substring(0, match.index) +\n heading.substring(match.index + match[0].length);\n notoc = ' notoc';\n }\n return \"<h\"+level+\" class='TML\"+notoc+\"'>\"+heading+\"</h\"+level+\">\";\n };\n\n\n this._addListItem = function(type, tag, indent) {\n indent = indent.replace(/\\t/g, \" \");\n var depth = indent.length / 3;\n var size = this.LIST.length;\n\n if (size < depth) {\n var firstTime = true;\n while (size < depth) {\n var obj = new Object();\n obj['type'] = type;\n obj['tag'] = tag;\n this.LIST.push(obj);\n if (!firstTime)\n this.result.push(\"<\"+tag+\">\");\n this.result.push(\"<\"+type+\">\");\n firstTime = false;\n size++;\n }\n } else {\n while (size > depth) {\n var types = this.LIST.pop();\n this.result.push(\"</\"+types['tag']+\">\");\n this.result.push(\"</\"+types['type']+\">\");\n size--;\n }\n if (size) {\n this.result.push(\"</this.{LIST}.[size-1].{element}>\");\n }\n }\n \n if (size) {\n var oldt = this.LIST[size-1];\n if (oldt['type'] != type) {\n this.result.push(\"</\"+oldt['type']+\">\\n<type>\");\n this.LIST.pop();\n var obj = new Object();\n obj['type'] = type;\n obj['tag'] = tag;\n this.LIST.push(obj);\n }\n }\n }\n \n this._emitTR = function(row) {\n \n row.replace(/^(\\s*)\\|/, \"\");\n var pre = 1;\n \n var tr = new Array();\n \n while (match = row.match(/^(.*?)\\|/)) {\n row = row.substring(match[0].length);\n var cell = 1;\n \n if (cell == '') {\n cell = '%SPAN%';\n }\n \n var attr = new Attrs();\n \n my (left, right) = (0, 0);\n if (cell.match(/^(\\s*).*?(\\s*)/)) {\n left = length (1);\n right = length (2);\n }\n \n if (left > right) {\n attr.set('class', 'align-right');\n attr.set('style', 'text-align: right');\n } else if (left < right) {\n attr.set('class', 'align-left');\n attr.set('style', 'text-align: left');\n } else if (left > 1) {\n attr.set('class', 'align-center');\n attr.set('style', 'text-align: center');\n }\n \n // make sure there's something there in empty cells. Otherwise\n // the editor will compress it to (visual) nothing.\n cell.replace(/^\\s*/g, \"&nbsp;\");\n \n // Removed TH to avoid problems with handling table headers. TWiki\n // allows TH anywhere, but Kupu assumes top row only, mostly.\n // See Item1185\n tr.push(\"<td \"+attr+\"> \"+cell+\" </td>\");\n }\n return pre+\"<tr>\" + tr.join('')+\"</tr>\";\n }\n}", "function parseComponent(tplc) {\n\t\tvar container = \"<html><head></head><body>\"+tplc+\"</body></html>\";\n\t\tvar parser = new DOMParser();\n\t\tvar doc = parser.parseFromString(container,\"text/html\");\n\t\t// body.innerHTML = container;\n\t\tlog(doc);\n\t\tvar body = doc.body;\n\t\tlog(body);\n\t\tvar first = body.firstChild;\n\t\tlog(first);\n\t\t\n\t\tlog(convert(first));\n\t\treturn first;\n\t}", "function htmlDecode() {\n utilitymanager_1.um.utilityManager({\n utilType: utilitymanager_1.um.TIXUtilityType.utTransform,\n sp: utilitymanager_1.um.TIXSelPolicy.Line,\n }, function (up) {\n var d = document.createElement('div');\n d.innerHTML = up.intext;\n return d.textContent;\n });\n }", "function parseSpellingBee(htmlText) {\n // If we can't find this substring, then we got back gibberish from the NY Times website.\n if (!htmlText.includes('<!DOCTYPE html>')) {\n alert(\n \"Error: Can't parse NY Times data./nUsing old NY Times data for debugging.\"\n );\n debugMode = true;\n htmlText = nytimesHTMLText;\n }\n let parser = new DOMParser();\n return parser.parseFromString(htmlText, 'text/html');\n}", "function parseHTML(str)\n{\n pParent = document.createElement('div');\n pParent.innerHTML = str;\n return pParent.firstChild;\n}", "function itemParser(text) {\n var returnText = text;\n returnText = returnText.replace(/<(script|style|title)[^<]+<\\/(script|style|title)>/gm,\"\").replace(/<(link|meta)[^>]+>/g,\"\");\n returnText = returnText.slice(returnText.indexOf(\"id=\\'right\") + 11, returnText.length);\n return returnText;\n}", "parse () {\n const place = [];\n const texts = [];\n const ids = {};\n\n const htmlParser = new htmlparser2.Parser({\n onopentag(tagname, attributes) {\n let id = uuid();\n\n ids[id] = {\n id: id,\n tag: tagname.toLowerCase(),\n attributes: attributes,\n text: null,\n descendants: []\n };\n\n // add it to all ancestors\n place.forEach(anscestorId => {\n ids[anscestorId].descendants.push(id);\n });\n\n place.push(id);\n },\n ontext(text) {\n texts.push(text.trim());\n },\n onclosetag() {\n let id = place.pop();\n\n if (id && (typeof ids[id] !== 'undefined')) {\n ids[id].text = texts.pop();\n }\n }\n });\n\n htmlParser.write(this.html);\n\n this.items = Object.values(ids);\n }", "function decodeHTML(text)\r\n{\r\n\tvar ctom = /&lt;([^&]*)&gt;/g;\r\n return text.replace(ctom,\"<$1>\");\r\n}", "decode(text){\n return new DOMParser().parseFromString(text,\"text/html\").documentElement.textContent;\n }", "function stripHtmlToText(e){var t=document.createElement(\"DIV\");t.innerHTML=e;var n=t.textContent||t.innerText||\"\";return n.replace(\"​\",\"\"),n=n.trim()}", "function sanitizeHtml(html,options,_recursing){var result='';// Used for hot swapping the result variable with an empty string in order to \"capture\" the text written to it.\nvar tempResult='';function Frame(tag,attribs){var that=this;this.tag=tag;this.attribs=attribs||{};this.tagPosition=result.length;this.text='';// Node inner text\nthis.updateParentNodeText=function(){if(stack.length){var parentFrame=stack[stack.length-1];parentFrame.text+=that.text;}};}if(!options){options=sanitizeHtml.defaults;options.parser=htmlParserDefaults;}else{options=extend(sanitizeHtml.defaults,options);if(options.parser){options.parser=extend(htmlParserDefaults,options.parser);}else{options.parser=htmlParserDefaults;}}// Tags that contain something other than HTML, or where discarding\n// the text when the tag is disallowed makes sense for other reasons.\n// If we are not allowing these tags, we should drop their content too.\n// For other tags you would drop the tag but keep its content.\nvar nonTextTagsArray=options.nonTextTags||['script','style','textarea'];var allowedAttributesMap;var allowedAttributesGlobMap;if(options.allowedAttributes){allowedAttributesMap={};allowedAttributesGlobMap={};each(options.allowedAttributes,function(attributes,tag){allowedAttributesMap[tag]=[];var globRegex=[];attributes.forEach(function(obj){if(isString(obj)&&obj.indexOf('*')>=0){globRegex.push(quoteRegexp(obj).replace(/\\\\\\*/g,'.*'));}else{allowedAttributesMap[tag].push(obj);}});allowedAttributesGlobMap[tag]=new RegExp('^('+globRegex.join('|')+')$');});}var allowedClassesMap={};each(options.allowedClasses,function(classes,tag){// Implicitly allows the class attribute\nif(allowedAttributesMap){if(!has(allowedAttributesMap,tag)){allowedAttributesMap[tag]=[];}allowedAttributesMap[tag].push('class');}allowedClassesMap[tag]=classes;});var transformTagsMap={};var transformTagsAll;each(options.transformTags,function(transform,tag){var transFun;if(typeof transform==='function'){transFun=transform;}else if(typeof transform===\"string\"){transFun=sanitizeHtml.simpleTransform(transform);}if(tag==='*'){transformTagsAll=transFun;}else{transformTagsMap[tag]=transFun;}});var depth=0;var stack=[];var skipMap={};var transformMap={};var skipText=false;var skipTextDepth=0;var parser=new htmlparser.Parser({onopentag:function onopentag(name,attribs){if(skipText){skipTextDepth++;return;}var frame=new Frame(name,attribs);stack.push(frame);var skip=false;var hasText=!!frame.text;var transformedTag;if(has(transformTagsMap,name)){transformedTag=transformTagsMap[name](name,attribs);frame.attribs=attribs=transformedTag.attribs;if(transformedTag.text!==undefined){frame.innerText=transformedTag.text;}if(name!==transformedTag.tagName){frame.name=name=transformedTag.tagName;transformMap[depth]=transformedTag.tagName;}}if(transformTagsAll){transformedTag=transformTagsAll(name,attribs);frame.attribs=attribs=transformedTag.attribs;if(name!==transformedTag.tagName){frame.name=name=transformedTag.tagName;transformMap[depth]=transformedTag.tagName;}}if(options.allowedTags&&options.allowedTags.indexOf(name)===-1||options.disallowedTagsMode==='recursiveEscape'&&!isEmptyObject(skipMap)){skip=true;skipMap[depth]=true;if(options.disallowedTagsMode==='discard'){if(nonTextTagsArray.indexOf(name)!==-1){skipText=true;skipTextDepth=1;}}skipMap[depth]=true;}depth++;if(skip){if(options.disallowedTagsMode==='discard'){// We want the contents but not this tag\nreturn;}tempResult=result;result='';}result+='<'+name;if(!allowedAttributesMap||has(allowedAttributesMap,name)||allowedAttributesMap['*']){each(attribs,function(value,a){if(!VALID_HTML_ATTRIBUTE_NAME.test(a)){// This prevents part of an attribute name in the output from being\n// interpreted as the end of an attribute, or end of a tag.\ndelete frame.attribs[a];return;}var parsed;// check allowedAttributesMap for the element and attribute and modify the value\n// as necessary if there are specific values defined.\nvar passedAllowedAttributesMapCheck=false;if(!allowedAttributesMap||has(allowedAttributesMap,name)&&allowedAttributesMap[name].indexOf(a)!==-1||allowedAttributesMap['*']&&allowedAttributesMap['*'].indexOf(a)!==-1||has(allowedAttributesGlobMap,name)&&allowedAttributesGlobMap[name].test(a)||allowedAttributesGlobMap['*']&&allowedAttributesGlobMap['*'].test(a)){passedAllowedAttributesMapCheck=true;}else if(allowedAttributesMap&&allowedAttributesMap[name]){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator10=allowedAttributesMap[name][Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator10.next()).done);_iteratorNormalCompletion=true){var o=_step.value;if(isPlainObject(o)&&o.name&&o.name===a){passedAllowedAttributesMapCheck=true;var newValue='';if(o.multiple===true){// verify the values that are allowed\nvar splitStrArray=value.split(' ');var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator11=splitStrArray[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator11.next()).done);_iteratorNormalCompletion2=true){var s=_step2.value;if(o.values.indexOf(s)!==-1){if(newValue===''){newValue=s;}else{newValue+=' '+s;}}}}catch(err){_didIteratorError2=true;_iteratorError2=err;}finally{try{if(!_iteratorNormalCompletion2&&_iterator11[\"return\"]!=null){_iterator11[\"return\"]();}}finally{if(_didIteratorError2){throw _iteratorError2;}}}}else if(o.values.indexOf(value)>=0){// verified an allowed value matches the entire attribute value\nnewValue=value;}value=newValue;}}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator10[\"return\"]!=null){_iterator10[\"return\"]();}}finally{if(_didIteratorError){throw _iteratorError;}}}}if(passedAllowedAttributesMapCheck){if(options.allowedSchemesAppliedToAttributes.indexOf(a)!==-1){if(naughtyHref(name,value)){delete frame.attribs[a];return;}}if(name==='iframe'&&a==='src'){var allowed=true;try{// naughtyHref is in charge of whether protocol relative URLs\n// are cool. We should just accept them\nparsed=url.parse(value,false,true);var isRelativeUrl=parsed&&parsed.host===null&&parsed.protocol===null;if(isRelativeUrl){// default value of allowIframeRelativeUrls is true unless allowIframeHostnames specified\nallowed=has(options,\"allowIframeRelativeUrls\")?options.allowIframeRelativeUrls:!options.allowedIframeHostnames;}else if(options.allowedIframeHostnames){allowed=options.allowedIframeHostnames.find(function(hostname){return hostname===parsed.hostname;});}}catch(e){// Unparseable iframe src\nallowed=false;}if(!allowed){delete frame.attribs[a];return;}}if(a==='srcset'){try{parsed=srcset.parse(value);each(parsed,function(value){if(naughtyHref('srcset',value.url)){value.evil=true;}});parsed=filter(parsed,function(v){return!v.evil;});if(!parsed.length){delete frame.attribs[a];return;}else{value=srcset.stringify(filter(parsed,function(v){return!v.evil;}));frame.attribs[a]=value;}}catch(e){// Unparseable srcset\ndelete frame.attribs[a];return;}}if(a==='class'){value=filterClasses(value,allowedClassesMap[name]);if(!value.length){delete frame.attribs[a];return;}}if(a==='style'){try{var abstractSyntaxTree=postcss.parse(name+\" {\"+value+\"}\");var filteredAST=filterCss(abstractSyntaxTree,options.allowedStyles);value=stringifyStyleAttributes(filteredAST);if(value.length===0){delete frame.attribs[a];return;}}catch(e){delete frame.attribs[a];return;}}result+=' '+a;if(value&&value.length){result+='=\"'+escapeHtml(value,true)+'\"';}}else{delete frame.attribs[a];}});}if(options.selfClosing.indexOf(name)!==-1){result+=\" />\";}else{result+=\">\";if(frame.innerText&&!hasText&&!options.textFilter){result+=frame.innerText;}}if(skip){result=tempResult+escapeHtml(result);tempResult='';}},ontext:function ontext(text){if(skipText){return;}var lastFrame=stack[stack.length-1];var tag;if(lastFrame){tag=lastFrame.tag;// If inner text was set by transform function then let's use it\ntext=lastFrame.innerText!==undefined?lastFrame.innerText:text;}if(options.disallowedTagsMode==='discard'&&(tag==='script'||tag==='style')){// htmlparser2 gives us these as-is. Escaping them ruins the content. Allowing\n// script tags is, by definition, game over for XSS protection, so if that's\n// your concern, don't allow them. The same is essentially true for style tags\n// which have their own collection of XSS vectors.\nresult+=text;}else{var escaped=escapeHtml(text,false);if(options.textFilter){result+=options.textFilter(escaped,tag);}else{result+=escaped;}}if(stack.length){var frame=stack[stack.length-1];frame.text+=text;}},onclosetag:function onclosetag(name){if(skipText){skipTextDepth--;if(!skipTextDepth){skipText=false;}else{return;}}var frame=stack.pop();if(!frame){// Do not crash on bad markup\nreturn;}skipText=false;depth--;var skip=skipMap[depth];if(skip){delete skipMap[depth];if(options.disallowedTagsMode==='discard'){frame.updateParentNodeText();return;}tempResult=result;result='';}if(transformMap[depth]){name=transformMap[depth];delete transformMap[depth];}if(options.exclusiveFilter&&options.exclusiveFilter(frame)){result=result.substr(0,frame.tagPosition);return;}frame.updateParentNodeText();if(options.selfClosing.indexOf(name)!==-1){// Already output />\nreturn;}result+=\"</\"+name+\">\";if(skip){result=tempResult+escapeHtml(result);tempResult='';}}},options.parser);parser.write(html);parser.end();return result;function escapeHtml(s,quote){if(typeof s!=='string'){s=s+'';}if(options.parser.decodeEntities){s=s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/\\>/g,'&gt;');if(quote){s=s.replace(/\\\"/g,'&quot;');}}// TODO: this is inadequate because it will pass `&0;`. This approach\n// will not work, each & must be considered with regard to whether it\n// is followed by a 100% syntactically valid entity or not, and escaped\n// if it is not. If this bothers you, don't set parser.decodeEntities\n// to false. (The default is true.)\ns=s.replace(/&(?![a-zA-Z0-9#]{1,20};)/g,'&amp;')// Match ampersands not part of existing HTML entity\n.replace(/</g,'&lt;').replace(/\\>/g,'&gt;');if(quote){s=s.replace(/\\\"/g,'&quot;');}return s;}function naughtyHref(name,href){// Browsers ignore character codes of 32 (space) and below in a surprising\n// number of situations. Start reading here:\n// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab\n// eslint-disable-next-line no-control-regex\nhref=href.replace(/[\\x00-\\x20]+/g,'');// Clobber any comments in URLs, which the browser might\n// interpret inside an XML data island, allowing\n// a javascript: URL to be snuck through\nhref=href.replace(/<\\!\\-\\-.*?\\-\\-\\>/g,'');// Case insensitive so we don't get faked out by JAVASCRIPT #1\nvar matches=href.match(/^([a-zA-Z]+)\\:/);if(!matches){// Protocol-relative URL starting with any combination of '/' and '\\'\nif(href.match(/^[\\/\\\\]{2}/)){return!options.allowProtocolRelative;}// No scheme\nreturn false;}var scheme=matches[1].toLowerCase();if(has(options.allowedSchemesByTag,name)){return options.allowedSchemesByTag[name].indexOf(scheme)===-1;}return!options.allowedSchemes||options.allowedSchemes.indexOf(scheme)===-1;}/**\n * Filters user input css properties by whitelisted regex attributes.\n *\n * @param {object} abstractSyntaxTree - Object representation of CSS attributes.\n * @property {array[Declaration]} abstractSyntaxTree.nodes[0] - Each object cointains prop and value key, i.e { prop: 'color', value: 'red' }.\n * @param {object} allowedStyles - Keys are properties (i.e color), value is list of permitted regex rules (i.e /green/i).\n * @return {object} - Abstract Syntax Tree with filtered style attributes.\n */function filterCss(abstractSyntaxTree,allowedStyles){if(!allowedStyles){return abstractSyntaxTree;}var filteredAST=cloneDeep(abstractSyntaxTree);var astRules=abstractSyntaxTree.nodes[0];var selectedRule;// Merge global and tag-specific styles into new AST.\nif(allowedStyles[astRules.selector]&&allowedStyles['*']){selectedRule=mergeWith(cloneDeep(allowedStyles[astRules.selector]),allowedStyles['*'],function(objValue,srcValue){if(Array.isArray(objValue)){return objValue.concat(srcValue);}});}else{selectedRule=allowedStyles[astRules.selector]||allowedStyles['*'];}if(selectedRule){filteredAST.nodes[0].nodes=astRules.nodes.reduce(filterDeclarations(selectedRule),[]);}return filteredAST;}/**\n * Extracts the style attribues from an AbstractSyntaxTree and formats those\n * values in the inline style attribute format.\n *\n * @param {AbstractSyntaxTree} filteredAST\n * @return {string} - Example: \"color:yellow;text-align:center;font-family:helvetica;\"\n */function stringifyStyleAttributes(filteredAST){return filteredAST.nodes[0].nodes.reduce(function(extractedAttributes,attributeObject){extractedAttributes.push(attributeObject.prop+':'+attributeObject.value);return extractedAttributes;},[]).join(';');}/**\n * Filters the existing attributes for the given property. Discards any attributes\n * which don't match the whitelist.\n *\n * @param {object} selectedRule - Example: { color: red, font-family: helvetica }\n * @param {array} allowedDeclarationsList - List of declarations which pass whitelisting.\n * @param {object} attributeObject - Object representing the current css property.\n * @property {string} attributeObject.type - Typically 'declaration'.\n * @property {string} attributeObject.prop - The CSS property, i.e 'color'.\n * @property {string} attributeObject.value - The corresponding value to the css property, i.e 'red'.\n * @return {function} - When used in Array.reduce, will return an array of Declaration objects\n */function filterDeclarations(selectedRule){return function(allowedDeclarationsList,attributeObject){// If this property is whitelisted...\nif(selectedRule.hasOwnProperty(attributeObject.prop)){var matchesRegex=selectedRule[attributeObject.prop].some(function(regularExpression){return regularExpression.test(attributeObject.value);});if(matchesRegex){allowedDeclarationsList.push(attributeObject);}}return allowedDeclarationsList;};}function filterClasses(classes,allowed){if(!allowed){// The class attribute is allowed without filtering on this tag\nreturn classes;}classes=classes.split(/\\s+/);return classes.filter(function(clss){return allowed.indexOf(clss)!==-1;}).join(' ');}}// Defaults are accessible to you so that you can use them as a starting point", "function decode(line) {\n var temp = $(\"<div/>\").html(line).text();\n var temp2 = temp.replace(\"<tab>\", \"\");\n var decoded = temp2.replace(\"</tab>\", \"\");\n return decoded;\n}", "function unescapeHtml(text){\n if( !text ) return;\n var tL, cleanRet='', temp = createEl('div',{},text);\n tL = temp.childNodes.length;\n for(var i=0; i<tL; i++){\n if( typeof(temp.childNodes[i])!='object' ) continue;\n cleanRet += (function (t){\n return t.replace( /\\&\\#(\\d+);/g, function( ent, cG ){return String.fromCharCode( parseInt( cG ) )})\n })(temp.childNodes[i].nodeValue);\n }\n try{ temp.removeChild(temp.firstChild) }catch(e){}\n return cleanRet;\n}", "function yellHTMLDecode(value) {\n var temp = document.createElement(\"div\");\n temp.innerHTML = value;\n var result = temp.childNodes[0].nodeValue;\n temp.removeChild(temp.firstChild);\n return result;\n}", "function TTMLParser() {\n\n let context = this.context;\n let log = Debug(context).getInstance().log;\n\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n let instance,\n timingRegex,\n ttml, // contains the whole ttml document received\n ttmlStyling, // contains the styling information from the document (from head following EBU-TT-D)\n ttmlLayout, // contains the positioning information from the document (from head following EBU-TT-D)\n fontSize,\n lineHeight,\n linePadding,\n defaultLayoutProperties,\n defaultStyleProperties,\n fontFamilies,\n textAlign,\n multiRowAlign,\n wrapOption,\n unicodeBidi,\n displayAlign,\n writingMode,\n videoModel,\n converter;\n\n let cueCounter = 0; // Used to give every cue a unique ID.\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n }\n\n /**\n * Get the begin-end interval if present, or null otherwise.\n *\n * @param {Object} element - TTML element which may have begin and end attributes\n */\n function getInterval(element) {\n if (element.hasOwnProperty('begin') && element.hasOwnProperty('end')) {\n let beginTime = parseTimings(element.begin);\n let endTime = parseTimings(element.end);\n return [beginTime, endTime];\n } else {\n return null;\n }\n }\n\n function getCueID() {\n let id = 'cue_TTML_' + cueCounter;\n cueCounter++;\n return id;\n }\n\n /*\n * Create list of intervals where spans start and end. Empty list if no times.\n * Clip to interval using startInterval and endInterval and add these two times.\n * Also support case when startInterval/endInteval not given (sideloaded file)\n *\n * @param {Array} spans - array of span elements\n */\n function createSpanIntervalList(spans, startInterval, endInterval) {\n\n let spanChangeTimes = [];\n let spanChangeTimeStrings = [];\n let cue_intervals = [];\n\n function addSpanTime(span, name) {\n if (span.hasOwnProperty(name)) {\n let timeString = span[name];\n if (spanChangeTimeStrings.indexOf(timeString) < 0) {\n spanChangeTimeStrings.push(timeString);\n }\n }\n }\n\n for (let i = 0; i < spans.length; i++) {\n let span = spans[i];\n addSpanTime(span, 'begin');\n addSpanTime(span, 'end');\n }\n if (spanChangeTimeStrings.length === 0) {\n return cue_intervals; // No span timing so no intervals.\n }\n\n if (typeof startInterval !== 'undefined' && typeof endInterval !== 'undefined' ) {\n for (let i = 0; i < spanChangeTimeStrings.length; i++) {\n let changeTime = parseTimings(spanChangeTimeStrings[i]);\n if (startInterval < changeTime && changeTime < endInterval) {\n spanChangeTimes.push(changeTime);\n }\n }\n spanChangeTimes.push(startInterval);\n spanChangeTimes.push(endInterval);\n } else {\n for (let i = 0; i < spanChangeTimeStrings.length; i++) {\n spanChangeTimes.push(parseTimings(spanChangeTimeStrings[i]));\n }\n }\n spanChangeTimes.sort(function (a, b) { return a - b;});\n for (let i = 0; i < spanChangeTimes.length - 1; i++) {\n cue_intervals.push([spanChangeTimes[i], spanChangeTimes[i + 1]]);\n }\n return cue_intervals;\n }\n\n\n function clipStartTime(startTime, intervalStart) {\n if (typeof startInterval !== 'undefined') {\n if (startTime < intervalStart) {\n startTime = intervalStart;\n }\n }\n return startTime;\n }\n\n\n function clipEndTime(endTime, intervalEnd) {\n if (typeof intervalEnd !== 'undefined') {\n if (endTime > intervalEnd) {\n endTime = intervalEnd;\n }\n }\n return endTime;\n }\n\n /*\n * Get interval from entity that has begin and end properties.\n * If intervalStart and intervalEnd defined, use them to clip the interval.\n * Return null if no overlap with interval\n */\n function getClippedInterval(entity, intervalStart, intervalEnd) {\n let startTime = parseTimings(entity.begin);\n let endTime = parseTimings(entity.end);\n startTime = clipStartTime(startTime, intervalStart);\n endTime = clipEndTime(endTime, intervalEnd);\n if (typeof intervalStart !== 'undefined' && typeof intervalEnd !== 'undefined') {\n if (endTime < intervalStart || startTime > intervalEnd) {\n log('TTML: Cue ' + startTime + '-' + endTime + ' outside interval ' +\n intervalStart + '-' + intervalEnd);\n return null;\n }\n }\n return [startTime, endTime];\n }\n\n /*\n * Check if entity timing has some overlap with interval\n */\n function inIntervalOrNoTiming(entity, interval) {\n let inInterval = true;\n if (entity.hasOwnProperty('span')) {\n let entityInterval = getInterval(entity.span);\n if (entityInterval !== null) { //Timing\n inInterval = (entityInterval[0] < interval[1] && entityInterval[1] > interval[0]);\n }\n }\n return inInterval;\n }\n\n /**\n * Parse the raw data and process it to return the HTML element representing the cue.\n * Return the region to be processed and controlled (hide/show) by the caption controller.\n * @param {string} data - raw data received from the TextSourceBuffer\n * @param {number} intervalStart\n * @param {number} intervalEnd\n * @param {array} imageArray - images represented as binary strings\n */\n\n function parse(data, intervalStart, intervalEnd, imageArray) {\n let tt, // Top element\n head, // head in tt\n body, // body in tt\n ttExtent, // extent attribute of tt element\n type,\n i;\n\n var errorMsg = '';\n\n // Parse the TTML in a JSON object.\n ttml = converter.xml_str2json(data);\n\n if (!ttml) {\n throw new Error('TTML document could not be parsed');\n }\n\n if (videoModel.getTTMLRenderingDiv()) {\n type = 'html';\n }\n\n // Check the document and compare to the specification (TTML and EBU-TT-D).\n tt = ttml.tt;\n if (!tt) {\n throw new Error('TTML document lacks tt element');\n }\n\n // Get the namespace if there is one defined in the JSON object.\n var ttNS = getNamespacePrefix(tt, 'http://www.w3.org/ns/ttml');\n\n // Remove the namespace before each node if it exists:\n if (ttNS) {\n removeNamespacePrefix(tt, ttNS);\n }\n\n ttExtent = tt['tts:extent']; // Should check that tts is right namespace.\n\n head = tt.head;\n if (!head) {\n throw new Error('TTML document lacks head element');\n }\n if (head.layout) {\n ttmlLayout = head.layout.region_asArray; //Mandatory in EBU-TT-D\n }\n if (head.styling) {\n ttmlStyling = head.styling.style_asArray; // Mandatory in EBU-TT-D\n }\n\n let imageDataUrls = {};\n\n if (imageArray) {\n for (i = 0; i < imageArray.length; i++) {\n let key = 'urn:mpeg:14496-30:subs:' + (i + 1).toString();\n let dataUrl = 'data:image/png;base64,' + btoa(imageArray[i]);\n imageDataUrls[key] = dataUrl;\n }\n }\n\n if (head.metadata) {\n let embeddedImages = head.metadata.image_asArray; // Handle embedded images\n if (embeddedImages) {\n for (i = 0; i < embeddedImages.length; i++) {\n let key = '#' + embeddedImages[i]['xml:id'];\n let imageType = embeddedImages[i].imagetype.toLowerCase();\n let dataUrl = 'data:image/' + imageType + ';base64,' + embeddedImages[i].__text;\n imageDataUrls[key] = dataUrl;\n }\n }\n }\n\n body = tt.body;\n if (!body) {\n throw new Error('TTML document lacks body element');\n }\n\n // Extract the cellResolution information\n var cellResolution = getCellResolution();\n\n // Recover the video width and height displayed by the player.\n var videoWidth = videoModel.getElement().clientWidth;\n var videoHeight = videoModel.getElement().clientHeight;\n\n // Compute the CellResolution unit in order to process properties using sizing (fontSize, linePadding, etc).\n var cellUnit = [videoWidth / cellResolution[0], videoHeight / cellResolution[1]];\n defaultStyleProperties['font-size'] = cellUnit[1] + 'px;';\n\n var regions = [];\n if (ttmlLayout) {\n for (i = 0; i < ttmlLayout.length; i++) {\n regions.push(processRegion(JSON.parse(JSON.stringify(ttmlLayout[i])), cellUnit));\n }\n }\n\n // Get the namespace prefix.\n var nsttp = getNamespacePrefix(ttml.tt, 'http://www.w3.org/ns/ttml#parameter');\n\n // Set the framerate.\n if (tt.hasOwnProperty(nsttp + ':frameRate')) {\n tt.frameRate = parseInt(tt[nsttp + ':frameRate'], 10);\n }\n var captionArray = [];\n // Extract the div\n var divs = tt.body_asArray[0].__children;\n\n // Timing is either on div, paragraph or span level.\n\n for (let k = 0; k < divs.length; k++) {\n let div = divs[k].div;\n let divInterval = null; // This is mainly for image subtitles.\n\n if (null !== (divInterval = getInterval(div))) {\n // Timing on div level is not allowed by EBU-TT-D.\n // We only use it for SMPTE-TT image subtitle profile.\n\n // Layout should be defined by a region. Given early test material, we also support that it is on\n // div level\n let layout;\n if (div.region) {\n let region = findRegionFromID(ttmlLayout, div.region);\n layout = getRelativePositioning(region, ttExtent);\n }\n if (!layout) {\n layout = getRelativePositioning(div, ttExtent);\n }\n\n let imgKey = div['smpte:backgroundImage'];\n if (imgKey !== undefined && imageDataUrls[imgKey] !== undefined) {\n captionArray.push({\n start: divInterval[0],\n end: divInterval[1],\n id: getCueID(),\n data: imageDataUrls[imgKey],\n type: 'image',\n layout: layout\n });\n }\n continue; // Next div\n }\n\n let paragraphs = div.p_asArray;\n // Check if cues is not empty or undefined.\n if (divInterval === null && (!paragraphs || paragraphs.length === 0)) {\n errorMsg = 'TTML has div that contains no timing and no paragraphs.';\n log(errorMsg);\n return captionArray;\n }\n\n for (let j2 = 0; j2 < paragraphs.length; j2++) {\n let paragraph = paragraphs[j2];\n let spans = paragraph.span_asArray;\n let cueIntervals = [];\n // For timing, the overall goal is to find the intervals where there should be cues\n // The timing may either be on paragraph or span level.\n if (paragraph.hasOwnProperty('begin') && paragraph.hasOwnProperty('end')) {\n // Timing on paragraph level\n let clippedInterval = getClippedInterval(paragraph, intervalStart, intervalEnd);\n if (clippedInterval !== null) {\n cueIntervals.push(clippedInterval);\n }\n } else {\n // Timing must be on span level\n cueIntervals = createSpanIntervalList(spans, intervalStart, intervalEnd);\n }\n if (cueIntervals.length === 0) {\n errorMsg = 'TTML: Empty paragraph';\n continue; // Nothing in this paragraph\n }\n\n let paragraphChildren = paragraph.__children;\n\n for (let i2 = 0; i2 < cueIntervals.length; i2++) {\n let interval = cueIntervals[i2];\n let childrenInInterval = [];\n for (let k2 = 0; k2 < paragraphChildren.length; k2++) {\n let child = paragraphChildren[k2];\n if (inIntervalOrNoTiming(child, interval)) {\n childrenInInterval.push(child);\n }\n }\n if (childrenInInterval.length === 0) {\n continue; // No children to render\n }\n\n if (type === 'html') {\n lineHeight = {};\n linePadding = {};\n fontSize = {};\n\n /**\n * Find the region defined for the cue.\n */\n // properties to be put in the \"captionRegion\" HTML element.\n var cueRegionProperties = constructCueRegion(paragraph, div, cellUnit);\n\n /**\n * Find the style defined for the cue.\n */\n // properties to be put in the \"paragraph\" HTML element.\n var cueStyleProperties = constructCueStyle(paragraph, cellUnit);\n\n /**\n * /!\\ Create the cue HTML Element containing the whole cue.\n */\n var styleIDs = cueStyleProperties[1];\n cueStyleProperties = cueStyleProperties[0];\n\n // Final cue HTML element.\n var cueParagraph = document.createElement('div');\n cueParagraph.className = styleIDs;\n\n // Create a wrapper containing the cue information about unicodeBidi and direction\n // as they need to be defined on at this level.\n // We append to the wrapper the cue itself.\n var cueDirUniWrapper = constructCue(childrenInInterval, cellUnit);\n cueDirUniWrapper.className = 'cueDirUniWrapper';\n\n // If the style defines these two properties, we place them in cueContainer\n // and delete them from the cue style so it is not added afterwards to the final cue.\n if (arrayContains('unicode-bidi', cueStyleProperties)) {\n cueDirUniWrapper.style.cssText += getPropertyFromArray('unicode-bidi', cueStyleProperties);\n deletePropertyFromArray('unicode-bidi', cueStyleProperties);\n }\n if (arrayContains('direction', cueStyleProperties)) {\n cueDirUniWrapper.style.cssText += getPropertyFromArray('direction', cueStyleProperties);\n deletePropertyFromArray('direction', cueStyleProperties);\n }\n\n // Apply the linePadding property if it is specified in the cue style.\n if (arrayContains('padding-left', cueStyleProperties) && arrayContains('padding-right', cueStyleProperties)) {\n cueDirUniWrapper.innerHTML = applyLinePadding(cueDirUniWrapper, cueStyleProperties);\n }\n\n /**\n * Clean and set the style and region for the cue to be returned.\n */\n\n // Remove the line padding property from being added at the \"paragraph\" element level.\n if (arrayContains('padding-left', cueStyleProperties) && arrayContains('padding-right', cueStyleProperties)) {\n deletePropertyFromArray('padding-left', cueStyleProperties);\n deletePropertyFromArray('padding-right', cueStyleProperties);\n }\n\n // Remove the ID of the region from being added at the \"paragraph\" element level.\n var regionID = '';\n if (arrayContains('regionID', cueRegionProperties)) {\n var wholeRegionID = getPropertyFromArray('regionID', cueRegionProperties);\n regionID = wholeRegionID.slice(wholeRegionID.indexOf(':') + 1, wholeRegionID.length - 1);\n }\n\n // We link the p style to the finale cueParagraph element.\n if (cueStyleProperties) {\n cueParagraph.style.cssText = cueStyleProperties.join(' ') + 'display:flex;';\n }\n // We define the CSS style for the cue region.\n if (cueRegionProperties) {\n cueRegionProperties = cueRegionProperties.join(' ');\n }\n\n // We then place the cue wrapper inside the paragraph element.\n cueParagraph.appendChild(cueDirUniWrapper);\n\n // Final cue.\n var finalCue = document.createElement('div');\n finalCue.appendChild(cueParagraph);\n finalCue.id = getCueID();\n finalCue.style.cssText = 'position: absolute; margin: 0; display: flex; box-sizing: border-box; pointer-events: none;' + cueRegionProperties;\n\n if (Object.keys(fontSize).length === 0) {\n fontSize.defaultFontSize = '100';\n }\n\n // We add all the cue information in captionArray.\n captionArray.push({\n start: interval[0],\n end: interval[1],\n type: 'html',\n cueHTMLElement: finalCue,\n regions: regions,\n regionID: regionID,\n cueID: finalCue.id,\n videoHeight: videoHeight,\n videoWidth: videoWidth,\n cellResolution: cellResolution,\n fontSize: fontSize || {\n defaultFontSize: '100'\n },\n lineHeight: lineHeight,\n linePadding: linePadding\n });\n\n } else {\n var text = '';\n var textElements = childrenInInterval;\n if (textElements.length) {\n textElements.forEach(function (el) {\n if (el.hasOwnProperty('span')) {\n var spanElements = el.span.__children;\n spanElements.forEach(function (spanEl) {\n // If metadata is present, do not process.\n if (spanElements.hasOwnProperty('metadata')) {\n return;\n }\n // If the element is a string\n if (spanEl.hasOwnProperty('#text')) {\n text += spanEl['#text'].replace(/[\\r\\n]+/gm, ' ').trim();\n // If the element is a 'br' tag\n } else if ('br' in spanEl) {\n // Create a br element.\n text += '\\n';\n }\n });\n } else if (el.hasOwnProperty('br')) {\n text += '\\n';\n } else {\n text += el['#text'].replace(/[\\r\\n]+/gm, ' ').trim();\n }\n });\n }\n\n captionArray.push({\n start: interval[0],\n end: interval[1],\n data: text,\n type: 'text'\n });\n }\n }\n }\n }\n\n if (errorMsg !== '') {\n log(errorMsg);\n }\n\n if (captionArray.length > 0) {\n return captionArray;\n } else { // This seems too strong given that there are segments with no TTML subtitles\n throw new Error(errorMsg);\n }\n }\n\n function setup() {\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n timingRegex = /^([0-9][0-9]+):([0-5][0-9]):([0-5][0-9])|(60)(\\.([0-9])+)?$/; // Regex defining the time\n fontSize = {};\n lineHeight = {};\n linePadding = {};\n defaultLayoutProperties = {\n 'top': 'auto;',\n 'left': 'auto;',\n 'width': '90%;',\n 'height': '10%;',\n 'align-items': 'flex-start;',\n 'overflow': 'visible;',\n '-ms-writing-mode': 'lr-tb, horizontal-tb;',\n '-webkit-writing-mode': 'horizontal-tb;',\n '-moz-writing-mode': 'horizontal-tb;',\n 'writing-mode': 'horizontal-tb;'\n };\n defaultStyleProperties = {\n 'color': 'rgb(255,255,255);',\n 'direction': 'ltr;',\n 'font-family': 'monospace, sans-serif;',\n 'font-style': 'normal;',\n 'line-height': 'normal;',\n 'font-weight': 'normal;',\n 'text-align': 'start;',\n 'justify-content': 'flex-start;',\n 'text-decoration': 'none;',\n 'unicode-bidi': 'normal;',\n 'white-space': 'normal;',\n 'width': '100%;'\n };\n fontFamilies = {\n monospace: 'font-family: monospace;',\n sansSerif: 'font-family: sans-serif;',\n serif: 'font-family: serif;',\n monospaceSansSerif: 'font-family: monospace, sans-serif;',\n monospaceSerif: 'font-family: monospace, serif;',\n proportionalSansSerif: 'font-family: Arial;',\n proportionalSerif: 'font-family: Times New Roman;',\n 'default': 'font-family: monospace, sans-serif;'\n };\n textAlign = {\n right: ['justify-content: flex-end;', 'text-align: right;'],\n start: ['justify-content: flex-start;', 'text-align: start;'],\n center: ['justify-content: center;', 'text-align: center;'],\n end: ['justify-content: flex-end;', 'text-align: end;'],\n left: ['justify-content: flex-start;', 'text-align: left;']\n };\n multiRowAlign = {\n start: 'text-align: start;',\n center: 'text-align: center;',\n end: 'text-align: end;',\n auto: ''\n };\n wrapOption = {\n wrap: 'white-space: normal;',\n noWrap: 'white-space: nowrap;'\n };\n unicodeBidi = {\n normal: 'unicode-bidi: normal;',\n embed: 'unicode-bidi: embed;',\n bidiOverride: 'unicode-bidi: bidi-override;'\n };\n displayAlign = {\n before: 'align-items: flex-start;',\n center: 'align-items: center;',\n after: 'align-items: flex-end;'\n };\n writingMode = {\n lrtb: '-webkit-writing-mode: horizontal-tb;' +\n 'writing-mode: horizontal-tb;',\n rltb: '-webkit-writing-mode: horizontal-tb;' +\n 'writing-mode: horizontal-tb;' +\n 'direction: rtl;' +\n 'unicode-bidi: bidi-override;',\n tbrl: '-webkit-writing-mode: vertical-rl;' +\n 'writing-mode: vertical-rl;' +\n '-webkit-text-orientation: upright;' +\n 'text-orientation: upright;',\n tblr: '-webkit-writing-mode: vertical-lr;' +\n 'writing-mode: vertical-lr;' +\n '-webkit-text-orientation: upright;' +\n 'text-orientation: upright;',\n lr: '-webkit-writing-mode: horizontal-tb;' +\n 'writing-mode: horizontal-tb;',\n rl: '-webkit-writing-mode: horizontal-tb;' +\n 'writing-mode: horizontal-tb;' +\n 'direction: rtl;',\n tb: '-webkit-writing-mode: vertical-rl;' +\n 'writing-mode: vertical-rl;' +\n '-webkit-text-orientation: upright;' +\n 'text-orientation: upright;'\n };\n converter = new X2JS({\n escapeMode: false,\n attributePrefix: '',\n arrayAccessForm: 'property',\n emptyNodeForm: 'object',\n stripWhitespaces: false,\n enableToStringFunc: false,\n matchers: []\n });\n }\n\n function parseTimings(timingStr) {\n // Test if the time provided by the caption is valid.\n var test = timingRegex.test(timingStr);\n var timeParts,\n parsedTime,\n frameRate;\n\n if (!test) {\n // Return NaN so it will throw an exception at internalParse if the time is incorrect.\n return NaN;\n }\n\n timeParts = timingStr.split(':');\n\n // Process the timings by decomposing it and converting it in numbers.\n parsedTime = (parseFloat(timeParts[0]) * SECONDS_IN_HOUR +\n parseFloat(timeParts[1]) * SECONDS_IN_MIN +\n parseFloat(timeParts[2]));\n\n // In case a frameRate is provided, we adjust the parsed time.\n if (timeParts[3]) {\n frameRate = ttml.tt.frameRate;\n if (frameRate && !isNaN(frameRate)) {\n parsedTime += parseFloat(timeParts[3]) / frameRate;\n } else {\n return NaN;\n }\n }\n return parsedTime;\n }\n\n function getNamespacePrefix(json, ns) {\n // Obtain the namespace prefix.\n var r = Object.keys(json)\n .filter(function (k) {\n return (k.split(':')[0] === 'xmlns' || k.split(':')[1] === 'xmlns') && json[k] === ns;\n }).map(function (k) {\n return k.split(':')[2] || k.split(':')[1];\n });\n if (r.length != 1) {\n return null;\n }\n return r[0];\n }\n\n function removeNamespacePrefix(json, nsPrefix) {\n for (var key in json) {\n if (json.hasOwnProperty(key)) {\n if ((typeof json[key] === 'object' || json[key] instanceof Object) && !Array.isArray(json[key])) {\n removeNamespacePrefix(json[key], nsPrefix);\n } else if (Array.isArray(json[key])) {\n for (var i = 0; i < json[key].length; i++) {\n removeNamespacePrefix(json[key][i], nsPrefix);\n }\n }\n var fullNsPrefix = nsPrefix + ':';\n var nsPrefixPos = key.indexOf(fullNsPrefix);\n if (nsPrefixPos >= 0) {\n var newKey = key.slice(nsPrefixPos + fullNsPrefix.length);\n json[newKey] = json[key];\n delete json[key];\n }\n }\n }\n }\n\n // backgroundColor = background-color, convert from camelCase to dash.\n function camelCaseToDash(key) {\n return key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }\n\n // Convert an RGBA value written in Hex to rgba(v,v,v,a).\n function convertHexToRGBA(rgba) {\n // Get the hexadecimal value without the #.\n var hex = rgba.slice(1);\n // Separate the values in pairs.\n var hexMatrice = hex.match(/.{2}/g);\n // Convert the alpha value in decimal between 0 and 1.\n var alpha = parseFloat(parseInt((parseInt(hexMatrice[3], 16) / 255) * 1000, 10) / 1000);\n // Get the standard RGB value.\n var rgb = hexMatrice.slice(0, 3).map(function (i) {\n return parseInt(i, 16);\n });\n // Return the RGBA value for CSS.\n return 'rgba(' + rgb.join(',') + ',' + alpha + ');';\n }\n\n // Convert an RGBA value written in TTML rgba(v,v,v,a => 0 to 255) to CSS rgba(v,v,v,a => 0 to 1).\n function convertAlphaValue(rgbaTTML) {\n let rgba,\n alpha,\n resu;\n\n rgba = rgbaTTML.replace(/^(rgb|rgba)\\(/,'').replace(/\\)$/,'').replace(/\\s/g,'').split(',');\n alpha = parseInt(rgba[rgba.length - 1], 10) / 255;\n resu = 'rgba(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ',' + alpha + ');';\n\n return resu;\n }\n\n // Return whether or not an array contains a certain text\n function arrayContains(text, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].indexOf(text) > -1) {\n return true;\n }\n }\n return false;\n }\n\n // Return the whole value that contains \"text\"\n function getPropertyFromArray(text, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].indexOf(text) > -1) {\n return array[i];\n }\n }\n return null;\n }\n\n // Delete a a property from an array.\n function deletePropertyFromArray(property, array) {\n array.splice(array.indexOf(getPropertyFromArray(property, array)), 1);\n }\n\n function mergeArrays(primeArray, arrayToAdd) {\n for (var i = 0; i < primeArray.length; i++) {\n for (var j = 0; j < arrayToAdd.length; j++) {\n // Take only the name of the property\n if (primeArray[i]) {\n if (primeArray[i].split(':')[0].indexOf(arrayToAdd[j].split(':')[0]) > -1) {\n primeArray.splice(i, 1);\n }\n }\n }\n }\n return primeArray.concat(arrayToAdd);\n }\n\n function getSizeTypeAndDefinition(cueStyleElement) {\n let returnTab = new Array(2);\n let startRef = cueStyleElement.indexOf(':') === -1 ? 0 : cueStyleElement.indexOf(':');\n let endRef;\n if (cueStyleElement.indexOf('%') === -1) {\n if (cueStyleElement.indexOf('c') === -1) {\n if (cueStyleElement.indexOf('p') === -1) {\n returnTab[0] = returnTab[1] = null;\n } else {\n returnTab[0] = 'p';\n endRef = cueStyleElement.indexOf('p');\n }\n } else {\n returnTab[0] = 'c';\n endRef = cueStyleElement.indexOf('c');\n }\n } else {\n returnTab[0] = '%';\n endRef = cueStyleElement.indexOf('%');\n }\n returnTab [1] = cueStyleElement.slice(startRef, endRef);\n return returnTab;\n }\n\n /**\n * Processing of styling information:\n * - processStyle: return an array of strings with the cue style under a CSS style form.\n * - findStyleFromID: Return the unprocessed style from TTMLStyling corresponding to the ID researched.\n * - getProcessedStyle: Return the processed style(s) from the ID(s) received in entry.\n * **/\n\n\n // Compute the style properties to return an array with the cleaned properties.\n function processStyle(cueStyle, cellUnit, includeRegionStyles) {\n var properties = [];\n var valueFtSizeInPx,\n valueLHSizeInPx;\n\n // Clean up from the xml2json parsing:\n for (var key in cueStyle) {\n if (cueStyle.hasOwnProperty(key)) {\n //Clean the properties from the parsing.\n var newKey = key.replace('ebutts:', '');\n newKey = newKey.replace('xml:', '');\n newKey = newKey.replace('tts:', '');\n\n // Clean the properties' names.\n newKey = camelCaseToDash(newKey);\n cueStyle[newKey] = cueStyle[key];\n delete cueStyle[key];\n }\n }\n\n // Line padding is computed from the cellResolution.\n if ('line-padding' in cueStyle) {\n var valuePadding = parseFloat(cueStyle['line-padding'].slice(cueStyle['line-padding'].indexOf(':') + 1,\n cueStyle['line-padding'].indexOf('c')));\n if ('id' in cueStyle) {\n linePadding[cueStyle.id] = valuePadding;\n }\n var valuePaddingInPx = valuePadding * cellUnit[0] + 'px;';\n properties.push('padding-left:' + valuePaddingInPx);\n properties.push('padding-right:' + valuePaddingInPx);\n }\n // Font size is computed from the cellResolution.\n if ('font-size' in cueStyle) {\n var fontSizeTab = getSizeTypeAndDefinition(cueStyle['font-size']);\n var valueFtSize = parseFloat(fontSizeTab[1]);\n if ('id' in cueStyle) {\n fontSize[cueStyle.id] = fontSizeTab;\n }\n\n if (fontSizeTab[0] === '%') {\n valueFtSizeInPx = valueFtSize / 100 * cellUnit[1] + 'px;';\n } else if (fontSizeTab[0] === 'c') {\n valueFtSizeInPx = valueFtSize * cellUnit[1] + 'px;';\n }\n\n properties.push('font-size:' + valueFtSizeInPx);\n }\n // Line height is computed from the cellResolution.\n if ('line-height' in cueStyle) {\n if (cueStyle['line-height'] === 'normal') {\n properties.push('line-height: normal;');\n } else {\n var LineHeightTab = getSizeTypeAndDefinition(cueStyle['line-height']);\n var valueLHSize = parseFloat(LineHeightTab[1]);\n if ('id' in cueStyle) {\n lineHeight[cueStyle.id] = LineHeightTab;\n }\n\n if (LineHeightTab[0] === '%') {\n valueLHSizeInPx = valueLHSize / 100 * cellUnit[1] + 'px;';\n } else if (LineHeightTab[0] === 'c') {\n valueLHSizeInPx = valueLHSize * cellUnit[1] + 'px;';\n }\n\n properties.push('line-height:' + valueLHSizeInPx);\n }\n }\n // Font-family can be specified by a generic family name or a custom family name.\n if ('font-family' in cueStyle) {\n if (cueStyle['font-family'] in fontFamilies) {\n properties.push(fontFamilies[cueStyle['font-family']]);\n } else {\n properties.push('font-family:' + cueStyle['font-family'] + ';');\n }\n }\n // Text align needs to be set from two properties:\n // The standard text-align CSS property.\n // The justify-content property as we use flex boxes.\n if ('text-align' in cueStyle) {\n if (cueStyle['text-align'] in textAlign) {\n properties.push(textAlign[cueStyle['text-align']][0]);\n properties.push(textAlign[cueStyle['text-align']][1]);\n }\n }\n // Multi Row align is set only by the text-align property.\n // TODO: TO CHECK\n if ('multi-row-align' in cueStyle) {\n if (arrayContains('text-align', properties) && cueStyle['multi-row-align'] != 'auto') {\n deletePropertyFromArray('text-align', properties);\n }\n if (cueStyle['multi-row-align'] in multiRowAlign) {\n properties.push(multiRowAlign[cueStyle['multi-row-align']]);\n }\n }\n // Background color can be specified from hexadecimal (RGB or RGBA) value.\n var rgbaValue;\n if ('background-color' in cueStyle) {\n if (cueStyle['background-color'].indexOf('#') > -1 && (cueStyle['background-color'].length - 1) === 8) {\n rgbaValue = convertHexToRGBA(cueStyle['background-color']);\n } else if (cueStyle['background-color'].indexOf('rgba') > -1) {\n rgbaValue = convertAlphaValue(cueStyle['background-color']);\n } else {\n rgbaValue = cueStyle['background-color'] + ';';\n }\n properties.push('background-color: ' + rgbaValue);\n }\n // Color can be specified from hexadecimal (RGB or RGBA) value.\n if ('color' in cueStyle) {\n if (cueStyle.color.indexOf('#') > -1 && (cueStyle.color.length - 1) === 8) {\n rgbaValue = convertHexToRGBA(cueStyle.color);\n } else if (cueStyle.color.indexOf('rgba') > -1) {\n rgbaValue = convertAlphaValue(cueStyle.color);\n } else {\n rgbaValue = cueStyle.color + ';';\n }\n properties.push('color: ' + rgbaValue);\n }\n // Wrap option is determined by the white-space CSS property.\n if ('wrap-option' in cueStyle) {\n if (cueStyle['wrap-option'] in wrapOption) {\n properties.push(wrapOption[cueStyle['wrap-option']]);\n } else {\n properties.push('white-space:' + cueStyle['wrap-option']);\n }\n }\n // Unicode bidi is determined by the unicode-bidi CSS property.\n if ('unicode-bidi' in cueStyle) {\n if (cueStyle['unicode-bidi'] in unicodeBidi) {\n properties.push(unicodeBidi[cueStyle['unicode-bidi']]);\n } else {\n properties.push('unicode-bidi:' + cueStyle['unicode-bidi']);\n }\n }\n\n // Standard properties identical to CSS.\n\n if ('font-style' in cueStyle) {\n properties.push('font-style:' + cueStyle['font-style'] + ';');\n }\n if ('font-weight' in cueStyle) {\n properties.push('font-weight:' + cueStyle['font-weight'] + ';');\n }\n if ('direction' in cueStyle) {\n properties.push('direction:' + cueStyle.direction + ';');\n }\n if ('text-decoration' in cueStyle) {\n properties.push('text-decoration:' + cueStyle['text-decoration'] + ';');\n }\n\n if (includeRegionStyles) {\n properties = properties.concat(processRegion(cueStyle, cellUnit));\n }\n\n // Handle white-space preserve\n if (ttml.tt.hasOwnProperty('xml:space')) {\n if (ttml.tt['xml:space'] === 'preserve') {\n properties.push('white-space: pre;');\n }\n }\n\n return properties;\n }\n\n // Find the style set by comparing the style IDs available.\n // Return null if no style is found\n function findStyleFromID(ttmlStyling, cueStyleID) {\n // For every styles available, search the corresponding style in ttmlStyling.\n for (var j = 0; j < ttmlStyling.length; j++) {\n var currStyle = ttmlStyling[j];\n if (currStyle['xml:id'] === cueStyleID || currStyle.id === cueStyleID) {\n // Return the style corresponding to the ID in parameter.\n return currStyle;\n }\n }\n return null;\n }\n // Return the computed style from a certain ID.\n function getProcessedStyle(reference, cellUnit, includeRegionStyles) {\n var styles = [];\n var ids = reference.match(/\\S+/g);\n ids.forEach(function (id) {\n // Find the style for each id received.\n var cueStyle = findStyleFromID(ttmlStyling, id);\n if (cueStyle) {\n // Process the style for the cue in CSS form.\n // Send a copy of the style object, so it does not modify the original by cleaning it.\n var stylesFromId = processStyle(JSON.parse(JSON.stringify(cueStyle)), cellUnit, includeRegionStyles);\n styles = styles.concat(stylesFromId);\n }\n });\n return styles;\n }\n\n // Calculate relative left, top, width, height from extent and origin in percent.\n // Return object with {left, top, width, height} as numbers in percent or null.\n function getRelativePositioning(element, ttExtent) {\n\n let pairRe = /([\\d\\.]+)(%|px)\\s+([\\d\\.]+)(%|px)/;\n\n if (('tts:extent' in element) && ('tts:origin' in element) ) {\n let extentParts = pairRe.exec(element['tts:extent']);\n let originParts = pairRe.exec(element['tts:origin']);\n if (extentParts === null || originParts === null) {\n log('Bad extent or origin: ' + element['tts:extent'] + ' ' + element['tts:origin']);\n return null;\n }\n let width = parseFloat(extentParts[1]);\n let height = parseFloat(extentParts[3]);\n let left = parseFloat(originParts[1]);\n let top = parseFloat(originParts[3]);\n\n if (ttExtent) { // Should give overall scale in pixels\n let ttExtentParts = pairRe.exec(ttExtent);\n if (ttExtentParts === null || ttExtentParts[2] !== 'px' || ttExtentParts[4] !== 'px') {\n log('Bad tt.extent: ' + ttExtent);\n return null;\n }\n let exWidth = parseFloat(ttExtentParts[1]);\n let exHeight = parseFloat(ttExtentParts[3]);\n if (extentParts[2] === 'px') {\n width = width / exWidth * 100;\n }\n if (extentParts[4] === 'px') {\n height = height / exHeight * 100;\n }\n if (originParts[2] === 'px') {\n left = left / exWidth * 100;\n }\n if (originParts[4] === 'px') {\n top = top / exHeight * 100;\n }\n }\n return { 'left': left, 'top': top, 'width': width, 'height': height };\n } else {\n return null;\n }\n }\n\n /**\n * Processing of layout information:\n * - processRegion: return an array of strings with the cue region under a CSS style form.\n * - findRegionFromID: Return the unprocessed region from TTMLLayout corresponding to the ID researched.\n * - getProcessedRegion: Return the processed region(s) from the ID(s) received in entry.\n ***/\n\n // Compute the region properties to return an array with the cleaned properties.\n function processRegion(cueRegion, cellUnit) {\n var properties = [];\n\n // Clean up from the xml2json parsing:\n for (var key in cueRegion) {\n //Clean the properties from the parsing.\n var newKey = key.replace('tts:', '');\n newKey = newKey.replace('xml:', '');\n\n // Clean the properties' names.\n newKey = camelCaseToDash(newKey);\n cueRegion[newKey] = cueRegion[key];\n if (newKey !== key) {\n delete cueRegion[key];\n }\n }\n // Extent property corresponds to width and height\n if ('extent' in cueRegion) {\n var coordsExtent = cueRegion.extent.split(/\\s/);\n properties.push('width: ' + coordsExtent[0] + ';');\n properties.push('height: ' + coordsExtent[1] + ';');\n }\n // Origin property corresponds to top and left\n if ('origin' in cueRegion) {\n var coordsOrigin = cueRegion.origin.split(/\\s/);\n properties.push('left: ' + coordsOrigin[0] + ';');\n properties.push('top: ' + coordsOrigin[1] + ';');\n }\n // DisplayAlign property corresponds to vertical-align\n if ('display-align' in cueRegion) {\n properties.push(displayAlign[cueRegion['display-align']]);\n }\n // WritingMode is not yet implemented (for CSS3, to come)\n if ('writing-mode' in cueRegion) {\n properties.push(writingMode[cueRegion['writing-mode']]);\n }\n // Style will give to the region the style properties from the style selected\n if ('style' in cueRegion) {\n var styleFromID = getProcessedStyle(cueRegion.style, cellUnit, true);\n properties = properties.concat(styleFromID);\n }\n\n // Standard properties identical to CSS.\n\n if ('padding' in cueRegion) {\n properties.push('padding:' + cueRegion.padding + ';');\n }\n if ('overflow' in cueRegion) {\n properties.push('overflow:' + cueRegion.overflow + ';');\n }\n if ('show-background' in cueRegion) {\n properties.push('show-background:' + cueRegion['show-background'] + ';');\n }\n if ('id' in cueRegion) {\n properties.push('regionID:' + cueRegion.id + ';');\n }\n\n return properties;\n }\n\n // Find the region set by comparing the region IDs available.\n // Return null if no region is found\n function findRegionFromID(ttmlLayout, cueRegionID) {\n // For every region available, search the corresponding style in ttmlLayout.\n for (var j = 0; j < ttmlLayout.length; j++) {\n var currReg = ttmlLayout[j];\n if (currReg['xml:id'] === cueRegionID || currReg.id === cueRegionID) {\n // Return the region corresponding to the ID in parameter.\n return currReg;\n }\n }\n return null;\n }\n\n // Return the computed region from a certain ID.\n function getProcessedRegion(reference, cellUnit) {\n var regions = [];\n var ids = reference.match(/\\S+/g);\n ids.forEach(function (id) {\n // Find the region for each id received.\n var cueRegion = findRegionFromID(ttmlLayout, id);\n if (cueRegion) {\n // Process the region for the cue in CSS form.\n // Send a copy of the style object, so it does not modify the original by cleaning it.\n var regionsFromId = processRegion(JSON.parse(JSON.stringify(cueRegion)), cellUnit);\n regions = regions.concat(regionsFromId);\n }\n });\n return regions;\n }\n\n //Return the cellResolution defined by the TTML document.\n function getCellResolution() {\n var defaultCellResolution = [32, 15]; // Default cellResolution.\n if (ttml.tt.hasOwnProperty('ttp:cellResolution')) {\n return ttml.tt['ttp:cellResolution'].split(' ').map(parseFloat);\n } else {\n return defaultCellResolution;\n }\n }\n\n // Return the cue wrapped into a span specifying its linePadding.\n function applyLinePadding(cueHTML, cueStyle) {\n // Extract the linePadding property from cueStyleProperties.\n var linePaddingLeft = getPropertyFromArray('padding-left', cueStyle);\n var linePaddingRight = getPropertyFromArray('padding-right', cueStyle);\n var linePadding = linePaddingLeft.concat(' ' + linePaddingRight + ' ');\n\n // Declaration of the HTML elements to be used in the cue innerHTML construction.\n var outerHTMLBeforeBr = '';\n var outerHTMLAfterBr = '';\n var cueInnerHTML = '';\n\n // List all the nodes of the subtitle.\n var nodeList = Array.prototype.slice.call(cueHTML.children);\n // Take a br element as reference.\n var brElement = cueHTML.getElementsByClassName('lineBreak')[0];\n // First index of the first br element.\n var idx = nodeList.indexOf(brElement);\n // array of all the br element indices\n var indices = [];\n // Find all the indices of the br elements.\n while (idx != -1) {\n indices.push(idx);\n idx = nodeList.indexOf(brElement, idx + 1);\n }\n\n // Strings for the cue innerHTML construction.\n var spanStringEnd = '<\\/span>';\n var br = '<br>';\n var clonePropertyString = '<span' + ' class=\"spanPadding\" ' + 'style=\"-webkit-box-decoration-break: clone; box-decoration-break: clone; ';\n\n // If br elements are found:\n if (indices.length) {\n // For each index of a br element we compute the HTML coming before and/or after it.\n indices.forEach(function (i, index) {\n // If this is the first line break, we compute the HTML of the element coming before.\n if (index === 0) {\n var styleBefore = '';\n // for each element coming before the line break, we add its HTML.\n for (var j = 0; j < i; j++) {\n outerHTMLBeforeBr += nodeList[j].outerHTML;\n // If this is the first element, we add its style to the wrapper.\n if (j === 0) {\n styleBefore = linePadding.concat(nodeList[j].style.cssText);\n }\n }\n // The before element will comprises the clone property (for line wrapping), the style that\n // need to be applied (ex: background-color) and the rest og the HTML.\n outerHTMLBeforeBr = clonePropertyString + styleBefore + '\">' + outerHTMLBeforeBr;\n }\n // For every element of the list, we compute the element coming after the line break.s\n var styleAfter = '';\n // for each element coming after the line break, we add its HTML.\n for (var k = i + 1; k < nodeList.length; k++) {\n outerHTMLAfterBr += nodeList[k].outerHTML;\n // If this is the last element, we add its style to the wrapper.\n if (k === nodeList.length - 1) {\n styleAfter += linePadding.concat(nodeList[k].style.cssText);\n }\n }\n\n // The before element will comprises the clone property (for line wrapping), the style that\n // need to be applied (ex: background-color) and the rest og the HTML.\n outerHTMLAfterBr = clonePropertyString + styleAfter + '\">' + outerHTMLAfterBr;\n\n // For each line break we must add the before and/or after element to the final cue as well as\n // the line break when needed.\n if (outerHTMLBeforeBr && outerHTMLAfterBr && index === (indices.length - 1)) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd + br + outerHTMLAfterBr + spanStringEnd;\n } else if (outerHTMLBeforeBr && outerHTMLAfterBr && index !== (indices.length - 1)) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd + br + outerHTMLAfterBr + spanStringEnd + br;\n } else if (outerHTMLBeforeBr && !outerHTMLAfterBr) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd;\n } else if (!outerHTMLBeforeBr && outerHTMLAfterBr && index === (indices.length - 1)) {\n cueInnerHTML += outerHTMLAfterBr + spanStringEnd;\n } else if (!outerHTMLBeforeBr && outerHTMLAfterBr && index !== (indices.length - 1)) {\n cueInnerHTML += outerHTMLAfterBr + spanStringEnd + br;\n }\n });\n } else {\n // If there is no line break in the subtitle, we simply wrap cue in a span indicating the linePadding.\n var style = '';\n for (var k = 0; k < nodeList.length; k++) {\n style += nodeList[k].style.cssText;\n }\n cueInnerHTML = clonePropertyString + linePadding + style + '\">' + cueHTML.innerHTML + spanStringEnd;\n }\n return cueInnerHTML;\n }\n\n /*\n * Create the cue element\n * I. The cues are text only:\n * i) The cue contains a 'br' element\n * ii) The cue contains a span element\n * iii) The cue contains text\n */\n\n function constructCue(cueElements, cellUnit) {\n var cue = document.createElement('div');\n cueElements.forEach(function (el) {\n // If metadata is present, do not process.\n if (el.hasOwnProperty('metadata')) {\n return;\n }\n\n /**\n * If the p element contains spans: create the span elements.\n */\n if (el.hasOwnProperty('span')) {\n\n // Stock the span subtitles in an array (in case there are only one value).\n var spanElements = el.span.__children;\n\n // Create the span element.\n var spanHTMLElement = document.createElement('span');\n // Extract the style of the span.\n if (el.span.hasOwnProperty('style')) {\n var spanStyle = getProcessedStyle(el.span.style, cellUnit);\n spanHTMLElement.className = 'spanPadding ' + el.span.style;\n spanHTMLElement.style.cssText = spanStyle.join(' ');\n }\n\n\n // if the span has more than one element, we check for each of them their nature (br or text).\n spanElements.forEach(function (spanEl) {\n // If metadata is present, do not process.\n if (spanElements.hasOwnProperty('metadata')) {\n return;\n }\n // If the element is a string\n if (spanEl.hasOwnProperty('#text')) {\n var textNode = document.createTextNode(spanEl['#text']);\n spanHTMLElement.appendChild(textNode);\n // If the element is a 'br' tag\n } else if ('br' in spanEl) {\n // To handle br inside span we need to add the current span\n // to the cue and then create a br and add that the cue\n // then create a new span that we use for the next line of\n // text, that is a copy of the current span\n\n // Add the current span to the cue, only if it has childNodes (text)\n if (spanHTMLElement.hasChildNodes()) {\n cue.appendChild(spanHTMLElement);\n }\n\n // Create a br and add that to the cue\n var brEl = document.createElement('br');\n brEl.className = 'lineBreak';\n cue.appendChild(brEl);\n\n // Create an replacement span and copy the style and classname from the old one\n var newSpanHTMLElement = document.createElement('span');\n newSpanHTMLElement.className = spanHTMLElement.className;\n newSpanHTMLElement.style.cssText = spanHTMLElement.style.cssText;\n\n // Replace the current span with the one we just created\n spanHTMLElement = newSpanHTMLElement;\n }\n });\n // We append the element to the cue container.\n cue.appendChild(spanHTMLElement);\n }\n\n /**\n * Create a br element if there is one in the cue.\n */\n else if (el.hasOwnProperty('br')) {\n // We append the line break to the cue container.\n var brEl = document.createElement('br');\n brEl.className = 'lineBreak';\n cue.appendChild(brEl);\n }\n\n /**\n * Add the text that is not in any inline element\n */\n else if (el.hasOwnProperty('#text')) {\n // Add the text to an individual span element (to add line padding if it is defined).\n var textNode = document.createElement('span');\n textNode.textContent = el['#text'];\n\n // We append the element to the cue container.\n cue.appendChild(textNode);\n }\n });\n return cue;\n }\n\n function constructCueRegion(cue, div, cellUnit) {\n var cueRegionProperties = []; // properties to be put in the \"captionRegion\" HTML element\n // Obtain the region ID(s) assigned to the cue.\n var pRegionID = cue.region;\n // If div has a region.\n var divRegionID = div.region;\n\n var divRegion;\n var pRegion;\n\n // If the div element reference a region.\n if (divRegionID) {\n divRegion = getProcessedRegion(divRegionID, cellUnit);\n }\n // If the p element reference a region.\n if (pRegionID) {\n pRegion = cueRegionProperties.concat(getProcessedRegion(pRegionID, cellUnit));\n if (divRegion) {\n cueRegionProperties = mergeArrays(divRegion, pRegion);\n } else {\n cueRegionProperties = pRegion;\n }\n } else if (divRegion) {\n cueRegionProperties = divRegion;\n }\n\n // Add initial/default values to what's not defined in the layout:\n applyDefaultProperties(cueRegionProperties, defaultLayoutProperties);\n\n return cueRegionProperties;\n }\n\n function constructCueStyle(cue, cellUnit) {\n var cueStyleProperties = []; // properties to be put in the \"paragraph\" HTML element\n // Obtain the style ID(s) assigned to the cue.\n var pStyleID = cue.style;\n // If body has a style.\n var bodyStyleID = ttml.tt.body.style;\n // If div has a style.\n var divStyleID = ttml.tt.body.div.style;\n\n var bodyStyle;\n var divStyle;\n var pStyle;\n var styleIDs = '';\n\n // If the body element reference a style.\n if (bodyStyleID) {\n bodyStyle = getProcessedStyle(bodyStyleID, cellUnit);\n styleIDs = 'paragraph ' + bodyStyleID;\n }\n\n // If the div element reference a style.\n if (divStyleID) {\n divStyle = getProcessedStyle(divStyleID, cellUnit);\n if (bodyStyle) {\n divStyle = mergeArrays(bodyStyle, divStyle);\n styleIDs += ' ' + divStyleID;\n } else {\n styleIDs = 'paragraph ' + divStyleID;\n }\n }\n\n // If the p element reference a style.\n if (pStyleID) {\n pStyle = getProcessedStyle(pStyleID, cellUnit);\n if (bodyStyle && divStyle) {\n cueStyleProperties = mergeArrays(divStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else if (bodyStyle) {\n cueStyleProperties = mergeArrays(bodyStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else if (divStyle) {\n cueStyleProperties = mergeArrays(divStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else {\n cueStyleProperties = pStyle;\n styleIDs = 'paragraph ' + pStyleID;\n }\n } else if (bodyStyle && !divStyle) {\n cueStyleProperties = bodyStyle;\n } else if (!bodyStyle && divStyle) {\n cueStyleProperties = divStyle;\n }\n\n\n // Add initial/default values to what's not defined in the styling:\n applyDefaultProperties(cueStyleProperties, defaultStyleProperties);\n\n return [cueStyleProperties, styleIDs];\n }\n\n function applyDefaultProperties(array, defaultProperties) {\n for (var key in defaultProperties) {\n if (defaultProperties.hasOwnProperty(key)) {\n if (!arrayContains(key, array)) {\n array.push(key + ':' + defaultProperties[key]);\n }\n }\n }\n }\n\n instance = {\n parse: parse,\n setConfig: setConfig\n };\n\n setup();\n return instance;\n}", "function parseSynonyymitHtml(htmlres) {\n let el = document.createElement('html');\n el.innerHTML = htmlres;\n\n let resstr = \" \";\n\n // 1. taulukko\n let searchResultCollection = el.getElementsByClassName('first')\n if( searchResultCollection.length > 0 ) {\n resultColl = searchResultCollection[0].children;\n\n for (let item of resultColl) {\n console.debug(\"[Synonyymit] -> \" + item.textContent);\n resstr += item.textContent;\n resstr += \" \";\n } \n }\n\n // päätaulukko\n searchResultCollection = el.getElementsByClassName('sec');\n if( searchResultCollection.length > 0 ) {\n resultColl = searchResultCollection[0].children;\n\n for (let item of resultColl) {\n console.debug(\"[Synonyymit] -> \" + item.textContent);\n resstr += item.textContent;\n resstr += \" \";\n }\n }\n\n\n // liittyvät sanat taulukko\n searchResultCollection = el.getElementsByClassName('rel');\n if( searchResultCollection.length > 0 ) {\n resultColl = searchResultCollection[0].children;\n\n for (let item of resultColl) {\n console.debug(\"[Synonyymit] -> \" + item.textContent);\n resstr += item.textContent;\n resstr += \" \";\n }\n }\n\n // katso myös taulukko\n if( searchResultCollection.length > 1 ) {\n resultColl = searchResultCollection[1].children;\n\n for (let item of resultColl) {\n console.debug(\"[Synonyymit] -> \" + item.textContent);\n resstr += item.textContent;\n resstr += \" \";\n }\n }\n\n // läheisiä sanoja taulukko\n if( searchResultCollection.length > 2 ) {\n resultColl = searchResultCollection[2].children;\n\n for (let item of searchResultCollection4) {\n console.debug(\"[Synonyymit] -> \" + item.textContent);\n resstr += item.textContent;\n resstr += \" \";\n }\n }\n\n return resstr;\n}", "function unescapeHtml(html) {\n\tvar temp = document.createElement(\"div\");\n\ttemp.innerHTML = html;\n\tvar result = temp.childNodes[0].nodeValue;\n\ttemp.removeChild(temp.firstChild);\n\treturn result;\n}", "function TTMLParser() {\n\n var context = this.context;\n var log = (0, _coreDebug2['default'])(context).getInstance().log;\n\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n var instance = undefined,\n timingRegex = undefined,\n ttml = undefined,\n // contains the whole ttml document received\n ttmlStyling = undefined,\n // contains the styling information from the document (from head following EBU-TT-D)\n ttmlLayout = undefined,\n // contains the positioning information from the document (from head following EBU-TT-D)\n fontSize = undefined,\n lineHeight = undefined,\n linePadding = undefined,\n defaultLayoutProperties = undefined,\n defaultStyleProperties = undefined,\n fontFamilies = undefined,\n textAlign = undefined,\n multiRowAlign = undefined,\n wrapOption = undefined,\n unicodeBidi = undefined,\n displayAlign = undefined,\n writingMode = undefined,\n videoModel = undefined,\n converter = undefined;\n\n var cueCounter = 0; // Used to give every cue a unique ID.\n\n function setConfig(config) {\n if (!config) return;\n\n if (config.videoModel) {\n videoModel = config.videoModel;\n }\n }\n\n /**\n * Get the begin-end interval if present, or null otherwise.\n *\n * @param {Object} element - TTML element which may have begin and end attributes\n */\n function getInterval(element) {\n if (element.hasOwnProperty('begin') && element.hasOwnProperty('end')) {\n var beginTime = parseTimings(element.begin);\n var endTime = parseTimings(element.end);\n return [beginTime, endTime];\n } else {\n return null;\n }\n }\n\n function getCueID() {\n var id = 'cue_TTML_' + cueCounter;\n cueCounter++;\n return id;\n }\n\n /*\n * Create list of intervals where spans start and end. Empty list if no times.\n * Clip to interval using startInterval and endInterval and add these two times.\n * Also support case when startInterval/endInteval not given (sideloaded file)\n *\n * @param {Array} spans - array of span elements\n */\n function createSpanIntervalList(spans, startInterval, endInterval) {\n\n var spanChangeTimes = [];\n var spanChangeTimeStrings = [];\n var cue_intervals = [];\n\n function addSpanTime(span, name) {\n if (span.hasOwnProperty(name)) {\n var timeString = span[name];\n if (spanChangeTimeStrings.indexOf(timeString) < 0) {\n spanChangeTimeStrings.push(timeString);\n }\n }\n }\n\n for (var i = 0; i < spans.length; i++) {\n var span = spans[i];\n addSpanTime(span, 'begin');\n addSpanTime(span, 'end');\n }\n if (spanChangeTimeStrings.length === 0) {\n return cue_intervals; // No span timing so no intervals.\n }\n\n if (typeof startInterval !== 'undefined' && typeof endInterval !== 'undefined') {\n for (var i = 0; i < spanChangeTimeStrings.length; i++) {\n var changeTime = parseTimings(spanChangeTimeStrings[i]);\n if (startInterval < changeTime && changeTime < endInterval) {\n spanChangeTimes.push(changeTime);\n }\n }\n spanChangeTimes.push(startInterval);\n spanChangeTimes.push(endInterval);\n } else {\n for (var i = 0; i < spanChangeTimeStrings.length; i++) {\n spanChangeTimes.push(parseTimings(spanChangeTimeStrings[i]));\n }\n }\n spanChangeTimes.sort(function (a, b) {\n return a - b;\n });\n for (var i = 0; i < spanChangeTimes.length - 1; i++) {\n cue_intervals.push([spanChangeTimes[i], spanChangeTimes[i + 1]]);\n }\n return cue_intervals;\n }\n\n function clipStartTime(startTime, intervalStart) {\n if (typeof startInterval !== 'undefined') {\n if (startTime < intervalStart) {\n startTime = intervalStart;\n }\n }\n return startTime;\n }\n\n function clipEndTime(endTime, intervalEnd) {\n if (typeof intervalEnd !== 'undefined') {\n if (endTime > intervalEnd) {\n endTime = intervalEnd;\n }\n }\n return endTime;\n }\n\n /*\n * Get interval from entity that has begin and end properties.\n * If intervalStart and intervalEnd defined, use them to clip the interval.\n * Return null if no overlap with interval\n */\n function getClippedInterval(entity, intervalStart, intervalEnd) {\n var startTime = parseTimings(entity.begin);\n var endTime = parseTimings(entity.end);\n startTime = clipStartTime(startTime, intervalStart);\n endTime = clipEndTime(endTime, intervalEnd);\n if (typeof intervalStart !== 'undefined' && typeof intervalEnd !== 'undefined') {\n if (endTime < intervalStart || startTime > intervalEnd) {\n log('TTML: Cue ' + startTime + '-' + endTime + ' outside interval ' + intervalStart + '-' + intervalEnd);\n return null;\n }\n }\n return [startTime, endTime];\n }\n\n /*\n * Check if entity timing has some overlap with interval\n */\n function inIntervalOrNoTiming(entity, interval) {\n var inInterval = true;\n if (entity.hasOwnProperty('span')) {\n var entityInterval = getInterval(entity.span);\n if (entityInterval !== null) {\n //Timing\n inInterval = entityInterval[0] < interval[1] && entityInterval[1] > interval[0];\n }\n }\n return inInterval;\n }\n\n /**\n * Parse the raw data and process it to return the HTML element representing the cue.\n * Return the region to be processed and controlled (hide/show) by the caption controller.\n * @param {string} data - raw data received from the TextSourceBuffer\n * @param {number} intervalStart\n * @param {number} intervalEnd\n * @param {array} imageArray - images represented as binary strings\n */\n\n function parse(data, intervalStart, intervalEnd, imageArray) {\n var tt = undefined,\n // Top element\n head = undefined,\n // head in tt\n body = undefined,\n // body in tt\n ttExtent = undefined,\n // extent attribute of tt element\n type = undefined,\n i = undefined;\n\n var errorMsg = '';\n\n // Parse the TTML in a JSON object.\n ttml = converter.xml_str2json(data);\n\n if (!ttml) {\n throw new Error('TTML document could not be parsed');\n }\n\n if (videoModel.getTTMLRenderingDiv()) {\n type = 'html';\n }\n\n // Check the document and compare to the specification (TTML and EBU-TT-D).\n tt = ttml.tt;\n if (!tt) {\n throw new Error('TTML document lacks tt element');\n }\n\n // Get the namespace if there is one defined in the JSON object.\n var ttNS = getNamespacePrefix(tt, 'http://www.w3.org/ns/ttml');\n\n // Remove the namespace before each node if it exists:\n if (ttNS) {\n removeNamespacePrefix(tt, ttNS);\n }\n\n ttExtent = tt['tts:extent']; // Should check that tts is right namespace.\n\n head = tt.head;\n if (!head) {\n throw new Error('TTML document lacks head element');\n }\n if (head.layout) {\n ttmlLayout = head.layout.region_asArray; //Mandatory in EBU-TT-D\n }\n if (head.styling) {\n ttmlStyling = head.styling.style_asArray; // Mandatory in EBU-TT-D\n }\n\n var imageDataUrls = {};\n\n if (imageArray) {\n for (i = 0; i < imageArray.length; i++) {\n var key = 'urn:mpeg:14496-30:subs:' + (i + 1).toString();\n var dataUrl = 'data:image/png;base64,' + btoa(imageArray[i]);\n imageDataUrls[key] = dataUrl;\n }\n }\n\n if (head.metadata) {\n var embeddedImages = head.metadata.image_asArray; // Handle embedded images\n if (embeddedImages) {\n for (i = 0; i < embeddedImages.length; i++) {\n var key = '#' + embeddedImages[i]['xml:id'];\n var imageType = embeddedImages[i].imagetype.toLowerCase();\n var dataUrl = 'data:image/' + imageType + ';base64,' + embeddedImages[i].__text;\n imageDataUrls[key] = dataUrl;\n }\n }\n }\n\n body = tt.body;\n if (!body) {\n throw new Error('TTML document lacks body element');\n }\n\n // Extract the cellResolution information\n var cellResolution = getCellResolution();\n\n // Recover the video width and height displayed by the player.\n var videoWidth = videoModel.getElement().clientWidth;\n var videoHeight = videoModel.getElement().clientHeight;\n\n // Compute the CellResolution unit in order to process properties using sizing (fontSize, linePadding, etc).\n var cellUnit = [videoWidth / cellResolution[0], videoHeight / cellResolution[1]];\n defaultStyleProperties['font-size'] = cellUnit[1] + 'px;';\n\n var regions = [];\n if (ttmlLayout) {\n for (i = 0; i < ttmlLayout.length; i++) {\n regions.push(processRegion(JSON.parse(JSON.stringify(ttmlLayout[i])), cellUnit));\n }\n }\n\n // Get the namespace prefix.\n var nsttp = getNamespacePrefix(ttml.tt, 'http://www.w3.org/ns/ttml#parameter');\n\n // Set the framerate.\n if (tt.hasOwnProperty(nsttp + ':frameRate')) {\n tt.frameRate = parseInt(tt[nsttp + ':frameRate'], 10);\n }\n var captionArray = [];\n // Extract the div\n var divs = tt.body_asArray[0].__children;\n\n // Timing is either on div, paragraph or span level.\n\n for (var k = 0; k < divs.length; k++) {\n var div = divs[k].div;\n var divInterval = null; // This is mainly for image subtitles.\n\n if (null !== (divInterval = getInterval(div))) {\n // Timing on div level is not allowed by EBU-TT-D.\n // We only use it for SMPTE-TT image subtitle profile.\n\n // Layout should be defined by a region. Given early test material, we also support that it is on\n // div level\n var layout = undefined;\n if (div.region) {\n var region = findRegionFromID(ttmlLayout, div.region);\n layout = getRelativePositioning(region, ttExtent);\n }\n if (!layout) {\n layout = getRelativePositioning(div, ttExtent);\n }\n\n var imgKey = div['smpte:backgroundImage'];\n if (imgKey !== undefined && imageDataUrls[imgKey] !== undefined) {\n captionArray.push({\n start: divInterval[0],\n end: divInterval[1],\n id: getCueID(),\n data: imageDataUrls[imgKey],\n type: 'image',\n layout: layout\n });\n }\n continue; // Next div\n }\n\n var paragraphs = div.p_asArray;\n // Check if cues is not empty or undefined.\n if (divInterval === null && (!paragraphs || paragraphs.length === 0)) {\n errorMsg = 'TTML has div that contains no timing and no paragraphs.';\n log(errorMsg);\n return captionArray;\n }\n\n for (var j2 = 0; j2 < paragraphs.length; j2++) {\n var paragraph = paragraphs[j2];\n var spans = paragraph.span_asArray;\n var cueIntervals = [];\n // For timing, the overall goal is to find the intervals where there should be cues\n // The timing may either be on paragraph or span level.\n if (paragraph.hasOwnProperty('begin') && paragraph.hasOwnProperty('end')) {\n // Timing on paragraph level\n var clippedInterval = getClippedInterval(paragraph, intervalStart, intervalEnd);\n if (clippedInterval !== null) {\n cueIntervals.push(clippedInterval);\n }\n } else {\n // Timing must be on span level\n cueIntervals = createSpanIntervalList(spans, intervalStart, intervalEnd);\n }\n if (cueIntervals.length === 0) {\n errorMsg = 'TTML: Empty paragraph';\n continue; // Nothing in this paragraph\n }\n\n var paragraphChildren = paragraph.__children;\n\n for (var i2 = 0; i2 < cueIntervals.length; i2++) {\n var interval = cueIntervals[i2];\n var childrenInInterval = [];\n for (var k2 = 0; k2 < paragraphChildren.length; k2++) {\n var child = paragraphChildren[k2];\n if (inIntervalOrNoTiming(child, interval)) {\n childrenInInterval.push(child);\n }\n }\n if (childrenInInterval.length === 0) {\n continue; // No children to render\n }\n\n if (type === 'html') {\n lineHeight = {};\n linePadding = {};\n fontSize = {};\n\n /**\n * Find the region defined for the cue.\n */\n // properties to be put in the \"captionRegion\" HTML element.\n var cueRegionProperties = constructCueRegion(paragraph, div, cellUnit);\n\n /**\n * Find the style defined for the cue.\n */\n // properties to be put in the \"paragraph\" HTML element.\n var cueStyleProperties = constructCueStyle(paragraph, cellUnit);\n\n /**\n * /!\\ Create the cue HTML Element containing the whole cue.\n */\n var styleIDs = cueStyleProperties[1];\n cueStyleProperties = cueStyleProperties[0];\n\n // Final cue HTML element.\n var cueParagraph = document.createElement('div');\n cueParagraph.className = styleIDs;\n\n // Create a wrapper containing the cue information about unicodeBidi and direction\n // as they need to be defined on at this level.\n // We append to the wrapper the cue itself.\n var cueDirUniWrapper = constructCue(childrenInInterval, cellUnit);\n cueDirUniWrapper.className = 'cueDirUniWrapper';\n\n // If the style defines these two properties, we place them in cueContainer\n // and delete them from the cue style so it is not added afterwards to the final cue.\n if (arrayContains('unicode-bidi', cueStyleProperties)) {\n cueDirUniWrapper.style.cssText += getPropertyFromArray('unicode-bidi', cueStyleProperties);\n deletePropertyFromArray('unicode-bidi', cueStyleProperties);\n }\n if (arrayContains('direction', cueStyleProperties)) {\n cueDirUniWrapper.style.cssText += getPropertyFromArray('direction', cueStyleProperties);\n deletePropertyFromArray('direction', cueStyleProperties);\n }\n\n // Apply the linePadding property if it is specified in the cue style.\n if (arrayContains('padding-left', cueStyleProperties) && arrayContains('padding-right', cueStyleProperties)) {\n cueDirUniWrapper.innerHTML = applyLinePadding(cueDirUniWrapper, cueStyleProperties);\n }\n\n /**\n * Clean and set the style and region for the cue to be returned.\n */\n\n // Remove the line padding property from being added at the \"paragraph\" element level.\n if (arrayContains('padding-left', cueStyleProperties) && arrayContains('padding-right', cueStyleProperties)) {\n deletePropertyFromArray('padding-left', cueStyleProperties);\n deletePropertyFromArray('padding-right', cueStyleProperties);\n }\n\n // Remove the ID of the region from being added at the \"paragraph\" element level.\n var regionID = '';\n if (arrayContains('regionID', cueRegionProperties)) {\n var wholeRegionID = getPropertyFromArray('regionID', cueRegionProperties);\n regionID = wholeRegionID.slice(wholeRegionID.indexOf(':') + 1, wholeRegionID.length - 1);\n }\n\n // We link the p style to the finale cueParagraph element.\n if (cueStyleProperties) {\n cueParagraph.style.cssText = cueStyleProperties.join(' ') + 'display:flex;';\n }\n // We define the CSS style for the cue region.\n if (cueRegionProperties) {\n cueRegionProperties = cueRegionProperties.join(' ');\n }\n\n // We then place the cue wrapper inside the paragraph element.\n cueParagraph.appendChild(cueDirUniWrapper);\n\n // Final cue.\n var finalCue = document.createElement('div');\n finalCue.appendChild(cueParagraph);\n finalCue.id = getCueID();\n finalCue.style.cssText = 'position: absolute; margin: 0; display: flex; box-sizing: border-box; pointer-events: none;' + cueRegionProperties;\n\n if (Object.keys(fontSize).length === 0) {\n fontSize.defaultFontSize = '100';\n }\n\n // We add all the cue information in captionArray.\n captionArray.push({\n start: interval[0],\n end: interval[1],\n type: 'html',\n cueHTMLElement: finalCue,\n regions: regions,\n regionID: regionID,\n cueID: finalCue.id,\n videoHeight: videoHeight,\n videoWidth: videoWidth,\n cellResolution: cellResolution,\n fontSize: fontSize || {\n defaultFontSize: '100'\n },\n lineHeight: lineHeight,\n linePadding: linePadding\n });\n } else {\n var text = '';\n var textElements = childrenInInterval;\n if (textElements.length) {\n textElements.forEach(function (el) {\n if (el.hasOwnProperty('span')) {\n var spanElements = el.span.__children;\n spanElements.forEach(function (spanEl) {\n // If metadata is present, do not process.\n if (spanElements.hasOwnProperty('metadata')) {\n return;\n }\n // If the element is a string\n if (spanEl.hasOwnProperty('#text')) {\n text += spanEl['#text'].replace(/[\\r\\n]+/gm, ' ').trim();\n // If the element is a 'br' tag\n } else if ('br' in spanEl) {\n // Create a br element.\n text += '\\n';\n }\n });\n } else if (el.hasOwnProperty('br')) {\n text += '\\n';\n } else {\n text += el['#text'].replace(/[\\r\\n]+/gm, ' ').trim();\n }\n });\n }\n\n captionArray.push({\n start: interval[0],\n end: interval[1],\n data: text,\n type: 'text'\n });\n }\n }\n }\n }\n\n if (errorMsg !== '') {\n log(errorMsg);\n }\n\n if (captionArray.length > 0) {\n return captionArray;\n } else {\n // This seems too strong given that there are segments with no TTML subtitles\n throw new Error(errorMsg);\n }\n }\n\n function setup() {\n /*\n * This TTML parser follows \"EBU-TT-D SUBTITLING DISTRIBUTION FORMAT - tech3380\" spec - https://tech.ebu.ch/docs/tech/tech3380.pdf.\n * */\n timingRegex = /^([0-9][0-9]+):([0-5][0-9]):([0-5][0-9])|(60)(\\.([0-9])+)?$/; // Regex defining the time\n fontSize = {};\n lineHeight = {};\n linePadding = {};\n defaultLayoutProperties = {\n 'top': 'auto;',\n 'left': 'auto;',\n 'width': '90%;',\n 'height': '10%;',\n 'align-items': 'flex-start;',\n 'overflow': 'visible;',\n '-ms-writing-mode': 'lr-tb, horizontal-tb;',\n '-webkit-writing-mode': 'horizontal-tb;',\n '-moz-writing-mode': 'horizontal-tb;',\n 'writing-mode': 'horizontal-tb;'\n };\n defaultStyleProperties = {\n 'color': 'rgb(255,255,255);',\n 'direction': 'ltr;',\n 'font-family': 'monospace, sans-serif;',\n 'font-style': 'normal;',\n 'line-height': 'normal;',\n 'font-weight': 'normal;',\n 'text-align': 'start;',\n 'justify-content': 'flex-start;',\n 'text-decoration': 'none;',\n 'unicode-bidi': 'normal;',\n 'white-space': 'normal;',\n 'width': '100%;'\n };\n fontFamilies = {\n monospace: 'font-family: monospace;',\n sansSerif: 'font-family: sans-serif;',\n serif: 'font-family: serif;',\n monospaceSansSerif: 'font-family: monospace, sans-serif;',\n monospaceSerif: 'font-family: monospace, serif;',\n proportionalSansSerif: 'font-family: Arial;',\n proportionalSerif: 'font-family: Times New Roman;',\n 'default': 'font-family: monospace, sans-serif;'\n };\n textAlign = {\n right: ['justify-content: flex-end;', 'text-align: right;'],\n start: ['justify-content: flex-start;', 'text-align: start;'],\n center: ['justify-content: center;', 'text-align: center;'],\n end: ['justify-content: flex-end;', 'text-align: end;'],\n left: ['justify-content: flex-start;', 'text-align: left;']\n };\n multiRowAlign = {\n start: 'text-align: start;',\n center: 'text-align: center;',\n end: 'text-align: end;',\n auto: ''\n };\n wrapOption = {\n wrap: 'white-space: normal;',\n noWrap: 'white-space: nowrap;'\n };\n unicodeBidi = {\n normal: 'unicode-bidi: normal;',\n embed: 'unicode-bidi: embed;',\n bidiOverride: 'unicode-bidi: bidi-override;'\n };\n displayAlign = {\n before: 'align-items: flex-start;',\n center: 'align-items: center;',\n after: 'align-items: flex-end;'\n };\n writingMode = {\n lrtb: '-webkit-writing-mode: horizontal-tb;' + 'writing-mode: horizontal-tb;',\n rltb: '-webkit-writing-mode: horizontal-tb;' + 'writing-mode: horizontal-tb;' + 'direction: rtl;' + 'unicode-bidi: bidi-override;',\n tbrl: '-webkit-writing-mode: vertical-rl;' + 'writing-mode: vertical-rl;' + '-webkit-text-orientation: upright;' + 'text-orientation: upright;',\n tblr: '-webkit-writing-mode: vertical-lr;' + 'writing-mode: vertical-lr;' + '-webkit-text-orientation: upright;' + 'text-orientation: upright;',\n lr: '-webkit-writing-mode: horizontal-tb;' + 'writing-mode: horizontal-tb;',\n rl: '-webkit-writing-mode: horizontal-tb;' + 'writing-mode: horizontal-tb;' + 'direction: rtl;',\n tb: '-webkit-writing-mode: vertical-rl;' + 'writing-mode: vertical-rl;' + '-webkit-text-orientation: upright;' + 'text-orientation: upright;'\n };\n converter = new _externalsXml2json2['default']({\n escapeMode: false,\n attributePrefix: '',\n arrayAccessForm: 'property',\n emptyNodeForm: 'object',\n stripWhitespaces: false,\n enableToStringFunc: false,\n matchers: []\n });\n }\n\n function parseTimings(timingStr) {\n // Test if the time provided by the caption is valid.\n var test = timingRegex.test(timingStr);\n var timeParts, parsedTime, frameRate;\n\n if (!test) {\n // Return NaN so it will throw an exception at internalParse if the time is incorrect.\n return NaN;\n }\n\n timeParts = timingStr.split(':');\n\n // Process the timings by decomposing it and converting it in numbers.\n parsedTime = parseFloat(timeParts[0]) * SECONDS_IN_HOUR + parseFloat(timeParts[1]) * SECONDS_IN_MIN + parseFloat(timeParts[2]);\n\n // In case a frameRate is provided, we adjust the parsed time.\n if (timeParts[3]) {\n frameRate = ttml.tt.frameRate;\n if (frameRate && !isNaN(frameRate)) {\n parsedTime += parseFloat(timeParts[3]) / frameRate;\n } else {\n return NaN;\n }\n }\n return parsedTime;\n }\n\n function getNamespacePrefix(json, ns) {\n // Obtain the namespace prefix.\n var r = Object.keys(json).filter(function (k) {\n return (k.split(':')[0] === 'xmlns' || k.split(':')[1] === 'xmlns') && json[k] === ns;\n }).map(function (k) {\n return k.split(':')[2] || k.split(':')[1];\n });\n if (r.length != 1) {\n return null;\n }\n return r[0];\n }\n\n function removeNamespacePrefix(json, nsPrefix) {\n for (var key in json) {\n if (json.hasOwnProperty(key)) {\n if ((typeof json[key] === 'object' || json[key] instanceof Object) && !Array.isArray(json[key])) {\n removeNamespacePrefix(json[key], nsPrefix);\n } else if (Array.isArray(json[key])) {\n for (var i = 0; i < json[key].length; i++) {\n removeNamespacePrefix(json[key][i], nsPrefix);\n }\n }\n var fullNsPrefix = nsPrefix + ':';\n var nsPrefixPos = key.indexOf(fullNsPrefix);\n if (nsPrefixPos >= 0) {\n var newKey = key.slice(nsPrefixPos + fullNsPrefix.length);\n json[newKey] = json[key];\n delete json[key];\n }\n }\n }\n }\n\n // backgroundColor = background-color, convert from camelCase to dash.\n function camelCaseToDash(key) {\n return key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }\n\n // Convert an RGBA value written in Hex to rgba(v,v,v,a).\n function convertHexToRGBA(rgba) {\n // Get the hexadecimal value without the #.\n var hex = rgba.slice(1);\n // Separate the values in pairs.\n var hexMatrice = hex.match(/.{2}/g);\n // Convert the alpha value in decimal between 0 and 1.\n var alpha = parseFloat(parseInt(parseInt(hexMatrice[3], 16) / 255 * 1000, 10) / 1000);\n // Get the standard RGB value.\n var rgb = hexMatrice.slice(0, 3).map(function (i) {\n return parseInt(i, 16);\n });\n // Return the RGBA value for CSS.\n return 'rgba(' + rgb.join(',') + ',' + alpha + ');';\n }\n\n // Convert an RGBA value written in TTML rgba(v,v,v,a => 0 to 255) to CSS rgba(v,v,v,a => 0 to 1).\n function convertAlphaValue(rgbaTTML) {\n var rgba = undefined,\n alpha = undefined,\n resu = undefined;\n\n rgba = rgbaTTML.replace(/^(rgb|rgba)\\(/, '').replace(/\\)$/, '').replace(/\\s/g, '').split(',');\n alpha = parseInt(rgba[rgba.length - 1], 10) / 255;\n resu = 'rgba(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ',' + alpha + ');';\n\n return resu;\n }\n\n // Return whether or not an array contains a certain text\n function arrayContains(text, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].indexOf(text) > -1) {\n return true;\n }\n }\n return false;\n }\n\n // Return the whole value that contains \"text\"\n function getPropertyFromArray(text, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i].indexOf(text) > -1) {\n return array[i];\n }\n }\n return null;\n }\n\n // Delete a a property from an array.\n function deletePropertyFromArray(property, array) {\n array.splice(array.indexOf(getPropertyFromArray(property, array)), 1);\n }\n\n function mergeArrays(primeArray, arrayToAdd) {\n for (var i = 0; i < primeArray.length; i++) {\n for (var j = 0; j < arrayToAdd.length; j++) {\n // Take only the name of the property\n if (primeArray[i]) {\n if (primeArray[i].split(':')[0].indexOf(arrayToAdd[j].split(':')[0]) > -1) {\n primeArray.splice(i, 1);\n }\n }\n }\n }\n return primeArray.concat(arrayToAdd);\n }\n\n function getSizeTypeAndDefinition(cueStyleElement) {\n var returnTab = new Array(2);\n var startRef = cueStyleElement.indexOf(':') === -1 ? 0 : cueStyleElement.indexOf(':');\n var endRef = undefined;\n if (cueStyleElement.indexOf('%') === -1) {\n if (cueStyleElement.indexOf('c') === -1) {\n if (cueStyleElement.indexOf('p') === -1) {\n returnTab[0] = returnTab[1] = null;\n } else {\n returnTab[0] = 'p';\n endRef = cueStyleElement.indexOf('p');\n }\n } else {\n returnTab[0] = 'c';\n endRef = cueStyleElement.indexOf('c');\n }\n } else {\n returnTab[0] = '%';\n endRef = cueStyleElement.indexOf('%');\n }\n returnTab[1] = cueStyleElement.slice(startRef, endRef);\n return returnTab;\n }\n\n /**\n * Processing of styling information:\n * - processStyle: return an array of strings with the cue style under a CSS style form.\n * - findStyleFromID: Return the unprocessed style from TTMLStyling corresponding to the ID researched.\n * - getProcessedStyle: Return the processed style(s) from the ID(s) received in entry.\n * **/\n\n // Compute the style properties to return an array with the cleaned properties.\n function processStyle(cueStyle, cellUnit, includeRegionStyles) {\n var properties = [];\n var valueFtSizeInPx, valueLHSizeInPx;\n\n // Clean up from the xml2json parsing:\n for (var key in cueStyle) {\n if (cueStyle.hasOwnProperty(key)) {\n //Clean the properties from the parsing.\n var newKey = key.replace('ebutts:', '');\n newKey = newKey.replace('xml:', '');\n newKey = newKey.replace('tts:', '');\n\n // Clean the properties' names.\n newKey = camelCaseToDash(newKey);\n cueStyle[newKey] = cueStyle[key];\n delete cueStyle[key];\n }\n }\n\n // Line padding is computed from the cellResolution.\n if ('line-padding' in cueStyle) {\n var valuePadding = parseFloat(cueStyle['line-padding'].slice(cueStyle['line-padding'].indexOf(':') + 1, cueStyle['line-padding'].indexOf('c')));\n if ('id' in cueStyle) {\n linePadding[cueStyle.id] = valuePadding;\n }\n var valuePaddingInPx = valuePadding * cellUnit[0] + 'px;';\n properties.push('padding-left:' + valuePaddingInPx);\n properties.push('padding-right:' + valuePaddingInPx);\n }\n // Font size is computed from the cellResolution.\n if ('font-size' in cueStyle) {\n var fontSizeTab = getSizeTypeAndDefinition(cueStyle['font-size']);\n var valueFtSize = parseFloat(fontSizeTab[1]);\n if ('id' in cueStyle) {\n fontSize[cueStyle.id] = fontSizeTab;\n }\n\n if (fontSizeTab[0] === '%') {\n valueFtSizeInPx = valueFtSize / 100 * cellUnit[1] + 'px;';\n } else if (fontSizeTab[0] === 'c') {\n valueFtSizeInPx = valueFtSize * cellUnit[1] + 'px;';\n }\n\n properties.push('font-size:' + valueFtSizeInPx);\n }\n // Line height is computed from the cellResolution.\n if ('line-height' in cueStyle) {\n if (cueStyle['line-height'] === 'normal') {\n properties.push('line-height: normal;');\n } else {\n var LineHeightTab = getSizeTypeAndDefinition(cueStyle['line-height']);\n var valueLHSize = parseFloat(LineHeightTab[1]);\n if ('id' in cueStyle) {\n lineHeight[cueStyle.id] = LineHeightTab;\n }\n\n if (LineHeightTab[0] === '%') {\n valueLHSizeInPx = valueLHSize / 100 * cellUnit[1] + 'px;';\n } else if (LineHeightTab[0] === 'c') {\n valueLHSizeInPx = valueLHSize * cellUnit[1] + 'px;';\n }\n\n properties.push('line-height:' + valueLHSizeInPx);\n }\n }\n // Font-family can be specified by a generic family name or a custom family name.\n if ('font-family' in cueStyle) {\n if (cueStyle['font-family'] in fontFamilies) {\n properties.push(fontFamilies[cueStyle['font-family']]);\n } else {\n properties.push('font-family:' + cueStyle['font-family'] + ';');\n }\n }\n // Text align needs to be set from two properties:\n // The standard text-align CSS property.\n // The justify-content property as we use flex boxes.\n if ('text-align' in cueStyle) {\n if (cueStyle['text-align'] in textAlign) {\n properties.push(textAlign[cueStyle['text-align']][0]);\n properties.push(textAlign[cueStyle['text-align']][1]);\n }\n }\n // Multi Row align is set only by the text-align property.\n // TODO: TO CHECK\n if ('multi-row-align' in cueStyle) {\n if (arrayContains('text-align', properties) && cueStyle['multi-row-align'] != 'auto') {\n deletePropertyFromArray('text-align', properties);\n }\n if (cueStyle['multi-row-align'] in multiRowAlign) {\n properties.push(multiRowAlign[cueStyle['multi-row-align']]);\n }\n }\n // Background color can be specified from hexadecimal (RGB or RGBA) value.\n var rgbaValue;\n if ('background-color' in cueStyle) {\n if (cueStyle['background-color'].indexOf('#') > -1 && cueStyle['background-color'].length - 1 === 8) {\n rgbaValue = convertHexToRGBA(cueStyle['background-color']);\n } else if (cueStyle['background-color'].indexOf('rgba') > -1) {\n rgbaValue = convertAlphaValue(cueStyle['background-color']);\n } else {\n rgbaValue = cueStyle['background-color'] + ';';\n }\n properties.push('background-color: ' + rgbaValue);\n }\n // Color can be specified from hexadecimal (RGB or RGBA) value.\n if ('color' in cueStyle) {\n if (cueStyle.color.indexOf('#') > -1 && cueStyle.color.length - 1 === 8) {\n rgbaValue = convertHexToRGBA(cueStyle.color);\n } else if (cueStyle.color.indexOf('rgba') > -1) {\n rgbaValue = convertAlphaValue(cueStyle.color);\n } else {\n rgbaValue = cueStyle.color + ';';\n }\n properties.push('color: ' + rgbaValue);\n }\n // Wrap option is determined by the white-space CSS property.\n if ('wrap-option' in cueStyle) {\n if (cueStyle['wrap-option'] in wrapOption) {\n properties.push(wrapOption[cueStyle['wrap-option']]);\n } else {\n properties.push('white-space:' + cueStyle['wrap-option']);\n }\n }\n // Unicode bidi is determined by the unicode-bidi CSS property.\n if ('unicode-bidi' in cueStyle) {\n if (cueStyle['unicode-bidi'] in unicodeBidi) {\n properties.push(unicodeBidi[cueStyle['unicode-bidi']]);\n } else {\n properties.push('unicode-bidi:' + cueStyle['unicode-bidi']);\n }\n }\n\n // Standard properties identical to CSS.\n\n if ('font-style' in cueStyle) {\n properties.push('font-style:' + cueStyle['font-style'] + ';');\n }\n if ('font-weight' in cueStyle) {\n properties.push('font-weight:' + cueStyle['font-weight'] + ';');\n }\n if ('direction' in cueStyle) {\n properties.push('direction:' + cueStyle.direction + ';');\n }\n if ('text-decoration' in cueStyle) {\n properties.push('text-decoration:' + cueStyle['text-decoration'] + ';');\n }\n\n if (includeRegionStyles) {\n properties = properties.concat(processRegion(cueStyle, cellUnit));\n }\n\n // Handle white-space preserve\n if (ttml.tt.hasOwnProperty('xml:space')) {\n if (ttml.tt['xml:space'] === 'preserve') {\n properties.push('white-space: pre;');\n }\n }\n\n return properties;\n }\n\n // Find the style set by comparing the style IDs available.\n // Return null if no style is found\n function findStyleFromID(ttmlStyling, cueStyleID) {\n // For every styles available, search the corresponding style in ttmlStyling.\n for (var j = 0; j < ttmlStyling.length; j++) {\n var currStyle = ttmlStyling[j];\n if (currStyle['xml:id'] === cueStyleID || currStyle.id === cueStyleID) {\n // Return the style corresponding to the ID in parameter.\n return currStyle;\n }\n }\n return null;\n }\n // Return the computed style from a certain ID.\n function getProcessedStyle(reference, cellUnit, includeRegionStyles) {\n var styles = [];\n var ids = reference.match(/\\S+/g);\n ids.forEach(function (id) {\n // Find the style for each id received.\n var cueStyle = findStyleFromID(ttmlStyling, id);\n if (cueStyle) {\n // Process the style for the cue in CSS form.\n // Send a copy of the style object, so it does not modify the original by cleaning it.\n var stylesFromId = processStyle(JSON.parse(JSON.stringify(cueStyle)), cellUnit, includeRegionStyles);\n styles = styles.concat(stylesFromId);\n }\n });\n return styles;\n }\n\n // Calculate relative left, top, width, height from extent and origin in percent.\n // Return object with {left, top, width, height} as numbers in percent or null.\n function getRelativePositioning(element, ttExtent) {\n\n var pairRe = /([\\d\\.]+)(%|px)\\s+([\\d\\.]+)(%|px)/;\n\n if ('tts:extent' in element && 'tts:origin' in element) {\n var extentParts = pairRe.exec(element['tts:extent']);\n var originParts = pairRe.exec(element['tts:origin']);\n if (extentParts === null || originParts === null) {\n log('Bad extent or origin: ' + element['tts:extent'] + ' ' + element['tts:origin']);\n return null;\n }\n var width = parseFloat(extentParts[1]);\n var height = parseFloat(extentParts[3]);\n var left = parseFloat(originParts[1]);\n var _top = parseFloat(originParts[3]);\n\n if (ttExtent) {\n // Should give overall scale in pixels\n var ttExtentParts = pairRe.exec(ttExtent);\n if (ttExtentParts === null || ttExtentParts[2] !== 'px' || ttExtentParts[4] !== 'px') {\n log('Bad tt.extent: ' + ttExtent);\n return null;\n }\n var exWidth = parseFloat(ttExtentParts[1]);\n var exHeight = parseFloat(ttExtentParts[3]);\n if (extentParts[2] === 'px') {\n width = width / exWidth * 100;\n }\n if (extentParts[4] === 'px') {\n height = height / exHeight * 100;\n }\n if (originParts[2] === 'px') {\n left = left / exWidth * 100;\n }\n if (originParts[4] === 'px') {\n _top = _top / exHeight * 100;\n }\n }\n return { 'left': left, 'top': _top, 'width': width, 'height': height };\n } else {\n return null;\n }\n }\n\n /**\n * Processing of layout information:\n * - processRegion: return an array of strings with the cue region under a CSS style form.\n * - findRegionFromID: Return the unprocessed region from TTMLLayout corresponding to the ID researched.\n * - getProcessedRegion: Return the processed region(s) from the ID(s) received in entry.\n ***/\n\n // Compute the region properties to return an array with the cleaned properties.\n function processRegion(cueRegion, cellUnit) {\n var properties = [];\n\n // Clean up from the xml2json parsing:\n for (var key in cueRegion) {\n //Clean the properties from the parsing.\n var newKey = key.replace('tts:', '');\n newKey = newKey.replace('xml:', '');\n\n // Clean the properties' names.\n newKey = camelCaseToDash(newKey);\n cueRegion[newKey] = cueRegion[key];\n if (newKey !== key) {\n delete cueRegion[key];\n }\n }\n // Extent property corresponds to width and height\n if ('extent' in cueRegion) {\n var coordsExtent = cueRegion.extent.split(/\\s/);\n properties.push('width: ' + coordsExtent[0] + ';');\n properties.push('height: ' + coordsExtent[1] + ';');\n }\n // Origin property corresponds to top and left\n if ('origin' in cueRegion) {\n var coordsOrigin = cueRegion.origin.split(/\\s/);\n properties.push('left: ' + coordsOrigin[0] + ';');\n properties.push('top: ' + coordsOrigin[1] + ';');\n }\n // DisplayAlign property corresponds to vertical-align\n if ('display-align' in cueRegion) {\n properties.push(displayAlign[cueRegion['display-align']]);\n }\n // WritingMode is not yet implemented (for CSS3, to come)\n if ('writing-mode' in cueRegion) {\n properties.push(writingMode[cueRegion['writing-mode']]);\n }\n // Style will give to the region the style properties from the style selected\n if ('style' in cueRegion) {\n var styleFromID = getProcessedStyle(cueRegion.style, cellUnit, true);\n properties = properties.concat(styleFromID);\n }\n\n // Standard properties identical to CSS.\n\n if ('padding' in cueRegion) {\n properties.push('padding:' + cueRegion.padding + ';');\n }\n if ('overflow' in cueRegion) {\n properties.push('overflow:' + cueRegion.overflow + ';');\n }\n if ('show-background' in cueRegion) {\n properties.push('show-background:' + cueRegion['show-background'] + ';');\n }\n if ('id' in cueRegion) {\n properties.push('regionID:' + cueRegion.id + ';');\n }\n\n return properties;\n }\n\n // Find the region set by comparing the region IDs available.\n // Return null if no region is found\n function findRegionFromID(ttmlLayout, cueRegionID) {\n // For every region available, search the corresponding style in ttmlLayout.\n for (var j = 0; j < ttmlLayout.length; j++) {\n var currReg = ttmlLayout[j];\n if (currReg['xml:id'] === cueRegionID || currReg.id === cueRegionID) {\n // Return the region corresponding to the ID in parameter.\n return currReg;\n }\n }\n return null;\n }\n\n // Return the computed region from a certain ID.\n function getProcessedRegion(reference, cellUnit) {\n var regions = [];\n var ids = reference.match(/\\S+/g);\n ids.forEach(function (id) {\n // Find the region for each id received.\n var cueRegion = findRegionFromID(ttmlLayout, id);\n if (cueRegion) {\n // Process the region for the cue in CSS form.\n // Send a copy of the style object, so it does not modify the original by cleaning it.\n var regionsFromId = processRegion(JSON.parse(JSON.stringify(cueRegion)), cellUnit);\n regions = regions.concat(regionsFromId);\n }\n });\n return regions;\n }\n\n //Return the cellResolution defined by the TTML document.\n function getCellResolution() {\n var defaultCellResolution = [32, 15]; // Default cellResolution.\n if (ttml.tt.hasOwnProperty('ttp:cellResolution')) {\n return ttml.tt['ttp:cellResolution'].split(' ').map(parseFloat);\n } else {\n return defaultCellResolution;\n }\n }\n\n // Return the cue wrapped into a span specifying its linePadding.\n function applyLinePadding(cueHTML, cueStyle) {\n // Extract the linePadding property from cueStyleProperties.\n var linePaddingLeft = getPropertyFromArray('padding-left', cueStyle);\n var linePaddingRight = getPropertyFromArray('padding-right', cueStyle);\n var linePadding = linePaddingLeft.concat(' ' + linePaddingRight + ' ');\n\n // Declaration of the HTML elements to be used in the cue innerHTML construction.\n var outerHTMLBeforeBr = '';\n var outerHTMLAfterBr = '';\n var cueInnerHTML = '';\n\n // List all the nodes of the subtitle.\n var nodeList = Array.prototype.slice.call(cueHTML.children);\n // Take a br element as reference.\n var brElement = cueHTML.getElementsByClassName('lineBreak')[0];\n // First index of the first br element.\n var idx = nodeList.indexOf(brElement);\n // array of all the br element indices\n var indices = [];\n // Find all the indices of the br elements.\n while (idx != -1) {\n indices.push(idx);\n idx = nodeList.indexOf(brElement, idx + 1);\n }\n\n // Strings for the cue innerHTML construction.\n var spanStringEnd = '<\\/span>';\n var br = '<br>';\n var clonePropertyString = '<span' + ' class=\"spanPadding\" ' + 'style=\"-webkit-box-decoration-break: clone; box-decoration-break: clone; ';\n\n // If br elements are found:\n if (indices.length) {\n // For each index of a br element we compute the HTML coming before and/or after it.\n indices.forEach(function (i, index) {\n // If this is the first line break, we compute the HTML of the element coming before.\n if (index === 0) {\n var styleBefore = '';\n // for each element coming before the line break, we add its HTML.\n for (var j = 0; j < i; j++) {\n outerHTMLBeforeBr += nodeList[j].outerHTML;\n // If this is the first element, we add its style to the wrapper.\n if (j === 0) {\n styleBefore = linePadding.concat(nodeList[j].style.cssText);\n }\n }\n // The before element will comprises the clone property (for line wrapping), the style that\n // need to be applied (ex: background-color) and the rest og the HTML.\n outerHTMLBeforeBr = clonePropertyString + styleBefore + '\">' + outerHTMLBeforeBr;\n }\n // For every element of the list, we compute the element coming after the line break.s\n var styleAfter = '';\n // for each element coming after the line break, we add its HTML.\n for (var k = i + 1; k < nodeList.length; k++) {\n outerHTMLAfterBr += nodeList[k].outerHTML;\n // If this is the last element, we add its style to the wrapper.\n if (k === nodeList.length - 1) {\n styleAfter += linePadding.concat(nodeList[k].style.cssText);\n }\n }\n\n // The before element will comprises the clone property (for line wrapping), the style that\n // need to be applied (ex: background-color) and the rest og the HTML.\n outerHTMLAfterBr = clonePropertyString + styleAfter + '\">' + outerHTMLAfterBr;\n\n // For each line break we must add the before and/or after element to the final cue as well as\n // the line break when needed.\n if (outerHTMLBeforeBr && outerHTMLAfterBr && index === indices.length - 1) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd + br + outerHTMLAfterBr + spanStringEnd;\n } else if (outerHTMLBeforeBr && outerHTMLAfterBr && index !== indices.length - 1) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd + br + outerHTMLAfterBr + spanStringEnd + br;\n } else if (outerHTMLBeforeBr && !outerHTMLAfterBr) {\n cueInnerHTML += outerHTMLBeforeBr + spanStringEnd;\n } else if (!outerHTMLBeforeBr && outerHTMLAfterBr && index === indices.length - 1) {\n cueInnerHTML += outerHTMLAfterBr + spanStringEnd;\n } else if (!outerHTMLBeforeBr && outerHTMLAfterBr && index !== indices.length - 1) {\n cueInnerHTML += outerHTMLAfterBr + spanStringEnd + br;\n }\n });\n } else {\n // If there is no line break in the subtitle, we simply wrap cue in a span indicating the linePadding.\n var style = '';\n for (var k = 0; k < nodeList.length; k++) {\n style += nodeList[k].style.cssText;\n }\n cueInnerHTML = clonePropertyString + linePadding + style + '\">' + cueHTML.innerHTML + spanStringEnd;\n }\n return cueInnerHTML;\n }\n\n /*\n * Create the cue element\n * I. The cues are text only:\n * i) The cue contains a 'br' element\n * ii) The cue contains a span element\n * iii) The cue contains text\n */\n\n function constructCue(cueElements, cellUnit) {\n var cue = document.createElement('div');\n cueElements.forEach(function (el) {\n // If metadata is present, do not process.\n if (el.hasOwnProperty('metadata')) {\n return;\n }\n\n /**\n * If the p element contains spans: create the span elements.\n */\n if (el.hasOwnProperty('span')) {\n\n // Stock the span subtitles in an array (in case there are only one value).\n var spanElements = el.span.__children;\n\n // Create the span element.\n var spanHTMLElement = document.createElement('span');\n // Extract the style of the span.\n if (el.span.hasOwnProperty('style')) {\n var spanStyle = getProcessedStyle(el.span.style, cellUnit);\n spanHTMLElement.className = 'spanPadding ' + el.span.style;\n spanHTMLElement.style.cssText = spanStyle.join(' ');\n }\n\n // if the span has more than one element, we check for each of them their nature (br or text).\n spanElements.forEach(function (spanEl) {\n // If metadata is present, do not process.\n if (spanElements.hasOwnProperty('metadata')) {\n return;\n }\n // If the element is a string\n if (spanEl.hasOwnProperty('#text')) {\n var textNode = document.createTextNode(spanEl['#text']);\n spanHTMLElement.appendChild(textNode);\n // If the element is a 'br' tag\n } else if ('br' in spanEl) {\n // To handle br inside span we need to add the current span\n // to the cue and then create a br and add that the cue\n // then create a new span that we use for the next line of\n // text, that is a copy of the current span\n\n // Add the current span to the cue, only if it has childNodes (text)\n if (spanHTMLElement.hasChildNodes()) {\n cue.appendChild(spanHTMLElement);\n }\n\n // Create a br and add that to the cue\n var brEl = document.createElement('br');\n brEl.className = 'lineBreak';\n cue.appendChild(brEl);\n\n // Create an replacement span and copy the style and classname from the old one\n var newSpanHTMLElement = document.createElement('span');\n newSpanHTMLElement.className = spanHTMLElement.className;\n newSpanHTMLElement.style.cssText = spanHTMLElement.style.cssText;\n\n // Replace the current span with the one we just created\n spanHTMLElement = newSpanHTMLElement;\n }\n });\n // We append the element to the cue container.\n cue.appendChild(spanHTMLElement);\n }\n\n /**\n * Create a br element if there is one in the cue.\n */\n else if (el.hasOwnProperty('br')) {\n // We append the line break to the cue container.\n var brEl = document.createElement('br');\n brEl.className = 'lineBreak';\n cue.appendChild(brEl);\n }\n\n /**\n * Add the text that is not in any inline element\n */\n else if (el.hasOwnProperty('#text')) {\n // Add the text to an individual span element (to add line padding if it is defined).\n var textNode = document.createElement('span');\n textNode.textContent = el['#text'];\n\n // We append the element to the cue container.\n cue.appendChild(textNode);\n }\n });\n return cue;\n }\n\n function constructCueRegion(cue, div, cellUnit) {\n var cueRegionProperties = []; // properties to be put in the \"captionRegion\" HTML element\n // Obtain the region ID(s) assigned to the cue.\n var pRegionID = cue.region;\n // If div has a region.\n var divRegionID = div.region;\n\n var divRegion;\n var pRegion;\n\n // If the div element reference a region.\n if (divRegionID) {\n divRegion = getProcessedRegion(divRegionID, cellUnit);\n }\n // If the p element reference a region.\n if (pRegionID) {\n pRegion = cueRegionProperties.concat(getProcessedRegion(pRegionID, cellUnit));\n if (divRegion) {\n cueRegionProperties = mergeArrays(divRegion, pRegion);\n } else {\n cueRegionProperties = pRegion;\n }\n } else if (divRegion) {\n cueRegionProperties = divRegion;\n }\n\n // Add initial/default values to what's not defined in the layout:\n applyDefaultProperties(cueRegionProperties, defaultLayoutProperties);\n\n return cueRegionProperties;\n }\n\n function constructCueStyle(cue, cellUnit) {\n var cueStyleProperties = []; // properties to be put in the \"paragraph\" HTML element\n // Obtain the style ID(s) assigned to the cue.\n var pStyleID = cue.style;\n // If body has a style.\n var bodyStyleID = ttml.tt.body.style;\n // If div has a style.\n var divStyleID = ttml.tt.body.div.style;\n\n var bodyStyle;\n var divStyle;\n var pStyle;\n var styleIDs = '';\n\n // If the body element reference a style.\n if (bodyStyleID) {\n bodyStyle = getProcessedStyle(bodyStyleID, cellUnit);\n styleIDs = 'paragraph ' + bodyStyleID;\n }\n\n // If the div element reference a style.\n if (divStyleID) {\n divStyle = getProcessedStyle(divStyleID, cellUnit);\n if (bodyStyle) {\n divStyle = mergeArrays(bodyStyle, divStyle);\n styleIDs += ' ' + divStyleID;\n } else {\n styleIDs = 'paragraph ' + divStyleID;\n }\n }\n\n // If the p element reference a style.\n if (pStyleID) {\n pStyle = getProcessedStyle(pStyleID, cellUnit);\n if (bodyStyle && divStyle) {\n cueStyleProperties = mergeArrays(divStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else if (bodyStyle) {\n cueStyleProperties = mergeArrays(bodyStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else if (divStyle) {\n cueStyleProperties = mergeArrays(divStyle, pStyle);\n styleIDs += ' ' + pStyleID;\n } else {\n cueStyleProperties = pStyle;\n styleIDs = 'paragraph ' + pStyleID;\n }\n } else if (bodyStyle && !divStyle) {\n cueStyleProperties = bodyStyle;\n } else if (!bodyStyle && divStyle) {\n cueStyleProperties = divStyle;\n }\n\n // Add initial/default values to what's not defined in the styling:\n applyDefaultProperties(cueStyleProperties, defaultStyleProperties);\n\n return [cueStyleProperties, styleIDs];\n }\n\n function applyDefaultProperties(array, defaultProperties) {\n for (var key in defaultProperties) {\n if (defaultProperties.hasOwnProperty(key)) {\n if (!arrayContains(key, array)) {\n array.push(key + ':' + defaultProperties[key]);\n }\n }\n }\n }\n\n instance = {\n parse: parse,\n setConfig: setConfig\n };\n\n setup();\n return instance;\n}", "function HTMLDecode(encodedStr){\n\t\treturn $(\"<div/>\").html(encodedStr).text();\n\t}", "function comment2HTML(str, complete)\r\n{\r\n txt = \"\";\r\n comments = str.split(\"--####--\");\r\n parts = comments[0].trim().split(\"-//-\");\r\n\r\n if (!complete)\r\n {\r\n\tfor (i = 0; i < parts.length; ++i)\r\n\t{\r\n part = parts[i].trim();\r\n title = /\\[.+\\]\\:/.exec(part)[0];\r\n title = title.substr(1, title.length - 3);\r\n partCom = part.substr(title.length + 3);\r\n txt += \"<p><b>\" + title + \"</b> :\" + partCom + \"</p>\";\r\n\t}\r\n }\r\n\r\n txt += \"<hr style='border: 0; background-color: Black; margin: 8px;' />\";\r\n general = comments[1].trim();\r\n txt += \"<p><b>General</b> : \" + general.substr(9) + \"</p>\";\r\n txt += \"<hr style='border: 0; background-color: Black; margin: 8px;' />\";\r\n\r\n comment = comments[comments.length - 1];\r\n if (!complete)\r\n {\r\n\tfor (i = 2; i < comments.length; ++i)\r\n\t{\r\n comment = comments[i].trim();\r\n login = /[^ ]+\\:/i.exec(comment)[0];\r\n login = login.substr(0, login.length - 1);\r\n text = comment.substr(login.length + 1).trim().replace(/\\/ (.+) \\: ([-0-9]+) /giU, \"\").replace(/\\/ ([0-9]{4})([0-9]{2})([0-9]{2}):([0-9]{2})([0-9]{2})([0-9]{2}) \\/ ([a-z_]+)/gi, \"\");\r\n\t txt += \"<p><img src='photo.php?login=\" + login + \"' style='width:60px; float: left; padding: 1px 2px 0 0;' /><b>\" + login + \"</b> : \" + text + \"<br style='clear: both'></p>\";\r\n\t}\r\n }\r\n // FinalNotes regex --> /\\/ (.+) \\: ([-0-9]+) /giU\r\n\r\n // SPECIFIQUE\r\n if (comment != \"\" && (info = comment.split(/\\/ ([0-9]{4})([0-9]{2})([0-9]{2}):([0-9]{2})([0-9]{2})([0-9]{2}) \\/ ([a-z_]+)/gi)))\r\n {\r\n //txt = txt.substr(0, txt.indexOf(end[0])) + txt.substr(txt.indexOf(end[0]) + end[0].length);\r\n //txt = txt.replace(/\\\\'/g, \"'\").replace(/\\\\\"/g, '\"');\r\n txt += \"<p style='text-align: right; font-style: italic;'>Not&eacute; \" +\r\n\t \"le \" + info[3] + \".\" + info[2] + \".\" + info[1] + \" a \" + info[4] + \":\" + info[5] + \":\" + info[6] +\r\n\t \" par : <b> <a href=\\\"/intra/index.php?section=etudiant&page=rapport&login=\" + info[7] + \"\\\" style=\\\"color:#333;\\\">\" + info[7] + \"</a></b></p>\";\r\n }\r\n return txt;\r\n}", "function ParseAndLoadTTML(ttml) {\n\n var rxBr = /<br\\s*\\/>/g;\n var rxMarkup = /<[^>]+>/g;\n var rxP = /<p\\s+([^>]+)>\\s*((?:\\s|.)*?)\\s*<\\/p>/g;\n var rxTime = /(begin|end|dur)\\s*=\\s*\"([\\d.:]+)(h|m|s|ms|t)?\"/g;\n\n var tickRateMatch = ttml.match(/<tt\\s[^>]*ttp:tickRate\\s*=\\s*\"(\\d+)\"[^>]*>/i);\n var tickRate = (tickRateMatch != null) ? parseInt(tickRateMatch[1], 10) : 1;\n if (tickRate == 0)\n tickRate = 1;\n\n var pMatch;\n while ((pMatch = rxP.exec(ttml)) != null) {\n var cues = {};\n var timeMatch;\n rxTime.lastIndex = 0;\n var attrs = pMatch[1];\n while ((timeMatch = rxTime.exec(attrs)) != null) {\n var seconds;\n var metric = timeMatch[3];\n if (metric) {\n seconds = parseFloat(timeMatch[2]);\n if (metric == \"h\")\n seconds *= (60 * 60);\n else if (metric == \"m\")\n seconds *= 60;\n else if (metric == \"ms\")\n seconds /= 1000;\n else if (metric == \"t\")\n seconds /= tickRate;\n }\n else {\n seconds = ParseTime(timeMatch[2]);\n }\n\n cues[timeMatch[1]] = seconds;\n }\n\n if (\"begin\" in cues && (\"end\" in cues || \"dur\" in cues)) {\n var cueEnd = \"end\" in cues ? cues.end : (cues.begin + cues.dur);\n var cueText = Trim(XMLDecode(pMatch[2].replace(/[\\r\\n]+/g, \"\").replace(rxBr, \"\\n\").replace(rxMarkup, \"\").replace(/ {2,}/g, \" \")));\n captionsArray.push({ start: cues.begin, end: cueEnd, caption: cueText });\n }\n }\n\n SortAndDisplayCaptionList();\n}", "function hstrip(eme){\r\n\teme = eme.replace(/\\n/g,\"\\\\n\")\r\n\teme = eme.replace(/<a.+?addclass.+?see more<\\/a>/g,\"\");/*special case: \"see more\" is a meme-spreading group. adding that to your blocklist will generate A TON of false-positivies.*/\r\n\teme = eme.replace(/<\\/?a ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/<\\/?i ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/<\\/?img ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/<\\/?div ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/<\\/?h5 ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/<\\/?li ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/<\\/?form ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/<\\/?span ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/<\\/?label ?.+?>/g,\"\");/*don't look *inside* tags*/\r\n\teme = eme.replace(/&quot;/g,'\"');/*basic stuff that apparently caused problems.*/\r\n\teme = eme.replace(/&amp;/g,'&');\r\n\teme = eme.replace(/&lt;/g,'<');\r\n\teme = eme.replace(/&gt;/g,'>');\r\n\treturn eme\r\n}", "_parseHTML(htmlString) {\n //current xpath is body.div[i].table.tbody.tr[j].td[1-5]\n let cleanedHtmlString = htmlString.replace(/(\\\\t|\\\\n|&nbsp;)/gi,'');\n let root = htmlParser.parse(htmlString);\n let divs = root.querySelectorAll('div');\n if (divs) {\n for (let div of divs) {\n let table = div.querySelector('table');\n if (!table) {\n continue;\n }\n\n let tbody = table.querySelector('tbody');\n if (!tbody) {\n continue;\n }\n\n let rows = tbody.querySelectorAll('tr');\n if (!rows) {\n continue;\n }\n for (let row of rows) {\n let cols = row.querySelectorAll('td');\n //take 5 cols from here\n this._data.add(cols[0].rawText, cols[1].rawText, cols[2].rawText, cols[4].rawText);\n }\n }\n }\n }", "function ver1GotPost (rslt){\r\n if (rslt == null){\r\n notify ({ok:false, msg:\"AJAX Error\"});\r\n return;\r\n }\r\n var m = /<div class=\\'nm\\'>(.*?)<\\/div/im.exec(rslt);\r\n if (m)\r\n notify ({ok:false, msg: 'Got '+ m[1]});\r\n else\r\n notify ({ok:true, msg:'OK'});\r\n }", "function parseHTMLInOpener (html) {\n var div = global.opener.document.createElement('div');\n div.innerHTML = html;\n return div.children[0];\n }", "function xhrParser(script) {\n var elements = []\n var lines = script.split(\"\\n\");\n var text = script.split(\"\");\n var i = 0;\n lines.forEach(e => {\n if (e.startsWith(\"//\")) return e.split(\"\").forEach(_=>i++);\n var str = false;\n e.split(\"\").forEach(v => {\n var s = script;\n if (v == \"\\\"\") str = !str;\n if (v == \"<\" && !str) {\n var ele = parseElement(s, i);\n if (ele) elements.push(ele);\n }\n i++;\n });\n i += 1;\n });\n elements.forEach((v, i) => {\n var s = script;\n fixChilds(s, elements, i);\n });\n elements.reverse().forEach(v => {\n script = remove(script, v[1][3], v[1][4], toJS(v));\n });\n ls.push(script);\n }", "function parseHTML(text) {\r\n\tvar dt = document.implementation.createDocumentType('html', '-//W3C//DTD HTML 4.01 Transitional//EN', 'http://www.w3.org/TR/html4/loose.dtd'),\r\n\t\tdoc = document.implementation.createDocument('', '', dt),\r\n\t\thtml = doc.createElement('html'),\r\n\t\thead = doc.createElement('head'),\r\n\t\tbody = doc.createElement('body');\r\n\tdoc.appendChild(html);\r\n\thtml.appendChild(head);\r\n\tbody.innerHTML = text;\r\n\thtml.appendChild(body);\r\n\treturn doc;\r\n}", "function parsePacketForHTML(packet){\n console.log(\"This is what requestTabForHTML recieves\",packet);\n return Promise.resolve(packet.response);\n}", "function parseHTML(str) {\n const tmp = document.implementation.createHTMLDocument();\n tmp.body.innerHTML = str;\n\n return tmp.body;\n}", "decodeString(string) {\n\t\tconst parser = new DOMParser();\n\t\tconst dom = parser.parseFromString(\n\t\t\t'<!doctype html><body>' + string,\n\t\t\t'text/html');\n\t\treturn dom.body.textContent;\n\t}", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]*>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n function unescape(s) {\n TEXTAREA_ELEMENT.innerHTML = s;\n s = TEXTAREA_ELEMENT.textContent;\n TEXTAREA_ELEMENT.textContent = \"\";\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n var classes = m[2].split('.');\n\n classes.forEach(function(cl) {\n var bgColor = /^bg_/.test(cl);\n // slice out `bg_` if it's a background color\n var colorName = bgColor ? cl.slice(3) : cl;\n\n if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {\n var propName = bgColor ? 'background-color' : 'color';\n var propValue = DEFAULT_COLOR_CLASS[colorName];\n\n node.style[propName] = propValue;\n }\n });\n\n node.className = classes.join(' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n}", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]*>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n function unescape(s) {\n TEXTAREA_ELEMENT.innerHTML = s;\n s = TEXTAREA_ELEMENT.textContent;\n TEXTAREA_ELEMENT.textContent = \"\";\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n var classes = m[2].split('.');\n\n classes.forEach(function(cl) {\n var bgColor = /^bg_/.test(cl);\n // slice out `bg_` if it's a background color\n var colorName = bgColor ? cl.slice(3) : cl;\n\n if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {\n var propName = bgColor ? 'background-color' : 'color';\n var propValue = DEFAULT_COLOR_CLASS[colorName];\n\n node.style[propName] = propValue;\n }\n });\n\n node.className = classes.join(' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n}", "function parseTag(tagText) {\n \n}", "function unescapeHtml(escapedStr) {\n var div = document.createElement('div');\n div.innerHTML = escapedStr;\n var child = div.childNodes[0];\n return child ? child.nodeValue : '';\n}", "function unescapeHtml(escapedStr) {\n var div = document.createElement('div');\n div.innerHTML = escapedStr;\n var child = div.childNodes[0];\n return child ? child.nodeValue : '';\n}", "function htmlToText(e){return e.replace(/<\\/div>\\n/gi,\"\").replace(/<\\/p>/gi,\"\").replace(/<\\/span>/gi,\"\").replace(/<\\/div>/gi,\"\").replace(/<\\/ul>/gi,\"\").replace(/<\\/li>/gi,\"\").replace(/<\\/strong>/gi,\"\").replace(/<\\/center>/gi,\"\").replace(/<\\/pre>/gi,\"\").replace(/<\\s*p[^>]*>/gi,\"\").replace(/<\\s*span[^>]*>/gi,\"\").replace(/<\\s*div[^>]*>/gi,\"\").replace(/<\\s*ul[^>]*>/gi,\"\").replace(/<\\s*li[^>]*>/gi,\"\").replace(/<\\s*strong[^>]*>/gi,\"\").replace(/<\\s*center[^>]*>/gi,\"\").replace(/<\\s*pre[^>]*>/gi,\"\").replace(/<hr>/gi,\"\").replace(/<div><br>/gi,\"\\n\").replace(/<div>/gi,\"\").replace(/<\\s*br[^>]*>/gi,\"\\n\").replace(/<\\s*\\/li[^>]*>/gi,\"\").replace(/<\\s*script[^>]*>[\\s\\S]*?<\\/script>/gim,\"\").replace(/<\\s*style[^>]*>[\\s\\S]*?<\\/style>/gim,\"\").replace(/<!--.*?-->/gim,\"\").replace(/<\\s*a[^>]*href=['\"](.*?)['\"][^>]*>([\\s\\S]*?)<\\/\\s*a\\s*>/gi,\"$2 ($1)\").replace(/&([^;]+);/g,decodeHtmlEntity)}", "function html_decode(text)\n{\n var tmp = document.createElement('textarea');\n tmp.innerHTML = text;\n return tmp.innerText;\n}", "function htmlDecode(encodedStr) {\n const parser = DOMParser && new DOMParser;\n if (parser && parser.parseFromString) {\n const dom = parser.parseFromString('<!doctype html><body>' + encodedStr, 'text/html');\n return dom && dom.body && dom.body.textContent;\n }\n else {\n // for some browsers that might not support DOMParser, use jQuery instead\n return $('<div/>').html(encodedStr).text();\n }\n}", "function parseBBList(bbdiv)\n{\n var lines = new Array(\n \"[b]$[/b]$Bold$font-weight:bold\",\n \"[i]$[/i]$Italic$font-style:italic\",\n \"[u]$[/u]$Underline$text-decoration:underline\",\n \"[code]$[/code]$Code$font-family:Courier\",\n \"---\",\n \"[red]$[/red]$Red$color:#ff0000\",\n \"[green]$[/green]$Green$color:#00ff00\",\n \"[blue]$[/blue]$Blue$color:#0000ff\");\n\n // Iterate through lines\n for (var i = 0; i < lines.length; i++)\n {\n if (lines[i] == \"---\")\n {\n var br = document.createElement(\"br\");\n bbdiv.appendChild(br);\n }\n else if (! lines[i] == \"\")\n {\n // Split entry into parts\n var parts = lines[i].split(\"$\");\n var start = parts[0];\n var end = parts[1];\n var meaning = parts[2];\n var htmlstyle = parts[3];\n // Add link to div\n bbdiv.appendChild(newLink(start, end, meaning, htmlstyle));\n }\n }\n}", "function parseTypografAnswer(text) {\r\n var re = /<ProcessTextResult>\\s*((.|\\n)*?)\\s*<\\/ProcessTextResult>/m;\r\n var response = re.exec(text);\r\n response = RegExp.$1;\r\n response = response.replace(/&gt;/g, '>');\r\n response = response.replace(/&lt;/g, '<');\r\n response = response.replace(/&amp;/g, '&');\r\n\r\n if (textarea) { // To be sure that user was not faster than script\r\n textarea.value = response;\r\n if (shouldSubmit) {\r\n submitForm(textarea);\r\n }\r\n }\r\n textarea = null;\r\n}", "function html2node(str){\n var container = document.createElement('div');\n container.innerHTML = str;\n return container.children[0];\n }", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n } // Consume 'n' characters from the input.\n\n\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]*>?)?/); // If there is some text before the next tag, return it, otherwise return\n // the tag.\n\n return consume(m[1] ? m[1] : m[2]);\n } // Unescape a string 's'.\n\n\n function unescape1(e) {\n return ESCAPE[e];\n }\n\n function unescape(s) {\n while (m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/)) {\n s = s.replace(m[0], unescape1);\n }\n\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName;\n } // Create an element for this tag.\n\n\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n\n if (!tagName) {\n return null;\n }\n\n var element = window.document.createElement(tagName);\n element.localName = tagName;\n var name = TAG_ANNOTATION[type];\n\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n } // Otherwise just ignore the end tag.\n\n\n continue;\n }\n\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/); // If we can't parse the tag, skip to the next tag.\n\n if (!m) {\n continue;\n } // Try to construct an element, and ignore the tag if we couldn't.\n\n\n node = createElement(m[1], m[3]);\n\n if (!node) {\n continue;\n } // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n\n\n if (!shouldAdd(current, node)) {\n continue;\n } // Set the class list (as a list of classes, separated by space).\n\n\n if (m[2]) {\n node.className = m[2].substr(1).replace('.', ' ');\n } // Append the node to the current node, and enter the scope of the new\n // node.\n\n\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n } // Text nodes are leaf nodes.\n\n\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n } // This is a list of all the Unicode characters that have a strong", "function processByDOM(responseHTML, target) {\n target.innerHTML = \"Extracted by id:<br />\";\n\n // does not work with Chrome/Safari\n //var message = responseHTML.getElementsByTagName(\"div\").namedItem(\"two\").innerHTML;\n var message = responseHTML.getElementsByTagName(\"div\").item(1).innerHTML;\n\n target.innerHTML += message;\n\n target.innerHTML += \"<br />Extracted by name:<br />\";\n\n message = responseHTML.getElementsByTagName(\"form\").item(0);\n target.innerHTML += message.dyn.value;\n}", "function makeDNODE(t, rowcount, div, shoutid )\r\n{\r\n\tvar ret = true;\r\n\r\n GM_xmlhttpRequest({\r\n method:\"GET\",\r\n url:t,\r\n headers:{\r\n \"User-Agent\":navigator.userAgent\r\n },\r\n onload:function(details)\r\n {\r\n ret = false;\r\n var mrowcount = rowcount;\r\n var mdiv = div;\r\n var span = document.createElement('span');\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Break out the link to the actual article so we can replace it\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar splitter = '<h3 id=\"title\">';\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar r1 = details.responseText;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar r2 = r1.split(splitter);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar r3 = r2[1].split(\"</h3>\");\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar r4 = r3[0].split('\"');\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar hr = r4[1];\r\n\r\n var DiggItLink = MyGetDiggitLink(details.responseText, mrowcount);\r\n\r\n if(DiggItLink)\r\n {\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Replace all links to the Digg page with the link to the actual article\r\n \t\t\t\t\t\t\t\t\t\tvar l2 = div.getElementsByTagName('a');\r\n \t\t\t\t\t\t\t\t\tfor(var j=0; j<l2.length; j++ ) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t if ( l2[j].href == t && l2[j].className != 'digg-count') {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t l2[j].href = hr;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t }\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\r\n\r\n span.id = 'diglink' + mrowcount;\r\n span.className = \"digg-it\";\r\n var a = document.createElement('a');\r\n a.href = DiggItLink;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t a.id = 'digg-shout-'+shoutid;\r\n var txt = document.createTextNode(' ');\r\n div.appendChild(txt);\r\n span.appendChild(a);\r\n var txt = document.createTextNode('[digg]');\r\n a.appendChild(txt);\r\n mdiv.appendChild(span);\r\n\r\n }\r\n else\r\n \t {\r\n \t span.innerHTML = ' <strong>dugg!<strong>';\r\n \t mdiv.appendChild(span);\r\n \t }\r\n\r\n\r\n },\r\n\r\n onerror:function(details)\r\n {\r\n ret = false;\r\n var span = document.createElement('span');\r\n var txt = document.createTextNode(details.statusText);\r\n span.appendChild(txt);\r\n div.appendChild(span);\r\n\r\n }\r\n\r\n });\r\nreturn ret;\r\n}", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]*>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n // Unescape a string 's'.\n function unescape1(e) {\n return ESCAPE[e];\n }\n function unescape(s) {\n while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {\n s = s.replace(m[0], unescape1);\n }\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n element.localName = tagName;\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n node.className = m[2].substr(1).replace('.', ' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n}", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]*>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n // Unescape a string 's'.\n function unescape1(e) {\n return ESCAPE[e];\n }\n function unescape(s) {\n while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {\n s = s.replace(m[0], unescape1);\n }\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n element.localName = tagName;\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n node.className = m[2].substr(1).replace('.', ' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n}", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]*>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n // Unescape a string 's'.\n function unescape1(e) {\n return ESCAPE[e];\n }\n function unescape(s) {\n while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {\n s = s.replace(m[0], unescape1);\n }\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n element.localName = tagName;\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n node.className = m[2].substr(1).replace('.', ' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n}", "function wikifyTextNodes(theNode,w)\r\n{\r\n\tfunction unmask(s) { return s.replace(/\\%%\\(/g,'<<').replace(/\\)\\%%/g,'>>').replace(/\\\\n/g,'\\n'); }\r\n\tswitch (theNode.nodeName.toLowerCase()) {\r\n\t\tcase 'style': case 'option': case 'select':\r\n\t\t\ttheNode.innerHTML=unmask(theNode.innerHTML);\r\n\t\t\tbreak;\r\n\t\tcase 'textarea':\r\n\t\t\ttheNode.value=unmask(theNode.value);\r\n\t\t\tbreak;\r\n\t\tcase '#text':\r\n\t\t\tvar txt=unmask(theNode.nodeValue);\r\n\t\t\tvar newNode=createTiddlyElement(null,\"span\");\r\n\t\t\ttheNode.parentNode.replaceChild(newNode,theNode);\r\n\t\t\twikify(txt,newNode,highlightHack,w.tiddler);\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tfor (var i=0;i<theNode.childNodes.length;i++)\r\n\t\t\t\twikifyTextNodes(theNode.childNodes.item(i),w); // recursion\r\n\t\t\tbreak;\r\n\t}\r\n}", "function strip(html)\n{\n var tmp = document.createElement(\"DIV\");\n tmp.innerHTML = html;\n return tmp.textContent || tmp.innerText || \"\";\n}", "function htmlDecode(str) {\n return $(\"<div/>\").html(str).text();\n}", "function parseDom(str, mime) {\n return (new DOMParser()).parseFromString(str, mime)\n}", "function decodeHTMLEntities(str) {\n var element = document.createElement('div');\n if (str && typeof str === 'string') {\n // strip script/html tags\n str = str.replace(/<script[^>]*>([\\S\\s]*?)<\\/script>/gmi, '');\n str = str.replace(/<\\/?\\w(?:[^\"'>]|\"[^\"]*\"|'[^']*')*>/gmi, '');\n element.innerHTML = str;\n str = element.textContent;\n element.textContent = '';\n }\n\n return str;\n }", "function sanitizeHtml(html, options, _recursing) {\n var result = '';\n\n function Frame(tag, attribs) {\n var that = this;\n this.tag = tag;\n this.attribs = attribs || {};\n this.tagPosition = result.length;\n this.text = ''; // Node inner text\n\n this.updateParentNodeText = function() {\n if (stack.length) {\n var parentFrame = stack[stack.length - 1];\n parentFrame.text += that.text;\n }\n };\n }\n\n if (!options) {\n options = sanitizeHtml.defaults;\n options.parser = htmlParserDefaults;\n } else {\n options = extend(sanitizeHtml.defaults, options);\n if (options.parser) {\n options.parser = extend(htmlParserDefaults, options.parser);\n } else {\n options.parser = htmlParserDefaults;\n }\n }\n\n // Tags that contain something other than HTML, or where discarding\n // the text when the tag is disallowed makes sense for other reasons.\n // If we are not allowing these tags, we should drop their content too.\n // For other tags you would drop the tag but keep its content.\n var nonTextTagsArray = options.nonTextTags || [ 'script', 'style', 'textarea' ];\n var allowedAttributesMap;\n var allowedAttributesGlobMap;\n if(options.allowedAttributes) {\n allowedAttributesMap = {};\n allowedAttributesGlobMap = {};\n each(options.allowedAttributes, function(attributes, tag) {\n allowedAttributesMap[tag] = [];\n var globRegex = [];\n attributes.forEach(function(name) {\n if(name.indexOf('*') >= 0) {\n globRegex.push(quoteRegexp(name).replace(/\\\\\\*/g, '.*'));\n } else {\n allowedAttributesMap[tag].push(name);\n }\n });\n allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$');\n });\n }\n var allowedClassesMap = {};\n each(options.allowedClasses, function(classes, tag) {\n // Implicitly allows the class attribute\n if(allowedAttributesMap) {\n if (!has(allowedAttributesMap, tag)) {\n allowedAttributesMap[tag] = [];\n }\n allowedAttributesMap[tag].push('class');\n }\n\n allowedClassesMap[tag] = classes;\n });\n\n var transformTagsMap = {};\n var transformTagsAll;\n each(options.transformTags, function(transform, tag) {\n var transFun;\n if (typeof transform === 'function') {\n transFun = transform;\n } else if (typeof transform === \"string\") {\n transFun = sanitizeHtml.simpleTransform(transform);\n }\n if (tag === '*') {\n transformTagsAll = transFun;\n } else {\n transformTagsMap[tag] = transFun;\n }\n });\n\n var depth = 0;\n var stack = [];\n var skipMap = {};\n var transformMap = {};\n var skipText = false;\n var skipTextDepth = 0;\n\n var parser = new htmlparser.Parser({\n onopentag: function(name, attribs) {\n if (skipText) {\n skipTextDepth++;\n return;\n }\n var frame = new Frame(name, attribs);\n stack.push(frame);\n\n var skip = false;\n var hasText = frame.text ? true : false;\n var transformedTag;\n if (has(transformTagsMap, name)) {\n transformedTag = transformTagsMap[name](name, attribs);\n\n frame.attribs = attribs = transformedTag.attribs;\n\n if (transformedTag.text !== undefined) {\n frame.innerText = transformedTag.text;\n }\n\n if (name !== transformedTag.tagName) {\n frame.name = name = transformedTag.tagName;\n transformMap[depth] = transformedTag.tagName;\n }\n }\n if (transformTagsAll) {\n transformedTag = transformTagsAll(name, attribs);\n\n frame.attribs = attribs = transformedTag.attribs;\n if (name !== transformedTag.tagName) {\n frame.name = name = transformedTag.tagName;\n transformMap[depth] = transformedTag.tagName;\n }\n }\n\n if (options.allowedTags && options.allowedTags.indexOf(name) === -1) {\n skip = true;\n if (nonTextTagsArray.indexOf(name) !== -1) {\n skipText = true;\n skipTextDepth = 1;\n }\n skipMap[depth] = true;\n }\n depth++;\n if (skip) {\n // We want the contents but not this tag\n return;\n }\n result += '<' + name;\n if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {\n each(attribs, function(value, a) {\n if (!allowedAttributesMap ||\n (has(allowedAttributesMap, name) && allowedAttributesMap[name].indexOf(a) !== -1 ) ||\n (allowedAttributesMap['*'] && allowedAttributesMap['*'].indexOf(a) !== -1 ) ||\n (has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a)) ||\n (allowedAttributesGlobMap['*'] && allowedAttributesGlobMap['*'].test(a))) {\n if ((a === 'href') || (a === 'src')) {\n if (naughtyHref(name, value)) {\n delete frame.attribs[a];\n return;\n }\n }\n if (a === 'class') {\n value = filterClasses(value, allowedClassesMap[name]);\n if (!value.length) {\n delete frame.attribs[a];\n return;\n }\n }\n result += ' ' + a;\n if (value.length) {\n result += '=\"' + escapeHtml(value) + '\"';\n }\n } else {\n delete frame.attribs[a];\n }\n });\n }\n if (options.selfClosing.indexOf(name) !== -1) {\n result += \" />\";\n } else {\n result += \">\";\n if (frame.innerText && !hasText && !options.textFilter) {\n result += frame.innerText;\n }\n }\n },\n ontext: function(text) {\n if (skipText) {\n return;\n }\n var lastFrame = stack[stack.length-1];\n var tag;\n\n if (lastFrame) {\n tag = lastFrame.tag;\n // If inner text was set by transform function then let's use it\n text = lastFrame.innerText !== undefined ? lastFrame.innerText : text;\n }\n\n if ((tag === 'script') || (tag === 'style')) {\n // htmlparser2 gives us these as-is. Escaping them ruins the content. Allowing\n // script tags is, by definition, game over for XSS protection, so if that's\n // your concern, don't allow them. The same is essentially true for style tags\n // which have their own collection of XSS vectors.\n result += text;\n } else {\n var escaped = escapeHtml(text);\n if (options.textFilter) {\n result += options.textFilter(escaped);\n } else {\n result += escaped;\n }\n }\n if (stack.length) {\n var frame = stack[stack.length - 1];\n frame.text += text;\n }\n },\n onclosetag: function(name) {\n\n if (skipText) {\n skipTextDepth--;\n if (!skipTextDepth) {\n skipText = false;\n } else {\n return;\n }\n }\n\n var frame = stack.pop();\n if (!frame) {\n // Do not crash on bad markup\n return;\n }\n skipText = false;\n depth--;\n if (skipMap[depth]) {\n delete skipMap[depth];\n frame.updateParentNodeText();\n return;\n }\n\n if (transformMap[depth]) {\n name = transformMap[depth];\n delete transformMap[depth];\n }\n\n if (options.exclusiveFilter && options.exclusiveFilter(frame)) {\n result = result.substr(0, frame.tagPosition);\n return;\n }\n\n frame.updateParentNodeText();\n\n if (options.selfClosing.indexOf(name) !== -1) {\n // Already output />\n return;\n }\n\n result += \"</\" + name + \">\";\n }\n }, options.parser);\n parser.write(html);\n parser.end();\n\n return result;\n\n function escapeHtml(s) {\n if (typeof(s) !== 'string') {\n s = s + '';\n }\n return s.replace(/\\&/g, '&amp;').replace(/</g, '&lt;').replace(/\\>/g, '&gt;').replace(/\\\"/g, '&quot;');\n }\n\n function naughtyHref(name, href) {\n // Browsers ignore character codes of 32 (space) and below in a surprising\n // number of situations. Start reading here:\n // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab\n href = href.replace(/[\\x00-\\x20]+/g, '');\n // Clobber any comments in URLs, which the browser might\n // interpret inside an XML data island, allowing\n // a javascript: URL to be snuck through\n href = href.replace(/<\\!\\-\\-.*?\\-\\-\\>/g, '');\n // Case insensitive so we don't get faked out by JAVASCRIPT #1\n var matches = href.match(/^([a-zA-Z]+)\\:/);\n if (!matches) {\n // Protocol-relative URL: \"//some.evil.com/nasty\"\n if (href.match(/^\\/\\//)) {\n return !options.allowProtocolRelative;\n }\n\n // No scheme\n return false;\n }\n var scheme = matches[1].toLowerCase();\n\n if (has(options.allowedSchemesByTag, name)) {\n return options.allowedSchemesByTag[name].indexOf(scheme) === -1;\n }\n\n return !options.allowedSchemes || options.allowedSchemes.indexOf(scheme) === -1;\n }\n\n function filterClasses(classes, allowed) {\n if (!allowed) {\n // The class attribute is allowed without filtering on this tag\n return classes;\n }\n classes = classes.split(/\\s+/);\n return classes.filter(function(clss) {\n return allowed.indexOf(clss) !== -1;\n }).join(' ');\n }\n}", "function sanitizeHtml(html, options, _recursing) {\n var result = '';\n\n function Frame(tag, attribs) {\n var that = this;\n this.tag = tag;\n this.attribs = attribs || {};\n this.tagPosition = result.length;\n this.text = ''; // Node inner text\n\n this.updateParentNodeText = function() {\n if (stack.length) {\n var parentFrame = stack[stack.length - 1];\n parentFrame.text += that.text;\n }\n };\n }\n\n if (!options) {\n options = sanitizeHtml.defaults;\n options.parser = htmlParserDefaults;\n } else {\n options = extend(sanitizeHtml.defaults, options);\n if (options.parser) {\n options.parser = extend(htmlParserDefaults, options.parser);\n } else {\n options.parser = htmlParserDefaults;\n }\n }\n\n // Tags that contain something other than HTML, or where discarding\n // the text when the tag is disallowed makes sense for other reasons.\n // If we are not allowing these tags, we should drop their content too.\n // For other tags you would drop the tag but keep its content.\n var nonTextTagsArray = options.nonTextTags || [ 'script', 'style', 'textarea' ];\n var allowedAttributesMap;\n var allowedAttributesGlobMap;\n if(options.allowedAttributes) {\n allowedAttributesMap = {};\n allowedAttributesGlobMap = {};\n each(options.allowedAttributes, function(attributes, tag) {\n allowedAttributesMap[tag] = [];\n var globRegex = [];\n attributes.forEach(function(name) {\n if(name.indexOf('*') >= 0) {\n globRegex.push(quoteRegexp(name).replace(/\\\\\\*/g, '.*'));\n } else {\n allowedAttributesMap[tag].push(name);\n }\n });\n allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$');\n });\n }\n var allowedClassesMap = {};\n each(options.allowedClasses, function(classes, tag) {\n // Implicitly allows the class attribute\n if(allowedAttributesMap) {\n if (!has(allowedAttributesMap, tag)) {\n allowedAttributesMap[tag] = [];\n }\n allowedAttributesMap[tag].push('class');\n }\n\n allowedClassesMap[tag] = classes;\n });\n\n var transformTagsMap = {};\n var transformTagsAll;\n each(options.transformTags, function(transform, tag) {\n var transFun;\n if (typeof transform === 'function') {\n transFun = transform;\n } else if (typeof transform === \"string\") {\n transFun = sanitizeHtml.simpleTransform(transform);\n }\n if (tag === '*') {\n transformTagsAll = transFun;\n } else {\n transformTagsMap[tag] = transFun;\n }\n });\n\n var depth = 0;\n var stack = [];\n var skipMap = {};\n var transformMap = {};\n var skipText = false;\n var skipTextDepth = 0;\n\n var parser = new htmlparser.Parser({\n onopentag: function(name, attribs) {\n if (skipText) {\n skipTextDepth++;\n return;\n }\n var frame = new Frame(name, attribs);\n stack.push(frame);\n\n var skip = false;\n var hasText = frame.text ? true : false;\n var transformedTag;\n if (has(transformTagsMap, name)) {\n transformedTag = transformTagsMap[name](name, attribs);\n\n frame.attribs = attribs = transformedTag.attribs;\n\n if (transformedTag.text !== undefined) {\n frame.innerText = transformedTag.text;\n }\n\n if (name !== transformedTag.tagName) {\n frame.name = name = transformedTag.tagName;\n transformMap[depth] = transformedTag.tagName;\n }\n }\n if (transformTagsAll) {\n transformedTag = transformTagsAll(name, attribs);\n\n frame.attribs = attribs = transformedTag.attribs;\n if (name !== transformedTag.tagName) {\n frame.name = name = transformedTag.tagName;\n transformMap[depth] = transformedTag.tagName;\n }\n }\n\n if (options.allowedTags && options.allowedTags.indexOf(name) === -1) {\n skip = true;\n if (nonTextTagsArray.indexOf(name) !== -1) {\n skipText = true;\n skipTextDepth = 1;\n }\n skipMap[depth] = true;\n }\n depth++;\n if (skip) {\n // We want the contents but not this tag\n return;\n }\n result += '<' + name;\n if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {\n each(attribs, function(value, a) {\n if (!allowedAttributesMap ||\n (has(allowedAttributesMap, name) && allowedAttributesMap[name].indexOf(a) !== -1 ) ||\n (allowedAttributesMap['*'] && allowedAttributesMap['*'].indexOf(a) !== -1 ) ||\n (has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a)) ||\n (allowedAttributesGlobMap['*'] && allowedAttributesGlobMap['*'].test(a))) {\n if ((a === 'href') || (a === 'src')) {\n if (naughtyHref(name, value)) {\n delete frame.attribs[a];\n return;\n }\n }\n if (a === 'class') {\n value = filterClasses(value, allowedClassesMap[name]);\n if (!value.length) {\n delete frame.attribs[a];\n return;\n }\n }\n result += ' ' + a;\n if (value.length) {\n result += '=\"' + value + '\"';\n }\n } else {\n delete frame.attribs[a];\n }\n });\n }\n if (options.selfClosing.indexOf(name) !== -1) {\n result += \" />\";\n } else {\n result += \">\";\n if (frame.innerText && !hasText && !options.textFilter) {\n result += frame.innerText;\n }\n }\n },\n ontext: function(text) {\n if (skipText) {\n return;\n }\n var lastFrame = stack[stack.length-1];\n var tag;\n\n if (lastFrame) {\n tag = lastFrame.tag;\n // If inner text was set by transform function then let's use it\n text = lastFrame.innerText !== undefined ? lastFrame.innerText : text;\n }\n\n if ((tag === 'script') || (tag === 'style')) {\n // htmlparser2 gives us these as-is. Escaping them ruins the content. Allowing\n // script tags is, by definition, game over for XSS protection, so if that's\n // your concern, don't allow them. The same is essentially true for style tags\n // which have their own collection of XSS vectors.\n result += text;\n } else {\n if (options.textFilter) {\n result += options.textFilter(text);\n } else {\n result += text;\n }\n }\n if (stack.length) {\n var frame = stack[stack.length - 1];\n frame.text += text;\n }\n },\n onclosetag: function(name) {\n\n if (skipText) {\n skipTextDepth--;\n if (!skipTextDepth) {\n skipText = false;\n } else {\n return;\n }\n }\n\n var frame = stack.pop();\n if (!frame) {\n // Do not crash on bad markup\n return;\n }\n skipText = false;\n depth--;\n if (skipMap[depth]) {\n delete skipMap[depth];\n frame.updateParentNodeText();\n return;\n }\n\n if (transformMap[depth]) {\n name = transformMap[depth];\n delete transformMap[depth];\n }\n\n if (options.exclusiveFilter && options.exclusiveFilter(frame)) {\n result = result.substr(0, frame.tagPosition);\n return;\n }\n\n frame.updateParentNodeText();\n\n if (options.selfClosing.indexOf(name) !== -1) {\n // Already output />\n return;\n }\n\n result += \"</\" + name + \">\";\n }\n }, options.parser);\n parser.write(html);\n parser.end();\n\n return result;\n\n function naughtyHref(name, href) {\n // Browsers ignore character codes of 32 (space) and below in a surprising\n // number of situations. Start reading here:\n // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab\n href = href.replace(/[\\x00-\\x20]+/g, '');\n // Clobber any comments in URLs, which the browser might\n // interpret inside an XML data island, allowing\n // a javascript: URL to be snuck through\n href = href.replace(/<\\!\\-\\-.*?\\-\\-\\>/g, '');\n // Case insensitive so we don't get faked out by JAVASCRIPT #1\n var matches = href.match(/^([a-zA-Z]+)\\:/);\n if (!matches) {\n // No scheme = no way to inject js (right?)\n return false;\n }\n var scheme = matches[1].toLowerCase();\n\n if (has(options.allowedSchemesByTag, name)) {\n return options.allowedSchemesByTag[name].indexOf(scheme) === -1;\n }\n\n return !options.allowedSchemes || options.allowedSchemes.indexOf(scheme) === -1;\n }\n\n function filterClasses(classes, allowed) {\n if (!allowed) {\n // The class attribute is allowed without filtering on this tag\n return classes;\n }\n classes = classes.split(/\\s+/);\n return classes.filter(function(clss) {\n return allowed.indexOf(clss) !== -1;\n }).join(' ');\n }\n}", "function parseResult(response)\n{\n\tvar res = response.match(/\\<response\\>((.|\\s)+?)\\<\\/response\\>/gm);\n\tvar fields = new Array();\n\tif (res != null)\n\t{\n\t\tcontents = RegExp.$1;\n\t\tres = contents.match(/\\<.+?\\>((.|\\s)+?)\\<\\/.+?\\>/gm);\n\t\tif (res == null)\n\t\t{\n\t\t\treturn fields;\n\t\t}\n\t\t\n\t\tfor (var i = 0; i < res.length; i++)\n\t\t{\n\t\t\tvar field = new Array();\n\t\t\tres[i].match(/^\\<(.+?)\\>/g);\n\t\t\tfield.push(RegExp.$1);\n\t\t\tres[i].match(/\\<.+?\\>((.|\\s)+)\\<\\/.+?\\>/gm);\n\t\t\tfield.push(unhtmlspecialchars(RegExp.$1));\n\t\t\t\n\t\t\tfields.push(field)\n\t\t}\n\t}\n\t\n\treturn fields;\n}", "function decode(string) {\n var div = document.createElement(\"div\");\n div.innerHTML = string; \n return typeof div.textContent !== 'undefined' ? div.textContent : div.innerText;\n}", "function sanitizeHtml(html, options, _recursing) {\n var result = '';\n\n function Frame(tag, attribs) {\n var that = this;\n this.tag = tag;\n this.attribs = attribs || {};\n this.tagPosition = result.length;\n this.text = ''; // Node inner text\n\n this.updateParentNodeText = function () {\n if (stack.length) {\n var parentFrame = stack[stack.length - 1];\n parentFrame.text += that.text;\n }\n };\n }\n\n if (!options) {\n options = sanitizeHtml.defaults;\n options.parser = htmlParserDefaults;\n } else {\n options = extend(sanitizeHtml.defaults, options);\n if (options.parser) {\n options.parser = extend(htmlParserDefaults, options.parser);\n } else {\n options.parser = htmlParserDefaults;\n }\n }\n\n // Tags that contain something other than HTML, or where discarding\n // the text when the tag is disallowed makes sense for other reasons.\n // If we are not allowing these tags, we should drop their content too.\n // For other tags you would drop the tag but keep its content.\n var nonTextTagsArray = options.nonTextTags || ['script', 'style', 'textarea'];\n var allowedAttributesMap;\n var allowedAttributesGlobMap;\n if (options.allowedAttributes) {\n allowedAttributesMap = {};\n allowedAttributesGlobMap = {};\n each(options.allowedAttributes, function (attributes, tag) {\n allowedAttributesMap[tag] = [];\n var globRegex = [];\n attributes.forEach(function (obj) {\n if (isString(obj) && obj.indexOf('*') >= 0) {\n globRegex.push(quoteRegexp(obj).replace(/\\\\\\*/g, '.*'));\n } else {\n allowedAttributesMap[tag].push(obj);\n }\n });\n allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$');\n });\n }\n var allowedClassesMap = {};\n each(options.allowedClasses, function (classes, tag) {\n // Implicitly allows the class attribute\n if (allowedAttributesMap) {\n if (!has(allowedAttributesMap, tag)) {\n allowedAttributesMap[tag] = [];\n }\n allowedAttributesMap[tag].push('class');\n }\n\n allowedClassesMap[tag] = classes;\n });\n\n var transformTagsMap = {};\n var transformTagsAll;\n each(options.transformTags, function (transform, tag) {\n var transFun;\n if (typeof transform === 'function') {\n transFun = transform;\n } else if (typeof transform === \"string\") {\n transFun = sanitizeHtml.simpleTransform(transform);\n }\n if (tag === '*') {\n transformTagsAll = transFun;\n } else {\n transformTagsMap[tag] = transFun;\n }\n });\n\n var depth = 0;\n var stack = [];\n var skipMap = {};\n var transformMap = {};\n var skipText = false;\n var skipTextDepth = 0;\n\n var parser = new htmlparser.Parser({\n onopentag: function onopentag(name, attribs) {\n if (skipText) {\n skipTextDepth++;\n return;\n }\n var frame = new Frame(name, attribs);\n stack.push(frame);\n\n var skip = false;\n var hasText = frame.text ? true : false;\n var transformedTag;\n if (has(transformTagsMap, name)) {\n transformedTag = transformTagsMap[name](name, attribs);\n\n frame.attribs = attribs = transformedTag.attribs;\n\n if (transformedTag.text !== undefined) {\n frame.innerText = transformedTag.text;\n }\n\n if (name !== transformedTag.tagName) {\n frame.name = name = transformedTag.tagName;\n transformMap[depth] = transformedTag.tagName;\n }\n }\n if (transformTagsAll) {\n transformedTag = transformTagsAll(name, attribs);\n\n frame.attribs = attribs = transformedTag.attribs;\n if (name !== transformedTag.tagName) {\n frame.name = name = transformedTag.tagName;\n transformMap[depth] = transformedTag.tagName;\n }\n }\n\n if (options.allowedTags && options.allowedTags.indexOf(name) === -1) {\n skip = true;\n if (nonTextTagsArray.indexOf(name) !== -1) {\n skipText = true;\n skipTextDepth = 1;\n }\n skipMap[depth] = true;\n }\n depth++;\n if (skip) {\n // We want the contents but not this tag\n return;\n }\n result += '<' + name;\n if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) {\n each(attribs, function (value, a) {\n if (!VALID_HTML_ATTRIBUTE_NAME.test(a)) {\n // This prevents part of an attribute name in the output from being\n // interpreted as the end of an attribute, or end of a tag.\n delete frame.attribs[a];\n return;\n }\n var parsed;\n // check allowedAttributesMap for the element and attribute and modify the value\n // as necessary if there are specific values defined.\n var passedAllowedAttributesMapCheck = false;\n if (!allowedAttributesMap || has(allowedAttributesMap, name) && allowedAttributesMap[name].indexOf(a) !== -1 || allowedAttributesMap['*'] && allowedAttributesMap['*'].indexOf(a) !== -1 || has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a) || allowedAttributesGlobMap['*'] && allowedAttributesGlobMap['*'].test(a)) {\n passedAllowedAttributesMapCheck = true;\n } else if (allowedAttributesMap && allowedAttributesMap[name]) {\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = allowedAttributesMap[name][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var o = _step.value;\n\n if (isPlainObject(o) && o.name && o.name === a) {\n passedAllowedAttributesMapCheck = true;\n var newValue = '';\n if (o.multiple === true) {\n // verify the values that are allowed\n var splitStrArray = value.split(' ');\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = splitStrArray[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var s = _step2.value;\n\n if (o.values.indexOf(s) !== -1) {\n if (newValue === '') {\n newValue = s;\n } else {\n newValue += ' ' + s;\n }\n }\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n } else if (o.values.indexOf(value) >= 0) {\n // verified an allowed value matches the entire attribute value\n newValue = value;\n }\n value = newValue;\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n }\n if (passedAllowedAttributesMapCheck) {\n if (options.allowedSchemesAppliedToAttributes.indexOf(a) !== -1) {\n if (naughtyHref(name, value)) {\n delete frame.attribs[a];\n return;\n }\n }\n if (name === 'iframe' && a === 'src') {\n //Check if value contains proper hostname prefix\n if (value.substring(0, 2) === '//') {\n var prefix = 'https:';\n value = prefix.concat(value);\n }\n try {\n parsed = url.parse(value);\n if (options.allowedIframeHostnames) {\n var whitelistedHostnames = options.allowedIframeHostnames.find(function (hostname) {\n return hostname === parsed.hostname;\n });\n if (!whitelistedHostnames) {\n delete frame.attribs[a];\n return;\n }\n }\n } catch (e) {\n // Unparseable iframe src\n delete frame.attribs[a];\n return;\n }\n }\n if (a === 'srcset') {\n try {\n parsed = srcset.parse(value);\n each(parsed, function (value) {\n if (naughtyHref('srcset', value.url)) {\n value.evil = true;\n }\n });\n parsed = filter(parsed, function (v) {\n return !v.evil;\n });\n if (!parsed.length) {\n delete frame.attribs[a];\n return;\n } else {\n value = srcset.stringify(filter(parsed, function (v) {\n return !v.evil;\n }));\n frame.attribs[a] = value;\n }\n } catch (e) {\n // Unparseable srcset\n delete frame.attribs[a];\n return;\n }\n }\n if (a === 'class') {\n value = filterClasses(value, allowedClassesMap[name]);\n if (!value.length) {\n delete frame.attribs[a];\n return;\n }\n }\n if (a === 'style') {\n try {\n var abstractSyntaxTree = postcss.parse(name + \" {\" + value + \"}\");\n var filteredAST = filterCss(abstractSyntaxTree, options.allowedStyles);\n\n value = stringifyStyleAttributes(filteredAST);\n\n if (value.length === 0) {\n delete frame.attribs[a];\n return;\n }\n } catch (e) {\n delete frame.attribs[a];\n return;\n }\n }\n result += ' ' + a;\n if (value.length) {\n result += '=\"' + escapeHtml(value) + '\"';\n }\n } else {\n delete frame.attribs[a];\n }\n });\n }\n if (options.selfClosing.indexOf(name) !== -1) {\n result += \" />\";\n } else {\n result += \">\";\n if (frame.innerText && !hasText && !options.textFilter) {\n result += frame.innerText;\n }\n }\n },\n ontext: function ontext(text) {\n if (skipText) {\n return;\n }\n var lastFrame = stack[stack.length - 1];\n var tag;\n\n if (lastFrame) {\n tag = lastFrame.tag;\n // If inner text was set by transform function then let's use it\n text = lastFrame.innerText !== undefined ? lastFrame.innerText : text;\n }\n\n if (tag === 'script' || tag === 'style') {\n // htmlparser2 gives us these as-is. Escaping them ruins the content. Allowing\n // script tags is, by definition, game over for XSS protection, so if that's\n // your concern, don't allow them. The same is essentially true for style tags\n // which have their own collection of XSS vectors.\n result += text;\n } else {\n var escaped = escapeHtml(text);\n if (options.textFilter) {\n result += options.textFilter(escaped);\n } else {\n result += escaped;\n }\n }\n if (stack.length) {\n var frame = stack[stack.length - 1];\n frame.text += text;\n }\n },\n onclosetag: function onclosetag(name) {\n\n if (skipText) {\n skipTextDepth--;\n if (!skipTextDepth) {\n skipText = false;\n } else {\n return;\n }\n }\n\n var frame = stack.pop();\n if (!frame) {\n // Do not crash on bad markup\n return;\n }\n skipText = false;\n depth--;\n if (skipMap[depth]) {\n delete skipMap[depth];\n frame.updateParentNodeText();\n return;\n }\n\n if (transformMap[depth]) {\n name = transformMap[depth];\n delete transformMap[depth];\n }\n\n if (options.exclusiveFilter && options.exclusiveFilter(frame)) {\n result = result.substr(0, frame.tagPosition);\n return;\n }\n\n frame.updateParentNodeText();\n\n if (options.selfClosing.indexOf(name) !== -1) {\n // Already output />\n return;\n }\n\n result += \"</\" + name + \">\";\n }\n }, options.parser);\n parser.write(html);\n parser.end();\n\n return result;\n\n function escapeHtml(s) {\n if (typeof s !== 'string') {\n s = s + '';\n }\n return s.replace(/\\&/g, '&amp;').replace(/</g, '&lt;').replace(/\\>/g, '&gt;').replace(/\\\"/g, '&quot;');\n }\n\n function naughtyHref(name, href) {\n // Browsers ignore character codes of 32 (space) and below in a surprising\n // number of situations. Start reading here:\n // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab\n href = href.replace(/[\\x00-\\x20]+/g, '');\n // Clobber any comments in URLs, which the browser might\n // interpret inside an XML data island, allowing\n // a javascript: URL to be snuck through\n href = href.replace(/<\\!\\-\\-.*?\\-\\-\\>/g, '');\n // Case insensitive so we don't get faked out by JAVASCRIPT #1\n var matches = href.match(/^([a-zA-Z]+)\\:/);\n if (!matches) {\n // Protocol-relative URL starting with any combination of '/' and '\\'\n if (href.match(/^[\\/\\\\]{2}/)) {\n return !options.allowProtocolRelative;\n }\n\n // No scheme\n return false;\n }\n var scheme = matches[1].toLowerCase();\n\n if (has(options.allowedSchemesByTag, name)) {\n return options.allowedSchemesByTag[name].indexOf(scheme) === -1;\n }\n\n return !options.allowedSchemes || options.allowedSchemes.indexOf(scheme) === -1;\n }\n\n /**\n * Filters user input css properties by whitelisted regex attributes.\n *\n * @param {object} abstractSyntaxTree - Object representation of CSS attributes.\n * @property {array[Declaration]} abstractSyntaxTree.nodes[0] - Each object cointains prop and value key, i.e { prop: 'color', value: 'red' }.\n * @param {object} allowedStyles - Keys are properties (i.e color), value is list of permitted regex rules (i.e /green/i).\n * @return {object} - Abstract Syntax Tree with filtered style attributes.\n */\n function filterCss(abstractSyntaxTree, allowedStyles) {\n if (!allowedStyles) {\n return abstractSyntaxTree;\n }\n\n var filteredAST = cloneDeep(abstractSyntaxTree);\n var astRules = abstractSyntaxTree.nodes[0];\n var selectedRule;\n\n // Merge global and tag-specific styles into new AST.\n if (allowedStyles[astRules.selector] && allowedStyles['*']) {\n selectedRule = mergeWith(cloneDeep(allowedStyles[astRules.selector]), allowedStyles['*'], function (objValue, srcValue) {\n if (Array.isArray(objValue)) {\n return objValue.concat(srcValue);\n }\n });\n } else {\n selectedRule = allowedStyles[astRules.selector] || allowedStyles['*'];\n }\n\n if (selectedRule) {\n filteredAST.nodes[0].nodes = astRules.nodes.reduce(filterDeclarations(selectedRule), []);\n }\n\n return filteredAST;\n }\n\n /**\n * Extracts the style attribues from an AbstractSyntaxTree and formats those\n * values in the inline style attribute format.\n *\n * @param {AbstractSyntaxTree} filteredAST\n * @return {string} - Example: \"color:yellow;text-align:center;font-family:helvetica;\"\n */\n function stringifyStyleAttributes(filteredAST) {\n return filteredAST.nodes[0].nodes.reduce(function (extractedAttributes, attributeObject) {\n extractedAttributes.push(attributeObject.prop + ':' + attributeObject.value + ';');\n return extractedAttributes;\n }, []).join('');\n }\n\n /**\n * Filters the existing attributes for the given property. Discards any attributes\n * which don't match the whitelist.\n *\n * @param {object} selectedRule - Example: { color: red, font-family: helvetica }\n * @param {array} allowedDeclarationsList - List of declarations which pass whitelisting.\n * @param {object} attributeObject - Object representing the current css property.\n * @property {string} attributeObject.type - Typically 'declaration'.\n * @property {string} attributeObject.prop - The CSS property, i.e 'color'.\n * @property {string} attributeObject.value - The corresponding value to the css property, i.e 'red'.\n * @return {function} - When used in Array.reduce, will return an array of Declaration objects\n */\n function filterDeclarations(selectedRule) {\n return function (allowedDeclarationsList, attributeObject) {\n // If this property is whitelisted...\n if (selectedRule.hasOwnProperty(attributeObject.prop)) {\n var matchesRegex = selectedRule[attributeObject.prop].some(function (regularExpression) {\n return regularExpression.test(attributeObject.value);\n });\n\n if (matchesRegex) {\n allowedDeclarationsList.push(attributeObject);\n }\n }\n return allowedDeclarationsList;\n };\n }\n\n function filterClasses(classes, allowed) {\n if (!allowed) {\n // The class attribute is allowed without filtering on this tag\n return classes;\n }\n classes = classes.split(/\\s+/);\n return classes.filter(function (clss) {\n return allowed.indexOf(clss) !== -1;\n }).join(' ');\n }\n}", "function htmlUnescape(escapedStr)\n{\n var div = document.createElement('div');\n div.innerHTML = escapedStr;\n var child = div.childNodes[0];\n\n return child ? child.nodeValue : '';\n}", "function HtmlDecode(str) {\n\t\tvar t = document.createElement(\"div\");\n\t\tt.innerHTML = str;\n\t\treturn t.innerText || t.textContent\n\t}", "function ParseTextAsHTML(rawHTML, id, stripJavaScript) {\n var returnString = \"\";\n // see https://www.w3schools.com/xml/xml_parser.asp \n // and see https://www.w3schools.com/xml/dom_intro.asp\n var parser = new DOMParser();\n if (parser) {\n var xmlDoc = parser.parseFromString(rawHTML, \"text/html\");\n if (xmlDoc && xmlDoc.body !== undefined && id !== undefined) {\n switch (id) {\n case 'body':\n returnString = xmlDoc.body.innerHTML;\n break;\n case 'head':\n returnString = xmlDoc.head.innerHTML;\n break;\n default:\n var XMLFragment = xmlDoc.getElementsByTagName(id);\n if (XMLFragment && XMLFragment.length > 0) {\n returnString = XMLFragment[0].innerHTML;\n }\n else {\n // XML has an error in it\n console.log(`HTML document has an improperly closed tag such as a <br>, an <img> etc.`);\n }\n break;\n }\n }\n }\n else {\n console.log(`Cannot parse fragment as XML`);\n console.log(rawXML);\n }\n if (stripJavaScript) {\n const scriptTagClose = '</script>';\n // see https://www.w3schools.com/jsref/jsref_search.asp\n var startPoint = returnString.search(/<script/i);\n while (startPoint > 0) {\n // see https://www.w3schools.com/jsref/jsref_indexof.asp\n var endPoint = returnString.toLowerCase().indexOf(scriptTagClose,startPoint +2) ;\n // see https://www.w3schools.com/jsref/jsref_substring.asp\n if (endPoint > 0){\n returnString = returnString.substring(0,startPoint) + returnString.substring(endPoint +scriptTagClose.length +1);\n }\n else {\n returnString = returnString.substring(0,startPoint)\n }\n // Are there any more script tags in the HTML?\n startPoint = returnString.search(/<script>/i);\n }\n }\n return returnString;\n}", "function htmlDecode( input ){\r\n var e = document.createElement( 'div' );\r\n e.innerHTML = input;\r\n return e.childNodes[0].nodeValue;\r\n }", "function unescapeHTML(html) {\r\n return unsafeWindow.$(\"<div />\").html(html).text();\r\n}", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]*>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n function unescape(s) {\n TEXTAREA_ELEMENT.innerHTML = s;\n s = TEXTAREA_ELEMENT.textContent;\n TEXTAREA_ELEMENT.textContent = \"\";\n return s;\n }\n\n function shouldAdd(current, element) {\n return (\n !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName\n );\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === \"<\") {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (\n tagStack.length &&\n tagStack[tagStack.length - 1] ===\n t.substr(2).replace(\">\", \"\")\n ) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\n \"timestamp\",\n ts\n );\n current.appendChild(node);\n continue;\n }\n var m = t.match(\n /^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/\n );\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n var classes = m[2].split(\".\");\n\n classes.forEach(function (cl) {\n var bgColor = /^bg_/.test(cl);\n // slice out `bg_` if it's a background color\n var colorName = bgColor ? cl.slice(3) : cl;\n\n if (\n DEFAULT_COLOR_CLASS.hasOwnProperty(\n colorName\n )\n ) {\n var propName = bgColor\n ? \"background-color\"\n : \"color\";\n var propValue =\n DEFAULT_COLOR_CLASS[colorName];\n\n node.style[propName] = propValue;\n }\n });\n\n node.className = classes.join(\" \");\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(\n window.document.createTextNode(unescape(t))\n );\n }\n\n return rootDiv;\n }", "function fromBBCode(e) {\n e.innerHTML = e.innerHTML.replace(/<br>/g, \"\\n\")\n\n var srcs = { \"img\": \"[img]%s[/img]\", \"iframe\": \"%s\" }\n , wraps = { \"strong\": \"b\", \"em\": \"i\", \"u\": \"u\", \"sup\": \"sup\"\n , \"sub\": \"sub\"\n }\n , datas = { \"object\": \"%s\" }\n\n for (var t in srcs) {\n var es = e.getElementsByTagName(t)\n for (var i = 0; i < es.length; i++)\n es[i].textContent = srcs[t].replace(/%s/g, es[i].src)\n }\n\n for (var t in wraps) {\n var es = e.getElementsByTagName(t)\n for (var i = 0; i < es.length; i++)\n es[i].textContent = \"[\" + wraps[t] + \"]\"\n + es[i].textContent\n + \"[/\" + wraps[t] + \"]\"\n }\n\n for (var t in datas) {\n var es = e.getElementsByTagName(t)\n for (var i = 0; i < es.length; i++)\n es[i].textContent =\n es[i].data.replace( /https?:\\/\\/(www\\.)?youtube.com\\/v\\/([^\\?]+).*/\n , \"https://youtu.be/$2\"\n )\n }\n\n var ss = e.getElementsByClassName(\"spoiler\")\n for (var i = 0; i < ss.length; i++) {\n ss[i].previousElementSibling.textContent =\n \"[spoiler=\" + ss[i].previousElementSibling.textContent + \"]\"\n ss[i].textContent = ss[i].textContent + \"[/spoiler]\"\n }\n\n var cs = e.getElementsByTagName(\"span\")\n for (var i = 0; i < cs.length; i++) {\n if (cs[i].style.color !== \"\")\n cs[i].textContent = \"[color=\" + cs[i].style.color + \"]\"\n + cs[i].textContent\n + \"[/color]\"\n\n else if (cs[i].style.backgroundColor !== \"\")\n cs[i].textContent = \"[bgcolor=\" + cs[i].style.backgroundColor + \"]\"\n + cs[i].textContent\n + \"[/bgcolor]\"\n\n else if (cs[i].style.textAlign === \"center\")\n cs[i].textContent = \"[center]\" + cs[i].textContent + \"[/center]\"\n\n else if (cs[i].style.fontFamily !== \"\")\n cs[i].textContent = \"[font=\" + cs[i].style.fontFamily + \"]\"\n + cs[i].textContent\n + \"[/font]\"\n\n else if (cs[i].style.border !== \"\")\n cs[i].textContent = \"[border=\" + cs[i].style.border + \"]\"\n + cs[i].textContent\n + \"[/border]\"\n }\n\n return e.textContent\n}", "_parseContent(item) {\n const textFieldClass = this.getCSS(this._data.mode, \"textField\");\n return item.querySelector(`.${textFieldClass}`).innerHTML;\n }", "function strip(html){\n let tmp = document.createElement(\"div\");\n tmp.innerHTML = html;\n return tmp.textContent || tmp.innerText || \"\";\n }", "function processByDOM(responseHTML, target) {\n target.innerHTML = \"Extracted by id:<br />\";\n\n // does not work with Chrome/Safari\n //var message = responseHTML.getElementsByTagName(\"div\").namedItem(\"two\").innerHTML;\n var message = responseHTML.getElementsByTagName(\"div\").item(1).innerHTML;\n\n target.innerHTML += message;\n\n target.innerHTML += \"<br />Extracted by name:<br />\";\n\n message = responseHTML.getElementsByTagName(\"form\").item(0);\n target.innerHTML += message.dyn.value;\n}", "extractFieldData( string )\n {\n let tx = string;\n\t if( tx && string.substr( 0, 13 ) == '<!--BASE64-->' )\n\t {\n\t \ttx = tx.substr( 13, tx.length - 13 );\n\t \ttx = Base64.decode( tx );\n\t }\n\t return tx;\n }", "function formatReviews() {\n var restore = GM_getValue('restore');\n\n $('//div[@class=\"review\"]').each(function(review) {\n if(isReviewPage()) {\n if(restore) {\n $('./preceding-sibling::p', review).each(function(p) {\n var revUrl = p.innerHTML.match(/\\/stumbler\\/[^\\/]+\\/review\\/\\d+\\//i);\n\n if(revUrl) {\n revUrl = revUrl[0];\n\n if(detectUTF8(review.innerHTML)) {\n loadReview(revUrl, review, 'UTF-8');\n } else {\n loadReview(revUrl, review);\n }\n }\n });\n } else {\n review.innerHTML = UrlFilter.filter(review.innerHTML.replace(/\\s+<span>/i,'<span>').replace(/\\n/g, '<br />'));\n }\n }\n\n // This is a workaround for making the crude Firefox extension FlashBlock work.\n // It essentially protects instances of embedded widgets.\n var wIdx = 0;\n var widgets = $('.//li[contains(@class, \"embedded_object\")]', review).each(function(node) {\n var div = document.createElement('div');\n div.setAttribute('SUF_widget', wIdx++);\n var parent = node.parentNode;\n parent.replaceChild(div, node);\n });\n\n review.innerHTML = twitterize(review.innerHTML).replace(suaRegex, '');\n\n $('.//div[boolean(@SUF_widget)]', review).each(function(node) {\n var parent = node.parentNode;\n parent.replaceChild(widgets.nodes[parseInt(node.getAttribute('SUF_widget'))], node);\n });\n });\n}", "function parseHTML(anHTMLString){\n if (typeof anHTMLString !== 'undefined' && anHTMLString !== null)\n return (new DOMParser()).parseFromString(anHTMLString, \"text/html\");\n return (new DOMParser()).parseFromString('', \"text/html\");\n}", "function readTextModal(filePath,divpath)\n{\n var rawFile = new XMLHttpRequest();\n rawFile.open(\"GET\", filePath, false);\n rawFile.onreadystatechange = function ()\n {\n if(rawFile.readyState === 4)\n {\n if(rawFile.status === 200 || rawFile.status == 0)\n {\n var allText = rawFile.responseText;\n var lines = allText.split('\\n');\n var text = allText.split(/[\\n:]+/);\n for (var i = 0; i < text.length; i++) {\n switch(text[i].trim())\n {\n case \"Title\":\n var node = document.createElement(\"H1\");\n var textnode = document.createTextNode(text[i+1]);\n node.appendChild(textnode);\n document.getElementById(divpath).appendChild(node); \n break;\n\n case \"Description\": \n while(text[i+1]!=null )\n {\n var node = document.createElement(\"P\");\n var textnode = document.createTextNode(text[i+1]);\n node.appendChild(textnode);\n console.log(textnode);\n var br = document.createElement(\"br\");\n node.appendChild(br);\n document.getElementById(divpath).appendChild(node);\n i++;\n }\n break;\n default: \n break;\n }\n }\n }\n }\n }\n rawFile.send(null);\n}", "function parse_DocumentTextInfoContainer(blob, length, opts) {\n\trecordhopper(blob, function env(R, val) {\n\t\tswitch(R.n) {\n\t\t\tcase 'RT_Kinsoku': break;\n\t\t\tcase 'RT_FontCollection': break;\n\t\t\tcase 'RT_TextCharFormatExceptionAtom': break;\n\t\t\tcase 'RT_TextParagraphFormatExceptionAtom': break;\n\t\t\tcase 'RT_TextSpecialInfoDefaultAtom': break;\n\t\t\tcase 'RT_TextMasterStyleAtom': break;\n\t\t\tdefault: if(opts.WTF) throw R.n; break;\n\t\t}\n\t}, blob.l + length, opts);\n}", "function escnotes(txt){\n txt=txt.replace(/<!--defang_/g,'&lt;');\n txt=txt.replace(/</g,'&lt;');\n txt=txt.replace(/-->/g,'&gt;');\n txt=txt.replace(/>/g,'&gt;');\n txt=txt.replace(/defang_@/g,'@');\n txt='<div>'+txt.replace(/\\n(Entered on [0-9\\-]+ at [0-9\\:]+ by .*?)\\n/mg,\"</div>\\n<b class='esc_user'>\\$1</b><div class='collapsible'>\");\n txt=txt.replace(/\\r\\n|\\n/g,'<br>');\n txt=txt.replace(/(http[s]?:\\/\\/[^ )\\n\\r\"<>]+)/g,'<a href=\"'+\"$1\"+'\" target=\"_blank\">'+\"$1</a>\");\n txt=txt.replace(/ (gid:)(\\S+) /g,' <a href=\"http://eiger.accessline.com/sw/SmartWatcher.html?type=gid&gid='+\"$2\"+'&internal=true\" target=\"_blank\">'+\"$1</a> <u>$2</u> \");\n return txt+'</div>';\n}", "function HTMLtoDiscord( html ) {\n // Fast exit if the description is empty.\n if( !html || html.length == 0 ) return \"\";\n \n // Convert <br> to line breaks.\n html = html.replace( /<br>/g, \"\\n\" );\n \n // Convert list items. Can't really do much about ordered lists without a\n // massive headache. All will appear as bulleted lists.\n html = html.replace( /<li>/g, \"\\n• \" );\n \n // Basic conversion of the styling tags.\n // The regex \\s* magic is to move the marks to be adjacent to the content,\n // otherwise the markdown will break.\n // Will probably break anyway if they're using mixed formatting without\n // caring about not leaving it hanging on whitespace.\n html = html.replace( /<b>(\\s*)/g, \"$1**\" );\n html = html.replace( /(\\s*)<\\/b>/g, \"**$1\" );\n \n html = html.replace( /<u>(\\s*)/g, \"$1__\" );\n html = html.replace( /(\\s*)<\\/u>/g, \"__$1\" );\n \n html = html.replace( /<i>(\\s*)/g, \"$1*\" );\n html = html.replace( /(\\s*)<\\/i>/g, \"*$1\" );\n \n // Convert links.\n // Input example: <a href=\"poop.url\">link text</a>\n // Output example: [link text](poop.url)\n // Discord supports these in embed objects.\n html = html.replace( /<a[^>]* href=\"([^\"]+)\"[^>]*>(.+?)<\\/a>/g, \"[$2]($1)\" );\n \n Logger.log(html);\n \n // Catch ends of paragraphs and divs. (This will fuck up with inline divs but oh well.)\n html = html.replace( /<\\/(div|p|h\\d)>/g, \"\\n\" );\n \n // And throw away any leftover tags that weren't handled.\n html = html.replace( /<[^>]*>/g, \"\" );\n \n // Convert HTMl entities back into normal characters.\n html = html.replace( /&.+?;/g, ReplaceHTMLEntity );\n \n return html\n}", "function _htmlToText() {\n var text = this._str;\n\n text = text\n // Remove line breaks\n .replace(/(?:\\n|\\r\\n|\\r)/ig, \" \")\n // Remove content in script tags.\n .replace(/<\\s*script[^>]*>[\\s\\S]*?<\\/script>/mig, \"\")\n // Remove content in style tags.\n .replace(/<\\s*style[^>]*>[\\s\\S]*?<\\/style>/mig, \"\")\n // Remove content in comments.\n .replace(/<!--.*?-->/mig, \"\")\n // Remove !DOCTYPE\n .replace(/<!DOCTYPE.*?>/ig, \"\");\n\n /* I scanned http://en.wikipedia.org/wiki/HTML_element for all html tags.\n I put those tags that should affect plain text formatting in two categories:\n those that should be replaced with two newlines and those that should be\n replaced with one newline. */\n var doubleNewlineTags = ['p', 'h[1-6]', 'dl', 'dt', 'dd', 'ol', 'ul', 'dir', 'address', 'blockquote', 'center', 'div', 'hr', 'pre', 'form', 'textarea', 'table'];\n\n var singleNewlineTags = ['li', 'del', 'ins', 'fieldset', 'legend','tr', 'th', 'caption', 'thead', 'tbody', 'tfoot'];\n\n for (var i = 0; i < doubleNewlineTags.length; i++) {\n var r = RegExp('</?\\\\s*' + doubleNewlineTags[i] + '[^>]*>', 'ig');\n text = text.replace(r, ' ');\n }\n\n for (var i = 0; i < singleNewlineTags.length; i++) {\n var r = RegExp('<\\\\s*' + singleNewlineTags[i] + '[^>]*>', 'ig');\n text = text.replace(r, ' ');\n }\n\n // Replace <br> and <br/> with a single newline\n text = text.replace(/<\\s*br[^>]*\\/?\\s*>/ig, ' ');\n\n text = text\n // Remove all remaining tags.\n .replace(/(<([^>]+)>)/ig, \"\")\n // Trim rightmost whitespaces for all lines\n .replace(/([^\\n\\S]+)\\n/g, \" \")\n .replace(/([^\\n\\S]+)$/, \"\")\n // Make sure there are never more than two\n // consecutive linebreaks.\n .replace(/\\n{2,}/g, \" \")\n // Remove newlines at the beginning of the text.\n .replace(/^\\n+/, \"\")\n // Remove newlines at the end of the text.\n .replace(/\\n+$/, \"\")\n // Remove HTML entities.\n .replace(/&([^;]+);/g, ' ')\n //remove all tabs and replace them with whitespace\n .replace(/\\t/g, \" \")\n //remove whitespace > 2\n .replace(/ {2,}/g, \" \");\n\n this._str = text;\n }", "function ParseTags () {\n var bufferEnd = this._buffer.length - 1;\n while (reTags.test(this._buffer)) {\n this._next = reTags.lastIndex - 1;\n var tagSep = this._buffer[this._next]; //The currently found tag marker\n var rawData = this._buffer.substring(this._current, this._next); //The next chunk of data to parse\n\n //A new element to eventually be appended to the element list\n var element = {\n raw: rawData\n , data: (this._parseState == ElementType.Text) ? rawData : rawData.replace(reTrim, \"\")\n , type: this._parseState\n };\n\n var elementName = this.ParseTagName(element.data);\n\n //This section inspects the current tag stack and modifies the current\n //element if we're actually parsing a special area (script/comment/style tag)\n if (this._tagStack.length) { //We're parsing inside a script/comment/style tag\n if (this._tagStack[this._tagStack.length - 1] == ElementType.Script) { //We're currently in a script tag\n if (elementName == \"/script\") //Actually, we're no longer in a script tag, so pop it off the stack\n this._tagStack.pop();\n else { //Not a closing script tag\n if (element.raw.indexOf(\"!--\") != 0) { //Make sure we're not in a comment\n //All data from here to script close is now a text element\n element.type = ElementType.Text;\n //If the previous element is text, append the current text to it\n if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) {\n var prevElement = this._elements[this._elements.length - 1];\n prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw;\n element.raw = element.data = \"\"; //This causes the current element to not be added to the element list\n }\n }\n }\n }\n else if (this._tagStack[this._tagStack.length - 1] == ElementType.Style) { //We're currently in a style tag\n if (elementName == \"/style\") //Actually, we're no longer in a style tag, so pop it off the stack\n this._tagStack.pop();\n else {\n if (element.raw.indexOf(\"!--\") != 0) { //Make sure we're not in a comment\n //All data from here to style close is now a text element\n element.type = ElementType.Text;\n //If the previous element is text, append the current text to it\n if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Text) {\n if (element.raw != \"\") {\n var prevElement = this._elements[this._elements.length - 1];\n prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep + element.raw;\n element.raw = element.data = \"\"; //This causes the current element to not be added to the element list\n }\n else //Element is empty, so just append the last tag marker found\n prevElement.raw = prevElement.data = prevElement.raw + this._prevTagSep;\n }\n else //The previous element was not text\n if (element.raw != \"\")\n element.raw = element.data = element.raw;\n }\n }\n }\n else if (this._tagStack[this._tagStack.length - 1] == ElementType.Comment) { //We're currently in a comment tag\n var rawLen = element.raw.length;\n if (element.raw[rawLen - 1] == \"-\" && element.raw[rawLen - 1] == \"-\" && tagSep == \">\") {\n //Actually, we're no longer in a style tag, so pop it off the stack\n this._tagStack.pop();\n //If the previous element is a comment, append the current text to it\n if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) {\n var prevElement = this._elements[this._elements.length - 1];\n prevElement.raw = prevElement.data = (prevElement.raw + element.raw).replace(reTrimComment, \"\");\n element.raw = element.data = \"\"; //This causes the current element to not be added to the element list\n element.type = ElementType.Text;\n }\n else //Previous element not a comment\n element.type = ElementType.Comment; //Change the current element's type to a comment\n }\n else { //Still in a comment tag\n element.type = ElementType.Comment;\n //If the previous element is a comment, append the current text to it\n if (this._elements.length && this._elements[this._elements.length - 1].type == ElementType.Comment) {\n var prevElement = this._elements[this._elements.length - 1];\n prevElement.raw = prevElement.data = prevElement.raw + element.raw + tagSep;\n element.raw = element.data = \"\"; //This causes the current element to not be added to the element list\n element.type = ElementType.Text;\n }\n else\n element.raw = element.data = element.raw + tagSep;\n }\n }\n }\n\n //Processing of non-special tags\n if (element.type == ElementType.Tag) {\n element.name = elementName;\n \n if (element.raw.indexOf(\"!--\") == 0) { //This tag is really comment\n element.type = ElementType.Comment;\n delete element[\"name\"];\n var rawLen = element.raw.length;\n //Check if the comment is terminated in the current element\n if (element.raw[rawLen - 1] == \"-\" && element.raw[rawLen - 2] == \"-\" && tagSep == \">\")\n element.raw = element.data = element.raw.replace(reTrimComment, \"\");\n else { //It's not so push the comment onto the tag stack\n element.raw += tagSep;\n this._tagStack.push(ElementType.Comment);\n }\n }\n else if (element.raw.indexOf(\"!\") == 0) {\n element.type = ElementType.Directive;\n //TODO: what about CDATA?\n }\n else if (element.name == \"script\") {\n element.type = ElementType.Script;\n //Special tag, push onto the tag stack if not terminated\n if (element.data[element.data.length - 1] != \"/\")\n this._tagStack.push(ElementType.Script);\n }\n else if (element.name == \"/script\")\n element.type = ElementType.Script;\n else if (element.name == \"style\") {\n element.type = ElementType.Style;\n //Special tag, push onto the tag stack if not terminated\n if (element.data[element.data.length - 1] != \"/\")\n this._tagStack.push(ElementType.Style);\n }\n else if (element.name == \"/style\")\n element.type = ElementType.Style;\n if (element.name && element.name[0] == \"/\")\n element.data = element.name;\n }\n\n //Add all tags and non-empty text elements to the element list\n if (element.raw != \"\" || element.type != ElementType.Text) {\n this.ParseAttribs(element);\n this._elements.push(element);\n //If tag self-terminates, add an explicit, separate closing tag\n if (\n element.type != ElementType.Text\n &&\n element.type != ElementType.Comment\n &&\n element.type != ElementType.Directive\n &&\n element.data[element.data.length - 1] == \"/\"\n )\n this._elements.push({\n raw: \"/\" + element.name\n , data: \"/\" + element.name\n , name: \"/\" + element.name\n , type: element.type\n });\n }\n this._parseState = (tagSep == \"<\") ? ElementType.Tag : ElementType.Text;\n this._current = this._next + 1;\n this._prevTagSep = tagSep;\n }\n\n this._buffer = (this._current < bufferEnd) ? this._buffer.substring(this._current) : \"\";\n this._current = 0;\n\n this.WriteHandler();\n}", "function tidy_xhtml() {\r\n var text = String(this);\r\n\r\n text = text.gsub(/\\r\\n?/, \"\\n\");\r\n\r\n text = text.gsub(/<([A-Z]+)([^>]*)>/, function(match) {\r\n return '<' + match[1].toLowerCase() + match[2] + '>';\r\n });\r\n\r\n text = text.gsub(/<\\/([A-Z]+)>/, function(match) {\r\n return '</' + match[1].toLowerCase() + '>';\r\n });\r\n\r\n text = text.replace(/<br>/g, \"<br />\");\r\n\r\n return text;\r\n }", "function parseVersionTwo(content,name){\r\n var contents = jQuery(content);\r\n var c2 = jQuery('<div>'+content+'</div>')\r\n if(jQuery(c2).find('form').length>0){\r\n contents = jQuery(c2).find('form').first();\r\n }\r\n \r\n var formname = formatName(name);\r\n var formData = {'target':'_blank','action':'http://www.response-o-matic.com/mail.php','responsomatic':'true','name':formname,'id':formname,'htmlName':formname,'elements':[],'type':'form'}\r\n if(jQuery(contents).find('[name=formid]').length>0){\r\n formData.id = jQuery(contents).find('[name=formid]').val()\r\n }\r\n var req = jQuery(contents).find('[name=required_vars]').val();\r\n if(req) req = req.split(',');\r\n jQuery(contents).find('input[type=hidden]').not('[name=required_vars]').each(function (index, hid) {\r\n var hidObj = {};\r\n hidObj.name = jQuery(hid).attr('name');\r\n hidObj.htmlName = jQuery(hid).attr('name');\r\n hidObj.id = jQuery(hid).attr('id');\r\n hidObj.defaultValue = jQuery(hid).val();\r\n hidObj.displayType = 'FormField_hidden';\r\n formData.elements.push(hidObj); \r\n });\r\n jQuery(contents).find('.field-wrapper').each(function (index, fw) {\r\n var elObj = {validations:[]};\r\n var target = jQuery(fw).find('input,textarea,select').first();\r\n elObj.name = jQuery(fw).find('label').text().trim();\r\n elObj.name = elObj.name.replace(/\\*/g,'')\r\n elObj.htmlName = jQuery(target).attr('name');\r\n elObj.id = jQuery(target).attr('id');\r\n elObj.type = 'FormField';\r\n elObj.displayType = jQuery(target)[0].nodeName.toLowerCase();\r\n if(jQuery(fw).find('[type=checkbox]').length >1){\r\n elObj.displayType = 'checkboxList';\r\n elObj.id = elObj.id.substring(0,elObj.id.indexOf('_'))\r\n elObj.optionListId = index;\r\n elObj.options = {elements:[],id:index,name:elObj.name};\r\n var str = jQuery(fw).find('.inner-field').text()\r\n str = str.replace(/\\t/g,'')\r\n str = str.replace(/<br\\/>/g,'');\r\n str = str.replace(/<br>/g,'');\r\n strArr = str.split('\\n');\r\n strArr = _.map(strArr,function(s){\r\n return s.trim();\r\n })\r\n strArr = _.compact(strArr);\r\n jQuery(fw).find('[type=checkbox]').each(function(index, option) {\r\n var opobj = {};\r\n opobj.id = jQuery(option).attr('id');\r\n opobj.value = jQuery(option).val();\r\n opobj.displayName = strArr[index];\r\n elObj.options.elements.push(opobj)\r\n });\r\n }else if(jQuery(fw).find('[type=checkbox]').length == 1){\r\n elObj.displayType = 'checkbox';\r\n }else if(jQuery(fw).find('[type=file]').length == 1){\r\n elObj.displayType = 'file';\r\n }else if(jQuery(fw).find('[type=radio]').length == 1){\r\n elObj.displayType = 'radio';\r\n elObj.id = elObj.id.substring(0,elObj.id.indexOf('_'))\r\n elObj.optionListId = index;\r\n elObj.options = {elements:[],id:index,name:elObj.name};\r\n jQuery(fw).find('[type=radio]').each(function(index, option) {\r\n var opobj = {};\r\n opobj.id = jQuery(option).attr('id');\r\n opobj.value = jQuery(option).val();\r\n opobj.displayName = jQuery(option).text().trim()\r\n elObj.options.elements.push(opobj)\r\n });\r\n }else if(jQuery(fw).find('input[type=submit]').length == 1){\r\n elObj.displayType = 'submit'\r\n elObj.htmlName = jQuery(fw).find('input[type=submit]').val()\r\n elObj.id = jQuery(fw).find('input[type=submit]').val().trim()\r\n elObj.name= jQuery(fw).find('input[type=submit]').val().trim()\r\n }else if(jQuery(fw).find('select').length == 1){\r\n elObj.displayType = 'singleSelect';\r\n elObj.options = {elements:[],id:index,name:elObj.name};\r\n jQuery(fw).find('option').each(function(index, option) {\r\n var opobj = {};\r\n opobj.id = jQuery(option).attr('id');\r\n opobj.value = jQuery(option).val();\r\n opobj.displayName = jQuery(option).text().trim(); \r\n elObj.options.elements.push(opobj);\r\n });\r\n }\r\n var require= _.find(req,function(r){\r\n return r == elObj.id;\r\n })\r\n if(require){\r\n elObj.validations.push({'condition':{'type':'IsRequiredCondition'},'isEnabled':'true','message':'This field is required'})\r\n if(elObj.name.toLowerCase().indexOf('email')!=-1 ||elObj.htmlName.toLowerCase().indexOf('email')!=-1){\r\n elObj.validations.push({'condition':{'type':'IsEmailAddressCondition'},'isEnabled':'true','message':'Please enter a valid email address'})\r\n }\r\n elObj.localEdits = {}\r\n elObj.localEdits.lockRequired = true;\r\n }\r\n formData.elements.push(elObj);\r\n })\r\n formData.version = codeVersion\r\n var str = buildFormStructure(formData);\r\n return {'data':formData, 'text':str[0].outerHTML}\r\n\r\n}", "function loadReview(url, target, altCharset) {\n var reviewNumber = (/\\/stumbler\\/[^\\/]+\\/review\\/(\\d+)\\//i).exec(url)[1];\n var data = {\n method: \"GET\",\n url: 'http://www.stumbleupon.com' + url,\n\n onload: function(response) {\n eval('regex = /<var\\\\s+id=\"' + reviewNumber +\n '\"[^>]*>(.|\\\\s)+?<div\\\\s+class=\"review\">((.|\\\\s)*?)<\\\\/div>/i');\n match = regex.exec(response.responseText)[2];\n match = twitterize(match.replace(/<object[^>]*>(.|\\s)*?<\\/object>/i, ''));\n target.innerHTML = match.replace(suaRegex, '');\n }\n };\n\n if(altCharset) {\n data.overrideMimeType = \"text/html; charset=\" + altCharset;\n }\n\n GM_xmlhttpRequest(data);\n}", "function parse(str, type){\n var ret;\n var that = smark;\n switch(type){\n case \"youtube\":\n str = str.replace(that.youtubeRE, \"$1\");\n ret = '<iframe class=\"smark youtube\" src=\"https://www.youtube.com/embed/' + str + '\" frameborder=\"0\" width=\"853\" height=\"480\" allowfullscreen></iframe>';\n break;\n\n case \"vimeo\":\n str = str.replace(that.vimeoRE, \"$1\");\n ret = '<iframe class=\"smark vimeo\" src=\"https://player.vimeo.com/video/' + str + '\" frameborder=\"0\" width=\"853\" height=\"480\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';\n break;\n\n case \"image\":\n var tmp1 = str.replace(that.imageRE, \"$1\");\n var tmp2 = str.replace(that.imageRE, \"$2\");\n if (typoMark){\n\t tmp2 = that.typographicChanges(tmp2);\n\t }\n ret = '<img class=\"smark image\" title=\"' + tmp2 + '\" src=\"' + tmp1 + '\">';\n if (that.imageLinkRE.test(str)) {\n var tmp3 = that.imageLinkRE.exec(str)[0];\n tmp3 = tmp3.substring(1, tmp3.length - 1);\n ret = '<a href=\"' + tmp3 + '\" target=_blank>' + ret + \"</a>\";\n }\n break;\n\n case \"link\":\n // Note: This is executed after Youtube and Vimeo test\n // because this will be a valid match for them as well.\n str = str.match(that.htmlRE)[0];\n ret = '<iframe class=\"smark website\" src=\"' + str + '\" width=\"853\" height=\"480\" frameborder=\"0\"></iframe>';\n break;\n\n case \"paragraph\":\n // Typographic changes will be made if noTypo is not passed.\n // Markdown style syntax will be converted as well.\n str = that.parseParagraph(typoMark, str);\n // Treat the source as just a paragraph of text.\n ret = '<p class=\"smark paragraph\">' + str + '</p>';\n break;\n\n default:\n ret = \"\";\n }\n return ret;\n }", "function parseQuestion() {\n const questionElem = document.getElementsByClassName(\n 'content__u3I1 question-content__JfgR',\n );\n if (!checkElem(questionElem)) {\n return null;\n }\n const qbody = questionElem[0].innerHTML;\n\n // Problem title.\n let qtitle = document.getElementsByClassName('css-v3d350')[0];\n if (checkElem(qtitle)) {\n qtitle = qtitle.innerHTML;\n } else {\n qtitle = 'unknown-problem';\n }\n\n // Problem difficulty, each problem difficulty has its own class.\n const isHard = document.getElementsByClassName('css-t42afm');\n const isMedium = document.getElementsByClassName('css-dcmtd5');\n const isEasy = document.getElementsByClassName('css-14oi08n');\n\n if (checkElem(isEasy)) {\n difficulty = 'Easy';\n } else if (checkElem(isMedium)) {\n difficulty = 'Medium';\n } else if (checkElem(isHard)) {\n difficulty = 'Hard';\n }\n // Final formatting of the contents of the README for each problem\n const markdown = `<h2>${qtitle}</h2><h3>${difficulty}</h3><hr>${qbody}`;\n return markdown;\n}", "function getNewBlogText() {\r\n \r\n var raw = $('#newBlogText').html();\r\n var formatted = raw.replace(/<div><br><\\/div>/g, '<br>'); // drop div around <br>s\r\n return formatted;\r\n}", "function getWikiTreeTurboComments() {\n const divs = $('.comment-body');\n return _.filter(_.toArray(divs), isWikiTreeTurboJSON);\n}", "function extractToText(strings) {\n var $htmlContent, $htmlPattern, $htmlReplace;\n\n // first remove to unnecessary gaps\n $htmlContent = strings.replace(/\\n/gim, '').replace(/\\r/gim, '').replace(/\\t/gim, '').replace(/&nbsp;/gim, ' ');\n\n $htmlPattern = [\n /\\<span(|\\s+.*?)><span(|\\s+.*?)>(.*?)<\\/span><\\/span>/gim, // trim nested spans\n// /<(\\w*[^p])\\s*[^\\/>]*>\\s*<\\/\\1>/gim, // remove empty or white-spaces tags (ignore paragraphs (<p>) and breaks (<br>))\n// [ COMMENT BCZ REMOVE THE <B> TAG -- ASHISH]\n\n /\\<div(|\\s+.*?)>(.*?)\\<\\/div>/gim, // convert div to p\n /\\<strong(|\\s+.*?)>(.*?)\\<\\/strong>/gim, // convert strong to b\n /\\<em(|\\s+.*?)>(.*?)\\<\\/em>/gim // convert em to i\n ];\n\n $htmlReplace = [\n '<span$2>$3</span>',\n// '', //[ COMMENT BCZ REMOVE THE <B> TAG -- ASHISH]\n '<p$1>$2</p>',\n '<b$1>$2</b>',\n '<i$1>$2</i>'\n ];\n\n // repeat the cleaning process 5 times\n for (c = 0; c < 5; c++) {\n // create loop as the number of pattern\n for (var i = 0; i < $htmlPattern.length; i++) {\n var pattern = $htmlPattern[i];\n var replaceby = $htmlReplace[i];\n $htmlContent = $htmlContent.replace(pattern, replaceby);\n }\n }\n\n // if paragraph is false (<p>), convert <p> to <br>\n if (!vars.p)\n $htmlContent = $htmlContent.replace(/\\<p(|\\s+.*?)>(.*?)\\<\\/p>/ig, '<br/>$2');\n\n // if break is false (<br>), convert <br> to <p>\n if (!vars.br) {\n $htmlPattern = [\n /\\<br>(.*?)/ig,\n /\\<br\\/>(.*?)/ig\n ];\n\n $htmlReplace = [\n '<p>$1</p>',\n '<p>$1</p>'\n ];\n\n // create loop as the number of pattern (for breaks)\n for (var i = 0; i < $htmlPattern.length; i++) {\n $htmlContent = $htmlContent.replace($htmlPattern[i], $htmlReplace[i]);\n }\n }\n\n // if paragraph and break is false (<p> && <br>), convert <p> to <div>\n if (!vars.p && !vars.br)\n $htmlContent = $htmlContent.replace(/\\<p>(.*?)\\<\\/p>/ig, '<div>$1</div>');\n\n return $htmlContent;\n }", "function htmlestATweet(rawTwatShite, format = \"json\") {\n\t/*\ttwitter structure\n\t**\n\t**\tso the class \"js-tweet-text-container\" contains a p tag with the\n\t**\t\ttweet in it\n\t**\tthe parent element of \"js-tweet-text-container\" contains the\n\t**\t\tother (relevant) classes;\n\t**\t\tuser/source;\n\t**\t\t\t\"stream-item-header\" > \"account-group js-account-group js-action-profile js-user-profile-link js-nav\"\n\t**\t\t\t-> \"avatar js-action-profile-avatar\"\n\t**\t\t\t-> \"FullNameGroup\" > \"fullname show-popup-with-id u-textTruncate \"\n\t**\t\t\t-> \"username u-dir u-textTruncate\"\n\t**\t\t\t-> \"stream-item-header\" > \"time\"\n\t**\t\treplies, rt's, favourite's;\n\t**\t\t\t\"stream-item-footer\" > \"ProfileTweet-actionCountList u-hiddenVisually\"\n\t**\t\t\t-> \"ProfileTweet-action--reply u-hiddenVisually\"\n\t**\t\t\t-> \"ProfileTweet-action--retweet u-hiddenVisually\"\n\t**\t\t\t-> \"ProfileTweet-action--favorite u-hiddenVisually\"\n\t**\n\t**\twatchout for retweets / replies / likes, they just show up as\n\t**\t\tsomeone else's tweet on the timeline at the moment, maybe\n\t**\t\tdo a status similar to \"tweeted\", \"retweeted\", etc. \n\t**\t\toperative status being \"tweeted\" for originally tweeted\n\t*/\n\n\tconsole.log(\"starting to parse tweet html now\")\n\t//\treturn messages\n\tvar output;\n\t//\thtml data, jsdom style\n\tconst dom = new JSDOM(rawTwatShite);\n\n\t//\teasy reference point for tweet text, it does get messy with \n\t//\t\tparent children elements either way though\n\tvar classes = dom.window.document.getElementsByClassName(\"js-tweet-text-container\");\n\n\t//\tconvinence variable\n\tvar header;\n\t//\tmeta details of tweet, used for situations such as;\n\t//\t\ttrump retweets a cnn article, in that case;\n\t//\t\tstatus == \"retweet\", puser == \"realdonaldtrump\", puserimg...\n\t//\t\tusername == \"CNN\", fullname == \"CNN\", tweet == \"CNN's\"\n\t//\ttodo; this status method still needs to be implemented\n\tvar status, puser, puserimg;\n\t//\ttweet id, tweet's local time, and epoch time\n\tvar id, time, epoch;\n\t//\tfocused (i.e. \"tweet\" or \"retweet\") details;\n\t//\t\ttweet's user, tweet, and stats (replies, rt's, etc.)\n\tvar username, fullname, userimg, tweet;\n\tvar replies, retweets, likes;\n\n\n\tif (format == \"json\") {\n\t\toutput = {\n\t\t\treqtime : Date.now(),\n\t\t\ttwts : []\n\t\t}\n\t} else if (format == \"html\") {\n\t\tvar marquee = true;\n\t\tif (marquee) {\n\t\t\toutput = \"<div><marquee class=\\\"slider-cst\\\" behaviour=\\\"slide\\\" direction=\\\"left\\\" scrollamount=\\\"5\\\" scrolldelay=\\\"1\\\">\";\n\t\t}\n\t} else if (format == \"text\") {\n\t\toutput = \"\";\n\t} else {\n\t\toutput = \"\";\n\t}\n\n\t//\tcycle through tweets to get deets\n\tfor (var i = 0; i < classes.length; ++i) {\n\n\t\tconsole.log(\"--tweet \" + i + \" of \" + classes.length);\n\t\t//\tprint out all elemets of tweet for debug purposes\n\t\tfor (var j = 0; j < classes[i].parentElement.children.length; ++j) {\n\t\t\t/*\tthere's how to do links / quotes / pictures or whatever \n\t\t\t**\t\tin tweets, check length of \n\t\t\t**\t\tclasses[i].parentElement.children, if greater \n\t\t\t**\t\tthan 3 (header, tweet-text, xxx, n xxx, footer)\n\t\t\t*/\n\t\t\tconsole.log(\"clss \" + j + \"; \" + classes[i].parentElement.children[j].className);\n\t\t}\n\t\tconsole.log(\"tweet elements; \" + classes[i].parentElement.children.length);\n\n\t\t//\ttweet id\n\t\tid = classes[i].parentElement.parentElement.getAttribute(\"data-item-id\");\n\t\tconsole.log(\"got tweet id; \" + id);\n\n\t\theader = classes[i].parentElement.getElementsByClassName(\"stream-item-header\")[0].getElementsByClassName(\"account-group js-account-group js-action-profile js-user-profile-link js-nav\")[0];\n\n\t\t//\tgetting user handle\n\t\tusername = header.getElementsByClassName(\"username u-dir u-textTruncate\")[0].innerHTML;\n\t\t//\tthey use b and s tags on usernames\n\t\tusername = cleanHTML(username);\n\t\tconsole.log(\"got username; \" + username);\n\n\t\t//\tgetting user's fullname\n\t\tfullname = header.getElementsByClassName(\"FullNameGroup\")[0].getElementsByClassName(\"fullname show-popup-with-id u-textTruncate \")[0].innerHTML;\n\t\tfullname = cleanHTML(fullname);\n\t\tconsole.log(\"got fullname; \" + fullname);\n\n\t\t//\tgetting user picture\n\t\tuserpic = header.getElementsByClassName(\"avatar js-action-profile-avatar\")[0].getAttribute(\"src\");\n\t\t//console.log(\"usr pc div keys; \" + getKeys(header.getElementsByClassName(\"avatar js-action-profile-avatar\")[0]));\n\t\t//console.log(\"usr pc div; \" + header.getElementsByClassName(\"avatar js-action-profile-avatar\")[0]);\n\t\t//console.log(\"usr pc div outr; \" + header.getElementsByClassName(\"avatar js-action-profile-avatar\")[0].outerHTML);\n\t\tuserpic = cleanHTML(header.getElementsByClassName(\"avatar js-action-profile-avatar\")[0].outerHTML);\n\t\tconsole.log(\"got userpic; \" + userpic);\n\n\t\t//\tgetting tweet\n\t\ttweet = classes[i].firstElementChild.innerHTML;\n\t\t//\ttodo; get any links in the tweet and reformat to be nice;\n\t\t//\t\ti.e. work on the cleanHTML function\n\t\ttweet = cleanHTML(tweet);\n\t\tconsole.log(\"got tweet; \" + tweet);\n\n\t\t//\ttime of tweet, time is local, epoch is usable\n\t\theader = classes[i].parentElement.getElementsByClassName(\"stream-item-header\")[0].getElementsByClassName(\"time\")[0].getElementsByClassName(\"tweet-timestamp js-permalink js-nav js-tooltip\")[0];\n\t\ttime = header.getAttribute(\"title\");\n\t\tepoch = header.getElementsByClassName(\"_timestamp js-short-timestamp \")[0].getAttribute(\"data-time\");\t\n\t\tconsole.log(\"got time; \" + time + \"; epoch; \" + epoch);\n\n\t\t//\taccessing the footer to get retweets etc.\n\t\theader = classes[i].parentElement.getElementsByClassName(\"stream-item-footer\")[0].getElementsByClassName(\"ProfileTweet-actionCountList u-hiddenVisually\")[0];\n\n\t\t//\tgetting reply count\n\t\treplies = header.getElementsByClassName(\"ProfileTweet-action--reply u-hiddenVisually\")[0].getElementsByClassName(\"ProfileTweet-actionCount\")[0].getElementsByClassName(\"ProfileTweet-actionCountForAria\")[0].innerHTML;\n\t\tconsole.log(\"got replies; \" + replies);\n\n\t\t//\tgetting retweet count\n\t\tretweets = header.getElementsByClassName(\"ProfileTweet-action--retweet u-hiddenVisually\")[0].getElementsByClassName(\"ProfileTweet-actionCount\")[0].getElementsByClassName(\"ProfileTweet-actionCountForAria\")[0].innerHTML;\n\t\tconsole.log(\"got retweets; \" + retweets);\n\n\t\t//\tgetting tweet's like count\n\t\tlikes = header.getElementsByClassName(\"ProfileTweet-action--favorite u-hiddenVisually\")[0].getElementsByClassName(\"ProfileTweet-actionCount\")[0].getElementsByClassName(\"ProfileTweet-actionCountForAria\")[0].innerHTML;\n\t\tconsole.log(\"got likes; \" + likes);\n\n\n\t\t//\tformat output values\n\t\t//\tfyi this will output html links (a) and images (img)\n\t\tif (format == \"json\") {\n\t\t\t//\treplacing reply / retwt / like text with just a number\n\t\t\t//\t\tthats the replace function below\n\t\t\toutput.twts.push({\n\t\t\t\tid : id, \n\t\t\t\tusername : username, \n\t\t\t\tfullname : fullname,\n\t\t\t\tuserpic : userpic, \n\t\t\t\ttweet : tweet,\n\t\t\t\ttime : time, \n\t\t\t\tepoch : epoch, \n\t\t\t\treplies : replies.replace(/[^0-9]/g, ''),\n\t\t\t\tretweets : retweets.replace(/[^0-9]/g, ''),\n\t\t\t\tlikes : likes.replace(/[^0-9]/g, '')\n\t\t\t});\n\t\t} else if (format == \"html\") {\n\t\t\t/*\tcurrent html format (rolling headlines 2018-12-03)\n\t\t\t**\t\t<marquee behaviour=\"slide\" direction=\"left\" scrollamount=\"5\" scrolldelay=\"1\">\n\t\t\t**\t\t\t(<img src=\"news/thejournal_ie/favicon.ico\" style=\"margin-bottom: 0.5em;\" width=\"16px\" height=\"16px\" align=\"middle\"> <a href=\"http://www.thejournal.ie/heres-what-happened-today-monday-28-4373967-Dec2018/\" target=\"_blank\">[Here's What Happened Today: Monday ]</a><p> Rise in rough sleepers, Brexit legal advice and an English language college closing had everyone talking today.</p>)\n\t\t\t**\t\t\t(<img src=\"news/thejournal_ie...\n\t\t\t**\t\t\t...\n\t\t\t**\t\t</marquee>\n\t\t\t*/\n\n\t\t\t//output += \"[ \" + fullname + \" (\" + twitterfy(username);\n\t\t\toutput += \"[\" + userpic + \" \" + twitterfy(username, fullname);\n\t\t\t//output += \" \" + userpic + \")\";\n\t\t\toutput += \" | \" + twitterfy(id, tweet) + \" | \";\n\t\t\t//output += \" | \" + tweet + \" | \";\n\t\t\t//output += replies + \", \" + retweets + \", \" + likes;\n\t\t\t//output += replies.replace(/[^0-9]/g, '') + \" rp's, \";\n\t\t\toutput += prettyNumber(replies.replace(/[^0-9]/g, '')) + \" rp's, \";\n\t\t\toutput += prettyNumber(retweets.replace(/[^0-9]/g, '')) + \" rt's, \";\n\t\t\toutput += prettyNumber(likes.replace(/[^0-9]/g, '')) + \" lk's\\n\";\n\t\t\toutput += \" ] \";\n\n\t\t} else {\n\t\t\t//\treturn plain text for unknowns (including \"text\")\n\t\t\toutput += \"\\n---\\n\" + id + \" | \" + fullname;\n\t\t\toutput += \" (\" + username + \"); \" + tweet + \"; \";\n\t\t\t//output += replies.replace(/[^0-9]/g, '') + \"rp's, \" + retweets.replace(/[^0-9]/g, '') + \"rt's, \" + likes.replace(/[^0-9]/g, '') + \"lk's\\n\";\n\t\t\toutput += replies + \", \" + retweets + \", \" + likes + \"\\n\";\n\t\t}\n\t}\n\n\tif ((format == \"html\") && (marquee == true)) {\n\t\toutput += \"</marquee></div>\";\n\t}\n\tconsole.log(\"finishing html tweet parse now\")\n\treturn output;\n}", "function extractText(node) {\n let text = '';\n\n if (node.type == 'tag') {\n for (var c = 0; c < node.children.length; c++) {\n text += extractText(node.children[c]);\n }\n }\n\n if (node.type == 'text') {\n text = node.data;\n }\n\n // Decode HTML\n text = entities.decode(text);\n // Strip HTML tags\n return text.replace(/(<([^>]+)>)/ig, '')\n .replace(/\\n/g, ' ')\n .replace(/\\r/g, ' ')\n .replace(/\\s+/g, ' ');\n}", "function parseHadoopID(data, type, full) {\n if (type === 'display') {\n return data;\n }\n\n var splits = data.split('>');\n // Return original string if there is no HTML tag\n if (splits.length === 1) return data;\n\n //Return the visible string rather than the entire HTML tag\n return splits[1].split('<')[0];\n}", "function unhtmlify(original) {\n original = original.trim();\n // Also remove any newlines, adding a space if there was none otherwise.\n original = original.replace(/( (\\r\\n|\\n|\\r)+|(\\r\\n|\\n|\\r)+ |(\\r\\n|\\n|\\r)+)/gm,\" \");\n var testversion = original.replace(/^ *<p>/i, '').replace(/<\\/p> *$/i, '');\n if(!html_only_regex.test(testversion)) {\n testversion = dounescape(testversion);\n if(!html_regex.test(testversion)) return testversion;\n }\n return original;\n}", "function autoEdHTMLtoWikitext(str) {\n // <b>, <strong>, <i>, and <em> tags\n str = str.replace(/<(B|STRONG)[ ]*>((?:[^<>]|<[a-z][^<>]*\\/>|<([a-z]+)(?:| [^<>]*)>[^<>]*<\\/\\3>)*?)<\\/\\1[ ]*>/gi, \"'''$2'''\");\n str = str.replace(/<(I|EM)[ ]*>((?:[^<>]|<[a-z][^<>]*\\/>|<([a-z]+)(?:| [^<>]*)>[^<>]*<\\/\\3>)*?)<\\/\\1[ ]*>/gi, \"''$2''\");\n // </br>, <\\br>, <br\\>, <BR />, ...\n str = str.replace(/<[\\\\\\/]+BR[\\\\\\/\\s]*>/gim, '<br />');\n str = str.replace(/<[\\\\\\/\\s]*BR[\\s]*[\\\\\\/]+[\\s]*>/gim, '<br />');\n // <.br>, <br.>, <Br>, ...\n str = str.replace(/<[\\s\\.]*BR[\\s\\.]*>/gim, '<br>');\n // <br>>, <<br />, <<br >> ...\n str = str.replace(/<[\\s]*(<br[\\s\\/]*>)/gim, '$1');\n str = str.replace(/(<br[\\s\\/]*>)[\\s]*>/gim, '$1');\n // <hr>\n str = str.replace(/([\\r\\n])[\\t ]*<[\\\\\\/\\. ]*HR[\\\\\\/\\. ]*>/gi, '$1----');\n str = str.replace(/(.)<[\\\\\\/\\. ]*HR[\\\\\\/\\. ]*>/gi, '$1\\n----');\n // Not really an HTML-to-wikitext fix, but close enough\n str = str.replace(/<[\\\\\\/\\s]*REFERENCES[\\\\\\/\\s]*>/gim, '<references />');\n // Repeated references tag\n str = str.replace(/(<references \\/>)[\\s]*\\1/gim, '$1');\n // Make sure <H1>, ..., <H6> is after a newline\n str = str.replace(/([^\\r\\n ])[\\t ]*(<H[1-6][^<>]*>)/gim, '$1\\n$2');\n // Make sure </H1>, ..., </H6> is before a newline\n str = str.replace(/(<\\/H[1-6][^<>]*>)[\\t ]*([^\\r\\n ])/gim, '$1\\n$2');\n // Remove newlines from inside <H1>, ..., <H6>\n var loopcount = 0;\n while( str.search( /<H([1-6])[^<>]*>(?:[^<>]|<\\/?[^\\/h\\r\\n][^<>]*>)*?<\\/H\\1[^<>]*>/gim ) >= 0 && loopcount <= 10 ) {\n str = str.replace(/(<H)([1-6])([^<>]*>(?:[^<>]|<\\/?[^\\/h\\r\\n][^<>]*>)*?)[\\r\\n]((?:[^<>]|<\\/?[^\\/h\\r\\n][^<>]*>)*?<\\/H)\\2([^<>]*>)/gim, '$1$2$3 $4$2$5');\n loopcount++;\n }\n // Replace <H1>, ..., <H6> with wikified section headings\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H1[^<>]*>([^\\r\\n]*?)<\\/H1[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1= $2 =$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H2[^<>]*>([^\\r\\n]*?)<\\/H2[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1== $2 ==$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H3[^<>]*>([^\\r\\n]*?)<\\/H3[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1=== $2 ===$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H4[^<>]*>([^\\r\\n]*?)<\\/H4[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1==== $2 ====$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H5[^<>]*>([^\\r\\n]*?)<\\/H5[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1===== $2 =====$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H6[^<>]*>([^\\r\\n]*?)<\\/H6[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1====== $2 ======$3');\n \n return str;\n}", "function shouldDecode(content,encoded){var div=document.createElement('div');div.innerHTML=\"<div a=\\\"\"+content+\"\\\">\";return div.innerHTML.indexOf(encoded)>0;}// #3663", "function vB_AJAX_TagThread(tag_container, linkid)\n{\n\tthis.edit_form = 'tag_edit_form';\n\tthis.edit_cancel = 'tag_edit_cancel';\n\n\tthis.form_progress = 'tag_form_progress';\n\tthis.submit_progress = 'tag_edit_progress';\n\n\tthis.form_visible = false;\n\tthis.do_ajax_submit = true;\n\n\tthis.tag_container = tag_container;\n\n\tvar match = fetch_object(linkid).href.match(/(\\?|&)t=([0-9]+)/);\n\tthis.threadid = match[2];\n}", "function parseBasic(body){\n\t\n\tvar items = [],\n\t\toutput = [],\n\t\theadings = [];\n\t\n\tvar $ = cheerio.load(body);\n\t\n\t//Get table contents\n\t$('.entry .custom-table tr').each(function(){\n\t\titems.push($(this).html());\t\n\t});\n\t\n\t//Pull out the first row for headings\n\tvar headingsSrc = items.splice(0, 1);\n\t\n\t//Store headings in an array\n\t$(headingsSrc[0]).each(function(){\n\t\theadings.push($(this).text());\n\t});\n\t\n\t//Loop through each content rpw\n\titems.forEach(function(item){\n\t\t\n\t\tvar tempItem = {};\t\t\t\n\t\t\n\t\t$(item).each(function(td){\n\t\t\t\n\t\t\ttempItem[headings[td].toLowerCase()] = $(this).text();\n\t\t\t\t\n\t\t});\n\t\t\n\t\toutput.push(tempItem);\t\t\n\t\t\n\t});\n\t\n\t//this.parsedData = output;\n\t\n\treturn output;\n}", "function Calendar_fixupTags( wtext )\n{\norig = new String( wtext )\norig = this.replaceStr( orig, \"<br>\", \"*br*\" )\norig = this.replaceStr( orig, \" \", \"&nbsp\" )\norig = this.replaceStr( orig, \"<\", \"<\" )\norig = this.replaceStr( orig, \">\", \">\" )\norig = this.replaceStr( orig, \"*br*\", \"<br>\" )\nreturn orig\n}", "function stripHtml(html)\n {\n html = html.replace(/<br>/g,\" \");\n var tmp = document.createElement(\"DIV\");\n tmp.innerHTML = html;\n return tmp.textContent || tmp.innerText || \"\";\n }", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]+>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n // Unescape a string 's'.\n function unescape1(e) {\n return ESCAPE[e];\n }\n function unescape(s) {\n while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {\n s = s.replace(m[0], unescape1);\n }\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n element.localName = tagName;\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n node.className = m[2].substr(1).replace('.', ' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n }", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]+>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n // Unescape a string 's'.\n function unescape1(e) {\n return ESCAPE[e];\n }\n function unescape(s) {\n while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {\n s = s.replace(m[0], unescape1);\n }\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n element.localName = tagName;\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n node.className = m[2].substr(1).replace('.', ' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n }", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]+>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n // Unescape a string 's'.\n function unescape1(e) {\n return ESCAPE[e];\n }\n function unescape(s) {\n while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {\n s = s.replace(m[0], unescape1);\n }\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n element.localName = tagName;\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n node.className = m[2].substr(1).replace('.', ' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n }", "function parseContent(window, input) {\n function nextToken() {\n // Check for end-of-string.\n if (!input) {\n return null;\n }\n\n // Consume 'n' characters from the input.\n function consume(result) {\n input = input.substr(result.length);\n return result;\n }\n\n var m = input.match(/^([^<]*)(<[^>]+>?)?/);\n // If there is some text before the next tag, return it, otherwise return\n // the tag.\n return consume(m[1] ? m[1] : m[2]);\n }\n\n // Unescape a string 's'.\n function unescape1(e) {\n return ESCAPE[e];\n }\n function unescape(s) {\n while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) {\n s = s.replace(m[0], unescape1);\n }\n return s;\n }\n\n function shouldAdd(current, element) {\n return !NEEDS_PARENT[element.localName] ||\n NEEDS_PARENT[element.localName] === current.localName;\n }\n\n // Create an element for this tag.\n function createElement(type, annotation) {\n var tagName = TAG_NAME[type];\n if (!tagName) {\n return null;\n }\n var element = window.document.createElement(tagName);\n element.localName = tagName;\n var name = TAG_ANNOTATION[type];\n if (name && annotation) {\n element[name] = annotation.trim();\n }\n return element;\n }\n\n var rootDiv = window.document.createElement(\"div\"),\n current = rootDiv,\n t,\n tagStack = [];\n\n while ((t = nextToken()) !== null) {\n if (t[0] === '<') {\n if (t[1] === \"/\") {\n // If the closing tag matches, move back up to the parent node.\n if (tagStack.length &&\n tagStack[tagStack.length - 1] === t.substr(2).replace(\">\", \"\")) {\n tagStack.pop();\n current = current.parentNode;\n }\n // Otherwise just ignore the end tag.\n continue;\n }\n var ts = parseTimeStamp(t.substr(1, t.length - 2));\n var node;\n if (ts) {\n // Timestamps are lead nodes as well.\n node = window.document.createProcessingInstruction(\"timestamp\", ts);\n current.appendChild(node);\n continue;\n }\n var m = t.match(/^<([^.\\s/0-9>]+)(\\.[^\\s\\\\>]+)?([^>\\\\]+)?(\\\\?)>?$/);\n // If we can't parse the tag, skip to the next tag.\n if (!m) {\n continue;\n }\n // Try to construct an element, and ignore the tag if we couldn't.\n node = createElement(m[1], m[3]);\n if (!node) {\n continue;\n }\n // Determine if the tag should be added based on the context of where it\n // is placed in the cuetext.\n if (!shouldAdd(current, node)) {\n continue;\n }\n // Set the class list (as a list of classes, separated by space).\n if (m[2]) {\n node.className = m[2].substr(1).replace('.', ' ');\n }\n // Append the node to the current node, and enter the scope of the new\n // node.\n tagStack.push(m[1]);\n current.appendChild(node);\n current = node;\n continue;\n }\n\n // Text nodes are leaf nodes.\n current.appendChild(window.document.createTextNode(unescape(t)));\n }\n\n return rootDiv;\n }" ]
[ "0.5318621", "0.5318207", "0.5248225", "0.5144867", "0.5083701", "0.5052744", "0.50308007", "0.4956494", "0.48256215", "0.48246196", "0.47761884", "0.472897", "0.4724978", "0.47094837", "0.47001305", "0.4687524", "0.46806896", "0.46773297", "0.4656406", "0.46519637", "0.46342188", "0.46260068", "0.4599386", "0.45957497", "0.45921284", "0.4585424", "0.4584582", "0.4575177", "0.45507672", "0.45491824", "0.45437416", "0.4539298", "0.45203775", "0.45203775", "0.4511787", "0.45089924", "0.45089924", "0.4505847", "0.45032954", "0.44939202", "0.44906253", "0.44895416", "0.4483019", "0.44791648", "0.44612813", "0.44585153", "0.44564942", "0.44564942", "0.44564942", "0.44493413", "0.44466177", "0.444324", "0.44267917", "0.4420442", "0.4420357", "0.4420357", "0.44138652", "0.44118452", "0.4404512", "0.4402554", "0.4394886", "0.43912482", "0.43867087", "0.43764597", "0.4366041", "0.4359734", "0.4357557", "0.43563977", "0.43562883", "0.43485108", "0.43453103", "0.43417197", "0.4336047", "0.43259877", "0.43191913", "0.4312887", "0.43092707", "0.43043712", "0.43028665", "0.43004408", "0.4295654", "0.42954388", "0.42927554", "0.42896816", "0.42796806", "0.4274191", "0.42726204", "0.4270108", "0.42559773", "0.42516264", "0.42504102", "0.42445913", "0.42408592", "0.423976", "0.4236195", "0.42322937", "0.4232083", "0.4232083", "0.4232083", "0.4232083" ]
0.72910213
0
Parse a string array from a bracketed list. For example "OneTiddler [[Another Tiddler]] LastOne"
function parseStringArray(value, allowDuplicate) { if(typeof value === "string") { var memberRegExp = /(?:^|[^\S\xA0])(?:\[\[(.*?)\]\])(?=[^\S\xA0]|$)|([\S\xA0]+)/mg, results = [], names = {}, match; do { match = memberRegExp.exec(value); if(match) { var item = match[1] || match[2]; if(item !== undefined && (!(item in names) || allowDuplicate)) { results.push(item); names[item] = true; } } } while(match); return results; } else if(Array.isArray(value)) { return value; } else { return null; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function parse (input) {\n\tvar output = [];\n\tinput = input.trim();\n\tinput = input.split(\" \");\n\n\tfor (var i = 0; i < input.length; i++) {\n\t\tif (input[i].charAt(0) == \"[\") {\n\t\t\toutput.push(input[i].slice(1,3));\n\t\t};\n\t};\n\n\treturn output;\n}", "function getBracketedItems(content) {\n\tvar retval = [ ];\n\tvar startIdx = 0;\n\tvar endIdx = 0;\n\n\t// so lange wie möglich doppelte öffnende eckige Klammern suchen \n\twhile((startIdx = content.indexOf(\"[[\", endIdx)) != -1) {\n\t\tvar length = 0;\n\n\t\t// zugehöriges schließendes Klammernpaar suchen \n\t\tendIdx = content.indexOf(\"]]\", startIdx);\n\t\tif(endIdx == -1) break;\n\n\t\t// länge des tokens ermitteln */\n\t\tlength = endIdx - startIdx - 2;\n\n\t\t// links mit http:// sind mindestens 7 zeichen lang, shortlinks (zunächst) weniger als 3\n\t\tif((length > 7) || (length <= 2)) {\n\t\t\t// gefundenes token als anonymes objekt ins array werfen\n\t\t\tretval.push( { 'content' : content.substring(startIdx + 2, endIdx), 'id' : null, 'link' : null } );\n\t\t} \n\t}\n\n\t// array mit token-objekten zurückgeben \n\treturn retval;\n}", "function parseSets(str) {\n // or \"[[1,2], [3,4]]\" -> [[1,2], [3,4]]\n var sets = str.match(/\\[[^\\[]+\\]/g) || [], i, j;\n\n for (i = 0; i < sets.length; i++) {\n sets[i] = sets[i].match(/[-\\d\\.]+/g);\n\n for (j = 0; j < sets[i].length; j++) {\n sets[i][j] = +sets[i][j];\n }\n }\n\n return sets;\n }", "function ParseArray(array){\n let chain = '';\n if(array.length){\n const symbol = array.shift();\n if(Array.isArray(symbol.value)){\n chain = `[${ParseArray(symbol.value)}`;\n }else if(typeof symbol.value == 'object' && symbol.value != null){\n chain = `[${ParseType(symbol.value)}`;\n }else{\n chain = `[${symbol.value}`;\n }\n }else{\n chain = '[';\n }\n array.forEach((symbol) => {\n if(Array.isArray(symbol.value)){\n chain += `, ${ParseArray(symbol.value)}`;\n }else if(typeof symbol.value == 'object' && symbol.value != null){\n chain += `, ${ParseType(symbol.value)}`;\n }else{\n chain += `, ${symbol.value}`;\n }\n });\n return chain += ']';\n}", "function decodeNestedArray(text) {\n text = text.trim();\n var result = [];\n var stack = [];\n stack.push(result);\n var text2 = '';\n for(var i = 1; i < text.length - 1; i++) {\n var c = text.charAt(i);\n if(c == '[') {\n var a = [];\n stack[stack.length - 1].push(a);\n stack.push(a);\n }\n else if(c == ']') {\n if(text2 != '') {\n stack[stack.length - 1].push(parseInt(text2));\n text2 = '';\n }\n stack.pop();\n }\n else if(c == ',') {\n if(text2 != '') {\n stack[stack.length - 1].push(parseInt(text2));\n text2 = '';\n }\n }\n else {\n text2 += c;\n }\n }\n if(text2 != '') stack[stack.length - 1].push(parseInt(text2));\n return result;\n}", "function parseArray(rawData){\n\tif (rawData.trim()==\"[]\"){ //when array is empty\n\t\treturn [];\n\t}else{\n\t\t//take everything except first and last character\n\t\treturn rawData.substring(1, rawData.length-1).split(\",\");\n\t}\n}", "function convertToArray(rawstring, myArray){\n\tcurrString = rawstring.substring(1)\n\tinitialIndex = rawstring.indexOf(\",\")\n\n\twhile (initialIndex!=-1){\n\t\tbeginString = currString.substring(2, initialIndex-2)\n\t\tmyArray.push(beginString)\n\t\tcurrString = currString.substring(initialIndex)\n\t\tinitialIndex = currString.indexOf(\",\")\t\t\n\t}\n\n\tlastString = currString.substring(1, currString.indexOf(\"]\")-1)\n\tmyArray.push(lastString)\n\treturn myArray\n\n}", "function brackets(str) {\n var arr = str.split('');\n while (arr.length > 1 && arr[0] !== ']' && arr[arr.length - 1] !== '[') { //find pair '[]' and delete it from array\n arr.splice(0, 1);\n arr.splice(arr.indexOf(']'), 1);\n }\n return arr.length === 0 ? 'OK' : 'NOT OK';\n}", "function bracket(arr) {\n let first = arr[0]\n let bracketed = '(' + first\n arr.shift()\n for (e of arr) {\n bracketed = bracketed.concat(', ')\n bracketed = bracketed.concat(e)\n }\n bracketed = bracketed.concat(')')\n arr.unshift(first)\n return bracketed\n}", "function caml_array_of_string (s) {\n if (s.t != 4 /* ARRAY */) caml_convert_string_to_array(s);\n return s.c;\n}", "function split(text) {\n\t\t\t\tvar len = text.length;\n\t\t\t\tvar arr = [];\n\t\t\t\tvar i = 0;\n\t\t\t\tvar brk = 0;\n\t\t\t\tvar level = 0;\n\n\t\t\t\twhile (i + 2 <= len) {\n\t\t\t\t\tif (text.slice(i, i + 2) === '[[') {\n\t\t\t\t\t\tlevel += 1;\n\t\t\t\t\t\ti += 1;\n\t\t\t\t\t} else if (text.slice(i, i + 2) === ']]') {\n\t\t\t\t\t\tlevel -= 1;\n\t\t\t\t\t\ti += 1;\n\t\t\t\t\t} else if (level === 0 && text[i] === ',' && text[i - 1] !== '\\\\') {\n\t\t\t\t\t\tarr.push(text.slice(brk, i).trim());\n\t\t\t\t\t\ti += 1;\n\t\t\t\t\t\tbrk = i;\n\t\t\t\t\t}\n\t\t\t\t\ti += 1;\n\t\t\t\t}\n\t\t\t\tarr.push(text.slice(brk, i + 1).trim());\n\t\t\t\treturn arr;\n\t\t\t}", "function parseTokens()\n {\n var arr = [];\n list.children('li').each(function () {\n arr.push( $(this).html().split(\" \")[0] );\n });\n return arr;\n }", "function parseArrayPattern(params, kind) {\n var node = new Node(), elements = [], rest, restNode;\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else {\n if (match('...')) {\n restNode = new Node();\n lex();\n params.push(lookahead);\n rest = parseVariableIdentifier(kind);\n elements.push(restNode.finishRestElement(rest));\n break;\n } else {\n elements.push(parsePatternWithDefault(params, kind));\n }\n if (!match(']')) {\n expect(',');\n }\n }\n\n }\n\n expect(']');\n\n return node.finishArrayPattern(elements);\n }", "function parseLiteralArray(content) {\n\t\n\tif (content[0].text !== '[' || content[content.length-1].text !== ']') {\n\t\terror(\"Literal array is not actually a literal array\");\n\t}\n\t\n\tif (content.length === 2) {\n\t\treturn tows(\"_emptyArray\", valueFuncKw);\n\t} else {\n\t\t//check for \"in\" keyword\n\t\t//format is \"var for var in array if condition\"\n\t\tvar inOperands = splitTokens(content.slice(1, content.length-1), \"in\", false);\n\t\tif (inOperands.length === 2) {\n\t\t\tvar ifOperands = splitTokens(inOperands[1], \"if\");\n\t\t\tif (ifOperands.length !== 2) {\n\t\t\t\t//Not a filtered array (eg: [player.C for player in playersInRadius()])\n\t\t\t\tvar forOperands = splitTokens(inOperands[0], \"for\");\n\t\t\t\tif (forOperands.length !== 2) {\n\t\t\t\t\terror(\"Malformed 'x for y in z'\");\n\t\t\t\t}\n\t\t\t\tvar forVarName = forOperands[1][0].text;\n\t\t\t\tif (forLoopVariables[forVarName] !== undefined) {\n\t\t\t\t\terror(\"Variable \"+forVarName+\" is already used\");\n\t\t\t\t}\n\t\t\t\tforLoopVariables[forVarName] = inOperands[1];\n\t\t\t\t\n\t\t\t\tvar result = parse(forOperands[0]);\n\t\t\t\tdelete forLoopVariables[forVarName];\n\t\t\t\treturn result;\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t//Filtered array\n\t\t\t\tif (inOperands[0].length !== 3 || inOperands[0][1].text !== \"for\" || inOperands[0][0].text !== inOperands[0][2].text) {\n\t\t\t\t\terror(\"Malformed 'x for x in y'\");\n\t\t\t\t}\n\t\t\t\tdebug(\"Parsing 'x for x in y if z', x='\"+inOperands[0][0].text+\"', y='\"+dispTokens(ifOperands[0])+\"', z='\"+dispTokens(ifOperands[1])+\"'\");\n\t\t\t\t\n\t\t\t\tcurrentArrayElementNames.push(inOperands[0][0].text);\n\t\t\t\tvar result = tows(\"_filteredArray\", valueFuncKw)+\"(\"+parse(ifOperands[0])+\", \"+parse(ifOperands[1])+\")\";\n\t\t\t\tcurrentArrayElementNames.pop();\n\t\t\t\treturn result;\n\t\t\t}\n\t\t} else {\n\t\t\t\n\t\t\t//Literal array with only values ([1,2,3])\n\t\t\tvar args = splitTokens(content.slice(1, content.length-1), \",\");\n\t\t\tvar appendFunc = tows(\"_appendToArray\", valueFuncKw);\n\t\t\tvar result = tows(\"_emptyArray\", valueFuncKw);\n\t\t\tfor (var i = 0; i < args.length; i++) {\n\t\t\t\tresult = appendFunc+\"(\"+result+\", \"+parse(args[i])+\")\";\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t}\n\t\n\terror(\"This shouldn't happen\");\n\t\n}", "function parseArrayPattern(params, kind) {\n\t var node = new Node(), elements = [], rest, restNode;\n\t expect('[');\n\n\t while (!match(']')) {\n\t if (match(',')) {\n\t lex();\n\t elements.push(null);\n\t } else {\n\t if (match('...')) {\n\t restNode = new Node();\n\t lex();\n\t params.push(lookahead);\n\t rest = parseVariableIdentifier(kind);\n\t elements.push(restNode.finishRestElement(rest));\n\t break;\n\t } else {\n\t elements.push(parsePatternWithDefault(params, kind));\n\t }\n\t if (!match(']')) {\n\t expect(',');\n\t }\n\t }\n\n\t }\n\n\t expect(']');\n\n\t return node.finishArrayPattern(elements);\n\t }", "function parseArrayPattern(params, kind) {\n var node = new Node(), elements = [], rest, restNode;\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else {\n if (match('...')) {\n restNode = new Node();\n lex();\n params.push(lookahead);\n rest = parseVariableIdentifier(kind);\n elements.push(restNode.finishRestElement(rest));\n break;\n } else {\n elements.push(parsePatternWithDefault(params, kind));\n }\n if (!match(']')) {\n expect(',');\n }\n }\n\n }\n\n expect(']');\n\n return node.finishArrayPattern(elements);\n }", "function parseArrayPattern(params, kind) {\n var node = new Node(), elements = [], rest, restNode;\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else {\n if (match('...')) {\n restNode = new Node();\n lex();\n params.push(lookahead);\n rest = parseVariableIdentifier(kind);\n elements.push(restNode.finishRestElement(rest));\n break;\n } else {\n elements.push(parsePatternWithDefault(params, kind));\n }\n if (!match(']')) {\n expect(',');\n }\n }\n\n }\n\n expect(']');\n\n return node.finishArrayPattern(elements);\n }", "function parseArrayPattern(params, kind) {\n var node = new Node(), elements = [], rest, restNode;\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else {\n if (match('...')) {\n restNode = new Node();\n lex();\n params.push(lookahead);\n rest = parseVariableIdentifier(kind);\n elements.push(restNode.finishRestElement(rest));\n break;\n } else {\n elements.push(parsePatternWithDefault(params, kind));\n }\n if (!match(']')) {\n expect(',');\n }\n }\n\n }\n\n expect(']');\n\n return node.finishArrayPattern(elements);\n }", "function arrayFromString(sectionString){\n return sectionString.replace(/(?:\\r\\n|\\r|\\n)/g, ' ')\n .replace(/\\s\\s+/g, ' ')\n .trim()\n .split(\" \");\n}", "function parseArrayPosition(str){\n var regex = /\\.[\\d]+/g;\n var m; \n while ((m = regex.exec(str)) !== null) { \n if (m.index === regex.lastIndex) {\n regex.lastIndex++;\n } \n m.forEach( function(item, index, arr){ \n var index = arr[0].substring(1,arr[0].length)\n var result = \"[\"+index+\"]\";\n str = str.replace(arr[0],result) ;\n });\n }\n return str;\n }", "function handleArrayInput(_splitted, _var, i) {\n var arr = [];\n arr.push(convertToType(_var.substr(1)));\n\n i++;\n var _var2 = _splitted[i];\n while (_var2.indexOf(']') == -1) {\n arr.push(convertToType(_var2));\n\n i++;\n _var2 = _splitted[i];\n }\n arr.push(convertToType(_var2.substr(0, _var2.length - 1)));\n\n return arr;\n}", "function arrayer(song) {\n let arrayOfParts = [];\n let startIndex = 1;\n let endIndex = 0;\n while (song) {\n endIndex = song.indexOf(\"[\", startIndex);\n if (endIndex === -1) {\n arrayOfParts.push(song.slice(startIndex - 1, song.length - 1));\n break;\n }\n arrayOfParts.push(song.slice(startIndex - 1, endIndex - 1));\n startIndex = endIndex + 1; \n }\n console.log(arrayOfParts[0].charCodeAt(10)); //87\n return arrayOfParts;\n }", "function FirstPairBracketsToWork(arrayExpression) {\n var arrayBrackets = [-1, -1];\n for (var i = 0; i < arrayExpression.length; i++) {\n if (arrayExpression[i] == \"(\") {\n arrayBrackets[0] = i;\n }\n\n if (arrayExpression[i] == \")\") {\n arrayBrackets[1] = i;\n break;\n }\n }\n return arrayBrackets;\n}", "function splitNested(str) {\n return [str].join('.').replace(/\\[/g, '.').replace(/\\]/g, '').split('.');\n}", "function parse() {\n var parsedInputArray = [];\n for (var i = 3; i < rawInput.length; i++) {\n parsedInputArray.push(rawInput[i]);\n }\n return parsedInputArray.join(' ');\n\n}", "function returnArray(s) {\n var firstIndex = s.indexOf('{');\n var lastIndex = s.lastIndexOf('}');\n var str = s.substring(firstIndex + 1, lastIndex);\n var arr = str.split(',');\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i].trim();\n }\n return arr;\n}", "function stringListConverter(inputValue) {\n const tokens = inputValue.split(/[,\\/]/);\n const output = [];\n for (let token of tokens) {\n const trimmed = token.toLowerCase().trim();\n if (trimmed) {\n // Skip empty tokens\n output.push(trimmed);\n }\n }\n return output;\n}", "function ParseArray()\n {\n value = [];\n\n while (true) {\n\n var tokenInfo = NextTokenInfo();\n var token = tokenInfo[0];\n var tokenRow = tokenInfo[1];\n var tokenColumn = tokenInfo[2];\n\n switch (token) {\n\n case ']':\n return true;\n\n case '}':\n case '.':\n error = \"ParseArray: expected type or ']' instead of \" + token;\n errorRow = tokenRow;\n errorColumn = tokenColumn;\n return false;\n\n case '{':\n\n valueStack.push(value);\n\n if (!ParseObject()) {\n return false;\n }\n\n var objectValue = value;\n value = valueStack.pop();\n value.push(objectValue);\n\n break;\n\n case '[':\n\n valueStack.push(value);\n\n if (!ParseArray()) {\n return false;\n }\n\n var arrayValue = value;\n value = valueStack.pop();\n value.push(arrayValue);\n\n break;\n\n default:\n\n var typeName = token;\n\n subScope = {\n sheetName: scope.sheetName,\n sheet: scope.sheet,\n isSingleSheet: scope.isSingleSheet,\n isSingleCell: true,\n row: scope.currentRow,\n column: tokenColumn,\n rowCount: 1,\n columnCount: 1,\n typeName: typeName,\n alreadyIndented: true,\n inTable: true,\n index: index,\n tableRow: scope.currentRow,\n tableColumn: firstHeaderColumn,\n tableRows: 1,\n tableColumns: headerColumns,\n inTableArray: true,\n inTableArrayIndex: subScope.value.length\n };\n\n scope.subScopes.push(subScope);\n\n scope.errorScope = LoadJSONFromSheet(sheets, ranges, subScope);\n if (scope.errorScope) {\n return false;\n }\n\n value.push(subScope.value);\n\n break;\n }\n\n }\n }", "function transformStringInArray(str) {\n const token = tokenizer.tokenize(str);\n return token;\n}", "function testTripleParser() \n{\n\t// equiv. turtle expression - :a :b :c ; :d :e , :f\n\tvar expression1 = [ ':a', [ ':b', ':c', ':d', [ ':e', ':f' ] ] ];\n\tvar result1 = JSON.stringify( parse( expression1 ) );\n\tequal( \"test1\", result1, '[[\":a\",\":b\",\":c\"],[\":a\",\":d\",\":e\"],[\":a\",\":d\",\":f\"]]' );\n\t\n\t// equiv. turtle expression - :a :b , :c , :d , :e , :f\n\tvar expression2 = [ ':a', ':b', [ ':c', ':d', ':e', ':f' ] ];\t\t\n\tvar result2 = JSON.stringify( parse( expression2 ) );\n\tequal( \"test2\", result2, '[[\":a\",\":b\",\":c\"],[\":a\",\":b\",\":d\"],[\":a\",\":b\",\":e\"],[\":a\",\":b\",\":f\"]]' );\n\t\n\t// not valid turtle expression, but parses anyway, \n\t// TODO: should we make this should throw an exception?\n\tvar expression3 = [ ':a', [ ':b', [ ':c', ':d', ':e', ':f' ] ] ];\t\t\n\tvar result3 = JSON.stringify( parse( expression3 ) );\n\tequal( \"test3\", result3, '[[\":a\",\":b\",\":c\"],[\":a\",\":b\",\":d\"],[\":a\",\":b\",\":e\"],[\":a\",\":b\",\":f\"]]' );\n\t\n\t// should throw exception 'too many levels'\n\tvar expression4 = [ ':a', [ ':b', [ ':c', [ ':d', ':e', ':f' ] ] ] ];\t\t\n\tvar result4;\n\ttry {\n\t\tresult4 = parse( expression4 );\n\t}\n\tcatch( e ) {\n\t\tresult4 = e;\n\t}\n\tequal( \"test4\", result4, 'parse error - invalid nested array' );\n\t\n\t// equiv. turtle expression - :a :b :c , :d ; :e :f , :g .\n\tvar expression5 = [ ':a', [ ':b', [ ':c', ':d' ] ], ':e', [ ':f', ':g' ] ]; \n\tvar result5 = JSON.stringify( parse( expression5 ) );\n\tequal( \"test5\", result5, '[[\":a\",\":b\",\":c\"],[\":a\",\":b\",\":d\"],[\":a\",\":e\",\":f\"],[\":a\",\":e\",\":g\"]]' );\n\t\n}", "function parseSetsWithStrings(str) {\n var sets = str.match(/\\[[^\\[]+\\]/g) || [], i, j;\n\n for (i = 0; i < sets.length; i++) {\n // Splitting apart numbers/strings from dataset string \n sets[i] = sets[i].match(/('(?:[^\\\\\"\\']+|\\\\.)*')|([-\\w\\.]+)/g);\n\n for (j = 0; j < sets[i].length; j++) {\n sets[i][j] = isNaN(sets[i][j]) ? stripSingleQuotes(sets[i][j]) : +sets[i][j];\n }\n }\n\n return sets;\n }", "function parse(x){\n var isp = function(x){\n return [\"(\",\")\"].includes(x)\n }\n var ins = function(x,L,fun){\n if (L.length > 0 && typeof L[0] == \"object\"){\n return [ins(x,L[0],fun)].concat(L.slice(1))\n }else{\n return fun(x,L)\n }\n }\n var jump = function(x,L){\n if (L.length > 0 && typeof L[0] == \"object\"){\n if (L[0].length > 0 && typeof L[0][0] != \"object\"){\n return [x].concat(L)\n }\n }\n return [jump(x,L[0])].concat(L.slice(1))\n }\n var listify = function(x){\n if (x.length == 0){\n return []\n }\n var car = x[0]\n var cdr = x.slice(1)\n\n var res = listify(cdr)\n if (car == \")\"){\n res = ins([],res,(x,L)=>[x].concat(L))\n }else if (car == \"(\"){\n res = jump(\"$\",res)\n }else if (isop(car)){\n res = ins(car,res,(x,L)=>[x].concat(L))\n }else{\n res = ins(car,res,(x,L)=>\n (L.length==0 || isop(L[0]))? [x].concat(L) : [x+L[0]].concat(L.slice(1))\n )\n }\n return res\n }\n var clean = function(x,L){\n return L.filter((y)=>typeof y==\"object\"?true:x!=y)\n .map((y)=>typeof y==\"object\"?clean(x,y):y)\n }\n var pfxop = function(L){\n if (typeof L != \"object\"){\n return L\n }\n if (L.length == 1){\n return pfxop(L[0])\n }\n return [L.filter(x=>isop(x)).join(\"\")].concat(L.filter(x=>!isop(x)).map(pfxop))\n\n }\n return pfxop(clean(\"$\",listify(x)))\n}", "function parseArray(str) {\n if (!str) {\n result = [];\n } else {\n var result = str.split(',').map(function (value) {\n // trim\n return value.replace(/^\\s+|\\s+$/g, '');\n }).filter(function (value) {\n return !!value;\n });\n }\n return result;\n}", "function _normalizeParameterList(tokens) {\n var params = $.map(tokens, function (e, i) { return e.string; }).join(\"\");\n var paramsNoParens = params.match(/^\\((.*)\\)/)[1];\n if (paramsNoParens) {\n return paramsNoParens.split(',');\n } else {\n return [];\n }\n }", "function parse(array){\n let result = [];\n let word = [];\n let first;\n const len = array.length;\n for (let i = 0; i < len; i++){\n let sound_ = sound(array[i]);\n if (isFirst(i, array)) word.push(array[i].toUpperCase());\n if (sound_ && sound_ !== ' ' && isDifferent(i, array, word) && !(isFirst(i, array))) word.push(sound_);\n if (isEnd(i, array)) {\n Array.prototype.push.apply(result, pad(word));\n word = [];\n }\n if (sound_ === ' ') result.push(sound_);\n }\n return result.join(''); \n}", "function parseArrayInitializer() {\n var elements = [], node = new Node(), restSpread;\n\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else if (match('...')) {\n restSpread = new Node();\n lex();\n restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));\n\n if (!match(']')) {\n isAssignmentTarget = isBindingElement = false;\n expect(',');\n }\n elements.push(restSpread);\n } else {\n elements.push(inheritCoverGrammar(parseAssignmentExpression));\n\n if (!match(']')) {\n expect(',');\n }\n }\n }\n\n lex();\n\n return node.finishArrayExpression(elements);\n }", "function deepFlatten(strList, array) {\n for (const item of array) {\n if (Array.isArray(item)) {\n deepFlatten(strList, item);\n } // else if (item instanceof Declaration) {\n // strList.push(item.toString());\n // }\n else {\n strList.push(item);\n }\n }\n }", "function formatResults(arr) {\n let formatter = arr.split(\" => \");\n let posts = [];\n if (formatter.length <= 1) {\n return posts;\n }\n for (let i = 1; i < formatter.length - 1; i++) {\n posts.push(JSON.parse(formatter[i].substring(0, formatter[i].length - 3)));\n }\n posts.push(JSON.parse(formatter[formatter.length - 1].substring(0, formatter[formatter.length - 1].length - 2)));\n return posts;\n }", "function tokenizeWithParentheses(value) {\n var parts = [];\n var partStart = 0;\n var parens = 0;\n for (var i = 0; i < value.length; i++) {\n switch (value[i]) {\n case '(':\n parens++;\n break;\n case ')':\n if (parens) {\n parens--;\n }\n break;\n case '\\t':\n case ' ':\n if (!parens) {\n // Add the new part if it's not an empty string\n if (i > partStart) {\n parts.push(value.substring(partStart, i));\n }\n partStart = i + 1;\n }\n break;\n }\n }\n // Add the last part\n if (partStart < value.length) {\n parts.push(value.substring(partStart));\n }\n return parts;\n}", "function tokenizeWithParentheses(value) {\n var parts = [];\n var partStart = 0;\n var parens = 0;\n for (var i = 0; i < value.length; i++) {\n switch (value[i]) {\n case '(':\n parens++;\n break;\n case ')':\n if (parens) {\n parens--;\n }\n break;\n case '\\t':\n case ' ':\n if (!parens) {\n // Add the new part if it's not an empty string\n if (i > partStart) {\n parts.push(value.substring(partStart, i));\n }\n partStart = i + 1;\n }\n break;\n }\n }\n // Add the last part\n if (partStart < value.length) {\n parts.push(value.substring(partStart));\n }\n return parts;\n}", "function parseArrayInitializer() {\n var elements = [], node = new Node(), restSpread;\n\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else if (match('...')) {\n restSpread = new Node();\n lex();\n restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));\n\n if (!match(']')) {\n isAssignmentTarget = isBindingElement = false;\n expect(',');\n }\n elements.push(restSpread);\n } else {\n elements.push(inheritCoverGrammar(parseAssignmentExpression));\n\n if (!match(']')) {\n expect(',');\n }\n }\n }\n\n lex();\n\n return node.finishArrayExpression(elements);\n }", "function parseArrayInitializer() {\n var elements = [], node = new Node(), restSpread;\n\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else if (match('...')) {\n restSpread = new Node();\n lex();\n restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));\n\n if (!match(']')) {\n isAssignmentTarget = isBindingElement = false;\n expect(',');\n }\n elements.push(restSpread);\n } else {\n elements.push(inheritCoverGrammar(parseAssignmentExpression));\n\n if (!match(']')) {\n expect(',');\n }\n }\n }\n\n lex();\n\n return node.finishArrayExpression(elements);\n }", "function parseArrayInitializer() {\n var elements = [], node = new Node(), restSpread;\n\n expect('[');\n\n while (!match(']')) {\n if (match(',')) {\n lex();\n elements.push(null);\n } else if (match('...')) {\n restSpread = new Node();\n lex();\n restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));\n\n if (!match(']')) {\n isAssignmentTarget = isBindingElement = false;\n expect(',');\n }\n elements.push(restSpread);\n } else {\n elements.push(inheritCoverGrammar(parseAssignmentExpression));\n\n if (!match(']')) {\n expect(',');\n }\n }\n }\n\n lex();\n\n return node.finishArrayExpression(elements);\n }", "function parseToArray(s) {\n return s.slice(1, s.length - 1).split(',');\n }", "function parseArrayInitializer() {\n\t var elements = [], node = new Node(), restSpread;\n\n\t expect('[');\n\n\t while (!match(']')) {\n\t if (match(',')) {\n\t lex();\n\t elements.push(null);\n\t } else if (match('...')) {\n\t restSpread = new Node();\n\t lex();\n\t restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));\n\n\t if (!match(']')) {\n\t isAssignmentTarget = isBindingElement = false;\n\t expect(',');\n\t }\n\t elements.push(restSpread);\n\t } else {\n\t elements.push(inheritCoverGrammar(parseAssignmentExpression));\n\n\t if (!match(']')) {\n\t expect(',');\n\t }\n\t }\n\t }\n\n\t lex();\n\n\t return node.finishArrayExpression(elements);\n\t }", "function parseModel(val){str=val;len=str.length;index$1=expressionPos=expressionEndPos=0;if(val.indexOf('[')<0||val.lastIndexOf(']')<len-1){return{exp:val,idx:null};}while(!eof()){chr=next();/* istanbul ignore if */if(isStringStart(chr)){parseString(chr);}else if(chr===0x5B){parseBracket(chr);}}return{exp:val.substring(0,expressionPos),idx:val.substring(expressionPos+1,expressionEndPos)};}", "function parseInput(string) {\n // remember, these get applied right-to-left\n var f = helpers.compose(createObjects, splitOnDashes, createArrays)\n return f(string)\n}", "function parseArray(array){\n\n var templates = array.map(parse);\n\n return Template(function (context){\n return templates.map(function (template){\n return template(context);\n });\n }, templates.reduce(function (parameters, template){\n return parameters.concat(template.parameters);\n }, []));\n\n}", "function parseElements(v) {\n if (!v) return [];\n var w = v.split(/,+/);\n var lg = [];\n for (var e in w) {\n var s = w[e].trim();\n if (s.length > 0) lg.push(s);\n }\n return lg;\n}", "function splitSquareBrackets(str) {\n var leftIx = 0, \n rightIx = str.length,\n ix = rightIx,\n level,\n obj = { \n before: '', inside: '', after: ''\n };\n\n // look for left bracket\n while (leftIx < str.length) {\n if (str[leftIx] === '[') {\n break;\n }\n leftIx += 1;\n }\n\n // look for right bracket\n ix = leftIx + 1;\n level = 1;\n while (ix < rightIx) {\n if (str[ix] === ']') {\n level -= 1;\n } else if (str[ix] === '[') {\n level += 1;\n }\n if (level === 0) {\n break;\n }\n ix += 1;\n }\n // if we did not find the right bracket (ix === rightIx), \n // or the brackets enclose nothing (ix - leftIx === 1),\n // or the brackets enclose everything, then do not split\n if (ix === rightIx || (ix - leftIx === 1) || \n ((leftIx === 0) && (ix + 1 === rightIx))) {\n leftIx = rightIx;\n } else {\n rightIx = ix;\n }\n\n obj.before = str.substr(0, leftIx);\n obj.inside = str.substr(leftIx + 1, rightIx - leftIx - 1); \n obj.after = str.substr(rightIx+1);\n return obj;\n }", "function stringToArray (string) {\n var namesListArray = string.split(\"\\n\");\n return namesListArray;\n}", "function parseTypeArray (type) {\n var tmp = type.match(/(.*)\\[(.*?)\\]$/)\n if (tmp) {\n return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10)\n }\n return null\n}", "function parseTypeArray (type) {\n var tmp = type.match(/(.*)\\[(.*?)\\]$/)\n if (tmp) {\n return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10)\n }\n return null\n}", "function parseTypeArray (type) {\n var tmp = type.match(/(.*)\\[(.*?)\\]$/)\n if (tmp) {\n return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10)\n }\n return null\n}", "function bparseList(str) {\n let p,\n list = [];\n while (str.charAt(0) !== \"e\" && str.length > 0) {\n p = bparse(str);\n if (null === p) {\n return null;\n }\n list[list.length] = p[0];\n str = p[1];\n }\n if (str.length <= 0) {\n throw \"unexpected end of buffer reading list\";\n }\n return [list, str.substr(1)];\n}", "function return2DArray(s) {\n var firstIndex = s.indexOf('{');\n var lastIndex = s.lastIndexOf('}');\n var str = s.substring(firstIndex+1, lastIndex);\n var temp = '';\n var a;\n var arr = [];\n var open_index = 0, close_index = 0;\n for(var i=0; i<str.length; i++) {\n if(str.charAt(i) == '{') {\n open_index = i;\n temp = temp + str.charAt(i);\n }\n else if(str.charAt(i) == '}') {\n close_index = i;\n temp = temp + str.charAt(i);\n a = returnArray(temp);\n arr.push(a);\n temp = '';\n }\n else {\n temp = temp + str.charAt(i);\n }\n }\n return arr;\n}", "function toList(string) {\n\t\tif (!string || !string.length) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (Array.isArray(string)) {\n\t\t\treturn string;\n\t\t}\n\n\t\tstring = string.replace(\"\\[\", \"\").replace(\"\\]\", \"\");\n\t\tstring = string.replaceAll(\"\\\"\", \"\");\n\n\t\treturn string.split(\",\");\n\t}", "function arrayFromList(list, sep){\n //match separator typos (repetitions) between list, considering spaces\n var re1 = new RegExp( \"\\\\\"+ sep +\"[ *\\\\\"+ sep +\"*]*\\\\\" + sep, \"g\");\n //match separator typos (repetitions) at the beginnigns and at the end of the list, considering spaces\n var re2 = new RegExp( \"(^[ *\\\\\"+ sep +\"*]*|[ *\\\\\"+ sep +\"*]*$)\", \"g\");\n\n var arr = (list)\n .replace( re1, \",\")\n .replace( re2, \"\");\n return arr.split(sep);\n }", "function X(a){for(var b,c=[],d=/\\[([^\\]]*)\\]|\\(([^\\)]*)\\)|(LT|(\\w)\\4*o?)|([^\\w\\[\\(]+)/g;b=d.exec(a);)b[1]?// a literal string inside [ ... ]\nc.push(b[1]):b[2]?// non-zero formatting inside ( ... )\nc.push({maybe:X(b[2])}):b[3]?// a formatting token\nc.push({token:b[3]}):b[5]&&// an unenclosed literal string\nc.push(b[5]);return c}", "function cd_parsePara(str, paraArray) {\n\n\tfor (var p in paraArray)\n\t\tparaArray[p] = cd_getTagValue(p, str);\n}", "function buildArrayOnIndex(value){\n\tif(value.toString().includes(\" \"))\n\t\treturn value.split(\" \");\n\telse\n\t\treturn [value];\n}", "function parse(ctr, items) {\n\t\t\tvar values = (/^function[^\\(]*\\(([^\\)]+)\\)/gi).exec(ctr.toString());\n\t\t\tif (!values) { return []; }\n\t\t\tvar items = values[1].split(',');\n\t\t\tfor (var i = 0; i < items.length; i++) { items[i] = items[i].trim(); }\n\t\t\treturn items;\n\t\t}", "function parse(inp) {\n var tokens;\n var ind = 0;\n var out = [];\n\n function tokenize(inp) {\n var tokens = [];\n for (var i = 0; i < inp.length; i++) {\n if (inp[i] === ';') {\n i++;\n while (inp[i] !== '\\n' && i < inp.length) {\n i++;\n }\n continue;\n } else if (inp[i] === ' ' ||\n inp[i] === '\\n' ||\n inp[i] === '\\r' ||\n inp[i] === '\\t') {\n continue;\n } else if (inp[i] === '(' ||\n inp[i] === ')') {\n tokens.push(inp[i]);\n } else {\n var token = \"\";\n while (inp[i] !== ';' &&\n inp[i] !== ' ' &&\n inp[i] !== '\\n' &&\n inp[i] !== '\\r' &&\n inp[i] !== '\\t' &&\n inp[i] !== '(' &&\n inp[i] !== ')' &&\n i < inp.length) {\n token += inp[i];\n i++;\n }\n i--; // FIXME: why the hack?\n if (!isNaN(token)) {\n tokens.push(+token);\n } else {\n tokens.push(token);\n }\n }\n }\n return tokens;\n }\n\n tokens = tokenize(inp);\n\n function parseList() {\n ind++;\n var lst = [];\n while (ind < tokens.length) {\n if (tokens[ind] === '(') {\n lst.push(parseList());\n } else if (tokens[ind] === ')') {\n return lst;\n } else {\n lst.push(tokens[ind]);\n }\n ind++;\n }\n }\n\n while (ind < tokens.length) {\n if (tokens[ind] === '(') {\n out.push(parseList());\n } else if (tokens[ind] === ')') {\n error(\"unexpected ')'\");\n } else {\n out.push(tokens[ind]);\n }\n ind++;\n }\n\n return out;\n}", "function parseTypeArray (type) {\n\t var tmp = type.match(/(.*)\\[(.*?)\\]$/)\n\t if (tmp) {\n\t return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10)\n\t }\n\t return null\n\t}", "function caml_string_of_array (a) { return new MlString(4,a,a.length); }", "parse (array = []) {\r\n // If already is an array, no need to parse it\r\n if (array instanceof Array) return array\r\n\r\n return array.trim().split(delimiter).map(parseFloat)\r\n }", "function splitLabels(input){\n for(const elem of input){\n var entry = elem.split(':')\n var text = entry[entry.length-1];\n entry.pop();\n createObject(entry,text) //sends the labels and text separate to create object\n }\n}", "function tplArray (str) {\n\t\t\tvar\n\t\t\tcallee = arguments.callee,\n\t\t\ttpl = str.match(\n\t\t\t\t(new RegExp('^([\\\\W\\\\w]*?)'+\n\t\t\t\tescapeRegExp(storage.opener)+\n\t\t\t\t'([\\\\W\\\\w]*?)'+\n\t\t\t\tescapeRegExp(storage.closer)+\n\t\t\t\t'([\\\\W\\\\w]*?)$'))\n\t\t\t),\n\t\t\tarr = [];\n\t\t\t//\n\t\t\tif (tpl !== null) arr = arr.concat([tpl[1]], [[tpl[2].substr(0, 1), tpl[2].substr(1)]], callee(tpl[3]));\n\t\t\telse arr.push(str);\n\t\t\t//\n\t\t\treturn arr;\n\t\t}", "function extractInternalsFromBrackets(parts, token, indexOffset = 0){\n var depth = -1;\n var args = [];\n for( var i = indexOffset; i < parts.length; i++){\n var inversToken = getInversToken(token);\n var startingIndex;\n var intermediateIndex;\n switch(parts[i]){\n\n case token:\n if(depth < 0)\n intermediateIndex = startingIndex = i + 1;\n depth++;\n break;\n\n case inversToken:\n if(depth == 0){\n args.push(parts.slice(intermediateIndex,i))\n return { endingIndex: i, startingIndex, args };\n }\n depth--;\n break;\n\n case \",\":\n if(depth == 0 && token === \"(\"){\n args.push(parts.slice(intermediateIndex,i));\n intermediateIndex = i + 1;\n }\n break;\n\n default:\n if(token === \"(\" && parts[i].match(/\\($/)){\n if(depth < 0)\n intermediateIndex = startingIndex = i + 1;\n depth++;\n break;\n }\n }\n }\n err(`Missing ${inversToken}`);\n return;\n }", "function readNumberArray(str, index) {\n var start = index;\n while (str[index++] != '[')\n start++;\n start++;\n\n var count = 0;\n while (str[index++] != ']')\n count++;\n\n str = str.substr(start, count);\n\n str = str.trim();\n // Remove adjacent spaces\n str = str.replace(/\\s+/g, ' ');\n\n var array = str.split(' ');\n for (var i = 0, ii = array.length; i < ii; i++)\n array[i] = parseFloat(array[i] || 0);\n return array;\n }", "function parseStringList(token) {\n var delim = ',';\n var list = splitOptionList(token, delim);\n if (list.length == 1) {\n list = splitOptionList(list[0], delim);\n }\n return list;\n }", "function parseSkills(message) {\n \n //var trim = message.replace(/()/g, \"\");\n const newMessage=message.replace(\"addSkill \",\"\")\n console.log(newMessage)\n skills = newMessage.split(\", \");\n\n skillArray = skills\n \n}", "function parseUpstream (upstream) {\n if (typeof upstream == 'undefined' || upstream == null) {\n return [];\n } else if (Array.isArray(upstream)) {\n return upstream;\n } else {\n return `${upstream}`.split(';');\n }\n}", "function parse(words){\n\n\n\n}", "function parseResponse (r) {\n if(r[0] === \"[\" || r[0] === \"{\" ) return JSON.parse(r);\n return r;\n }", "function parseArray(arr) {\n return {\n winid: arr[0],\n app: arr[1],\n title: arr[2],\n pid: arr[3],\n }\n}", "function parsePythonResult(result){\n\tvar parsedList = [];\n\tfor (var i = 0; i < result.length; i++){\n\t\tvar appStringSplit = result[i].split(\"->\")\n\t\tvar appName = appStringSplit[0];\n\t\tvar version = appStringSplit[1];\n\t\tparsedList.push({\n\t\t\t\"name\": appName,\n\t\t\t\"old_version\": \"1\",\n\t\t\t\"new_version\": version,\n\t\t\t\"id\": \"0\",\n\t\t\t\"updatable\": \"false\"\n\t\t});\n\t}\n\treturn parsedList;\n}", "function splitStringByRef(string) {\n const newStringReplaced = string.split(/(?=[$])/)\n .map(inner => {\n if (inner.charAt(0) === \"$\" && inner.charAt(1) === \"{\") {\n const parentheseAt = inner.indexOf('}') + 1;\n return R.pair(inner.substr(0, parentheseAt), inner.substr(parentheseAt));\n }\n return inner;\n });\n return R.flatten(newStringReplaced);\n}", "function unserialize_array_2d(str) {\n// {{{\n\tvar arr1 = str.split('|');\n\tvar arr = new Array();\n\tfor (var i = 0; i < arr1.length; ++i) {\n\t\tarr[i] = arr1[i].split(',');\n\t}\n\treturn arr;\n// }}}\n}", "function parseSpaceSeparated(string) {\n if (string == \"\" || string == null) {\n return []\n } else {\n return String(string).replace(/(^\\s*,)|(,\\s*$)/g, '').trim().split(/[\\s,]+/);\n }\n}", "function processArrayOfStringOrRegExp(iv) {\n if (!Array.isArray(iv)) {\n return;\n }\n var rv = [];\n var i = 0;\n while (rv && (i < iv.length)) {\n var elt = iv[i];\n if (typeof elt === 'string') {\n // string values OK\n rv.push(elt);\n } else if (elt instanceof RegExp) {\n // existing RegExp OK\n rv.push(elt);\n } else if (elt && (typeof elt === 'object')) {\n try {\n // ESTree RegExpLiteral ok if it produces RegExp\n rv.push(new RegExp(elt.regex.pattern, elt.regex.flags || ''));\n } catch (e) {\n // Not a valid RegExpLiteral\n rv = null;\n }\n } else {\n // Unknown value\n rv = null;\n }\n ++i;\n }\n return rv;\n}", "function parse_PtgArray(blob, length) {\n\tvar type = (blob[blob.l++] & 0x60) >> 5;\n\tblob.l += 7;\n\treturn [type];\n}", "function parse_PtgArray(blob, length) {\n\tvar type = (blob[blob.l++] & 0x60) >> 5;\n\tblob.l += 7;\n\treturn [type];\n}", "function parse_PtgArray(blob, length) {\n\tvar type = (blob[blob.l++] & 0x60) >> 5;\n\tblob.l += 7;\n\treturn [type];\n}", "function parse_PtgArray(blob, length) {\n\tvar type = (blob[blob.l++] & 0x60) >> 5;\n\tblob.l += 7;\n\treturn [type];\n}", "function parse (externalHolder) {\n var internalHolder = [];\n var internal;\n\n if (_.isArray(externalHolder)) {\n _.each(externalHolder, function (external) {\n internal = convert(external);\n internalHolder.push(internal);\n });\n }\n return internalHolder;\n}", "function decodeString(s) {\n var nums = []\n var strs = []\n var number = ''\n strs.push('')\n for (let i = 0; i < s.length; i++) {\n if (!isNaN(s[i])) {\n number += s[i]\n if (isNaN(s[i+1])) {\n nums.push(Number(number));\n number = ''\n }\n } else if (s[i] === '[') {\n strs.push('')\n } else if (s[i] === ']') {\n let count = nums.pop()\n let chars = strs.pop()\n let substr = ''\n substr += chars.repeat(count)\n strs.push(strs.pop() + substr)\n } else {\n strs.push(strs.pop() + s[i])\n }\n }\n return strs[0]\n}", "function tokenizeArray (array) {\n let all_tokens = [];\n const arrayCount = array.length;\n\n for (let i = 0; i < arrayCount; i++) {\n const string_tokens = array[i].split(/,?\\s+/);\n all_tokens = all_tokens.concat(string_tokens);\n }\n\n return all_tokens;\n}", "function lisp_read_from_string(s) {\n return lisp_array_to_cons_list(lisp_parse(s));\n}", "function parse_interpol(value) {\n const items = [];\n let pos = 0;\n let next = 0;\n let match;\n\n while (true) {\n // Match up to embedded string\n next = value.substr(pos).search(embedder);\n if (next < 0) {\n if (pos < value.length) {\n items.push(JSON.stringify(value.substr(pos)));\n }\n break;\n }\n items.push(JSON.stringify(value.substr(pos, next)));\n pos += next;\n\n // Match embedded string\n match = value.substr(pos).match(embedder);\n next = match[0].length;\n if (next < 0) {\n break;\n }\n if (match[1] === '#') {\n items.push(`${escaperName}(${match[2] || match[3]})`);\n } else {\n // unsafe!!!\n items.push(match[2] || match[3]);\n }\n\n pos += next;\n }\n\n return items.filter(part => part && part.length > 0).join(' +\\n');\n}", "static getPossibleSubjects(chunked) {\n let vpStart = chunked.indexOf('[VP');\n if (vpStart === -1) {\n return [];\n }\n let numParenthesis = 0;\n let possibleSubjects = []\n for (let i = vpStart; i < chunked.length; i++) {\n if (chunked[i] === '[') {\n numParenthesis++;\n } else if (chunked[i] === ']') {\n numParenthesis--;\n }\n if (numParenthesis === 0) {\n const vp = chunked.substring(vpStart, i+1);\n possibleSubjects.push(vp.trim());\n vpStart = chunked.substring(i).indexOf('[VP');\n if (vpStart === -1) {\n break;\n }\n vpStart = vpStart + i - 1\n i = vpStart;\n numParenthesis = 0;\n // numClosing = 0\n }\n }\n return possibleSubjects;\n }", "function parseColonStr(aStr)\n{\n var rv = [\"\", \"\"];\n if (!aStr)\n return rv;\n\n var idx = aStr.indexOf(\":\");\n if (idx >= 0)\n {\n if (idx > 0)\n rv[0] = aStr.substring(0, idx);\n rv[1] = aStr.substring(idx + 1);\n }\n else\n {\n rv[0] = aStr;\n }\n\n return rv;\n}", "function tag(strings) {\n console.log(strings.raw[0]);\n\n}", "function ParseArray(array, encoding, obj) {\n for (var n = 0; n < encoding.length; ++n) {\n var value = array[n];\n if (!value)\n continue;\n var field = encoding[n];\n var fieldAlpha = field.replace(NON_ALPHA_CHARS, \"\");\n if (field != fieldAlpha)\n value = new RegExp(field.replace(fieldAlpha, value));\n obj[fieldAlpha] = value;\n }\n return obj;\n }", "parse() {\n let array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n // If already is an array, no need to parse it\n if (array instanceof Array) return array;\n return array.trim().split(delimiter).map(parseFloat);\n }", "function getAccessoriesArray(accessoriesString) {\n return accessoriesString.strip().split(\" \");\n}", "function MultipleBrackets(str) {\n var flag = 1;\n var openParens = 0;\n var closeParens = 0;\n var openBrackets = 0;\n var closeBrackets = 0;\n\n function rec(a) {\n\n if (a.length === 0) {\n return;\n }\n\n var ch = a.splice(0,1)[0];\n\n if (ch === \"(\") {\n openParens++;\n } else if (ch === \")\") {\n closeParens++;\n } else if (ch === \"[\") {\n openBrackets++;\n } else if (ch === \"]\") {\n closeBrackets++;\n }\n\n if (closeParens > openParens || closeBrackets > openBrackets) {\n flag = 0;\n }\n\n rec(a);\n }\n \n rec(str.split(\"\"));\n\n if (openParens !== closeParens || openBrackets !== closeBrackets) {\n flag = 0;\n }\n\n return flag === 0 ? 0 : (openBrackets + openParens) === 0 ? 1 : 1 + \" \" + (openBrackets + openParens); \n}", "parseList(list) {\n let object = {}\n list = list.replace(/^\\|+|\\|+$/, \"\").split(\"|\")\n list.forEach(pair => {\n pair = pair.split(\"=\")\n if (!0 in pair) throw new Error(\"invalid list format\")\n const key = pair[0].trim()\n const value = (1 in pair) ? pair[1].trim() : true\n object[key] = value\n })\n return object\n }", "function strsplit(str){\r\n var tmp,tmp1;\r\n if (Array.isArray(str)) {tmp = str[0];}else{tmp=str;}\r\n tmp1 = tmp.indexOf(',');\r\n if (tmp1===-1) {return [tmp,''];}\r\n return [tmp.substring(0,tmp1),tmp.substring(tmp1)];\r\n }", "static stringToArray(inp, splitPoint) {\n return splitPoint !== undefined && splitPoint !== 'ws'\n ? inp.split(splitPoint)\n : inp.match(/\\S+/g) || [];\n }" ]
[ "0.6090226", "0.58942544", "0.5650764", "0.564346", "0.5586686", "0.54979575", "0.5393847", "0.5298447", "0.5221156", "0.51865894", "0.51759875", "0.5132924", "0.51271933", "0.51052076", "0.50977755", "0.50975245", "0.50975245", "0.50975245", "0.50962394", "0.5062018", "0.50312936", "0.5030409", "0.49884146", "0.49710944", "0.49695167", "0.4942914", "0.49323675", "0.49317968", "0.4901935", "0.48909447", "0.48824376", "0.48770294", "0.48742235", "0.48629695", "0.48615777", "0.48592356", "0.48469108", "0.48436397", "0.48277375", "0.48277375", "0.48159954", "0.48159954", "0.48159954", "0.48080015", "0.47955006", "0.47943452", "0.47708476", "0.47613004", "0.47604957", "0.47577348", "0.47363853", "0.4735443", "0.4735443", "0.4735443", "0.47333294", "0.4732409", "0.4732276", "0.4728541", "0.4674723", "0.4662307", "0.46575293", "0.4627451", "0.46203065", "0.46164545", "0.461485", "0.46139142", "0.46129587", "0.46099782", "0.45984966", "0.45980126", "0.45962036", "0.45899", "0.4589865", "0.4589041", "0.45875058", "0.45715982", "0.45711514", "0.45652196", "0.45586765", "0.45530567", "0.45504484", "0.45327628", "0.45327628", "0.45327628", "0.45327628", "0.45223877", "0.45213065", "0.45200038", "0.4514375", "0.450515", "0.4495338", "0.44915515", "0.4485073", "0.44755623", "0.4474486", "0.44663173", "0.44632205", "0.4459171", "0.44534737", "0.44481307" ]
0.52878827
8
Stringify an array of tiddler titles into a list string
function stringifyList(value) { if(Array.isArray(value)) { var result = new Array(value.length); for(var t=0, l=value.length; t<l; t++) { var entry = value[t] || ""; if(entry.indexOf(" ") !== -1) { result[t] = "[[" + entry + "]]"; } else { result[t] = entry; } } return result.join(" "); } else { return value || ""; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function titleize(arr, cb){\n let titleized = arr.map(name => `Mx. ${name} Jingleheimer Schmidt`)\n cb(titleized);\n}", "function readTitles(_aMoviesArr) {\r\n var _stringToShow = \"The names of the movies are: \";\r\n\r\n for (var i = 0; i < _aMoviesArr.length; i++) {\r\n if (i < _aMoviesArr.length - 1) {\r\n _stringToShow += _aMoviesArr[i].Title + \", \";\r\n } else \r\n {\r\n _stringToShow += _aMoviesArr[i].Title;\r\n }\r\n }\r\n _stringToShow += \".\";\r\n return _stringToShow;\r\n\r\n}", "function movieTitleToArray() {\n let string = movie.title.toLowerCase();\n return string.split(\"\");\n}", "function stringify(array){\n\tvar arrayB=[]\n\tfor(i in array)\n\t\tarrayB[i]=\"\"+array[i];\n\treturn arrayB;\n}", "function createTitleWordsArray (array) {\n // PREFIX: \n allTitleWords = [];\n\n // Split all the words\n array.forEach(element => {\n let ElementTitleWords = element.title.split(' ');\n // Push every word to the array\n ElementTitleWords.forEach(word => {\n allTitleWords.push(word.toLowerCase());\n });\n });\n}", "function stringifyList(inputList) {\n var printList = \"\";\n printList = inputList.name + \" (\" + inputList.type + \") [\" + inputList.color + \"] - \";\n var i = 0;\n for (i = 0; i < inputList.sites.length; i += 1) {\n printList += inputList.sites[i];\n printList += \", \";\n }\n return printList;\n}", "function stringifyArr(arr){\n\tvar str = \"[\";\n\tarr.forEach(function(e){\n\t\tstr += \"'\"+e+\"', \";\n\t});\n\tstr += \"]\";\n\treturn str.replace(\"', ]\", \"']\");\t\n}", "function ArrayToString(oList, sName, sIndent, bNumberItems ) {\n\tif( sName == undefined || oList == undefined ) {\n\t\tHandleWarning(\"ArrayToString() needs a list and a name\");\n\t\treturn \"\";\n\t}\n\n\tsIndent = sIndent == undefined ? \"\" : sIndent;\n\tvar tRet = \"\";\n\n\tvar i = 0 ;\n\tfor( var tItem in oList ) {\n\t\tvar sNumber =bNumberItems == true ? \" [\" + tItem + \"]\" : \" \";\n\t\ttRet += sIndent + sNumber + oList[tItem].toString() + \"\\n\";\n\t\ti++;\n\t}\n\tif( i == 0) {\n\t\treturn sIndent + \"Object has no \" + sName +\"\\n\";\n\t}\n\n\treturn sIndent + sName + \":\\n\" + tRet;\n}", "function readableList(array) {\n var list = '',\n lastItem;\n switch (array.length) {\n case 0:\n return '';\n\n case 1:\n return array[0];\n case 2:\n return array[0] + ' and ' + array[1];\n\n default:\n lastItem = array.pop();\n array.each(function (item) {\n list += item + ', ';\n });\n list += 'and ' + lastItem;\n array.push(lastItem);\n return list;\n }\n }", "function getDesc(descArr) {\n let descString = '';\n descArr.forEach((desc) => {\n descString += desc.value;\n });\n return descString;\n}", "function arrToList(array) {\n var listStr = ''\n array.forEach(item => listStr += `${item}\\n`)\n return listStr;\n}", "function BOT_lemTagsToString (t) {\r\n\tvar s = \"[ \";\r\n\tvar x = \"\";\r\n\tfor(var i in t) {\r\n\t\tif( typeof(t[i][1]) == \"string\") x = t[i][1]\r\n\t\telse x = \"[\"+ t[i][1].toString() +\"]\";\r\n\t\ts = s + \"[\" + t[i][0]+\",\"+x+\"] \"\r\n\t}\r\n\treturn s+\"]\"\r\n}", "function arrayToString(array) {\n var string = \"\";\n for (let j = 0; j < array.length; j++){\n var string = string + array[j] + '\\n';\n };\n return string = string.slice(0, -1);\n }", "function simpleStringify(arr) {\n if (arr.length == 0) {\n return \"\";\n }\n\n var keys = Object.keys(arr[0]);\n return keys.join(\",\") + \"\\n\" +\n arr.map(function(obj) {\n return Object.values(obj).map(function(v){\n return typeof v === \"string\" ? '\"' + (''+v).replace(/\"/g,'\"\"') + '\"' : v\n }).join(\",\");\n }).join(\"\\n\");\n }", "list(elements) {\n const length = elements && elements.length || 0,\n contents = new Array(length);\n for (let i = 0; i < length; i++) contents[i] = this._encodeObject(elements[i]);\n return new SerializedTerm(`(${contents.join(' ')})`);\n }", "function outputArray( heading, theArray, output )\n{\n output.innerHTML = heading + theArray.join( \" \" ); \n} // end function outputArray", "function array2string($arr) {\n\tvar str = \"\";\n\t$arr.forEach(item => {\n\t\tstr += item + '\\n';\n\t});\n\treturn str;\n}", "function showItems(arr) {\r\n document.write('your to list has :\\n');\r\n for (let i = 0; i < arr.length; i++) {\r\n document.write(`${arr[i]} \\n`);\r\n }\r\n}", "function getReviews(shoe) {\n return shoe.reviews.map(r => `<li class=\"list-group-item\">${r.content}</li>`).join('')\n}", "function arrayToHtml() {\n let fullString = '';\n let tipsList = '';\n const startDiv = '<div>';\n const endDiv = '</div>';\n \n const lb = '<br>';\n let newTip = 0;\n let endTip = 2;\n const auth ='Submited By: ';\n const ti = 'Title: '\n \n for (i = 0; i < tips.length; i++)\n {\n if (i == newTip)\n { // start of new Tip add Div and author string\n fullString += startDiv + ti + tips[i] + lb;\n \n newTip += 3;\n } else if (i == endTip)\n { // end of Tip add text and close Div\n fullString += tips[i] + endDiv;\n endTip +=3;\n } else \n { // add Author data\n fullString += '<em>' + auth + tips[i] + '</em>' + lb + lb;\n }\n \n }\n \n document.getElementById(\"tipData\").innerHTML = fullString;\n // console.log(fullString);\n\n}", "function makeListItem(array){\n return \" <li> <span> <p id='name'> To do: \"+array[0]+\" </p> <p id='loc'> Location: \" + array[4] + \"</p> <p id='loc'> Time: \" + array[5] + \"</p> </span> </li> \";\n}", "function arrayOutput(ar){\n\tvar s = \"\";\n\tar.map((el)=>{\n\t\ts += JSON.stringify(el) + \"\\n\";\n\t});\n\treturn s;\n}", "function outputArray(heading, theArray, output) {\n\toutput.innerHTML = heading + theArray.join(\" \");\n} //end function outputArray", "toString() {\n const names = [];\n this.elements.forEach((element) => {\n names.push(element.toString());\n });\n return \"[\" + names.join(\", \") + \"]\";\n }", "arrayToBulletList(arr) {\n var str = \"• \"+arr[0]+\" •\\n\";\n for(var i = 1; i < arr.length; i++) {\n str += arr[i]+\" •\\n\";\n }\n return str;\n }", "function arrayToString(array) {\n return array.join('')\n }", "function textify_filters (filters_array) {\n\treturn filters_array.join(',');\n}", "function transferToString(arr) {\r\n\tvar str = \"[\";\r\n\tfor (var i = 0; i < arr.length; i++){\r\n\t\tstr += JSON.stringify(arr[i]);\r\n\t\tif (i != arr.length-1)\r\n\t\t\tstr += \",\";\r\n//\t\tfor (var j = 0; j < q[i].length; j++){\r\n//\t\t\tstr += \"'\" + q[i][j] ;\r\n//\t\t\tif (j != (q[i].length-1) ){\r\n//\t\t\t\tstr += \"', \";\r\n//\t\t\t}\r\n//\t\t\telse{\r\n//\t\t\t\tstr += \"' \";\r\n//\t\t\t}\r\n//\t\t\t\t\r\n//\t\t}\r\n//\t\tif (i != (q.length-1) )\r\n//\t\t\tstr += \"], \";\r\n//\t\telse{\r\n//\t\t\tstr += \"] \";\r\n//\t\t}\r\n\t}\r\n\tstr += \"]\";\r\n\treturn str;\r\n}", "formatArray(arrayInfo) {\n // To store the final, desired string displaying all the author names\n let stringInfo = '';\n\n if (arrayInfo === undefined) {\n stringInfo = 'Unknown'\n } else if (arrayInfo.length === 1) {\n stringInfo = arrayInfo[0]\n } else if (arrayInfo.length === 2) {\n stringInfo = `${arrayInfo[0]} and ${arrayInfo[1]}`\n } else {\n for (let i=0; i<arrayInfo.length-1; i++) {\n stringInfo += `${arrayInfo[i]}, `;\n }\n stringInfo += `and ${arrayInfo[arrayInfo.length-1]}`\n }\n\n return stringInfo;\n }", "function formatHashtagArray(array){\n\tvar hashtags = [];\n\tarray.forEach(function(entry){\n\t\thashtags.push(entry.text);\n\t});\n\treturn hashtags;\n}", "function showGiphyTrends(array){\n giphy_trends.innerText = `${array[0]}, ${array[1]}, ${array[2]}, ${array[3]}, ${array[4]}`;\n}", "function canonicalString(listArray){\n tubeStrings = []\n for (const tube of listArray){\n tubeStrings.push(tube.join())\n tubeStrings.sort()\n }\n return tubeStrings.join(\";\")\n}", "function listString (list) {\n\tresult = \"Number items: \" + list.length + \", type \" + typeof(list) + \" \" ;\n\tfor ( i = 0 ; i < list.length ; i++ ){\n\t\tresult += list[i].getAttribute(\"name\") + \"\\n\" ;\n\t}\n\treturn result ;\n}", "function transferToString(arr) {\n\tvar str = \"[\";\n\tfor (var i = 0; i < arr.length; i++){\n\t\tstr += JSON.stringify(arr[i]);\n\t\tif (i != arr.length-1)\n\t\t\tstr += \",\";\n//\t\tfor (var j = 0; j < q[i].length; j++){\n//\t\t\tstr += \"'\" + q[i][j] ;\n//\t\t\tif (j != (q[i].length-1) ){\n//\t\t\t\tstr += \"', \";\n//\t\t\t}\n//\t\t\telse{\n//\t\t\t\tstr += \"' \";\n//\t\t\t}\n//\t\t\t\t\n//\t\t}\n//\t\tif (i != (q.length-1) )\n//\t\t\tstr += \"], \";\n//\t\telse{\n//\t\t\tstr += \"] \";\n//\t\t}\n\t}\n\t\t\n\tstr += \"]\";\n\t\n\treturn str;\n}", "_createTitle(obj) {\n let res = \"\";\n for (let p in obj) {\n res += `${p}=${obj[p]},`;\n }\n return res.substr(0, res.length - 1);\n }", "function convertToString() {\n\tarrayString = genreInfo.toString();\n\tobjectString = JSON.stringify(userInfo);\n}", "function html_list_of(arb) {\n return arb.smap((x) => {\n let output = [];\n output.push(\"<ul>\");\n for (let i = 0; i < x.length; i += 1) {\n output.push(\"<li>\");\n output.push(x[i]);\n output.push(\"</li>\");\n }\n output.push(\"</ul>\");\n return output.join(\" \");\n });\n}", "function onlyTheTitles(){\r\n let result = []\r\n for (let i = 0; i < movies.length; i++){\r\n let movie = movies[i]\r\n result.push(movie.Title)\r\n }\r\n return result\r\n}", "function list(arr){\n\t\tvar listHTML = \"<ol>\";\n\t\t\tfor (var i=0; i < arr.length; i+=1){\n\t\t\t\tlistHTML += \"<li>\" + arr[i] + \"</li>\"\n\t\t\t}\n\t\t\tlistHTML += \"</ol>\"\t;\n\t\t\treturn listHTML;\n\t}", "function do_table(arr, title) {\n\t\tvar map_of_keys = {};\n\t\tarr.forEach(function(obj) {\n\t\t\tObject.keys(obj).filter(function(key) {\n\t\t\t\treturn key[0] !== '_';\n\t\t\t}).forEach(function(key) {\n\t\t\t\tmap_of_keys[key] = true;\n\t\t\t});\n\t\t});\n\t\n\t\tvar keys = Object.keys(map_of_keys);\n\t\tkeys.sort();\n\n\t\treturn ['=== ' + title + ' ==='].concat(\n\t\t\t[keys.join(' | ')]\n\t\t).concat( \n\t\t\t[keys.map(function(k) {\n\t\t\t\treturn '----';\n\t\t\t}).join(' | ')]\n\t\t).concat(\n\t\t\tarr.map(function(obj) {\n\t\t\t\treturn keys.map(function(key) {\n\t\t\t\t\treturn util.inspect( obj[key] ).replace(/\\n/g, \" \");\n\t\t\t\t}).join(' | ');\n\t\t\t})\n\t\t).join('\\n');\n\t}", "function stringify(arr) {\n\tarr.forEach(function(number){\n\t\toutputStr += number + '\\n'\n\t});\n}", "function extract(msg_desc,msg_title,msg_url){\n var desc = [];\n var title = [];\n var url = [];\n desc = msg_desc;\n title = msg_title;\n url = msg_url;\n var tags = \"\";\n for(var x = 0; x < desc.length; x ++){\n tags += \"<h3>'\"+title[x]+\"'</h3><h4>'\"+desc[x]+\"'</h4><a href='\"+url[x]+\"'>Link</a><br>\"\n }\n return tags;\n }", "function getArtists(artistsArray) {\n var result = '';\n // if there are more than one elements\n if (artistsArray && artistsArray[1]) {\n var artists = _.pluck(artistsArray, 'name');\n result = artists.join(', ');\n } else if (artistsArray && artistsArray[0]) {\n result = artistsArray[0].name;\n } else {\n result = '';\n }\n return result;\n }", "toListString(arr) {\n\t\tif (!arr.length) return '';\n\t\tif (arr.length === 1) return arr[0];\n\t\tif (arr.length === 2) return `${arr[0]} and ${arr[1]}`;\n\t\treturn `${arr.slice(0, -1).join(\", \")}, and ${arr.slice(-1)[0]}`;\n\t}", "function showArrayH(showItems, stopRequest){\n\tlet len = showItems.length;\n\tlet stop = (showItems.length < stopRequest)? showItems.length - 1 : stopRequest - 1;\n\tlet i = 0, showString='';\n\twhile(i++ < stop){\n\t\tshowString += '| ' + String(showItems[i]);\n\t}\n\treturn showString;\n}", "function emotesArraytoHTML(emotes){\n\tret_str = \"\"\n\tvar i;\n\tfor(i = 0; i < emotes.length; i++){\n\t\tif(emotes[i][0] != 'null'){\n\t\t\tif(LITE){\n\t\t\t\tret_str += '<p><b>\"' + emotes[i][1] + '</b>\": ' + emotes[i][2] + '</p>';\n\t\t\t}\n\t\t\telse{\n\t\t\t\tret_str += '<p><img src=\"' + IDtoImage(emotes[i][0]) + '\">: ' + emotes[i][2] + '</p>';\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn ret_str;\n}", "function makeListItems() {\n const jokes = jokeFacade.getJokes();\n let jokeList = jokes.map(joke => `<li> ${joke} </li>`);\n const listItemsAsStr = jokeList.join(\"\");\n document.getElementById(\"jokes\").innerHTML = listItemsAsStr;\n}", "function extractRecipeNameToString(groceryItems) {\n //console.log(\"Grocery Items Param: \",groceryItems)\n let textString = \"\";\n for (let i = 0; i < groceryItems.length; i++) {\n textString += `${groceryItems[i].originalString}, \\n`;\n }\n return textString;\n }", "function arrayToString(arr) {\n return arr.join(\"\")\n }", "function populateFavorites(arr) {\n favoritesList.innerHTML = \"\";\n for (let i = 0; i < arr.length; i++) {\n var item = arr[i].recipeName;\n var li = document.createElement(\"li\");\n li.innerText = item;\n favoritesList.append(li);\n }\n}", "function showArrays(arr){\n arr.forEach(eachItem => { // use += to replace the first one, and add items\n document.body.innerHTML += `<li> ${eachItem.name} </li>`\n });\n // arr.forEach(function(eachItem){\n // document.body.innerHTML += `<li> ${eachItem.name} </li>`\n // })\n }", "function reprCardArray(array: Array<Card>) {\n var cards = [];\n for(var i=0;i<array.length;i++) cards.push(array[i].reprString());\n return \"[\" + cards.join(', ') + \"]\";\n}", "function orderAlphabetically(array){\n const arrayOfTitles = array.map(element => element.title)\n const sortedArrayOfTitles = arrayOfTitles.sort()\n if(arrayOfTitles.length < 20){\n return sortedArrayOfTitles\n }\n else{\n return sortedArrayOfTitles.slice(0,20)\n }\n}", "function orderAlphabetically(array) {\n const titleArray = array.map(movie => movie.title).sort((a, b) => a.localeCompare(b));\n return titleArray.slice(0, 20);\n}", "function createListItems(arr){\n let items = '';\n\nfor(let i =0; i<arr.length; i++){\n items += `<li>${arr[i]}</li>`;\n}\nreturn items;\n}", "function orderAlphabetically(array){\nlet newArray = array.map(function(order){\n return order.title\n});\nlet title = newArray.sort();\nreturn title.slice(0,20);\n}", "function setOutString(itemList) {\r\n return setArray2Str(itemList)\r\n}", "function names(array) {\n if (array === undefined) {\n return NAMES.slice();\n } else if (!Array.isArray(array)) {\n return [];\n } else {\n return onlyNotes(array).map(toName);\n }\n}", "function outputSeriesTitel( seriesArray, chooser ) {\n urlSeries = \"https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&ids=\" + seriesArray[0];\n for( var i = 1; i < seriesArray.length; i++) {\n urlSeries = urlSeries + \"|\" + seriesArray[i];\n }\n $.ajax({\n url: urlSeries,\n dataType: 'jsonp',\n success: function( results ){\n for( var i = 0; i < seriesArray.length; i++) {\n var labelSeries = results['entities'][seriesArray[i]]['labels']['en']['value'];\n chooser.options[i] = new Option( labelSeries, seriesArray[i] );\n }\n }\n })\n\n}", "function showArray(elements, customText = \"\"){ \n document.write(\"<h1>Content of array \"+customText+\"</hl>\"); \n document.write(\"<ul>\"); \n elements.forEach((element, index) => { \n document.write(\"<li>\"+element+\"</li><br/>\"); \n }); \n document.write(\"</ul>\"); \n}", "function convertToArrayOfStrings(object) {\n suggestions.push(object.category);\n suggestions.push(object.subject);\n }", "function constructQueryListFrom(goodTitles) {\n const result = [];\n for (let i = 0, n = goodTitles.length; i < n; i++) {\n result.push(goodTitles[i].article);\n }\n return result;\n}", "function orderAlphabetically(arr) {\n const newOrderByTitle = arr.map(function toto(element) {\n return element.title;\n });\n\n newOrderByTitle.sort(function tata(a, b) {\n if (a.toLowerCase() < b.toLowerCase()) return -1;\n if (a.toLowerCase() > b.toLowerCase()) return 1;\n return 0;\n });\n const printTitle = newOrderByTitle.reduce(function tata(\n counter,\n currentValue,\n i\n ) {\n if (i < 20) {\n counter.push(currentValue);\n return counter;\n }\n return counter;\n },\n []);\n return printTitle;\n}", "function speachifyResponse(data){\n var events = data._embedded.events;\n var dyn_text = [];\n \n events.forEach(function(item) {\n var name = getEventName(item.id);\n if(!name) {\n name = item.description;\n }\n var date_str = dateToString(new Date(item.datetime), item.duration);\n \n dyn_text.push(name + \" on \" + date_str); \n });\n\n return dyn_text.join(\" , and, a \");\n}", "function customPrintNames(array) {\n\tvar stringtoPrint = \" \";\n\tfor(var i = 0; i < array.length; i++) {\n\t\tstringtoPrint = stringtoPrint + array[i].get(\"name\") + \" \";\n\t}\n\t//log(\"Final object order\" + stringtoPrint);\n}", "function orderAlphabetically (array){\n\n var titulosPeliculas = array.map(function(element){\n \n return element.title;\n });\n\n return titulosPeliculas.sort().slice(0,20);\n}", "handAsStrings() {\n const result = new Array();\n for (const i of this.hand) {\n result.push(i.toString());\n }\n return result;\n }", "function arrToString(arr) {\n pantryString = \"\";\n for (let i = 0; i < arr.length; i++) {\n if (i < arr.length - 1) {\n pantryString += arr[i] + \", \";\n } else if (i === arr.length - 1) {\n pantryString += arr[i];\n }\n }\n return pantryString;\n}", "function populateRecentDrink(arr) {\n savedDrinks.innerHTML = \"<h3>Drinks</h3>\";\n for (let i = 0; i < arr.length; i++) {\n var item = arr[i];\n var li = document.createElement(\"li\");\n li.innerText = item;\n savedDrinks.append(li);\n }\n}", "handleAuthors(arr) {\n\t\tif (typeof arr === 'undefined') {\n\t\treturn 'Unknown';\n\t\t}\n\t\treturn arr.join(', ');\n\t}", "function buildHTMLlist(array) {\n var html = `<div id=\"contents\">\n <h1>List of contents</h1>\n <ul class=\"contents-list\">`\n array.forEach(function(item) {\n item = item.toJSON();\n html += `<li class=\"content-item\">\n <h2 class=\"content-item__title\">\n <p>${item.voteScore ? item.voteScore : 0}</p>\n <a href=${item.url}>${item.title}</a>\n </h2>\n <p> ${item.user.username}</p>\n <form action=\"/voteContent\" method=\"post\">\n <input type=\"hidden\" name=\"upVote\" value=\"true\">\n <input type=\"hidden\" name=\"contentId\" value=\"${item.id}\">\n <button type=\"submit\">Upvote this!</button>\n </form>\n <form action=\"/voteContent\" method=\"post\">\n <input type=\"hidden\" name=\"upVote\" value=\"false\">\n <input type=\"hidden\" name=\"contentId\" value=\"${item.id}\">\n <button type=\"submit\">Downvote this!</button>\n </form>\n </li>`\n })\n html += `</ul> \n </div>`\n return html;\n}", "function toString(array) {\n var string = '';\n for (i = 0 ; i<array.length ; i++) {\n string = string + array[i] + ' ';\n }\n return string;\n}", "function JsontoHTMLSort(array) {\n $(\"ul.items\").empty()\n all_html = []\n for (let j = 0; j < array.length; j++) {\n for (let i = 0; i < databaseObj.length; i++) {\n c = databaseObj[i];\n if (c[\"title\"] === array[j]) {\n let keywrd = (JSON.parse(c[\"keywords\"]))\n kwrds = []\n for (let k = 0; k < keywrd.length; k++) {\n kwrds.push(keywrd[k][\"name\"])\n }\n let movieObj = new MovieInfo(c[\"budget\"], c[\"genres\"], c[\"homepage\"], c[\"runtime\"], c[\"vote_average\"],\n kwrds, c[\"title\"], c[\"id\"], c[\"image_url\"], c[\"image_url1\"], c[\"image_url2\"],\n c[\"overview\"])\n all_html.push(movieObj)\n }\n }\n }\n }", "function addTitles() {\n for (var t in titles) {\n var e = document.getElementById(t);\n e.setAttribute('title', titles[t]);\n }\n}", "function readyToPutInTheDOM(arr){\r\n return arr.map(name => \"<h1>\" + name.name + \"</h1><h2>\" + name.age + \"</h2>\")\r\n }", "function stringifySoldOutArray(soldOutArray) {\n var soldOutString = \"[\";\n\n for(var i=0; i<soldOutArray.length; i++) {\n soldOutString += \"[\";\n if(Array.isArray(soldOutArray[i])) {\n for(var j=0; j<soldOutArray[i].length; j++) {\n if(Array.isArray(soldOutArray[i][j])) {\n soldOutString += \"[\";\n for(var k=0; k<soldOutArray[i][j].length; k++) {\n\t\t\t\t\t\tsoldOutString += soldOutArray[i][j][k] + \",\";\n }\n soldOutString = soldOutString.slice(0,-1) + \"],\";\n } else {\n\t\t\t\t\tsoldOutString += soldOutArray[i][j] + \",\";\n }\n }\n }\n soldOutString = soldOutString.slice(0,-1) + \"], \";\n }\n soldOutString = soldOutString.slice(0,-2) + \"]\";\n\n return soldOutString;\n}", "function getKeywordOverview(arr) {\n if (arr.length > 2) {\n arr = arr.slice(0, 3);\n } else {\n return \"Not Enough Keywords\";\n }\n var str = arr[0];\n for (var i = 1; i < arr.length; i++) { str += \", \" + arr[i]}\n return str;\n}", "function orderAlphabetically(arr){\n let newArr = JSON.parse(JSON.stringify(arr));\n newArr.sort((a,b) => {\n if(a.title < b.title) return -1;\n });\n newArr = newArr.slice(0,20).map(e=>{\n return e.title;\n });\n return newArr;\n}", "function orderAlphabetically(array) {\n let arrayTitle = array.map(movie => movie.title);\n\n return arrayTitle.sort().slice(0,20);\n\n\n}", "function listToString(list,space){\r\n if(space === undefined){space = ' '}\r\n var out = '';\r\n list.map(function(s){out = out + s.toString()+space});\r\n out = out.slice(0,out.length-space.length);\r\n return out;\r\n}", "function emotesArraytoString(emotes){\n\tret_str = \"\"\n\tvar i;\n\tfor(i = 0; i < emotes.length; i++){\n\t\tif(emotes[i][0] != 'null'){\n\t\t\tret_str += emotes[i][1] + ': ' + emotes[i][2] + '; ';\n\t\t}\n\t}\n\t\n\treturn ret_str;\n}", "function displayItems(items) {\r\n const container=document.querySelector('.items');\r\n container.innerHTML=items.map(item=>createHTMLString(item)).join('');\r\n}", "function buildList (searchResults) {\n let format = {\n 'response_type': \"ephemeral\",\n 'as_user': true,\n 'text': '*Here are your results*',\n 'unfurl_links': true,\n 'mrkdwn': true,\n 'attachments': [{\n 'text': ':small_orange_diamond: ' + searchResults.join('\\n:small_orange_diamond: '),\n 'footer': 'The Morning Bunch :green_heart:',\n 'color': '#439FE0'\n }]\n }\nreturn format;\n}", "function stringifyArray(input){\n return input.join(',');\n}", "function orderAlphabetically(myArray) {\n\tconst titleArray = []\n\tfor (const movie of myArray) {\n\t\ttitleArray.push(movie.title.toLowerCase());\n\t}\n\ttitleArray.sort()\n\treturn titleArray.slice(0,20)\n}", "function formatNameList(names) {\n var str = \"\";\n names.forEach(function (name) {\n str = str + (name.name + \": \" + name.value + \" \\n\");\n });\n return str.trim();\n}", "function getTasksAsArray() {\n let liArray = document.querySelectorAll(\"li\");\n let newArray = [];\n\n for (let i = 0; i < liArray.length; i++) {\n newArray.push(liArray[i].innerText);\n }\n newArray = newArray.join(\" \");\n console.log(newArray);\n}", "function playerArrayToString(playerArray) {\n return playerArray.map(capitalize).join(', ');\n}", "function exercise(arr){\n\treturn arr.map(element => `https://example.com/${urlify(element)}`);\n}", "function courseTeachers(teachersArray){\n var nbrTeachers=teachersArray.length;\n var texte=\"\";\n for (var i=0;i<nbrTeachers;i++){\n texte+=teachersArray[i][\"teacher_name\"];\n if (i!==nbrTeachers-1){\n texte+=\", \"\n }\n }\n return texte;\n }", "function orderAlphabetically(array) {\n const orderedByTitle = [...array].sort((a, b) => a.title < b.title ? -1 : 1);\n let onlyTitle = orderedByTitle.slice(0, 20).map(function (a) {\n return a.title\n })\n return onlyTitle\n\n}", "function arrayToString(a) {\n return \"[\" + a.join(\", \") + \"]\";\n}", "function writeCards(arrayOfNames, eventName) {\n let returnArray = []\n for (let i = 0; i < arrayOfNames.length; i++) {\n returnArray.push(`Thank you, ${arrayOfNames[i]}, for the wonderful ${eventName} gift!`); \n }\n return returnArray; \n}", "function arrWithNoBrsAndSpacesToString(array) {\n\tlet arrSpaces = array.map((item) => {\n\t\treturn item.join(' ')\n\t})\n\tconsole.log(arrSpaces)\n\t// console.log(arrSpaces)\n\tlet strBrsSpaces = arrSpaces.join('<br>')\n\treturn strBrsSpaces\n}", "function arrayToString(obj) {\n\tvar s = '[';\n\tvar first = true;\n\t$.each(obj, function(i, val) {\n\t\tif (!first) {\n\t\t\ts += ',';\n\t\t}\n\t\tfirst = false;\n\t\ts += valueToString(val);\n\t});\n\ts += ']';\n\treturn s;\n}", "function List2TSV(LST){\n\t\tvar out=\"\";\n\t\tfor (var i in LST){\n\t\t\tvar LSTI=LST[i].join(\"\t\");\n\t\t\tout+=LSTI+'\\n';\n\t\t}\n\t\treturn out;\n\t}", "function turnNodeArrayIntoStringArray(arrayNodes){\n var stringArray=[];\n arrayNodes.forEach(function(element){\n var elementArray = [];\n element.each(function(index, title){\n elementArray.push(title.innerHTML);\n });\n stringArray.push(elementArray);\n });\n return stringArray;\n}", "function list(names){\n var output = \"\";\n for (var i = 0; i < names.length; i ++){ \n if (i < (names.length - 2)){\n output = output + names[i][\"name\"] + \", \"; \n } else if (i == names.length - 2){\n output = output + names[i][\"name\"] + \" & \"; \n } else {\n output = output + names[i][\"name\"] ; \n }\n }\n return output;\n}", "function orderAlphabetically(arr) {\n let moviesCopy = [];\n let sortedTitles = [];\n for (let movie of arr) {moviesCopy.push(movie.title);}\n moviesCopy.sort();\n if (moviesCopy.length < 20) {\n for (let j = 0; j < moviesCopy.length; j++) {sortedTitles.push(moviesCopy[j]);}\n } else for (let i = 0; i < 20; i++) {sortedTitles.push(moviesCopy[i]);}\n return sortedTitles;\n}", "_getShareKeywordsList() {\n const oThis = this,\n channelId = oThis.apiResponseData['meeting'].channel_id,\n channelDetails = oThis.apiResponseData['channel_details'][channelId],\n tagIds = channelDetails['tag_ids'],\n tagDetails = oThis.apiResponseData['tags'],\n tagNameList = ['Pepo', 'Pepo Live'];\n\n for(let i=0;i<tagIds.length;i++) {\n tagNameList.push(tagDetails[tagIds[i]].text);\n }\n\n return tagNameList.join(',')\n }" ]
[ "0.5963072", "0.59265506", "0.5860149", "0.5830318", "0.5664834", "0.5647244", "0.5615575", "0.55590373", "0.5557116", "0.55049396", "0.5464863", "0.54521245", "0.5445746", "0.5445021", "0.5444259", "0.5418803", "0.54169464", "0.54118204", "0.54090154", "0.53917605", "0.5390888", "0.53849727", "0.5368334", "0.5362587", "0.5349002", "0.533962", "0.5335353", "0.5325274", "0.5321623", "0.53210074", "0.5320127", "0.5298803", "0.52966946", "0.529586", "0.52900803", "0.5278143", "0.5278061", "0.52765197", "0.52757716", "0.52754766", "0.5272093", "0.5260126", "0.52583826", "0.52581114", "0.5252633", "0.5242613", "0.52374184", "0.5233411", "0.5231929", "0.52275974", "0.5212451", "0.52063173", "0.52013266", "0.51997006", "0.519674", "0.5190778", "0.51878476", "0.5173218", "0.5167199", "0.51621246", "0.5158779", "0.5158437", "0.51527286", "0.515125", "0.51461834", "0.51424754", "0.5133758", "0.51264685", "0.51246744", "0.5114522", "0.5100577", "0.5097668", "0.50893384", "0.5086626", "0.50852835", "0.50803363", "0.50801885", "0.5074719", "0.5067426", "0.5062776", "0.50617015", "0.50609356", "0.5057296", "0.5057132", "0.50559753", "0.50551754", "0.5054638", "0.50537646", "0.5051331", "0.5043633", "0.50432765", "0.50360805", "0.503299", "0.5024336", "0.502005", "0.5016495", "0.501155", "0.5006182", "0.50056636", "0.5005579" ]
0.5767215
4
Convert "&amp;" to &, "&nbsp;" to nbsp, "&lt;" to and "&quot;" to "
function htmlDecode(s) { return s.toString().replace(/&lt;/mg,"<").replace(/&nbsp;/mg,"\xA0").replace(/&gt;/mg,">").replace(/&quot;/mg,"\"").replace(/&amp;/mg,"&"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function handleHtmlEntities(data){\n\t\t\tdata = data.replace(/&/g, '&amp;')\n\t\t\t.replace(/\"/g, '&quot;')\n\t\t\t.replace(/'/g, '&#39;')\n\t\t\t.replace(/</g, '&lt;')\n\t\t\t.replace(/>/g, '&gt;');\n\t\t\tdata = data.replace(/ /g, '&nbsp;');\n\t\t\treturn data;\n\t\t}", "function encodeHtml(str) {\n str = str.replace(/&/g, '&amp;');\n str = str.replace(/</g, '&lt;');\n str = str.replace(/>/g, '&gt;');\n str = str.replace(/ /g, '&nbsp;');\n return str;\n}", "function convertHTML(str) {\n var temp = str.split(\"\");\n for(var i =0; i < temp.length; i++){\n switch(temp[i]){\n case \"<\":\n temp[i] = \"&lt;\";\n break;\n case \"&\":\n temp[i] = '&amp;'; \n break;\n case \">\":\n temp[i] = \"&gt;\";\n break;\n case '\"':\n temp[i] = \"&quot;\";\n break;\n case \"'\":\n temp[i] = \"&apos;\";\n break;\n }\n }\n temp = temp.join('');\n return temp;\n }", "function html_unesc_amp_only($s) {\n return str_ireplace('&amp;','&',$s);\n}", "function textToHtml(str) {\n return str.replace(pr_amp, '&amp;')\n .replace(pr_lt, '&lt;')\n .replace(pr_gt, '&gt;');\n }", "function textToHtml(str) {\n return str.replace(pr_amp, '&amp;')\n .replace(pr_lt, '&lt;')\n .replace(pr_gt, '&gt;');\n }", "function convertTextToHTML(s) {\n\t\ts = s.replace(/\\&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\\n/g, \"<BR>\");\n\t\twhile (/\\s\\s/.test(s))\n\t\t\ts = s.replace(/\\s\\s/, \"&nbsp; \");\n\t\treturn s.replace(/\\s/g, \" \");\n\t}", "function htmlescape(str) {\n str = str.replace(\"&\",\"&amp;\");\n str = str.replace(\"<\",\"&lt;\");\n str = str.replace(\">\",\"&gt;\");\n return str;\n \n}", "function convertHTML(str) {\n //split string into character array\n var placeHolder = str.split(\"\");\n //itterate through character array\n for(var i=0; i<placeHolder.length; i++) {\n //check current value of character\n switch(placeHolder[i]) {\n //if case is met, replace with html entity\n case '&':\n placeHolder[i]='&amp;';\n break;\n case '<':\n placeHolder[i]='&lt;';\n break;\n case '>':\n placeHolder[i]='&gt;';\n break;\n case '\"':\n placeHolder[i]='&quot;';\n break;\n case \"'\":\n placeHolder[i]='&apos;';\n break;\n }\n }\n //join character array back into string\n str = placeHolder.join(\"\");\n return str;\n}", "function htmlSpecialChars(str, quote_style)\r\n{\r\n\tstr = str.replace(/&/ig,\"&amp;\");\r\n\tif(!quote_style || quote_style==1)\r\n\t{\r\n\t\tstr = str.replace(/\\\"/ig,\"&quot;\")\r\n\t\tif(quote_style==1)\r\n\t\t\tstr = str.replace(/\\'/ig,\"&#039;\")\r\n\t}\r\n\tstr = str.replace(/\\>/ig,\"&gt;\");\r\n\tstr = str.replace(/\\</ig,\"&lt;\");\r\n\treturn str;\r\n}", "function chgEntities(passedStr)\n{\nvar myStr = repStrs(passedStr,'%22','&quot;') \n myStr = repStrs(myStr,'%26','&amp;') \n myStr = repStrs(myStr,'%3C','&gt;') \n myStr = repStrs(myStr,'%2E','&lt;') \n// myStr = repStrs(myStr,'%27',\"\\\\'\")\n\n\treturn unescape(myStr)\n}", "function convertHTML(str) {\n // &colon;&rpar;\n str = str.replace(/&/g,\"&amp;\");\n str = str.replace(/</g, \"&lt;\");\n str = str.replace(/>/g, \"&gt;\");\n str = str.replace(/\"/g, \"&quot;\");\n str = str.replace(/'/g, \"&apos;\");\n return str;\n}", "function htmlEncode(text){\n return (\n text.replace(/&/g,'&amp;')\n .replace(/</g,'&lt;')\n .replace(/</g,'&lt;')\n .replace(/ /g,'&nbsp;')\n .replace(/([^<>&]{10})/g,'$1<wbr>&shy;' + wbr)\n );\n }", "function escapeHTML(txt)\n{\n return txt.replace(/&/g, '&#0038;')\n .replace(/\"/g, '&#0034;')\n .replace(/'/g, '&#0039;')\n .replace(/</g, '&#0060;')\n .replace(/>/g, '&#0062;');\n}", "function convertHTML(str) {\n return str.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/'/g, '&apos;').replace(/\"/g, '&quot;');\n\n}", "function encodeHTML(text) {\n\t return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\n\t }", "function replaceSpecialChars(textToChange){\n newText = textToChange.replace('&amp;','&').replace('&gt;','>').replace('&lt;','<');\n return newText;\n}", "function HTMLEnCode(str) {\n var s = \"\";\n if (str.length == 0) return \"\";\n s = str.replace(/&/g, \"&gt;\");\n s = s.replace(/</g, \"&lt;\");\n s = s.replace(/>/g, \"&gt;\");\n s = s.replace(/ /g, \"&nbsp;\");\n s = s.replace(/\\'/g, \"&#39;\");\n s = s.replace(/\\\"/g, \"&quot;\");\n s = s.replace(/\\n/g, \"<br>\");\n return s;\n}", "function encodeText(txt) {\n\treturn txt.replace(/\\&/g, '&amp;').replace(/\\</g, '&lt;').replace(/\\>/g, '&gt;').replace(/\\\"/g, '&quot;').replace(/\\'/g, '&apos;');\n}", "function htmlToText(html) {\n var pos = html.indexOf('&');\n if (pos < 0) { return html; }\n // Handle numeric entities specially. We can't use functional substitution\n // since that doesn't work in older versions of Safari.\n // These should be rare since most browsers convert them to normal chars.\n for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {\n var end = html.indexOf(';', pos);\n if (end >= 0) {\n var num = html.substring(pos + 3, end);\n var radix = 10;\n if (num && num.charAt(0) === 'x') {\n num = num.substring(1);\n radix = 16;\n }\n var codePoint = parseInt(num, radix);\n if (!isNaN(codePoint)) {\n html = (html.substring(0, pos) + String.fromCharCode(codePoint) +\n html.substring(end + 1));\n }\n }\n }\n\n return html.replace(pr_ltEnt, '<')\n .replace(pr_gtEnt, '>')\n .replace(pr_aposEnt, \"'\")\n .replace(pr_quotEnt, '\"')\n .replace(pr_nbspEnt, ' ')\n .replace(pr_ampEnt, '&');\n }", "function htmlToText(html) {\n var pos = html.indexOf('&');\n if (pos < 0) { return html; }\n // Handle numeric entities specially. We can't use functional substitution\n // since that doesn't work in older versions of Safari.\n // These should be rare since most browsers convert them to normal chars.\n for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {\n var end = html.indexOf(';', pos);\n if (end >= 0) {\n var num = html.substring(pos + 3, end);\n var radix = 10;\n if (num && num.charAt(0) === 'x') {\n num = num.substring(1);\n radix = 16;\n }\n var codePoint = parseInt(num, radix);\n if (!isNaN(codePoint)) {\n html = (html.substring(0, pos) + String.fromCharCode(codePoint) +\n html.substring(end + 1));\n }\n }\n }\n\n return html.replace(pr_ltEnt, '<')\n .replace(pr_gtEnt, '>')\n .replace(pr_aposEnt, \"'\")\n .replace(pr_quotEnt, '\"')\n .replace(pr_nbspEnt, ' ')\n .replace(pr_ampEnt, '&');\n }", "function convertHTML(str) {\n // &colon;&rpar;\n return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&apos;');\n}", "function escapeHTML(text) {\n return text.replace(/\\&/g, '&amp;').replace(/\\</g, '&lt;').replace(/\\>/g, '&gt;');\n }", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlspecialchars(text) {\r\n return text\r\n .replace(/&/g, \"&amp;\")\r\n .replace(/</g, \"&lt;\")\r\n .replace(/>/g, \"&gt;\")\r\n .replace(/\"/g, \"&quot;\")\r\n .replace(/'/g, \"&#039;\");\r\n}", "function escapeHTML(text) {\n return text.replace(/\\&/g,'&amp;').replace(/\\</g,'&lt;').replace(/\\>/g,'&gt;');\n }", "function convertHTML(str) {\n str = str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n return str;\n}", "function replaceHTMLChars(value) {\n\treturn value.replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\\'').replace(/&quot;/gi,'\"');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function convertHTML (str) {\n return str.replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function convertHTML(str) {\n // &colon;&rpar;\n var emptyString = \"\";\n \n for (var i = 0; i < str.length; i++) { \n if (str[i] === \"&\") {\n emptyString += \"&amp;\";\n } else if (str[i] === \"<\") { \n emptyString += \"&lt;\";\n } else if (str[i] === \">\") { \n emptyString += \"&gt;\";\n } else if (str[i] === '\"') { \n emptyString += \"&quot;\";\n } else if (str[i] === \"'\") { \n emptyString += \"&apos;\";\n } else { \n emptyString += str[i];\n }\n }\n \n return emptyString;\n}", "function entityEncode(str){\n\t\t\t\t//entities copied from Wikipedia ( http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML )\n\t\t\t\treturn str\n\t\t\t\t\t\t\t.replace(/\\u0026([a-zA-Z]+;)?/g, function($0, $1){\n\t\t\t\t\t\t\t\treturn $1? $0 : \"&amp;\"; //make sure it only replace '&' if it isn't an HTML entity already\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.replace(/\\u0022/g, \"&quot;\")\n\t\t\t\t\t\t\t.replace(/\\u0027/g, \"&apos;\")\n\t\t\t\t\t\t\t.replace(/\\u003C/g, \"&lt;\")\n\t\t\t\t\t\t\t.replace(/\\u003E/g, \"&gt;\")\n\t\t\t\t\t\t\t.replace(/\\u00A0/g, \"&nbsp;\")\n\t\t\t\t\t\t\t.replace(/\\u00A1/g, \"&iexcl;\")\n\t\t\t\t\t\t\t.replace(/\\u00A2/g, \"&cent;\")\n\t\t\t\t\t\t\t.replace(/\\u00A3/g, \"&pound;\")\n\t\t\t\t\t\t\t.replace(/\\u00A4/g, \"&curren;\")\n\t\t\t\t\t\t\t.replace(/\\u00A5/g, \"&yen;\")\n\t\t\t\t\t\t\t.replace(/\\u00A6/g, \"&brvbar;\")\n\t\t\t\t\t\t\t.replace(/\\u00A7/g, \"&sect;\")\n\t\t\t\t\t\t\t.replace(/\\u00A8/g, \"&uml;\")\n\t\t\t\t\t\t\t.replace(/\\u00A9/g, \"&copy;\")\n\t\t\t\t\t\t\t.replace(/\\u00AA/g, \"&ordf;\")\n\t\t\t\t\t\t\t.replace(/\\u00AB/g, \"&laquo;\")\n\t\t\t\t\t\t\t.replace(/\\u00AC/g, \"&not;\")\n\t\t\t\t\t\t\t.replace(/\\u00AD/g, \"&shy;\")\n\t\t\t\t\t\t\t.replace(/\\u00AE/g, \"&reg;\")\n\t\t\t\t\t\t\t.replace(/\\u00AF/g, \"&macr;\")\n\t\t\t\t\t\t\t.replace(/\\u00B0/g, \"&deg;\")\n\t\t\t\t\t\t\t.replace(/\\u00B1/g, \"&plusmn;\")\n\t\t\t\t\t\t\t.replace(/\\u00B2/g, \"&sup2;\")\n\t\t\t\t\t\t\t.replace(/\\u00B3/g, \"&sup3;\")\n\t\t\t\t\t\t\t.replace(/\\u00B4/g, \"&acute;\")\n\t\t\t\t\t\t\t.replace(/\\u00B5/g, \"&micro;\")\n\t\t\t\t\t\t\t.replace(/\\u00B6/g, \"&para;\")\n\t\t\t\t\t\t\t.replace(/\\u00B7/g, \"&middot;\")\n\t\t\t\t\t\t\t.replace(/\\u00B8/g, \"&cedil;\")\n\t\t\t\t\t\t\t.replace(/\\u00B9/g, \"&sup1;\")\n\t\t\t\t\t\t\t.replace(/\\u00BA/g, \"&ordm;\")\n\t\t\t\t\t\t\t.replace(/\\u00BB/g, \"&raquo;\")\n\t\t\t\t\t\t\t.replace(/\\u00BC/g, \"&frac14;\")\n\t\t\t\t\t\t\t.replace(/\\u00BD/g, \"&frac12;\")\n\t\t\t\t\t\t\t.replace(/\\u00BE/g, \"&frac34;\")\n\t\t\t\t\t\t\t.replace(/\\u00BF/g, \"&iquest;\")\n\t\t\t\t\t\t\t.replace(/\\u00C0/g, \"&Agrave;\")\n\t\t\t\t\t\t\t.replace(/\\u00C1/g, \"&Aacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00C2/g, \"&Acirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00C3/g, \"&Atilde;\")\n\t\t\t\t\t\t\t.replace(/\\u00C4/g, \"&Auml;\")\n\t\t\t\t\t\t\t.replace(/\\u00C5/g, \"&Aring;\")\n\t\t\t\t\t\t\t.replace(/\\u00C6/g, \"&AElig;\")\n\t\t\t\t\t\t\t.replace(/\\u00C7/g, \"&Ccedil;\")\n\t\t\t\t\t\t\t.replace(/\\u00C8/g, \"&Egrave;\")\n\t\t\t\t\t\t\t.replace(/\\u00C9/g, \"&Eacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00CA/g, \"&Ecirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00CB/g, \"&Euml;\")\n\t\t\t\t\t\t\t.replace(/\\u00CC/g, \"&Igrave;\")\n\t\t\t\t\t\t\t.replace(/\\u00CD/g, \"&Iacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00CE/g, \"&Icirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00CF/g, \"&Iuml;\")\n\t\t\t\t\t\t\t.replace(/\\u00D0/g, \"&ETH;\")\n\t\t\t\t\t\t\t.replace(/\\u00D1/g, \"&Ntilde;\")\n\t\t\t\t\t\t\t.replace(/\\u00D2/g, \"&Ograve;\")\n\t\t\t\t\t\t\t.replace(/\\u00D3/g, \"&Oacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00D4/g, \"&Ocirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00D5/g, \"&Otilde;\")\n\t\t\t\t\t\t\t.replace(/\\u00D6/g, \"&Ouml;\")\n\t\t\t\t\t\t\t.replace(/\\u00D7/g, \"&times;\")\n\t\t\t\t\t\t\t.replace(/\\u00D8/g, \"&Oslash;\")\n\t\t\t\t\t\t\t.replace(/\\u00D9/g, \"&Ugrave;\")\n\t\t\t\t\t\t\t.replace(/\\u00DA/g, \"&Uacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00DB/g, \"&Ucirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00DC/g, \"&Uuml;\")\n\t\t\t\t\t\t\t.replace(/\\u00DD/g, \"&Yacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00DE/g, \"&THORN;\")\n\t\t\t\t\t\t\t.replace(/\\u00DF/g, \"&szlig;\")\n\t\t\t\t\t\t\t.replace(/\\u00E0/g, \"&agrave;\")\n\t\t\t\t\t\t\t.replace(/\\u00E1/g, \"&aacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00E2/g, \"&acirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00E3/g, \"&atilde;\")\n\t\t\t\t\t\t\t.replace(/\\u00E4/g, \"&auml;\")\n\t\t\t\t\t\t\t.replace(/\\u00E5/g, \"&aring;\")\n\t\t\t\t\t\t\t.replace(/\\u00E6/g, \"&aelig;\")\n\t\t\t\t\t\t\t.replace(/\\u00E7/g, \"&ccedil;\")\n\t\t\t\t\t\t\t.replace(/\\u00E8/g, \"&egrave;\")\n\t\t\t\t\t\t\t.replace(/\\u00E9/g, \"&eacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00EA/g, \"&ecirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00EB/g, \"&euml;\")\n\t\t\t\t\t\t\t.replace(/\\u00EC/g, \"&igrave;\")\n\t\t\t\t\t\t\t.replace(/\\u00ED/g, \"&iacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00EE/g, \"&icirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00EF/g, \"&iuml;\")\n\t\t\t\t\t\t\t.replace(/\\u00F0/g, \"&eth;\")\n\t\t\t\t\t\t\t.replace(/\\u00F1/g, \"&ntilde;\")\n\t\t\t\t\t\t\t.replace(/\\u00F2/g, \"&ograve;\")\n\t\t\t\t\t\t\t.replace(/\\u00F3/g, \"&oacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00F4/g, \"&ocirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00F5/g, \"&otilde;\")\n\t\t\t\t\t\t\t.replace(/\\u00F6/g, \"&ouml;\")\n\t\t\t\t\t\t\t.replace(/\\u00F7/g, \"&divide;\")\n\t\t\t\t\t\t\t.replace(/\\u00F8/g, \"&oslash;\")\n\t\t\t\t\t\t\t.replace(/\\u00F9/g, \"&ugrave;\")\n\t\t\t\t\t\t\t.replace(/\\u00FA/g, \"&uacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00FB/g, \"&ucirc;\")\n\t\t\t\t\t\t\t.replace(/\\u00FC/g, \"&uuml;\")\n\t\t\t\t\t\t\t.replace(/\\u00FD/g, \"&yacute;\")\n\t\t\t\t\t\t\t.replace(/\\u00FE/g, \"&thorn;\")\n\t\t\t\t\t\t\t.replace(/\\u00FF/g, \"&yuml;\")\n\t\t\t\t\t\t\t.replace(/\\u0152/g, \"&OElig;\")\n\t\t\t\t\t\t\t.replace(/\\u0153/g, \"&oelig;\")\n\t\t\t\t\t\t\t.replace(/\\u0160/g, \"&Scaron;\")\n\t\t\t\t\t\t\t.replace(/\\u0161/g, \"&scaron;\")\n\t\t\t\t\t\t\t.replace(/\\u0178/g, \"&Yuml;\")\n\t\t\t\t\t\t\t.replace(/\\u0192/g, \"&fnof;\")\n\t\t\t\t\t\t\t.replace(/\\u02C6/g, \"&circ;\")\n\t\t\t\t\t\t\t.replace(/\\u02DC/g, \"&tilde;\")\n\t\t\t\t\t\t\t.replace(/\\u0391/g, \"&Alpha;\")\n\t\t\t\t\t\t\t.replace(/\\u0392/g, \"&Beta;\")\n\t\t\t\t\t\t\t.replace(/\\u0393/g, \"&Gamma;\")\n\t\t\t\t\t\t\t.replace(/\\u0394/g, \"&Delta;\")\n\t\t\t\t\t\t\t.replace(/\\u0395/g, \"&Epsilon;\")\n\t\t\t\t\t\t\t.replace(/\\u0396/g, \"&Zeta;\")\n\t\t\t\t\t\t\t.replace(/\\u0397/g, \"&Eta;\")\n\t\t\t\t\t\t\t.replace(/\\u0398/g, \"&Theta;\")\n\t\t\t\t\t\t\t.replace(/\\u0399/g, \"&Iota;\")\n\t\t\t\t\t\t\t.replace(/\\u039A/g, \"&Kappa;\")\n\t\t\t\t\t\t\t.replace(/\\u039B/g, \"&Lambda;\")\n\t\t\t\t\t\t\t.replace(/\\u039C/g, \"&Mu;\")\n\t\t\t\t\t\t\t.replace(/\\u039D/g, \"&Nu;\")\n\t\t\t\t\t\t\t.replace(/\\u039E/g, \"&Xi;\")\n\t\t\t\t\t\t\t.replace(/\\u039F/g, \"&Omicron;\")\n\t\t\t\t\t\t\t.replace(/\\u03A0/g, \"&Pi;\")\n\t\t\t\t\t\t\t.replace(/\\u03A1/g, \"&Rho;\")\n\t\t\t\t\t\t\t.replace(/\\u03A3/g, \"&Sigma;\")\n\t\t\t\t\t\t\t.replace(/\\u03A4/g, \"&Tau;\")\n\t\t\t\t\t\t\t.replace(/\\u03A5/g, \"&Upsilon;\")\n\t\t\t\t\t\t\t.replace(/\\u03A6/g, \"&Phi;\")\n\t\t\t\t\t\t\t.replace(/\\u03A7/g, \"&Chi;\")\n\t\t\t\t\t\t\t.replace(/\\u03A8/g, \"&Psi;\")\n\t\t\t\t\t\t\t.replace(/\\u03A9/g, \"&Omega;\")\n\t\t\t\t\t\t\t.replace(/\\u03B1/g, \"&alpha;\")\n\t\t\t\t\t\t\t.replace(/\\u03B2/g, \"&beta;\")\n\t\t\t\t\t\t\t.replace(/\\u03B3/g, \"&gamma;\")\n\t\t\t\t\t\t\t.replace(/\\u03B4/g, \"&delta;\")\n\t\t\t\t\t\t\t.replace(/\\u03B5/g, \"&epsilon;\")\n\t\t\t\t\t\t\t.replace(/\\u03B6/g, \"&zeta;\")\n\t\t\t\t\t\t\t.replace(/\\u03B7/g, \"&eta;\")\n\t\t\t\t\t\t\t.replace(/\\u03B8/g, \"&theta;\")\n\t\t\t\t\t\t\t.replace(/\\u03B9/g, \"&iota;\")\n\t\t\t\t\t\t\t.replace(/\\u03BA/g, \"&kappa;\")\n\t\t\t\t\t\t\t.replace(/\\u03BB/g, \"&lambda;\")\n\t\t\t\t\t\t\t.replace(/\\u03BC/g, \"&mu;\")\n\t\t\t\t\t\t\t.replace(/\\u03BD/g, \"&nu;\")\n\t\t\t\t\t\t\t.replace(/\\u03BE/g, \"&xi;\")\n\t\t\t\t\t\t\t.replace(/\\u03BF/g, \"&omicron;\")\n\t\t\t\t\t\t\t.replace(/\\u03C0/g, \"&pi;\")\n\t\t\t\t\t\t\t.replace(/\\u03C1/g, \"&rho;\")\n\t\t\t\t\t\t\t.replace(/\\u03C2/g, \"&sigmaf;\")\n\t\t\t\t\t\t\t.replace(/\\u03C3/g, \"&sigma;\")\n\t\t\t\t\t\t\t.replace(/\\u03C4/g, \"&tau;\")\n\t\t\t\t\t\t\t.replace(/\\u03C5/g, \"&upsilon;\")\n\t\t\t\t\t\t\t.replace(/\\u03C6/g, \"&phi;\")\n\t\t\t\t\t\t\t.replace(/\\u03C7/g, \"&chi;\")\n\t\t\t\t\t\t\t.replace(/\\u03C8/g, \"&psi;\")\n\t\t\t\t\t\t\t.replace(/\\u03C9/g, \"&omega;\")\n\t\t\t\t\t\t\t.replace(/\\u03D1/g, \"&thetasym;\")\n\t\t\t\t\t\t\t.replace(/\\u03D2/g, \"&upsih;\")\n\t\t\t\t\t\t\t.replace(/\\u03D6/g, \"&piv;\")\n\t\t\t\t\t\t\t.replace(/\\u2002/g, \"&ensp;\")\n\t\t\t\t\t\t\t.replace(/\\u2003/g, \"&emsp;\")\n\t\t\t\t\t\t\t.replace(/\\u2009/g, \"&thinsp;\")\n\t\t\t\t\t\t\t.replace(/\\u200C/g, \"&zwnj;\")\n\t\t\t\t\t\t\t.replace(/\\u200D/g, \"&zwj;\")\n\t\t\t\t\t\t\t.replace(/\\u200E/g, \"&lrm;\")\n\t\t\t\t\t\t\t.replace(/\\u200F/g, \"&rlm;\")\n\t\t\t\t\t\t\t.replace(/\\u2013/g, \"&ndash;\")\n\t\t\t\t\t\t\t.replace(/\\u2014/g, \"&mdash;\")\n\t\t\t\t\t\t\t.replace(/\\u2018/g, \"&lsquo;\")\n\t\t\t\t\t\t\t.replace(/\\u2019/g, \"&rsquo;\")\n\t\t\t\t\t\t\t.replace(/\\u201A/g, \"&sbquo;\")\n\t\t\t\t\t\t\t.replace(/\\u201C/g, \"&ldquo;\")\n\t\t\t\t\t\t\t.replace(/\\u201D/g, \"&rdquo;\")\n\t\t\t\t\t\t\t.replace(/\\u201E/g, \"&bdquo;\")\n\t\t\t\t\t\t\t.replace(/\\u2020/g, \"&dagger;\")\n\t\t\t\t\t\t\t.replace(/\\u2021/g, \"&Dagger;\")\n\t\t\t\t\t\t\t.replace(/\\u2022/g, \"&bull;\")\n\t\t\t\t\t\t\t.replace(/\\u2026/g, \"&hellip;\")\n\t\t\t\t\t\t\t.replace(/\\u2030/g, \"&permil;\")\n\t\t\t\t\t\t\t.replace(/\\u2032/g, \"&prime;\")\n\t\t\t\t\t\t\t.replace(/\\u2033/g, \"&Prime;\")\n\t\t\t\t\t\t\t.replace(/\\u2039/g, \"&lsaquo;\")\n\t\t\t\t\t\t\t.replace(/\\u203A/g, \"&rsaquo;\")\n\t\t\t\t\t\t\t.replace(/\\u203E/g, \"&oline;\")\n\t\t\t\t\t\t\t.replace(/\\u2044/g, \"&frasl;\")\n\t\t\t\t\t\t\t.replace(/\\u20AC/g, \"&euro;\")\n\t\t\t\t\t\t\t.replace(/\\u2111/g, \"&image;\")\n\t\t\t\t\t\t\t.replace(/\\u2118/g, \"&weierp;\")\n\t\t\t\t\t\t\t.replace(/\\u211C/g, \"&real;\")\n\t\t\t\t\t\t\t.replace(/\\u2122/g, \"&trade;\")\n\t\t\t\t\t\t\t.replace(/\\u2135/g, \"&alefsym;\")\n\t\t\t\t\t\t\t.replace(/\\u2190/g, \"&larr;\")\n\t\t\t\t\t\t\t.replace(/\\u2191/g, \"&uarr;\")\n\t\t\t\t\t\t\t.replace(/\\u2192/g, \"&rarr;\")\n\t\t\t\t\t\t\t.replace(/\\u2193/g, \"&darr;\")\n\t\t\t\t\t\t\t.replace(/\\u2194/g, \"&harr;\")\n\t\t\t\t\t\t\t.replace(/\\u21B5/g, \"&crarr;\")\n\t\t\t\t\t\t\t.replace(/\\u21D0/g, \"&lArr;\")\n\t\t\t\t\t\t\t.replace(/\\u21D1/g, \"&uArr;\")\n\t\t\t\t\t\t\t.replace(/\\u21D2/g, \"&rArr;\")\n\t\t\t\t\t\t\t.replace(/\\u21D3/g, \"&dArr;\")\n\t\t\t\t\t\t\t.replace(/\\u21D4/g, \"&hArr;\")\n\t\t\t\t\t\t\t.replace(/\\u2200/g, \"&forall;\")\n\t\t\t\t\t\t\t.replace(/\\u2202/g, \"&part;\")\n\t\t\t\t\t\t\t.replace(/\\u2203/g, \"&exist;\")\n\t\t\t\t\t\t\t.replace(/\\u2205/g, \"&empty;\")\n\t\t\t\t\t\t\t.replace(/\\u2207/g, \"&nabla;\")\n\t\t\t\t\t\t\t.replace(/\\u2208/g, \"&isin;\")\n\t\t\t\t\t\t\t.replace(/\\u2209/g, \"&notin;\")\n\t\t\t\t\t\t\t.replace(/\\u220B/g, \"&ni;\")\n\t\t\t\t\t\t\t.replace(/\\u220F/g, \"&prod;\")\n\t\t\t\t\t\t\t.replace(/\\u2211/g, \"&sum;\")\n\t\t\t\t\t\t\t.replace(/\\u2212/g, \"&minus;\")\n\t\t\t\t\t\t\t.replace(/\\u2217/g, \"&lowast;\")\n\t\t\t\t\t\t\t.replace(/\\u221A/g, \"&radic;\")\n\t\t\t\t\t\t\t.replace(/\\u221D/g, \"&prop;\")\n\t\t\t\t\t\t\t.replace(/\\u221E/g, \"&infin;\")\n\t\t\t\t\t\t\t.replace(/\\u2220/g, \"&ang;\")\n\t\t\t\t\t\t\t.replace(/\\u2227/g, \"&and;\")\n\t\t\t\t\t\t\t.replace(/\\u2228/g, \"&or;\")\n\t\t\t\t\t\t\t.replace(/\\u2229/g, \"&cap;\")\n\t\t\t\t\t\t\t.replace(/\\u222A/g, \"&cup;\")\n\t\t\t\t\t\t\t.replace(/\\u222B/g, \"&int;\")\n\t\t\t\t\t\t\t.replace(/\\u2234/g, \"&there4;\")\n\t\t\t\t\t\t\t.replace(/\\u223C/g, \"&sim;\")\n\t\t\t\t\t\t\t.replace(/\\u2245/g, \"&cong;\")\n\t\t\t\t\t\t\t.replace(/\\u2248/g, \"&asymp;\")\n\t\t\t\t\t\t\t.replace(/\\u2260/g, \"&ne;\")\n\t\t\t\t\t\t\t.replace(/\\u2261/g, \"&equiv;\")\n\t\t\t\t\t\t\t.replace(/\\u2264/g, \"&le;\")\n\t\t\t\t\t\t\t.replace(/\\u2265/g, \"&ge;\")\n\t\t\t\t\t\t\t.replace(/\\u2282/g, \"&sub;\")\n\t\t\t\t\t\t\t.replace(/\\u2283/g, \"&sup;\")\n\t\t\t\t\t\t\t.replace(/\\u2284/g, \"&nsub;\")\n\t\t\t\t\t\t\t.replace(/\\u2286/g, \"&sube;\")\n\t\t\t\t\t\t\t.replace(/\\u2287/g, \"&supe;\")\n\t\t\t\t\t\t\t.replace(/\\u2295/g, \"&oplus;\")\n\t\t\t\t\t\t\t.replace(/\\u2297/g, \"&otimes;\")\n\t\t\t\t\t\t\t.replace(/\\u22A5/g, \"&perp;\")\n\t\t\t\t\t\t\t.replace(/\\u22C5/g, \"&sdot;\")\n\t\t\t\t\t\t\t.replace(/\\u2308/g, \"&lceil;\")\n\t\t\t\t\t\t\t.replace(/\\u2309/g, \"&rceil;\")\n\t\t\t\t\t\t\t.replace(/\\u230A/g, \"&lfloor;\")\n\t\t\t\t\t\t\t.replace(/\\u230B/g, \"&rfloor;\")\n\t\t\t\t\t\t\t.replace(/\\u2329/g, \"&lang;\")\n\t\t\t\t\t\t\t.replace(/\\u232A/g, \"&rang;\")\n\t\t\t\t\t\t\t.replace(/\\u25CA/g, \"&loz;\")\n\t\t\t\t\t\t\t.replace(/\\u2660/g, \"&spades;\")\n\t\t\t\t\t\t\t.replace(/\\u2663/g, \"&clubs;\")\n\t\t\t\t\t\t\t.replace(/\\u2665/g, \"&hearts;\")\n\t\t\t\t\t\t\t.replace(/\\u2666/g, \"&diams;\");\n\t\t\t}", "function escapeHtml(str){\n str = str.replace(/&/g, '&amp;');\n str = str.replace(/>/g, '&gt;');\n str = str.replace(/</g, '&lt;');\n str = str.replace(/\"/g, '&quot;');\n str = str.replace(/'/g, '&#x27;');\n str = str.replace(/`/g, '&#x60;');\n return str;\n}", "function htmlEntities(str) {\n return String(str)\n .replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str)\n .replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str)\n .replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str)\n .replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;')\n \t.replace(/>/g, '&gt;').replace(/\"/g, '').replace(/\\'/g, '')\n \t.replace(/\\[/g, '&#91;').replace(/\\]/g, '&#93;').replace(/\\{/g, '&#123;')\n \t.replace(/\\}/g, '&#124;').replace(/\\(/g, '&#40;').replace(/\\)/g, '&#41;');\n}", "function escapeHTML(text) {\n\t\t\treturn text.replace(/\\&/g,'&amp;').replace(/\\</g,'&lt;').replace(/\\>/g,'&gt;');\n\t\t}", "function escapeHtml(text) {\n\t\tvar map = {\n\t\t\t'&': '&amp;',\n\t\t\t'<': '&lt;',\n\t\t\t'>': '&gt;',\n\t\t\t'\"': '&quot;',\n\t\t\t\"'\": '&#039;'\n\t\t};\n\n\t\treturn text.replace(/[&<>\"']/g, function(m) {\n\t\t\treturn map[m];\n\t\t});\n\t}", "function escapehtml(str) {\n\treturn (''+str).replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/\"/g,'&quot;').replace(/ /g,'&nbsp;&nbsp;');\n}", "function htmlEncode(text)\n{\n return text.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}", "function escapeHTML(text) {\n\treturn text.toString()\n\t\t.split('&').join('&amp;')\n\t\t.split('<').join('&lt;')\n\t\t.split('>').join('&gt;')\n\t\t.split('\"').join('&quot;')\n\t\t.split('\\'').join('&#039;')\n}", "function encodeHTML(s) {\n return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\"/g, '&quot;');\n}", "function escapeHTML(text) {\n return text.replace(/\\&/g, '&amp;').replace(/\\</g, '&lt;').replace(/\\>/g, '&gt;');\n }", "function escapeHTML(text) {\n return text.replace(/\\&/g, '&amp;').replace(/\\</g, '&lt;').replace(/\\>/g, '&gt;');\n }", "function htmlEntities(str) {\n return String(str).replace(/&/g, '&').replace(/</g, '<')\n .replace(/>/g, '>').replace(/\"/g, '\"');\n}", "function htmlEntities(str) {\n\t\treturn String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n\t}", "function escapeHtml(text) \n{\n return text\n\t .replace(/&/g, \"&amp;\")\n\t .replace(/</g, \"&lt;\")\n\t .replace(/>/g, \"&gt;\")\n\t .replace(/\"/g, \"&quot;\")\n\t .replace(/'/g, \"&#039;\");\n}", "function escapeHTML(txt) {\n \"use strict\";\n return txt.replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\n}", "function htmlEntities(str) {\n return String(str)\n .replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function htmlEntities(str) {\n return String(str)\n .replace(/&/g, '&amp;').replace(/</g, '&lt;')\n .replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}", "function escapeXml(text)\n{\n var rval = '';\n \n var LT = new RegExp(\"<\", \"g\"); \n var GT = new RegExp(\">\", \"g\"); \n var AMP = new RegExp(\"&\", \"g\"); \n var TAB = new RegExp(\"\\t\", \"g\");\n \n rval = text.replace(AMP,\"&amp;\").replace(LT, \"&lt;\").replace(GT, \"&gt;\").replace(TAB, \" \");\n\n return rval;\n}", "function convertHTML(str) {\r\n var htmlEntities = {\r\n \"&\": \"&amp;\",\r\n \"<\": \"&lt;\",\r\n \">\": \"&gt;\",\r\n \"\\\"\": \"&quot;\",\r\n \"'\": \"&apos;\"\r\n };\r\n return str.split(\"\").map((entity) => htmlEntities[entity] || entity).join(\"\");\r\n}", "function convertHTML(str) {\n const chars = str.split(\"\");\n const string = chars.map((char) => {\n if (char === \"&\") {\n return \"&amp;\";\n } else if (char === \"<\") {\n return \"&lt;\";\n } else if (char === \">\") {\n return \"&gt;\";\n } else if (char === '\"') {\n return \"&quot;\";\n } else if (char === \"'\") {\n return \"&apos;\";\n } else {\n return char;\n }\n });\n const joinedStr = string.join(\"\");\n return joinedStr;\n}", "function quoteHTML(s) {\r\n\ts = s.replace(/&/g, \"&amp;\");\r\n\ts = s.replace(/</g, \"&lt;\");\r\n\ts = s.replace(/>/g, \"&gt;\");\r\n\treturn s;\r\n }", "function convertHTML(str) {\n //turn the string into an array to iterate through it later\n let strArr = str.split(\"\");\n \n //iterate through it with a loop\n for(let i = 0, l = strArr.length; i < l; i++){\n //use switch to convert items when found\n switch(strArr[i]){\n case \"&\":\n strArr[i] = \"&amp;\";\n break;\n case \"<\":\n strArr[i] = \"&lt;\";\n break;\n case \">\":\n strArr[i] = \"&gt;\";\n break;\n case '\"':\n strArr[i] = \"&quot;\";\n break;\n case \"'\":\n strArr[i] = \"&apos;\";\n break;\n //use default to process all other letters and spaces\n default:\n break;\n }\n }\n //merge everything back together \n return strArr.join(\"\");\n}", "function convertHTML(str) {\n\n let regex1 = /[&]/g, regex2 = /[<]/g, regex3 = /[>]/g, regex4 = /[\"]/g, regex5 = /[']/g; \n\n let html = {\n '&': '&amp;', \n '<': '&lt;', \n '>': '&gt;', \n '\\\"': '&quot;', \n '\\'': '&apos;'\n }; \n\n str = str.split('').map((entity) => {\n return html[entity]|| entity; \n }).join('');\n\n return str;\n}", "function escapeHTML(s) {\n return s.split(\"&\").join(\"&amp;\").\n\tsplit(\"<\").join(\"&lt;\").split(\">\").join(\"&gt;\");\n}", "function convertHTML(str) {\n\tvar result = '';\n\n\t// work\n\tresult = str.replace(/&/g, \"&amp;\");\n\tresult = result.replace(/</g, \"&lt;\");\n\tresult = result.replace(/>/g, \"&gt;\");\n\tresult = result.replace(/\"/g, \"&quot;\");\n\tresult = result.replace(/'/g, \"&apos;\");\n \n return result;\n// return str;\n}", "function escapeHtml(text) {\n var map = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#039;'\n };\n\n return text.replace(/[&<>\"']/g, function (m) {\n return map[m];\n });\n }", "static convertHtml(str) {\n const HtmlConverter = {\n \"&\": \"&​amp;\",\n \"<\": \"&​lt;\", \n \">\": \"&​gt;\", \n '\"': \"&​quot;\",\n \"'\": \"&​apos;\"\n }\n return str.replace(/\\&|<|>|\\\"|\\'/g, specialChar => HtmlConverter[specialChar]);\n\n }", "function escapeHtml(str){\n\t str = toString(str)\n\t .replace(/&/g, '&amp;')\n\t .replace(/</g, '&lt;')\n\t .replace(/>/g, '&gt;')\n\t .replace(/'/g, '&#39;')\n\t .replace(/\"/g, '&quot;');\n\t return str;\n\t }", "function convertHTML(str) {\n let regEx = /[&<>\"']/g\n let match = str.match(regEx)\n\n return str.replace(regEx, function(match){\n if(match === \"&\"){\n return \"&amp;\"\n }else if(match === \"<\"){\n return \"&lt;\"\n }else if(match === \">\"){\n return \"&gt;\"\n }else if(match === \"'\"){\n return \"&apos;\"\n }else if(match === '\"'){\n return \"&quot;\"\n }\n })\n}", "function htmlEncode(html) {\r\n if (html.length == 0) return \"\";\r\n html = html.replace(/&/g, \"&amp;\");\r\n html = html.replace(/</g, \"&lt;\");\r\n html = html.replace(/>/g, \"&gt;\");\r\n html = html.replace(/ /g, \"&nbsp;\");\r\n html = html.replace(/\\'/g, \"'\");\r\n html = html.replace(/\\\"/g, \"&quot;\");\r\n html = html.replace(/\\n/g, \"<br/>\");\r\n return html;\r\n}", "function HTMLEntityConvert(string) { return string.replace(/&/g, '&#38;').replace(/</g, '&#60;').replace(/>/g, '&#62;').replace(/\"/g, '&#34;').replace(/'/g, '&#39;'); }", "function escapeHTML(s) {\n return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n }", "function xkit_htmlspecialchars(str) {\n\t\tif (typeof(str) == \"string\") {\n\t\t\tstr = str.replace(/&/g, \"&amp;\");\n\t\t\tstr = str.replace(/\"/g, \"&quot;\");\n\t\t\tstr = str.replace(/'/g, \"&#039;\");\n\t\t\tstr = str.replace(/</g, \"&lt;\");\n\t\t\tstr = str.replace(/>/g, \"&gt;\");\n\t\t}\n\t\treturn str;\n\t}", "function convertHTML(str) {\n // &colon;&rpar;\n const htmlEntities = {\n '&': 'amp',\n '<': 'lt',\n '>': 'gt',\n '\"': 'quot',\n \"'\": 'apos',\n };\n let charRegex = /&|<|>|\"|'/g;\n return str.replace(charRegex, match =>`&${htmlEntities[match]};`);\n}", "function HtmlEscape(str) {\n if (!str) return \"\";\n return str.replace(amp_re_, \"&amp;\").replace(lt_re_, \"&lt;\").\n replace(gt_re_, \"&gt;\").replace(quote_re_, \"&quot;\");\n}", "function replaceXMLAmp(str_original){\n var objRegExp = /\\&amp;/gi;\n var str_new = str_original.replace(objRegExp, '&');\n return str_new;\n}", "function htmlEscape(str) {\r\n return String(str)\r\n .replace(/&/g, '&amp;')\r\n .replace(/\"/g, '&quot;')\r\n .replace(/'/g, '&#39;')\r\n .replace(/</g, '&lt;')\r\n .replace(/>/g, '&gt;')\r\n }", "function xmlEnc(value){\n return !value ? value : String(value).replace(/&/g, \"&amp;\").replace(/>/g, \"&gt;\").replace(/</g, \"&lt;\").replace(/\"/g, \"&quot;\").replace(/\\u001b\\[\\d{1,2}m/g, '');\n}", "function convert(str) { /* & = &amp; < = &lt; > = &gt; ' = &apos; \" = &quot;*/\n\n var found_matches = str.match(/[&<>\"']g/);\n if (found_matches == null) {\n return str;\n } else {\n\n for (var i = 0, i < found_matches.length; i++) {\n switch (str[i]) {\n case '&':\n str.replace(/&/g, '&amp;');\n break;\n case '<':\n str.replace(/</g, '&lt;');\n break;\n case '>':\n str.replace(/>/g, '&gt;');\n break;\n case '\"':\n str.replace(/\"/g, '&#34;');\n break;\n case \"'\":\n str.replace(/'/g, '&apos;');\n break;\n\n }\n }\n }\n console.log(str);\n return str;\n}", "function escapeHTML(s) {\n return s.split('&').join('&amp;').split('<').join('&lt;').split('\"').join('&quot;');\n}", "function escapeHtml(text) {\n var map = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#039;'\n };\n return text.replace(/[&<>\"']/g, function(m) { return map[m]; });\n}", "function htmlEscape(text) {\n return text.replace(/[<>&\"]/g, function(match, pos, originalText) {\n switch(match) {\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case \"&\":\n return \"&amp;\";\n case \"\\\"\":\n return \"&quot;\";\n }\n })\n}", "function echosc(str)\n{\n\tstr=str.replace(/&/g,\"&amp;\");\n\tstr=str.replace(/</g,\"&lt;\");\n\tstr=str.replace(/>/g,\"&gt;\");\n\tstr=str.replace(/\"/g,\"&quot;\");\n\tstr=str.replace(/'/g,\"\\'\");\n\tstr=str.replace(/ /g,\"&nbsp;\");\n\tdocument.write(str);\n}", "function escapeHtml(str) {\n return str.replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}", "function specialCharacters(code) {\n return code.replace(/\\t/g, '&nbsp;&nbsp;');\n }", "escapeHTML(text) {\n const replacers = {'<': '&lt;', '>': '&gt;', '&': '&amp;', '\"': '&quot;'};\n return String(text || '').replace(/[<>&\"]/g, (x) => { return replacers[x]; });\n }", "function escapeHtml(text) {\n var map = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#039;'\n };\n\n return text.replace(/[&<>\"']/g, function(m) { return map[m]; });\n}", "function escapeHtml(text) {\r\n var map = {\r\n '&': '&amp;',\r\n '<': '&lt;',\r\n '>': '&gt;',\r\n '\"': '&quot;',\r\n \"'\": '&#039;'\r\n };\r\n return text.replace(/[&<>\"']/g, function(m) { return map[m]; });\r\n}", "function unEntity(str){\n return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>');\n}", "function escapeHtml(html){\n return String(html)\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\n}", "function convertEntities(str){\n let htmlEntities = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&apos;'\n };\n return str.split(\"\").map(x => htmlEntities[x] || x).join('');\n}", "function escapeHtml(unsafe) {\n return unsafe\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}", "function unescapeHtml(str){\n\t str = toString(str)\n\t .replace(/&amp;/g , '&')\n\t .replace(/&lt;/g , '<')\n\t .replace(/&gt;/g , '>')\n\t .replace(/&#0*39;/g , \"'\")\n\t .replace(/&quot;/g, '\"');\n\t return str;\n\t }", "function convertHTML(str) {\n\treturn (str = str\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;')\n\t\t.replace(/'/g, '&apos;'));\n}", "function ssml_escape ( orig ) {\n return orig.replace('&', ' and ')\n}", "function convertHTML(str) {\r\n\r\n let entities = {\r\n '&': '&amp;',\r\n '\\\"': '&quot;',\r\n '\\'': '&apos;',\r\n '<': '&lt;',\r\n '>': '&gt;'\r\n };\r\n\r\n return str.split('').map(function (char) {\r\n return entities[char] || char;\r\n }).join('');\r\n}", "function escapeHtml(str) {\n\t\treturn String(str)\n\t\t\t.replace(/&/g, \"&amp;\")\n\t\t\t.replace(/</g, \"&lt;\")\n\t\t\t.replace(/>/g, \"&gt;\")\n\t\t\t.replace(/\"/g, \"&quot;\")\n\t\t\t.replace(/'/g, \"&#039;\")\n\t\t\t.replace(/\\//g, \"&#x2F;\") \n\t}", "function escapeHtml(str) {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\")\n .replace(/\\n/g, '<br>');\n }", "function dm3_escape_html(str) {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n }" ]
[ "0.7283393", "0.70207536", "0.701524", "0.7010876", "0.6963887", "0.6963887", "0.69562256", "0.6934616", "0.6924484", "0.69124436", "0.685737", "0.6850765", "0.68409127", "0.68366456", "0.68317014", "0.6829094", "0.6807098", "0.67730194", "0.67401475", "0.6698233", "0.6698233", "0.6688227", "0.6682103", "0.6673339", "0.6673339", "0.6671351", "0.6671306", "0.66674054", "0.666647", "0.66614765", "0.6646146", "0.6643888", "0.6643888", "0.6643888", "0.6643888", "0.6643888", "0.6643888", "0.6640739", "0.66326076", "0.66321814", "0.66247654", "0.66247654", "0.66247654", "0.66247654", "0.6620497", "0.6613822", "0.66113555", "0.66020375", "0.660014", "0.65945643", "0.6583381", "0.6576206", "0.6576206", "0.6573374", "0.6572627", "0.6570564", "0.6570428", "0.656949", "0.656949", "0.6545057", "0.6523146", "0.65064096", "0.65057373", "0.6495165", "0.64942175", "0.64874667", "0.64786434", "0.64758176", "0.6470068", "0.64698064", "0.64653724", "0.6458424", "0.64528257", "0.64518905", "0.6448541", "0.64456004", "0.64435714", "0.6438706", "0.6432396", "0.6431817", "0.6408218", "0.6406112", "0.6402495", "0.63990116", "0.6398263", "0.63926536", "0.63925016", "0.63909936", "0.6377915", "0.6360304", "0.6357248", "0.6347775", "0.633922", "0.63383275", "0.6337432", "0.63355637", "0.63343346", "0.6334321", "0.63112307", "0.6304451", "0.6304284" ]
0.0
-1
So our reducer will be:
function doAction2(state = initialState, action) { return dispatchTable[action.type] ? dispatchTable[action.type](state, action) : state; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function reducer(){\n\n}", "reducer(res) {\n return res;\n }", "function reducer(a,b) {\n return a + b;\n}", "function reducer(result, value, index) {\n const fieldId = info.fields[index].id\n const processorId = info.fields[index].type\n const processor = get(processorId, processType)\n return set(fieldId, processor(value), result)\n }", "function reducer(acc, element) {\n return element + acc;\n}", "function reducer(a,b){\n return a += b;\n }", "reducerFilter(acc, xs) {\n xs.map((item, index)=> {\n if (xs[index] === xs[index+1]) {\n } else {\n acc.push(item);\n }\n })\n return acc;\n }", "reduce(state, payload) {\n let {action, data} = payload;\n\n switch(action) {\n case 'moveTo':\n state = state.withMutations(s => {\n s = s.set('isMoving', true);\n s = s.set('movingTo', [data[0], data[1]]);\n });\n break;\n case 'stopMoving':\n state = state.withMutations(s => {\n let movingTo = s.get('movingTo');\n s = s.set('x', movingTo[0]);\n s = s.set('z', movingTo[1]);\n s = s.set('isMoving', false);\n s = s.set('movingTo', null);\n });\n break;\n case 'turnTo':\n state = state.withMutations(s => {\n s = s.set('isTurning', true);\n s = s.set('turningTo', data);\n });\n break;\n case 'stopTurning':\n state = state.withMutations(s => {\n s = s.set('isTurning', false);\n s = s.set('dir', s.get('turningTo'));\n });\n break;\n case 'turn':\n state = state.updateIn(['dir'], dir => {\n dir = (dir + data)%4;\n if(dir < 0) {\n dir = 4 + dir;\n }\n return dir;\n })\n break;\n case 'inventory':\n state = state.updateIn(['inventory'], inventory => inventory.push(1));\n break;\n }\n\n return state;\n }", "reduce(state, payload) {\n let {action, data} = payload;\n\n switch(action) {\n case 'move':\n state = state.updateIn(['currentRoom'], value => value += data);\n break;\n }\n\n return state;\n }", "function reducer( state = 기본State, 액션){ \n// 33c-(6) (6)-3\n if(액션.type ==='수량증가'){\n let copy = [...state];\n copy[0].quan++;\n return copy \n }\n// 33c-(8)\nelse if (액션.type ==='수량감소'){\n let copy = [...state];\n copy[0].quan--;\n return copy \n } \n else{ \n return state}\n }", "function reduce(currState, { type, payload }){\n return (type in actions) ? actions[type](currState, payload) : currState;\n }", "function reducer(state = estadoInicial, algo){\n switch(algo.type){\n case agregarTarea: {\n if(!algo.payload){\n return[]\n }\n return[\n ...state,\n algo.payload\n ]\n }\n default: \n return state\n }\n}", "function reducer(total, num) {\n return total + num\n }", "function reducer (input, context) {\n console.log('INPUT:')\n console.log(input)\n console.log('\\nCONTEXT:')\n console.log(JSON.stringify(context, null, 2))\n}", "reduce(state, action) {\n\t\tswitch (action) {\n\t\t\tcase 'blue':\n\t\t\t\treturn Object.assign({}, state, { blue: state.blue + 1 });\n\t\t\tcase 'red':\n\t\t\t\treturn Object.assign({}, state, { red: state.red + 1 });\n\t\t\tdefault:\n\t\t\t\treturn state;\n\t\t}\n\t}", "reducer (func) {\n return function (property) {\n var result = this[0];\n if (property) {\n //apply the reducer function along the array, using the value of the given property\n result = result && result[property];\n for (var i = 1, l = this.length; i < l; i++) {\n result = func(result, this[i][property]);\n }\n } else {\n //apply the reducer function along the array, using the value in the array\n for (var i = 1, l = this.length; i < l; i++) {\n result = func(result, this[i]);\n }\n }\n return result;\n }\n }", "function reducer(accumulator, currentValue){\n return accumulator + currentValue;\n }", "function reduce(reducer, reducible) {\n\t return transformWithSpec(reducer, reducible, _shiftSpec2.default[reducible.type]);\n\t}", "function greetingReducer() {}", "function reducer(accumulator, item){\n //console.log(accumulator, item)\n let total = item.price * item.inventory\n return accumulator += total\n}", "function Reducer(state = loadState() , action) {\n switch (action.type) {\n case 'UPDATE':\n let newState = [...state];\n newState[action.index] = action.data\n return newState;\n default:\n return state\n }\n}", "function myReduceFunc() {\n \n\n\n}", "function combinedReduction() {\n var reducers = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n reducers[_i - 0] = arguments[_i];\n }\n var dispatchPairs = _.reduce(reducers, function (m, r) { return m.concat(_findReducers(r)); }, []);\n return function (state, action) {\n //if (state === void 0) { state = {}; }\n for (var _i = 0, dispatchPairs_1 = dispatchPairs; _i < dispatchPairs_1.length; _i++) {\n var _a = dispatchPairs_1[_i], path = _a[0], reducer = _a[1];\n var currentState = path.length === 0 ? state : _.get(state, path);\n var newState = void 0;\n try {\n newState = reducer(currentState, action);\n }\n catch (error) {\n console.error(\"Error in reducer mounted at \" + path.join('.') + \":\", error);\n continue;\n }\n if (currentState === newState)\n continue;\n state = deepUpdate(state, path, { $set: newState });\n }\n return state;\n };\n}", "function reduce(action,base,array)\n{\n\tforEach(array,function(element)\n\t{\n\t\tbase = action(base,element)\n\t});\n\treturn base;\n}", "reducer({ settings, translations, searchState, keyword, englishWords }) {\n return {\n settings,\n translations,\n searchState,\n keyword,\n englishWords,\n };\n }", "function liftReducer(field) {\n const lift = ({ key, reducer }) => (tree => {\n const treeCopy = { ...tree };\n treeCopy.children = [ ...treeCopy.children ];\n const index = treeCopy.children.findIndex(c => c.key === key);\n if (index >= 0) {\n treeCopy.children[index] = reducer(treeCopy.children[index]);\n }\n return treeCopy;\n });\n return stream$$ => stream$$.compose(extractConcurrently(field)).map(lift);\n}", "function productsReducer(state = [], action){\n return state;\n}", "function reducer(state = defaultState, {type, payload}) {\n\tswitch(type) {\n\t\tdefault:\n\t\t\treturn state;\n\n\t}\n\n}", "function reducer(state, action) {\n console.log(action)\n switch (action.type) {\n case 'plus':\n return {\n counter: state.counter + 1,\n clicks: state.clicks + 1,\n };\n\n case 'minus':\n return {\n counter: state.counter - 1,\n clicks: state.clicks + 1,\n };\n\n default:\n return state;\n }\n}", "function reducer(state = {}, action){\n return state;\n}", "function reducer(state,action){\n console.log(action);\n\n switch(action.type){ //update user when they log in/out\n\n case 'SET_USER':\n return{\n ...state, user:action.user ///sets user to authenticated user name \n\n }\n case 'ADD_TO_BASKET':\n //Logic for adding item to basket\n return{\n ...state,basket:[...state.basket,action.item],};\n case 'REMOVE_FROM_BASKET':\n let newBasket = [...state.basket]; //current state of basket\n const index = state.basket.findIndex((basketItem)=>basketItem.id===action.id)//find index of basketItem where item id = action id\n if(index>=0){\n\n newBasket.splice(index,1); //removing index\n ///....\n\n }\n \n //Logic for removing item to basket\n return{ ...state,basket:newBasket };//setting basket to new basket\n\n default:\n return state; \n }\n}", "actionReducer(action){\n return unitActionReducer.call(this, this.state, action);\n }", "function reducer(state = initialState, action) {\n switch (action.type) {\n case 'ADD': {\n return state + action.payload;\n }\n case 'REPLACE': {\n return action.payload;\n }\n case 'SQUARE': {\n return state**2;\n }\n default: {\n return state;\n }\n }\n}", "function reducer(state=initeState,action){\n\tswitch(action.type){\n\t\tcase GET_DATA:\n\t\t\treturn {...state, number:state.number+1, ...action.payload};\n\t\tdefault:\n\t\t\treturn state\n\t}\n}", "function reducer(state, action) {\n // swqitch between the actions\n switch (action.type) {\n default:\n return state\n }\n}", "function reducer(state, action) {\n //b. create switch statement where each case is a possible action.type\n switch (action.type) {\n case 'ACTION_TYPE':\n return state.someMethod(action.payload)\n default:\n return state;\n }\n }", "function reducer(state, action) {\n switch (action.type) {\n case 'incrementby1':\n return { score: state.score + 50 };\n case 'incrementby2':\n return { score: state.score + 100 };\n case 'incrementby3':\n return { score: state.score + 150 };\n default:\n throw new Error();\n }\n}", "function reducer (currentState=getInitialState(), action) {\n console.log(\"Current State:\", currentState, \"Action:\", action)\n //based on the action.type, return {newState}\n switch(action.type){\n case BIGGER_COUNT:\n return {...currentState, count: currentState.count + action.payload}\n case LITTLER_COUNT:\n return {...currentState, count: currentState.count - action.payload}\n default:\n return currentState\n }\n}", "function reActorReducer(state = [], action){\n\n\n switch(action.type){\n\n default: \n return state\n }\n\n\n}", "function reducer() {\n\t var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {\n\t isFetching: false,\n\t isAuthenticated: _utils.webStorage.getItem('token') ? true : false,\n\t token: _utils.webStorage.getItem('token'),\n\t userId: _utils.webStorage.getItem('userId'),\n\t account: {}\n\t };\n\t var action = arguments[1];\n\t\n\t switch (action.type) {\n\t case _loginActions.LOGIN_REQUEST:\n\t return Object.assign({}, state, {\n\t isFetching: true,\n\t isAuthenticated: false\n\t });\n\t case _loginActions.LOGIN_SUCCESS:\n\t return Object.assign({}, state, {\n\t isFetching: false,\n\t isAuthenticated: true,\n\t errorMessage: ''\n\t });\n\t case _loginActions.LOGIN_FAILURE:\n\t return Object.assign({}, state, {\n\t isFetching: false,\n\t isAuthenticated: false,\n\t errorMessage: action.message\n\t });\n\t case _logoutActions.LOGOUT_SUCCESS:\n\t return Object.assign({}, state, {\n\t isFetching: true,\n\t isAuthenticated: false\n\t });\n\t case _getAccountActions.GET_ACCOUNT_REQUEST:\n\t return Object.assign({}, state, {\n\t isFetching: true\n\t });\n\t case _getAccountActions.GET_ACCOUNT_SUCCESS:\n\t return Object.assign({}, state, {\n\t isFetching: false,\n\t account: action.account,\n\t errorMessage: ''\n\t });\n\t case _getAccountActions.GET_ACCOUNT_FAILURE:\n\t return Object.assign({}, state, {\n\t isFetching: false,\n\t errorMessage: action.message\n\t });\n\t default:\n\t return state;\n\t }\n\t}", "reducer(book) {\n return {\n // cursor: `${launch.launch_date_unix}`,\n cursor: 1,\n id: book.isbn13,\n title: book.title,\n subtitle: book.subtitle,\n isbn13: book.isbn13,\n author: book.author,\n link: book.link,\n };\n }", "function reducer(total, current) {\n const newCurrent = isNaN(Number(current)) ? 0 : Number(current);\n return total + newCurrent;\n}", "function inventoryReducer(totals, item){\n // totals[item.type] ? totals[item.type]+= 1 : totals[item.type] = 1;\n totals[item.type] = totals[item.type] + 1 || 1;\n return totals;\n}", "function reducer(state = { counter: 0 }, action) {\n console.log('%c REDUCER!', 'color: blue', state, action);\n\n switch(action.type) {\n case \"INCREMENT_COUNTER\": // by convention, make these all CAPS\n return {...state, counter: state.counter + 1}\n case \"NOT_INCREMENT_COUNTER\":\n return {...state, counter: state.counter - 1}\n case \"SET_COUNT_VALUE\":\n return {...state, counter: action.payload}\n case \"SET_SET_COUNT\":\n // return {...state, counter: action.payload.counter}\n // return {...state, counter: action.payload.counter}\n return {...state, ...action.payload} // Object.assign({}, state, action.payload)\n default:\n return state;\n }\n}", "function Reducer2(state = INITIAL_STATE, action) {\r\n switch(action.type) {\r\n default : {\r\n\r\n const var_name = action.argument_var_name;\r\n let NEW_STATE = [];\r\n if(Math.max.apply(Math, warehouse) < action[var_name]) {\r\n warehouse.push(action[var_name]);\r\n console.log(warehouse)\r\n NEW_STATE = [...INITIAL_STATE, action[var_name]];\r\n }\r\n else {\r\n NEW_STATE = [...INITIAL_STATE, Math.max.apply(Math, warehouse)];\r\n }\r\n //alert(`In Reducer:\\n ${ JSON.stringify(action) },\\n-------------\\n, ${ JSON.stringify(state) }`);\r\n \r\n \r\n return NEW_STATE;\r\n }\r\n }\r\n }", "function Left$prototype$reduce(f, x) {\n return x;\n }", "function combineReducer() {\n var reducerMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var updater = arguments[1];\n\n\n // Generate a combined reducer function\n return function () {\n var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n var newState = {},\n dirtyKeys = [];\n\n // Spread the action to all reducers inside the combined one\n for (var key in reducerMap) {\n // Pass the whole state down as argument for\n // cross state key access\n var reducedState = reducerMap[key](state[key], action, state);\n\n if (reducedState !== state[key]) {\n dirtyKeys.push(key);\n }\n\n newState[key] = reducedState;\n }\n\n // Call update function for each reduced state\n updater(newState, dirtyKeys);\n\n // dirtyKeys.forEach((dirtyKey) => {\n // updaterMap[dirtyKey](newState, dirtyKey)\n // })\n\n return newState;\n };\n}", "function reducer(state = {}, action) {\n\tswitch (action.type) {\n\t\tcase 'random number':\n\t\t\treturn action.payload;\n\t\tcase 'value + 1':\n\t\t\treturn action.payload;\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}", "function runtimeReducer(state, action) {\n switch (action.type) {\n case 'SET':\n return action.payload\n case 'RESET':\n return 0\n default:\n return state\n }\n}", "function reducer (state, action) { \n switch(action.type) {\n case \"SET_TRANSACTIONS\":\n return { ...state, transactions: action.transactions }\n case \"ADD_PENDING\":\n return { ...state, pending: [...state.pending, action.pending] }\n case \"ADD_AUTHORIZED\":\n return { ...state, authorized: [...state.authorized, action.authorized] }\n case \"ADD_REJECTED\":\n return { ...state, rejected: [...state.rejected, action.rejected] }\n default:\n return state;\n }\n}", "function reducer(acc, features) {\n\t\t\t\tfor (var i = 0; i < features.length; i++) {\n\t\t\t\t\tif (acc.sum[i] == undefined) acc.sum[i] = 0;\t// suboptimal initialization (as number of features is unknown)\n\t\t\t\t\tvar delta = features[i] - acc.mean[i];\n\t\t\t\t\tacc.sum[i] += delta * delta;\n\t\t\t\t}\n\t\t\t\treturn acc;\t\t\t\t\n\t\t\t}", "function myReduce(arr, cb) {\n //let intially storage at 0th index\n let storage = arr[0];\n // start from index 1 till size of array\n for(let i=1;i<arr.length;i++){\n //call the function cb\n storage=cb(storage,arr[i]);\n }\n // return cb function\n return storage;\n}", "function myreduce(arr,cb,acc){\n for(var i=0;i<arr.length;i++){\n acc=cb(acc,arr[i])\n }\n return acc\n}", "reduce(state, action) {\n // Because this is a template for specific ReduceStores, we expect this to be overwritten by specific sub-ReduceStores\n // So we'll simply throw an error telling the user this, if the primary ReduceStore's reduce method is called\n throw new Error('\"ReduceStore.reduce\": Substores must override reduce method of a Flux ReduceStore');\n }", "function _reduce(event, merge, initial) {\n var output = initial;\n return _map(event, function (e) {\n output = merge(output, e);\n return output;\n });\n}", "function totalReducer(acc, curProduct) {\n let price = curProduct.price * curProduct.cart_to_product.quantity;\n return acc + price;\n }", "function firstReducer(state = initialState, action){\n if(action.type === \"INCREMENT\"){\n //pure function that doesn't have any side effect\n let copy = { ...state };\n copy.count++;\n return copy\n } else if (action.type === \"DECREMENT\") {\n let copy = { ...state};\n copy.count--;\n return copy\n }\n return state;\n\n}", "reduce(startAccumulator, folder) {\n let accumulator = startAccumulator;\n for (const element of this)\n accumulator = folder(accumulator, element);\n return accumulator;\n }", "function reducer(state, action) {\n // nums.push(5); // no: mutable\n // const newNums = nums.concat([5]) // yes: immutable\n\n // Move in all four directions.\n if (action.type === 'MOVE') {\n // const next = Object.assign({}, state); // copy properties of 'state' into a new object\n // next.gas--;\n // next.score++;\n\n // return next;\n return {\n gas: state.gas - 1,\n score: state.score + 1,\n x: state.x + action.payload.x,\n y: state.y + action.payload.y,\n };\n }\n\n return state;\n}", "function reducer(state=defaultState, action) {\n switch (action.type) {\n case INCREMENT_ORDER:\n console.log(state[0].orderNum);\n console.log(\"action.order\" + action.order);\n const updatedStateObj = {...state[0], orderNum: action.order + 1};\n return [updatedStateObj];\n case ADD_SELECTIONS:\n console.log(action.selection);\n const newSelections = [...state[0].selections, action.selection];\n console.log(newSelections);\n const ObjWithNewSelections = {...state[0], selections: newSelections};\n console.log(ObjWithNewSelections);\n return [ObjWithNewSelections];\n case ADD_PROFIT:\n console.log(\"total money: \" + state[0].totalMoney);\n console.log(\"action.profit: \" + action.profit);\n const ObjWithUpdatedMoney = {...state[0], totalMoney: state[0].totalMoney + action.profit};\n console.log(\"total money updated: \" + ObjWithUpdatedMoney.totalMoney);\n return [ObjWithUpdatedMoney];\n case UPDATE_THIS_ROUND_RATING:\n console.log(\"thisRoundRating\" + state[0].thisRoundRating);\n console.log(\"action.changedRating\" + action.changedRating);\n if (state[0].thisRoundRating + action.changedRating <= 5.0){\n const ObjWithUpdatedRating = {...state[0], thisRoundRating: state[0].thisRoundRating + action.changedRating};\n return [ObjWithUpdatedRating];\n }else {\n const ObjWithMaxRating = {...state[0], thisRoundRating: 5.0};\n return [ObjWithMaxRating];\n }\n case RESET_ROUND_RATING:\n const ObjWithInitialRating = {...state[0], thisRoundRating: 5.0};\n return [ObjWithInitialRating];\n case ADD_RATING:\n console.log(\"ratings: \" + state[0].ratings);\n console.log(action.rating);\n const newRatings = [...state[0].ratings, action.rating];\n console.log(newRatings);\n const ObjWithNewRatings = {...state[0], ratings: newRatings};\n console.log(ObjWithNewRatings);\n return [ObjWithNewRatings];\n case RESET_RATINGS:\n const ObjWithNoRatings = {...state[0], ratings: []};\n return [ObjWithNoRatings];\n case RESET_ORDER_NUM:\n const ObjWithInitialOrderNum = {...state[0], orderNum: 0};\n return [ObjWithInitialOrderNum];\n case RESET_SELECTIONS:\n const ObjWithNoSelections = {...state[0], selections: []};\n return [ObjWithNoSelections];\n case RESET_MONEY:\n const ObjWithInitialMoney = {...state[0], totalMoney: 80};\n return [ObjWithInitialMoney];\n case RESET_TIME_REMAINED:\n const ObjWithInitialTime = {...state[0], timeRemained: 20};\n return [ObjWithInitialTime];\n // case UPDATE_TIME_REMAINED:\n // console.log(state[0].timeRemained);\n // console.log(\"action.changedRating\" + action.timeSpent);\n // const ObjWithUpdatedTime = {...state[0], timeRemained: state[0].timeRemained - action.timeSpent};\n // return [ObjWithUpdatedTime];\n default:\n console.log(state[0].orderNum);\n return state;\n }\n}", "[REDUCE_ITEM](state, payload) {\n state.cartItems.filter(e => {\n if (e.id === payload) {\n if (e.quantity > 1) {\n const quantity = e.quantity - 1;\n return {\n ...e,\n quantity\n }\n }\n }\n return e;\n });\n }", "function serchReducer(state, action) {\n switch (action.type) {\n case 'startDate':\n return { ...state, startDate: action.payload };\n case 'endDate':\n return { ...state, endDate: action.payload };\n case 'sourceCategory':\n return {\n ...state,\n sourceID: action.payload\n };\n case 'searchByName':\n return {\n ...state,\n title: action.payload,\n };\n default:\n return state;\n }\n}", "function reducerA(state, action) {\n switch (action) {\n case 'increment':\n return state + 1;\n case 'reset':\n return 0;\n }\n }", "function myReducer(state = {}, action) {\n if (action.type == 'TEST_ACTION') {\n return { ...state, 'a': 1, 'c': 1 }\n }\n return state\n}", "function reducer(arr, ele) {\n\treturn arr.reduce(function(acc, cur, ind, src) {\n\t\tif (cur === doSubs(ele)) {\n\t\t\tacc.push(ind);\n\t\t}\n\t\treturn acc;\n\t}, []);\n}", "reducer(state, action) {\n const nextState = toggleReducer(state, action);\n if (count > 5 && action.type === toggleActionTypes.toggle) {\n return state;\n }\n setCount((c) => c + 1);\n return nextState;\n }", "function enhanceReducer(reducer) {\n return (state, action) => (action.type !== 'RESET_STORE' ? reducer(state, action) :\n {\n okapi: state.okapi,\n discovery: state.discovery,\n }\n );\n}", "applyCollectionReducer(cache = {}, action) {\n const entityName = action.payload.entityName;\n const collection = cache[entityName];\n const reducer = this.entityCollectionReducerRegistry.getOrCreateReducer(entityName);\n let newCollection;\n try {\n newCollection = collection\n ? reducer(collection, action)\n : reducer(this.entityCollectionCreator.create(entityName), action);\n }\n catch (error) {\n this.logger.error(error);\n action.payload.error = error;\n }\n return action.payload.error || collection === newCollection\n ? cache\n : { ...cache, [entityName]: newCollection };\n }", "function mapReducer(mappingFn) {\n return function reducer(list, v) {\n list.push(mappingFn(v));\n return list;\n };\n}", "function server_messages(state = { orderedSets: {}, server: {}, messages: '> ' }, action) {\n //console.log (`store: reducer called with ${JSON.stringify(action)}`)\n let ret = {}\n switch (action.type) {\n case 'LEFT': \n ret = { orderedSets: {}, server: {}}\n break\n case 'JOINED':\n // http://redux.js.org/docs/recipes/UsingObjectSpreadOperator.html\n ret = {server: {name: action.name, server: action.server, interval: action.interval}}\n break\n case 'UPDATEKEY':\n if (!state.orderedSets[action.key]) { \n ret = {orderedSets: { ...state.orderedSets, [action.key]: [action]}}\n } else {\n let updt_idx = state.orderedSets[action.key].findIndex((e) => e.id === action.id);\n if (updt_idx >=0) {\n // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\n ret = {orderedSets: update (state.orderedSets, {[action.key]: {$splice:[[updt_idx, 1, action]]}})}\n } else {\n ret = {orderedSets: update (state.orderedSets, {[action.key]: {$push:[action]}})}\n }\n }\n break\n case 'REMOVEKEY':\n if (state.orderedSets[action.key]) { \n let rm_idx = state.orderedSets[action.key] && state.orderedSets[action.key].findIndex((e) => e.id === action.id);\n if (rm_idx >=0) {// perform 1 splice, at position existing_idx, remove 1 element\n ret = {orderedSets: update (state.orderedSets, {[action.key]: {$splice: [[rm_idx, 1]]}})}\n }\n }\n break\n default:\n console.log (`unknown mesg ${action.key}`)\n }\n // update(this.state.alldatafromserver, {$push: [server_data]})}\n return { ...state, ...ret, messages: state.messages + JSON.stringify(action) + '\\n> '}\n}", "function transactionReducer(state = initialState, action) {\n switch (action.type) {\n case actions.ADD_TRANSACTION: {\n return [\n ...state,\n {\n // All the details about the transaction\n id: action.payload.id,\n Address: action.payload.Address,\n Buyer: action.payload.Buyer,\n BuyerId: action.payload.BuyerId,\n Completion: action.payload.Completion,\n Floors: action.payload.Floors,\n HomeInspectionVoided: action.payload.HomeInspectionVoided,\n Pool: action.payload.Pool,\n SquareFt: action.payload.SquareFt,\n Stage: action.payload.Stage,\n BuyerData: null, // To store the Buyer Data\n // All the steps\n PreApproval: action.payload.PreApproval,\n FindAgent: action.payload.FindAgent,\n FindHome: action.payload.FindHome,\n EscrowTitle: action.payload.EscrowTitle,\n HomeInspection: action.payload.HomeInspection,\n HomeInsurance: action.payload.HomeInsurance,\n Closing: action.payload.Closing,\n },\n ];\n }\n case actions.REMOVE_ALL_TRANSACTIONS: {\n return initialState;\n }\n case actions.ADD_PREAPPROVAL_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.PreApproval = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_FINDAGENT_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.FindAgent = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_FINDHOME_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.FindHome = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_HOMEINSPECTION_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.HomeInspection = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_ESCROWTITLE_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.EscrowTitle = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_HOMEINSURANCE_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.HomeInsurance = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_CLOSING_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.Closing = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_BUYER_INFO: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.BuyerData = action.buyerData;\n }\n });\n\n return state;\n }\n default: {\n return state;\n }\n }\n}", "function tableReducer(state = [], action) {\n switch (action.type) {\n case 'ADD_TABLE':\n if (action.tableData.after_id === -1) {\n return [action.tableData.table, ...state];\n } else {\n return [...state, action.tableData.table];\n }\n return;\n case 'REMOVE_TABLE':\n return state.filter(table => table.id !== action.tableData.id);\n\n case 'UPDATE_TABLE':\n let tableToUpdateIndex;\n state.some((t,i) => t.id === action.tableData.table.id ? tableToUpdateIndex = i : null);\n\n return [\n ...state.slice(0, tableToUpdateIndex),\n action.tableData.table,\n ...state.slice(tableToUpdateIndex+1)\n ];\n case 'SET_TABLES':\n return state.concat(action.tables);\n case 'UNSUBSCRIBE_TABLES':\n\n return [];\n default:\n return state;\n }\n}", "function genericReducer(state = {}, {type, payload}) {\n switch (type) {\n case \"update\":\n return payload;\n default:\n return state;\n }\n}", "function reducer(state, action) {\n switch (action) {\n case 'INC':\n return {\n ...state,\n counter: state.counter + 1\n };\n\n case 'DEC':\n return {\n ...state,\n counter: state.counter - 1\n };\n\n default:\n return state;\n }\n}", "function ourReducer (draft, action) {\n switch (action.type) {\n case 'login':\n draft.loggedIn = true\n draft.user = action.data // save user info\n return\n case 'logout':\n draft.loggedIn = false\n return\n case 'flashMessage':\n draft.flashMessages.push(action.value)\n return\n case 'openSearch':\n draft.isSearchOpen = true\n return\n case 'closeSearch':\n draft.isSearchOpen = false\n return\n case 'toggleChat':\n draft.isChatOpen = !draft.isChatOpen\n return\n case 'closeChat':\n draft.isChatOpen = false\n return\n case 'incrementUnreadChatCount':\n draft.unreadChatCount++\n return\n case 'clearUnreadChatCount':\n draft.unreadChatCount = 0\n return\n }\n }", "function split (splitter) {\n return function (rf) {\n // this takes 2 things and makes them 1\n return async (acc, val) => {\n var rs = await splitter(val)\n var reduction = { reduced: [] }\n try {\n var acc2 = acc\n for (var i = 0; i < rs.length; i++) {\n var r = rs[i]\n acc2 = await rf(acc2, r)\n if (acc2.hasOwnProperty('reduced')) {\n if (acc2.reduced) {\n reduction.reduced.push(acc2.reduced)\n }\n } else {\n reduction.reduced.push(acc2)\n }\n }\n return reduction\n } catch (ex) {\n console.log(ex)\n }\n }\n }\n}", "wrapReducer(reducer) {\n this._historyReducer = orderedHistory.reducer(reducer)\n\n // wrap the root reducer to track history and rewind occasionally\n return (currentState, action) => {\n return this._historyReducer(currentState, action)\n }\n }", "function reducer(state, action) { //we have access to current state, action: object passed down to dispatch(). Returns new state to be set.\n switch(action.type) {\n case ACTIONS.MAKE_REQUEST:\n return {loading: true, jobs: []};\n case ACTIONS.GET_DATA: \n return {...state, loading: false, jobs: action.payload.jobs};\n case ACTIONS.ERROR:\n return {...state, loading: false, error: action.payload.error, jobs: []};\n case ACTIONS.HAS_NEXT_PAGE:\n return {...state, hasNextPage: action.payload.hasNextPage};\n default:\n return state;\n }\n}", "mergeQuerySetReducer(entityCache, action) {\n // eslint-disable-next-line prefer-const\n let { mergeStrategy, querySet, tag } = action.payload;\n mergeStrategy =\n mergeStrategy === null ? MergeStrategy.PreserveChanges : mergeStrategy;\n const entityOp = EntityOp.QUERY_MANY_SUCCESS;\n const entityNames = Object.keys(querySet);\n entityCache = entityNames.reduce((newCache, entityName) => {\n const payload = {\n entityName,\n entityOp,\n data: querySet[entityName],\n mergeStrategy,\n };\n const act = {\n type: `[${entityName}] ${action.type}`,\n payload,\n };\n newCache = this.applyCollectionReducer(newCache, act);\n return newCache;\n }, entityCache);\n return entityCache;\n }", "static *reduceRight$e(thiz, args, s) {\n\t\tlet l = yield * getLength(thiz);\n\t\tlet acc;\n\t\tlet fx = args[0];\n\n\t\tif ( args.length < 1 || !fx.isCallable ) {\n\t\t\treturn yield CompletionRecord.makeTypeError(s.realm, 'First argument to reduceRight must be a function.');\n\t\t}\n\n\t\tif ( args.length > 1 ) {\n\t\t\tacc = args[1];\n\t\t}\n\n\t\tfor ( let i = l - 1; i >= 0; --i ) {\n\t\t\tif ( !thiz.has(i) ) continue;\n\t\t\tlet lv = yield * thiz.get(i);\n\t\t\tif ( !acc ) {\n\t\t\t\tacc = lv;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tacc = yield * fx.call(thiz, [acc, lv], s);\n\t\t}\n\n\t\tif ( !acc ) return yield CompletionRecord.makeTypeError(s.realm, 'Reduce an empty array with no initial value.');\n\t\treturn acc;\n\t}", "function reducer2(state, action) {\n return {\n ...state,\n [action.name]: action.value\n };\n}", "function reducer(state, action) {\n\tswitch (action.type) {\n\t\tcase \"SET_USER\":\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tuser: action.user,\n\t\t\t};\n\t\tcase \"ADD_TO_BASKET\":\n\t\t\t// Logic for adding to basket\n\t\t\treturn { ...state, basket: [...state.basket, action.item] };\n\t\tcase \"REMOVE_FROM_BASKET\":\n\t\t\t// Logic for removing from basket\n\n\t\t\t// we cloned the old basket\n\t\t\tlet newBasket = [...state.basket];\n\n\t\t\t// we check to see if product exists,grab the index of it by going through all the items of the basket and then seeing whether basketItem.id === action.id , if we get -1 means no item matched else item with that id is there\n\t\t\tconst index = state.basket.findIndex(\n\t\t\t\t(basketItem) => basketItem.id === action.id\n\t\t\t);\n\t\t\tif (index >= 0) {\n\t\t\t\t// item exits in basket , remove it by splicing from the last.\n\t\t\t\tnewBasket.splice(index, 1);\n\t\t\t} else {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`Cant remove product (id: ${action.id}) as its not in basket`\n\t\t\t\t);\n\t\t\t}\n\t\t\t// return the new state which carries the old state and the new basket\n\t\t\treturn { ...state, basket: newBasket };\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}", "function counterReducer(state = defaultState, action){\n\n switch (action.type) {\n case counterActions.INCREMENT:{\n return {\n ...state, \n counter : state.counter + 1\n }\n }\n case counterActions.DECREMENT:{\n return {\n ...state,\n counter : state.counter - 1\n }\n }\n case counterActions.ADD :{\n return {\n ...state,\n counter : state.counter + action.value\n }\n }\n case counterActions.SUBTRACT :{\n return {\n ...state,\n counter : state.counter - action.value\n }\n }\n default:\n return state;\n }\n}", "function reduce(arr, func) {\n\n //vzimame purviq element\n let result = arr[0];\n\n //obhojdame ostanalite elementi\n for(let nextElement of arr.splice(1))\n result = func(result, nextElement);\n //prilagame funkciqta kato podavame purviq element i sledvahtiq\n //kato promenqme purviq element, i posle produljavame napred\n\n //vrushtame rezultata\n return result;\n}", "function reducer(state = initialState, action) {\n console.log('reducer', state, action);\n\n switch(action.type) {\n case 'INCREMENT':\n return {\n count: state.count + 1\n };\n case 'DECREMENT':\n return {\n count: state.count - 1\n };\n case 'RESET':\n return {\n count: 0\n };\n default:\n return state;\n }\n}", "reduce(callback, accumulator) {\n for (let i = 0; i < this.arr.length; ++i) {\n accumulator = callback(accumulator, this.arr[i], i);\n }\n\n return accumulator;\n }", "function reduceFilter(fn) {\n return function (mapped, x) {\n if (fn(x)) {\n mapped.push(x);\n }\n return mapped;\n };\n}", "function reducer(event, state) {\n switch (state.current) {\n case 'idle':\n switch (event.type) {\n case 'SHOW':\n return { ...state, current: 'star-rating', init: true, event: event.type }\n default:\n return state\n }\n case 'star-rating':\n switch (event.type) {\n case 'RATE': {\n if (event.payload <= 3) {\n return { ...state, rating: event.payload, current: 'form', event: event.type }\n }\n return { ...state, rating: event.payload, current: 'thanks', event: event.type }\n }\n case 'CLOSE':\n return { ...initialState, event: event.type }\n default:\n return state\n }\n case 'form':\n switch (event.type) {\n case 'SUBMIT':\n return { ...state, text: event.payload, submitting: true, event: event.type }\n case 'FINISH':\n return { ...state, result: event.payload, current: 'thanks', event: event.type }\n case 'CLOSE':\n return { ...initialState, event: event.type }\n default:\n return state\n }\n case 'thanks':\n switch (event.type) {\n case 'CLOSE':\n return { ...initialState, event: event.type }\n default:\n return state\n }\n default:\n return state\n }\n}", "function reducer(state, action) {\n switch (action.type) {\n case 'INC':\n return {...state, counter: state.counter + 1 };\n case 'DEC':\n return Object.assign({}, state, { counter: state.counter - 1 });\n default:\n return state;\n }\n}", "function flatReducer (accumulator, currentValue) {\n // If current value is not an array, concat it to the accumulator.\n // Otherwise, trigger recursive call to steamRollArray\n return accumulator.concat(Array.isArray(currentValue) ? steamrollArray(currentValue) : currentValue);\n }", "function computeNextEntry(reducer, action, state, error) {\n\t if (error) {\n\t return {\n\t state: state,\n\t error: 'Interrupted by an error up the chain'\n\t };\n\t }\n\t\n\t var nextState = state;\n\t var nextError = undefined;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && typeof window.chrome !== 'undefined') {\n\t // In Chrome, rethrowing provides better source map support\n\t setTimeout(function () {\n\t throw err;\n\t });\n\t } else {\n\t console.error(err);\n\t }\n\t }\n\t\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "function combineReducers ($ngReduxProvider,\n productReducer,\n userReducer,\n middlewares) {\n\n console.log(productReducer);\n console.log(userReducer);\n\n var reducers = {\n product: productReducer,\n user: userReducer\n };\n\n var rootReducer = Redux.combineReducers(reducers);\n\n // var actions = userActions();\n // actions.action1();\n // actions.action2();\n\n // $ngReduxProvider.createStoreWith(rootReducer);\n\n $ngReduxProvider.createStoreWith(rootReducer, middlewares);\n }", "function reduce (l, r) {\n l[r] = true\n return l\n }", "reduce (){\n this.hunger -= 2\n this.energy -= 1\n this.hygiene -= 1\n this.fun -= 2\n }", "function reducer() {\n\t var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : resetState;\n\t var action = arguments[1];\n\n\t if (action && action.type === typeToReset) {\n\t return resetState;\n\t } else {\n\t return originalReducer(state, action);\n\t }\n\t }", "function reducer(state, action, fibonaccistate) {\n switch (action.type) {\n case \"increment\":\n return { count: state.count + 1 };\n case \"decrement\":\n return { count: state.count - 1 };\n case \"incrementOdd\":\n return {\n count: state.count % 2 === 1 ? state.count + 2 : state.count + 1,\n };\n case \"incrementFibonacci\":\n return {\n ...fibonaccistate,\n fibonaccicount: fibonacci(state.fibonaccicount.length + 1),\n };\n default:\n return state;\n }\n}", "function computeNextEntry(reducer, action, state, error) {\n\t if (error) {\n\t return {\n\t state: state,\n\t error: 'Interrupted by an error up the chain'\n\t };\n\t }\n\n\t var nextState = state;\n\t var nextError = undefined;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && typeof window.chrome !== 'undefined') {\n\t // In Chrome, rethrowing provides better source map support\n\t setTimeout(function () {\n\t throw err;\n\t });\n\t } else {\n\t console.error(err);\n\t }\n\t }\n\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "function imageUpdateReducer(imageId){\n const match = initialState.allImages[imageId];\n return match;\n }", "function reduce(event, merge, initial, disposable) {\n let output = initial;\n return map(event, e => {\n output = merge(output, e);\n return output;\n }, disposable);\n }", "function mapStateToProps({ usersReducer }) {\n return {};\n}", "function useReducer(){\n const allNums = numbers.reduce((accumulator, value) => accumulator + value)\n\n\n return allNums\n}" ]
[ "0.8031392", "0.73299253", "0.68282187", "0.6596326", "0.6583302", "0.65826577", "0.6521134", "0.6516463", "0.6515308", "0.6285352", "0.6234829", "0.62317985", "0.62311137", "0.61962295", "0.6195356", "0.6192386", "0.6192382", "0.6173222", "0.60710514", "0.60470694", "0.59985924", "0.59980553", "0.5984748", "0.59457827", "0.58976126", "0.5837372", "0.5786813", "0.57843924", "0.57812274", "0.5775075", "0.5765098", "0.5758474", "0.5722297", "0.57088435", "0.56837934", "0.5677476", "0.5658201", "0.5652625", "0.5652605", "0.5650528", "0.563603", "0.56253344", "0.5623346", "0.56194085", "0.56161994", "0.5592693", "0.558347", "0.5580652", "0.5545525", "0.5543431", "0.5520195", "0.55157346", "0.54975057", "0.54784167", "0.54778063", "0.54758596", "0.54754615", "0.54747546", "0.5457081", "0.5442762", "0.5441163", "0.5429702", "0.54221565", "0.5416165", "0.541387", "0.54064476", "0.5391683", "0.5381834", "0.5381205", "0.5380666", "0.5376368", "0.5367132", "0.53508866", "0.53497636", "0.53493726", "0.53407454", "0.53298694", "0.53274137", "0.5320244", "0.5312403", "0.5304102", "0.52986455", "0.5298032", "0.52965015", "0.5291491", "0.52900434", "0.52860576", "0.5284534", "0.52791655", "0.5277146", "0.5271381", "0.52665436", "0.5262998", "0.52573586", "0.5253701", "0.5249667", "0.5248938", "0.52479714", "0.5245956", "0.52430665", "0.52408445" ]
0.0
-1
FUNZIONE CHE CONVERTE LE COORDINATE BROWSER DEL MOUSE ALLE COORDINATE CANVAS
function mouseBrowserToCanvas(canvas, x, y) { //x,y sono le coordinate browser del puntatore del mouse var bbox = canvas.getBoundingClientRect(); return { x: Math.round(x - bbox.left * (canvas.width / bbox.width)), y: Math.round(y - bbox.top * (canvas.height / bbox.height)) }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "mouseDown(pt) {}", "mouseDown(pt) {}", "function click(){\n rect = leinwand.getBoundingClientRect();\n mouseX = event.clientX - rect.left;\n mouseY = event.clientY - rect.top;\n //draw();\n //context.fillStyle();\n context.fillRect(mouseX, mouseY, 40, 40);\n }", "mouseDown(x, y, _isLeftButton) {}", "function onMouseDown(e){\n drawing = true;\n current.x = e.clientX;\n current.y = e.clientY;\n }", "disengage (e){\n this.dragging=false;\n this.ctx.closePath();\n\n\n\n \n \n\n console.log(\"j'aii fini de dessiner\")\n }", "sketchpad_mouseUp() {\n this.mouseDown = 0\n }", "function mousePressed() {y=1}", "function mysketchpad_mouseUp() {\n mouseDown = 0;\n lastX=-1;\n lastY=-1;\n }", "function canvasMouseDown(e) {\n\tblockus.mouseDown();\n}", "onMouseDown(e) {}", "function clickShape() {\n\tidName('shape-layer').style.pointerEvents = 'auto';\n\tclassName('upper-canvas')[0].style.pointerEvents = 'auto';\n\tidName('paint-layer').style.pointerEvents = 'none';\n}", "setPosition(e) {\n\n this.mouseIsDown = true;\n this.ctx.beginPath();\n this.ctx.moveTo(e.offsetX, e.offsetY);\n\n // Ajouter un event pour commencer à dessiner lorsq'on deplace la souris //\n this.carte.signElt.addEventListener('mousemove', (e) => { this.draw(e) });\n\n }", "onMouseMove(event) {\n //Mausposition soll fuer den Canvas(bzw. auch den CanvasDiv berechnet werden)\n event.preventDefault();\n let wrapper = $('#visualizationsCanvasDiv');\n const pos = this.getCanvasRelativePosition(event);\n //in mouse(2d Vektor) wird aktuelle x und y Position der Maus in der Szene gespeichert\n //wert zwischen -1 und 1, wenn auf Canvas und |1|> wenn nicht auf Canvas\n this.mouse.x = (pos.x / wrapper.width()) * 2 - 1;\n this.mouse.y = -(pos.y / wrapper.height()) * 2 + 1;\n //rendert das Bild neu\n if (window.actionDrivenRender)\n this.render();\n }", "clickHandler(event) {\n let p = this.mouse.add(this.cartography._view);\n if (event.shiftKey) {\n this.state.player.data.input.fire = new Vector(p);\n } else {\n this.state.cursor.data.position.set(p);\n this.state.player.data.destination.set(p);\n }\n }", "function mouseClicked() {\n fill('#222222');\n rect(300,300,150,150)\n return false;\n }", "function mousemove() {\n if (isMouseDown) {\n draw();\n }\n}", "function my_mousedown(e)//e is an event which has relation with mousedown\r\n{\r\n //taking color from input box\r\n color = document.getElementById(\"input1\").value;\r\n \r\n \r\n \r\n mouse_x = e.clientX - canvas.offsetLeft;//moves mouse to x coordinate of canvas when clicked\r\n mouse_y = e.clientY - canvas.offsetTop;//moves mouse to y coordinate of canvas when clicked\r\n\r\n \r\n circle(mouse_x , mouse_y); //passing coordinates to circle function \r\n}", "on_mousedown(e, localX, localY) {\n\n }", "handlemouseMove(e) {\n const rect = this.canvas.getBoundingClientRect();\n if (this.flag) {\n this.prevX = this.currX;\n this.prevY = this.currY;\n this.currX = e.clientX - rect.left;\n this.currY = e.clientY - rect.top;\n this.draw(this.template, this.ctx);\n }\n }", "canvasPressed() {\n let rowClicked = floor(this.beatLength * (mouseY - this.yOffset) / this.lineEnd);\n let columnClicked = floor(this.beatLength * (mouseX - this.xOffset) / this.lineEnd);\n\n this.mouseIsDragged = true;\n\n if (this.polyMatrix[rowClicked][columnClicked] === 1) {\n this.lastCellState = 1;\n } else if (this.polyMatrix[rowClicked][columnClicked] === 0) {\n this.lastCellState = 0;\n }\n cnv.mouseReleased = function() {\n this.mouseIsDragged = false;\n }\n\n }", "function canvas_on_mouseover(e) {\r\n canvas.focus(); \r\n}", "function draw() {\n let isClicked = false;\n const cells = document.querySelectorAll('.container-item');\n\n cells.forEach((item) => item.addEventListener('mousedown', () => {\n isClicked = true;\n }));\n\n cells.forEach((item) => item.addEventListener('mousemove', (event) => {\n if (isClicked === true) {\n event.target.style.background = colors[currentColor];\n }\n }));\n\n cells.forEach((item) => item.addEventListener('mouseup', () => {\n isClicked = false;\n }));\n}", "function sketchpad_mouseDown() {\n g_mouseDown = 1;\n drawDot(g_ctx, g_mouseX, g_mouseY, 12);\n}", "function clickCanvas(e){\n if(cerrado == false){\n var eX = e.layerX;\n var eY = e.layerY;\n let circulo = new Circulo(eX, eY, 10, \"0\", \"100%\", 50, false);\n circulo.dibujarCirculo();\n poligono.addCirculo(circulo);\n poligono.trazarLinea(eX, eY);\n console.log(\"Coordenada en x: \" + eX);\n console.log(\"Coordenada en y: \" + eY);\n}\n}", "onMouseDown(coord, event) {\n this.context.fillStyle = colorPicker.colors[0].hexString;\n this.context.strokeStyle = colorPicker.colors[0].hexString;\n this.context.lineJoin = \"round\";\n this.context.lineWidth = $('#pen-width').val();;\n \n this.context.beginPath();\n this.context.moveTo(coord[0], coord[1]);\n this.draw(coord[0], coord[1]);\n }", "function canvasClick(e) {\n\tblockus.mouseClicked();\n}", "onMouseDown(e) {\n this.initX = this.prevX = e.pageX - this.offsetX;\n this.initY = this.prevY = e.pageY - this.offsetY;\n this.canvas.addEventListener(\"mouseup\", this.onUpHandler);\n this.canvas.addEventListener(\"mousemove\", this.onMoveHandler);\n }", "function clickPaint() {\n\tidName('paint-layer').style.pointerEvents = 'auto';\n\tidName('shape-layer').style.pointerEvents = 'none';\n\tclassName('upper-canvas')[0].style.pointerEvents = 'none';\n}", "function mouseClicked(){\n // the x position will take the value of the horizontal mouse position\n xPos=mouseX;\n // the y position will take the value of the vertical mouse position\n yPos = mouseY;\n}", "function dashboardMouseDown( event ) {\n // check this is not chart\n console.info(\"event : \", event);\n console.info(\"pos : \", $(this).position());\n var curpagePos = $(this).position();\n \n if (currentDashboard.checkChartHit((event.clientX - curpagePos.left),(event.clientY - curpagePos.top)))\n {\n return;\n }\n \n if (lasso) {\n lasso = null;\n }\n \n lasso = $('#selectRect')\n .attr(\"ox\",event.clientX)\n .attr(\"oy\",event.clientY)\n .attr(\"x\",event.clientX)\n .attr(\"y\",event.clientY)\n .attr(\"class\",\"lasso\")\n .css('top', event.clientY)\n .css('left', event.clientX)\n .width(0)\n .height(0)\n .show()\n ; \n }", "function move(ev, gl, canvas) {\r\n if (buttonC === true){\r\n var x = ev.clientX; //x coord of mouse\r\n var y = ev.clientY; //y coord of mouse\r\n var z = 0; //z coord of mouse\r\n var rect = ev.target.getBoundingClientRect();\r\n\r\n //translates cooridinates based on canvas size\r\n x = 500*((x - rect.left) - canvas.width/2) / (canvas.width/2);\r\n y = 500*(canvas.height/2 - (y - rect.top)) / (canvas.height/2);\r\n\r\n if (stop === false){\r\n //push coords onto array\r\n points.push(x); points.push(y); points.push(z);\r\n pointColor.push(0.0); pointColor.push(1.0); pointColor.push(0.0);\r\n }\r\n \r\n //draw \r\n drawClicked(gl);\r\n \r\n if (stop === false) {\r\n //pop off last mouse position from array\r\n points.pop(); points.pop(); points.pop();\r\n pointColor.pop(); pointColor.pop(); pointColor.pop(); \r\n }\r\n }\r\n}", "function onMouseDown(e) {\n //Pega a posição\n var pos = getMousePos(canvas, e);\n //Começa o arrastar\n if (gameState == gameStates.ready && !pause && !gameOver) {\n if (!drag) {\n //Tile sob o mouse\n mt = getMouseTile(pos);\n if (mt.valid) {\n var swapped = false;\n if (level.selectedtile.selected) {\n if (canSwap(mt.x, mt.y, level.selectedtile.column, level.selectedtile.row)) {\n //Pode trocar, mova-os\n mouseSwap(mt.x, mt.y, level.selectedtile.column, level.selectedtile.row);\n swapped = true;\n }\n }\n if (!swapped) {\n //Faz o tile selecionado\n level.selectedtile.column = mt.x;\n level.selectedtile.row = mt.y;\n level.selectedtile.selected = true;\n }\n } else {\n //Tile invalido\n level.selectedtile.selected = false;\n }\n //Começa o arrastar\n drag = true;\n }\n }\n //Verificação de clique nos botões\n if (pos.x >= buttons[0].x && pos.x < buttons[0].x + buttons[0].w && pos.y >= buttons[0].y && pos.y < buttons[0].y + buttons[0].h) {\n if (!gameOver && gameState != gameStates.init) {\n pause = !pause;\n }\n }\n if (gameState == gameStates.init) {\n if (pos.x >= buttons[3].x && pos.x < buttons[3].x + buttons[3].w && pos.y >= buttons[3].y && pos.y < buttons[3].y + buttons[3].h) {\n firsTime = false;\n gameState = gameStates.ready;\n }\n }\n if (pause || gameOver) {\n for (var i = 1; i < buttons.length; i++) {\n if (pos.x >= buttons[i].x && pos.x < buttons[i].x + buttons[i].w && pos.y >= buttons[i].y && pos.y < buttons[i].y + buttons[i].h) {\n switch (i) {\n case 1:\n window.cancelAnimationFrame(vari);\n window.score = Math.floor(score / 4);\n if (score > high) localStorage.high = score;\n canvas.removeEventListener(\"mousemove\", onMouseMove);\n canvas.removeEventListener(\"mousedown\", onMouseDown);\n window.nav = 3;\n window.troca = 2;\n break;\n case 2:\n newGame();\n firsTime = true;\n break;\n case 3:\n pause = false;\n break;\n }\n }\n }\n }\n }", "mouseDown(e){\n if(e.button == 0){\n e.stopPropagation();\n e.preventDefault();\n\n this.set('moveStart', true);\n\n const self = this;\n this.set('mouseMoveListener', function(e){\n if(self.mouseMove){\n self.mouseMove(e);\n }\n });\n\n this.set('mouseUpListener', function(e){\n if(self.mouseUp){\n self.mouseUp(e);\n }\n });\n\n document.addEventListener('mousemove', this.get('mouseMoveListener'));\n document.addEventListener('mouseup', this.get('mouseUpListener'));\n }\n }", "function mouseReleased(){\r\n constr.fly();\r\n}", "function cust_MouseDown() {\n\n}", "function mousePressed()\n{\n Dlocx = width*.9;\n animate = !animate;\n}", "function onCanvasMouseDown(event) {\n window.mouseDown = true;\n clickCell(event.pageX, event.pageY);\n}", "mouseDown(event) {\n var button = event.which || event.button;\n this.activeCommands[button] = true;\n }", "mouseDown(event) {\n var button = event.which || event.button;\n this.activeCommands[button] = true;\n }", "function canvasMouseDown(event) {\r\n MOUSE_IS_DOWN = true;\r\n var pos = mousePos(event);\r\n LAST_X = pos[0];\r\n LAST_y = pos[1];\r\n userMove(event, pos[0], pos[1]);\r\n }", "mouseUp(pt) {}", "mouseUp(pt) {}", "function canvas_mouseMove(e) {\n // Update the mouse co-ordinates when moved\n getMousePos(e);\n\n // Draw a dot if the mouse button is currently being pressed\n if (mouseDown==1) {\n drawLine(ctx,mouseX,mouseY,14);\n //neu zum testen\n if(mouseX > bereichDarunter && mouseX < bereichDarueber){\n ctx.clearRect(window.innerWidth/6, 0, window.innerWidth/1.5, window.innerHeight);\n }\n }\n\n}", "function mousePressed() {\n\tx = 40;//Cada vez que pressiona o mouse posicao x recebe o valor\n\ty = 10;//Cada vez que pressiona o mouse posicao y recebe o valor\n}", "function mousedownForCanvas(event)\n{\n global_mouseButtonDown = true;\n event.preventDefault(); //need? (maybe not on desktop)\n}", "function eraserClick(){\n ctx.strokeStyle = \"white\";\n eraser.style.border = \"2px solid red\";\n brush.style.border = \"none\";\n canvas.addEventListener(\"mousedown\",brushDown,false);\n canvas.addEventListener(\"mousemove\",brushMove,false);\n canvas.addEventListener(\"mouseup\",brushUp,false);\n }", "function habilitarEntradas(){\n //evento del movimiento del mouse\n document.addEventListener('mousemove',function(evt){\n raton.x=evt.pageX-canvas.offsetLeft - 6;\n raton.y=evt.pageY-canvas.offsetTop - 28;\n },false);\n\n //evento del click del mouse\n document.addEventListener('mouseup', function(evt){\n ultimaliberacion=evt.which;\n },false);\n //evento del soltar el click del mouse \n canvas.addEventListener('mousedown',function(evt){\n evt.preventDefault();\n ultinaPresion=evt.which;\n },false);\n}", "mouseUp(x, y, _isLeftButton) {}", "function canvas_mouseDown(){\r\n drawing = true;\r\n context.moveTo(event.pageX, event.pageY);\r\n context.beginPath();\r\n}", "function canvasMouseDown(e){\r\n\tif(!e) e = window.event;\r\n\tcanvas.focus();\r\n\tif(useStates){\r\n\t\tStates.current().input.mouseDown(e);\r\n\t}\r\n\tgInput.mouseDown(e);\r\n}", "function OnMouseDown()\n{\n\n\n}", "function click(ev, gl, canvas) {\r\n lastButton = ev.button;\r\n \r\n var x = ev.clientX; //x coord of mouse\r\n var y = ev.clientY; //y coord of mouse\r\n var z = 0; //z coord of mouse\r\n var rect = ev.target.getBoundingClientRect();\r\n\r\n //translates coordinates based on canvas size\r\n x = 500*((x - rect.left) - canvas.width/2) / (canvas.width/2);\r\n y = 500*(canvas.height/2 - (y - rect.top)) / (canvas.height/2);\r\n\r\n disx = x;\r\n disy = y;\r\n \r\n if(!buttonC && lights){\r\n lightsOn(x, y);\r\n }\r\n \r\n if(buttonC === true){\r\n //push coords onto array\r\n polyLine.push(new coord(x, y, z));\r\n points.push(x); points.push(y); points.push(z);\r\n pointColor.push(0.0); pointColor.push(1.0); pointColor.push(0.0);\r\n\r\n //echos clicked points to console\r\n if (lastButton === 0){\r\n console.log('Left click: (',x,',', y,',', z,')');\r\n //draw connecting line\r\n drawClicked(gl); \r\n } else if (lastButton === 2){\r\n console.log('Right click: (',x,',', y,',', z,')');\r\n moveOn; //sets stop to true\r\n buttonC = false;\r\n shape.push(polyLine);\r\n createSOR();\r\n calcVertices();\r\n getSmoothNormz(shape[0].length, shape.length, normFaces, smoothNormz);\r\n getSmoothColors(smoothNormz, smoothColor);\r\n drawSOR(gl);\r\n drawLights(gl);\r\n if (save) {saveFile(new SOR(\"\", vert, ind))};\r\n save = false;\r\n }\r\n }\r\n}", "function onClick(ev) {\n var coords = getCanvasXY(ev);\n var x = coords[0];\n var y = coords[1];\n\n//here is the problem....how do we know we clicked on canvas\n /*var fig=STACK.figures[STACK.figureGetMouseOver(x,y,null)];\n if(CNTRL_PRESSED && fig!=null){\n TEMPORARY_GROUP.addPrimitive();\n STACK.figureRemove(fig);\n STACK.figureAdd(TEMPORARY_GROUP);\n }\n else if(STACK.figureGetMouseOver(x,y,null)!=null){\n TEMPORARY_GROUP.primitives=[];\n TEMPORARY_GROUP.addPrimitive(fig);\n STACK.figureRemove(fig);\n }*/\n//draw();\n}", "function ev_canvas (ev) {\n\n ev._x = ev.pageX - $drawingCanvas.offset().left;\n ev._y = ev.pageY - $drawingCanvas.offset().top;\n\n // Call the event handler of the tool.\n if (undefined !== currentTool) {\n var func = currentTool[ev.type];\n if (func) {\n func(ev);\n }\n }\n }", "function canvasMouseMove(e) {\n\tblockus.setMousePosition(getCursorPosition(e));\n}", "function onCanvasMouseMove(event) {\n if (window.mouseDown) {\n clickCell(event.pageX, event.pageY);\n }\n}", "onIntersectedByMouse(){\n }", "clicked(x, y) {}", "function mouse(kind, pt, id) {\n \n}", "function mouse_down(e) {\n var h = e.pageX - Number($('#can').css('left').replace('px', ''));\n var w = e.pageY - Number($('#can').css('top').replace('px', ''));\n draw = true;\n context.beginPath();\n context.lineWidth = 3;\n context.lineJoin = context.lineCap = 'round';\n context.shadowBlur = 0;\n context.shadowColor = 'rgb(0, 0, 0)';\n context.moveTo(h, w);\n }", "function sketchpad_mouseDown() {\n mouseDown=1;\n drawDot(ctx,mouseX,mouseY,6);\n }", "function sketchpad_mouseMove(e) { \n\n // Update the mouse co-ordinates when moved\n getMousePos(e);\n\n // Draw a dot if the mouse button is currently being pressed\n if (g_mouseDown==1) {\n drawDot(g_ctx, g_mouseX, g_mouseY, 12);\n }\n}", "function canvasClicked() {\r\n setTimeout(canvasClicked, fps / drawParams.two);\r\n n++\r\n\r\n a = n * nltLIB.dtr(divergence);\r\n r = c * Math.sqrt(n);\r\n\r\n x = mouseX + r * Math.cos(a) + canvasWidth / drawParams.two;\r\n y = mouseY + r * Math.sin(a) + canvasHeight / drawParams.two;\r\n }", "function mousePreciona (eventos) \n{\n\t\n\t//guarda la ubicacion el puntero\n\tx = eventos.layerX;\n\ty = eventos.layerY;\n\t\n\testado = EstadoDeEstadoXd();\n\n}", "function onMouseMove(e) {\n console.log(e);\n draw(e);\n}", "handleCanvasClick(e){\n let xpos = 0, ypos = 0;\n if (e.offsetX == undefined){\n xpos = e.pageX-e.target.offsetLeft;\n ypos = e.pageY-e.target.offsetTop;\n }else{\n xpos = e.offsetX;\n ypos = e.offsetY;\n }\n let x = Math.floor(xpos / (e.target.width / this.pattern.width));\n let y = Math.floor(ypos / (e.target.height / this.pattern.width));\n if (e.which == 1){this.drawHandler(x, y, this);}\n if (e.which == 3){this.drawHandlerAlt(x, y, this);}\n }", "mouseMove(x, y) {}", "function select() {\n let xPos = event.offsetX;\n let yPos = event.offsetY;\n player.cards.onHand.forEach(element => {\n if (\n yPos > element.y &&\n yPos < element.y + element.height &&\n xPos > element.x &&\n xPos < element.x + element.width\n ) {\n console.log(\"we got ya\");\n element.selected = true;\n element.degrees = 0;\n console.log(element);\n //than create event listener\n myDom.canvas3.addEventListener(\"mousemove\", getCurPos, false);\n }\n });\n}", "function sketchpad_mouseMove(e) { \n // Update the mouse co-ordinates when moved\n getMousePos(e);\n\n // Draw a dot if the mouse button is currently being pressed\n if (mouseDown==1) {\n drawDot(ctx,mouseX,mouseY,6);\n }\n }", "handlemousedown(e) {\n this.ctx = this.canvas.getContext(\"2d\");\n const rect = this.canvas.getBoundingClientRect();\n this.prevX = this.currX;\n this.prevY = this.currY;\n this.currX = e.clientX - rect.left;\n this.currY = e.clientY - rect.top;\n\n this.flag = true;\n this.dot_flag = true;\n if (this.dot_flag) {\n this.ctx.beginPath();\n this.ctx.fillRect(this.currX, this.currY, 2, 2);\n this.ctx.closePath();\n this.dot_flag = false;\n }\n }", "function handleMouseDown(event) {\n // get the mouse relative to canvas\n oldMouseX = event.layerX;\n oldMouseY = event.layerY;\n mouseDown = true;\n}", "function clickyClick (evt) {\n // get mouse coordinates relative to canvas\n var rect = canv.getBoundingClientRect();\n let x = evt.clientX - rect.left;\n let y = evt.clientY - rect.top;\n \n if (x >= 0 && x <= canvWidth && y >= 0 && y <= canvHeight) {\n \n let cellNumber;\n cellX = x + (cellSize - x % cellSize);\n cellY = y + (cellSize - y % cellSize);\n cellNumber = ((cellX / cellSize) - 1) + (((cellY / cellSize) - 1) * xCells);\n \n switch (input) {\n case 'click':\n singleClick (cellNumber);\n break;\n case 'glider':\n glider(cellNumber);\n break;\n case 'pulsar':\n pulsar(cellNumber);\n break;\n }\n\n fillCanvas();\n\n displayCells();\n }\n}", "_MouseDown(x, y){\n this.mousedown = true;\n this.originX = x;\n this.originY = y;\n }", "function sketchpad_mouseMove(e) { \n // Update the mouse co-ordinates when moved\n getMousePos(e);\n\n // Draw a line if the mouse button is currently being pressed\n if (mouseDown==1) {\n drawLine(ctx, mouseX, mouseY);\n }\n}", "function move (e){\n\t\t\t\t// Determine the mouse position in the canvas (X,Y)\n\t\t\t\tvar mouseX;\n\t\t\t\tvar mouseY;\n\t\t\t\t// if the user is painting\n\t\t\t\tif(paint){\n\t\t\t\t\tmouseX = e.pageX - this.offsetParent.offsetLeft;// - this.offsetLeft;\n\t\t\t\t\tmouseY = e.pageY - this.offsetParent.offsetTop;// - this.offsetTop;\n\t\t\t\t\t// Save the mouse position and redraw the image\n\t\t \t\taddClick(mouseX, mouseY, true);\n\t\t \t\tredraw();\n\t\t \t\t}\n\t\t\t}", "function sketchpad_mouseMove(e) {\n // Update the mouse co-ordinates when moved\n getMousePos(e);\n // checkCoordinates(mouseX,mouseY);\n // Draw a dot if the mouse button is currently being pressed\n if (mouseDown==1) {\n drawDot(ctx,mouseX,mouseY,12);\n }\n}", "function doMousedown(e){\n\t\tdragging = true;\n\t\tlet mouse = getMouse(e);\n\t\tctx.beginPath();\n\t\tctx.moveTo(mouse.x, mouse.y);\n\t\t\n\t\t//points\n\t\tcurrentLayer.push(mouse);\n\t\tallPoints.push(currentLayer);\n\t}", "onMouseDown(coord, event) {\n if (this.mouseUp == true) {\n \n this.startX = [];\n this.startY = [];\n this.contextReal.moveTo(coord[0], coord[1])\n this.contextReal.beginPath();\n this.mouseUp = false;\n }\n }", "function mouseDown(mousePos) {\n\t}", "function mouseDown(mousePos) {\n\t}", "function canvas_mouseDown() {\n mouseDown=1;\n drawLine(ctx,mouseX,mouseY,12);\n\n}", "function onMouseMove( event ) {\n\t\tif (isMouseDown)\n\t\t{\n\t\t\tvar canvasSize = 200;\n\t\t\t\n\t\t\tmouseX = event.clientX-(window.innerWidth-spinMenuRight-canvasSize);\n\t\t\tmouseY = event.clientY-spinMenuTop;\n\t\t\t\n\t\t\tcanvX = mouseX/canvasSize*2-1;\n\t\t\tcanvY = 1-mouseY/canvasSize*2;\n\t\t\t\n\t\t\t\n\t\t\tif (pressedO) {\n\t\t\t\tif (!selectedXZ) \n\t\t\t\t{\n\t\t\t\t\tdirVecXZ = new THREE.Vector(1,0,0);\n\t\t\t\t\tangleX = 0;\n\t\t\t\t}\n\t\t\t\tremoveArrows();\n\t\t\t\tif (dirVecXZ.getComponent(0) > 0)\n\t\t\t\t\tdirVecXY = new THREE.Vector3(-canvX, canvY,0);\n\t\t\t\telse\n\t\t\t\t\tdirVecXY = new THREE.Vector3(canvX, canvY,0);\n\t\t\t\tdirVecXY.applyAxisAngle(new THREE.Vector3(0,1,0), angleX);\n\t\t\t\tdirVecXY.normalize();\n\t\t\t\tarrowSpinXY = new THREE.ArrowHelper(dirVecXY, new THREE.Vector3(0,0,0),2, 0x29A3CC,3.5,0.5);\n\t\t\t\tscene.add(arrowSpinXY);\n\t\t\t\tselectedXY = true;\n\t\t\t\tdirVec.set(dirVecXY.getComponent(0),dirVecXY.getComponent(1),dirVecXY.getComponent(2))\n\t\t\t} else {\n\t\t\t\tremoveArrows();\n\t\t\t\tif (selectedXY){\n\t\t\t\t\tvar X = -canvX;\n\t\t\t\t\tvar Y = dirVecXY.getComponent(1);\n\t\t\t\t\tvar Z;\n\t\t\t\t\tif (canvY < 0)\n\t\t\t\t\t\tZ = Math.sqrt(1-X*X-Y*Y);\n\t\t\t\t\telse\n\t\t\t\t\t\tZ = -Math.sqrt(1-X*X-Y*Y);\n\t\t\t\t\tdirVecXZ = new THREE.Vector3(X, Y, Z);\n\t\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t\tdirVecXZ = new THREE.Vector3(-canvX,0, canvY);\n\t\t\t\tdirVecXZ.normalize();\n\t\t\t\tarrowSpinXZ = new THREE.ArrowHelper(dirVecXZ, new THREE.Vector3(0,0,0),2, 0x29A3CC,3.5,0.5);\n\t\t\t\t\n\t\t\t\tscene.add(arrowSpinXZ);\n\t\t\t\tselectedXZ = true;\n\t\t\t\tdirVec.set(dirVecXZ.getComponent(0),dirVecXZ.getComponent(1),dirVecXZ.getComponent(2));\n\t\t\t}\n\t\t}\n\t\tif (selectedXY || selectedXZ || selectedForm)\n\t\t\tsetMenu(dirVec.getComponent(0),dirVec.getComponent(1),dirVec.getComponent(2));\n\t\t\tangularVelocity[0]=dirVec.x;\n\t\t\tangularVelocity[1]=dirVec.y;\n\t\t\tangularVelocity[2]=dirVec.z;\n\t\t\t//console.log(dirVec.getComponent(0)+\",\"+dirVec.getComponent(1)+\",\"+dirVec.getComponent(2));\n\t}", "function initDraw(canvass) {\n \n // setMousePosition: (e) => void\n // e: mouse event\n // Adjusts the cursor position\n function setMousePosition(e) {\n var ev = e || window.event; //Moz || IE\n if (ev.pageX) { //Moz\n mouse.x = ev.pageX + window.pageXOffset;\n mouse.y = ev.pageY + window.pageYOffset;\n } else if (ev.clientX) { //IE\n mouse.x = ev.clientX + document.body.scrollLeft;\n mouse.y = ev.clientY + document.body.scrollTop;\n }\n };\n\n var mouse = {\n x: 0,\n y: 0,\n startX: 0,\n startY: 0\n };\n var element = null;\n var initialOffset = 0\n\n canvass.onmousemove = function (e) {\n setMousePosition(e);\n if (element !== null) {\n element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';\n element.style.height = Math.abs(mouse.y - window.pageYOffset + initialOffset - mouse.startY) + 'px';\n element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';\n element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y - window.pageYOffset + 'px' : mouse.startY - initialOffset + 'px';\n }\n }\n\n canvass.onclick = function (e) {\n if (element !== null) {\n element = null;\n canvass.style.cursor = \"default\";\n boxes = [mouse.x/canvas.width * 100, (mouse.y - window.pageYOffset)/canvas.height * 100, mouse.startX/canvas.width * 100, (mouse.startY - initialOffset)/canvas.height * 100];\n console.log(boxes);\n } else {\n mouse.startX = mouse.x;\n mouse.startY = mouse.y;\n initialOffset = window.pageYOffset;\n element = document.createElement('div');\n element.className = 'rectangle';\n element.style.left = mouse.x + 'px';\n element.style.top = (mouse.y - window.pageYOffset) + 'px';\n if(canvass.firstChild){\n canvass.removeChild(canvass.firstChild);\n }\n canvass.appendChild(element)\n canvass.style.cursor = \"crosshair\";\n }\n }\n}", "function canvasMouseDownEv(event) {\n this.camera_move = false; //\n\n if (this.active_region && this.last_active_annotation !== this.active_region) this.last_active_annotation = this.active_region; // Context menu\n\n if (event.which === 3 && (this.active_row || this.active_region) && this.canvasIsToolActive(this.scale_move_tool)) this.activateContextMenu();else this.deactivateContextMenu(); //\n\n if (!this.active_region && !this.active_row) return; //\n\n var canvasMousePosition = new paper.Point(event.offsetX, event.offsetY);\n var viewPosition = this.scope.view.viewToProject(canvasMousePosition);\n var checks = [];\n if (this.active_region && this.left_alt_active) checks.push({\n path: this.active_region.view.path,\n segm_type: 'region_path'\n });else if (this.active_row && this.left_control_active) {\n checks.push({\n path: this.active_row.view.baseline.baseline_path,\n segm_type: 'baseline_path',\n baseline: this.active_row.view.baseline\n });\n checks.push({\n path: this.active_row.view.baseline.baseline_left_path,\n segm_type: 'left_path',\n baseline: this.active_row.view.baseline\n });\n checks.push({\n path: this.active_row.view.baseline.baseline_right_path,\n segm_type: 'right_path',\n baseline: this.active_row.view.baseline\n });\n } //\n\n var min_dist = 200;\n\n for (var _i2 = 0, _checks = checks; _i2 < _checks.length; _i2++) {\n var check = _checks[_i2];\n\n var _iterator = _createForOfIteratorHelper(check.path.segments),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var segment = _step.value;\n var dist = pointDistance(viewPosition, segment.point);\n\n if (dist < min_dist) {\n min_dist = dist;\n this.last_baseline = check.baseline;\n this.last_segm = segment;\n this.last_segm_type = check.segm_type;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n}", "function sketchpad_mouseDown() {\n mouseDown=1;\n drawDot(ctx,mouseX,mouseY,1);\n}", "function mouseDownCanvas() {\n \n var mouseCoords = d3.mouse(this);\n\n var x = mouseCoords[0] - network.display.width / 2.0;\n var y = mouseCoords[1] - network.display.height / 2.0;\n \n mouseDownPos.down = true;\n mouseDownPos.x = x;\n mouseDownPos.y = y;\n mouseDownPos.angle = (Math.atan2(y, x) * 180.0/Math.PI) % 360;\n\n d3.event.preventDefault();\n }", "function mouseClicked() {\n \n rect(Math.floor(Math.floor(mouseX) / scale), Math.floor(Math.floor(mouseY) / scale), scale, scale);\n fill(51);\n}", "function sketchpad_mouseDown () {\n mouseDown = 1\n drawDot(mouseX, mouseY, 8, r, g, b, a)\n \n connection.invoke('UpdateCanvas', mouseX, mouseY, r, g, b, a).catch(function (err) {\n return console.error(err.toString())\n })\n}", "function onMouseDown(event) { }", "function doMouseDown(evt) {\n if (evt.button != 0) {\n return; // don't respond unless the button is the main (left) mouse button.\n }\n var canvas = document.getElementById(\"glcanvas\");\n var r = canvas.getBoundingClientRect();\n var x,y;\n x = Math.round(evt.clientX - r.left); // translate mouse position from screen coords to canvas coords.\n y = Math.round(evt.clientY - r.top); // round to integer values; some browsers would give non-integers.\n\n personMove(x,y);\n}", "mouseMove(prev, pt) {}", "function mousePressed() {\r\n mouseIsDown = true;\r\n}", "function sketchpad_mouseMove(e) {\n // Update the mouse co-ordinates when moved\n getMousePos(e);\n\n // Draw a dot if the mouse button is currently being pressed\n if (mouseDown==1) {\n drawDot(ctx,mouseX,mouseY,1);\n }\n}", "function OnMouseDown(){\n\tif(Input.GetKey( KeyCode.J )){ // Are you also pressing the \"j\" key while clicking\n\t\tLeanTween.dispatchEvent(MyEvents.JUMP);\n\t}else{\n\t\tLeanTween.dispatchEvent(MyEvents.CHANGE_COLOR, transform); // with every dispatched event, you can include an object (retrieve this object with the *.data var in LTEvent)\n\t}\n}", "mousedown_handler(e) {\n const local = this.getLocalCoords(this.mainCanvas, e);\n this.mouseDown = true;\n\n this.scratchLine(local.x, local.y, true);\n\n e.preventDefault();\n return false;\n }", "function myMouseDown(ev) {\n //==============================================================================\n // Called when user PRESSES down any mouse button;\n // \t\t\t\t\t\t\t\t\t(Which button? console.log('ev.button='+ev.button); )\n // \t\tev.clientX, ev.clientY == mouse pointer location, but measured in webpage \n //\t\tpixels: left-handed coords; UPPER left origin; Y increases DOWNWARDS (!) \n \n // Create right-handed 'pixel' coords with origin at WebGL canvas LOWER left;\n var rect = ev.target.getBoundingClientRect();\t// get canvas corners in pixels\n var xp = ev.clientX - rect.left;\t\t\t\t\t\t\t\t\t// x==0 at canvas left edge\n var yp = g_canvas.height - (ev.clientY - rect.top);\t// y==0 at canvas bottom edge\n // console.log('myMouseDown(pixel coords): xp,yp=\\t',xp,',\\t',yp);\n \n // Convert to Canonical View Volume (CVV) coordinates too:\n var x = (xp - g_canvas.width/2) / \t\t// move origin to center of canvas and\n (g_canvas.width/2);\t\t\t// normalize canvas to -1 <= x < +1,\n var y = (yp - g_canvas.height/2) /\t\t//\t\t\t\t\t\t\t\t\t\t -1 <= y < +1.\n (g_canvas.height/2);\n \t// console.log('myMouseDown(CVV coords ): x, y=\\t',x,',\\t',y);\n \n g_isDrag = true;\t\t\t\t\t\t\t\t\t\t\t// set our mouse-dragging flag\n g_xMclik = x;\t\t\t\t\t\t\t\t\t\t\t\t\t// record where mouse-dragging began\n g_yMclik = y;\n // report on webpage\n document.getElementById('MouseAtResult').innerHTML = \n 'Mouse At: '+x.toFixed(5)+', '+y.toFixed(5);\n \n}", "mousedownHandler(event) {\n\n // Set mouse state\n if (this._state === this.STATE.NONE) {\n this._state = event.button;\n }\n\n this._moveCurr = this.getMouseLocation(event.pageX, event.pageY);\n\n this._canvas.addEventListener('mousemove', this.mousemove);\n this._canvas.addEventListener('mouseup', this.mouseup);\n }", "onMouseDown (e) {\n this.isMouseDown = true;\n\n this.emit('mouse-down', {x: e.offsetX, y: e.offsetY});\n }", "function dibujoMouse(evento)\n{\n estado = true;//paso1: la variable estado cambia a true\n xinic = evento.offsetX;//paso1: le asigna la posicion donde se dio el click en x\n yinic = evento.offsetY;//paso1: le asigna la posicion donde se dio el click en y\n // console.log(\"clientX \"+evento.clientX+\" clientY \"+evento.clientY); \n // console.log(\"layerX \"+evento.layerX+\" layerY \"+evento.layerY); \n // console.log(\"offsetX \"+evento.offsetX+\" offsetY \"+evento.offsetY); \n // console.log(\"pageX \"+evento.pageX+\" pageY \"+evento.pageY); \n // console.log(\"screenX \"+evento.screenX+\" screenY \"+evento.screenY); \n // console.log(\"x \"+evento.x+\" y \"+evento.y); \n // console.log(\"--------------------------\"); \n}", "function mouseDown(event) {\n mouseClicked = true;\n startPoint = new Point(event.offsetX, event.offsetY);\n var figure = getIntersectedFigure();\n\n if (ButtonState === CANVAS_STATE.SELECTED) {//? da se iznesyt\n unselectAllFigure();\n currentFigure = undefined;\n selectedFigure = undefined;\n selectFigure();\n\n }\n\n if (ButtonState === CANVAS_STATE.SELECTED && figure === false) {\n unselectAllFigure();\n }\n}" ]
[ "0.68491703", "0.68491703", "0.68264055", "0.68190515", "0.67626137", "0.6726853", "0.66449887", "0.6611337", "0.6606188", "0.6588052", "0.6565388", "0.65525806", "0.6547862", "0.6529904", "0.6520954", "0.6498423", "0.6492553", "0.64751375", "0.6472459", "0.6459162", "0.64505553", "0.6443337", "0.644206", "0.6438428", "0.64280695", "0.6418893", "0.6412913", "0.64121014", "0.63775986", "0.6369746", "0.63637197", "0.63513196", "0.63433033", "0.6336258", "0.6332302", "0.63219553", "0.63141906", "0.6311508", "0.63075966", "0.63075966", "0.6306643", "0.6303153", "0.6303153", "0.6301771", "0.62899214", "0.6285278", "0.6281723", "0.62810135", "0.62790424", "0.62775534", "0.6276349", "0.6272523", "0.6271092", "0.6267106", "0.62584937", "0.6256159", "0.6246987", "0.6245235", "0.62451583", "0.62423533", "0.6242092", "0.6239271", "0.62386656", "0.6237304", "0.62365806", "0.623548", "0.623167", "0.62303025", "0.6227891", "0.6224149", "0.62122464", "0.62058306", "0.6203921", "0.62031466", "0.61998653", "0.61936754", "0.61935437", "0.61910975", "0.61882126", "0.61865485", "0.61865485", "0.6178222", "0.6175077", "0.6173767", "0.61608624", "0.61603075", "0.6158223", "0.61519104", "0.615164", "0.6151014", "0.6146691", "0.61453825", "0.61448425", "0.6142668", "0.6142025", "0.6141519", "0.61307305", "0.61303246", "0.61242425", "0.6123668", "0.61235464" ]
0.0
-1
====================== GESTIONE DEI CLICK/TOUCH SULLE DUE CANVAS "GAMEPAD" ======================
function doMouseUp(e){ if(e.srcElement.id == "touchCanvas1"){ clicked1 = false; ctxTouchCanvas1.clearRect(0, 0, ctxTouchCanvas1.canvas.width, ctxTouchCanvas1.canvas.height); ctxTouchCanvas1.drawImage(cursorImg, -5, -5, 200, 200); cameraInteraction.moveForward = false; cameraInteraction.moveBackward = false; cameraInteraction.moveRight = false; cameraInteraction.moveLeft = false; key[0] = false; key[1] = false; key[2] = false; key[3] = false; } else{ clicked2 = false; ctxTouchCanvas2.clearRect(0, 0, ctxTouchCanvas2.canvas.width, ctxTouchCanvas2.canvas.height); ctxTouchCanvas2.drawImage(cursorImg, -5, -5, 200, 200); cameraInteraction.rotateUp = false; cameraInteraction.rotateDown = false; cameraInteraction.rotateRight = false; cameraInteraction.rotateLeft = false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function onTouchStart(ev) {\n onClickCanvas(ev, true);\n}", "function mouseClickedOnCanvas() {\n game.click = true;\n}", "function onClick( event ) {\n event.preventDefault();\n \n mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;\n mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;\n \n raycaster = new THREE.Raycaster();\n \n raycaster.setFromCamera( mouse, camera );\n \n intersects = raycaster.intersectObjects(pads);\n \n if (intersects.length > 0) {\n \n padPressed((intersects[0].object.name.substring(3)) - 1);\n \n window.setTimeout(function() {\n padUnpressed(intersects[0]);\n }, 100);\n } else {\n intersects = null;\n }\n }", "handleClick() {\n this.canvas.addEventListener('mousedown', event => {\n if (!this.paused) {\n this.collisionTest(event);\n }\n });\n }", "function handleCanvasClick(_event) {\n if (_event.shiftKey || _event.altKey) {\n getPlayer(_event);\n }\n else if (Soccer.animation == false) {\n shootBall(_event);\n }\n }", "function CALCULATE_TOUCH_OR_CLICK(){\r\n\r\n\r\n \r\n// \tvar KLIKER = new KLIKER_POINT(GLOBAL_CLICK.x,GLOBAL_CLICK.y);\r\n \r\n\t\r\n // for rect\r\n for (var x=0; x<GLOBAL_CONTAINER.length ; x++)\r\n {\r\n\r\n if ( GLOBAL_CLICK.x > GLOBAL_CONTAINER[x].X && GLOBAL_CLICK.x < GLOBAL_CONTAINER[x].X + GLOBAL_CONTAINER[x].W && GLOBAL_CLICK.y > GLOBAL_CONTAINER[x].Y && GLOBAL_CLICK.y < GLOBAL_CONTAINER[x].Y + GLOBAL_CONTAINER[x].H ) {\r\n GLOBAL_CONTAINER[x].EVENTS();\r\n \r\n }\r\n \r\n }\r\n \r\n \r\n\r\n//###########################################\r\n// CLICK ON PLAYER ACTION \r\n//###########################################\r\n //alert(GET_DISTANCE_FROM_PLAYER.VALUE());\r\n //if (GET_DISTANCE_FROM_PLAYER.VALUE() < PLAYER.RADIUS) {\r\n //console.log(\"PLAYER TOUCHED\");\r\n //VOICE.SPEAK(\"Your Energy level is \" + PLAYER.RADIUS.toFixed(2) + \" radius\");\r\n //}\r\n \r\n\r\n for (var x=0;x<BUTTONS.length;x++){\r\n if ( GLOBAL_CLICK.x > BUTTONS[x].POSITION.x && GLOBAL_CLICK.x <BUTTONS[x].POSITION.x + BUTTONS[x].DIMENSIONS.W() && GLOBAL_CLICK.y > BUTTONS[x].POSITION.y && GLOBAL_CLICK.y < BUTTONS[x].POSITION.y + BUTTONS[x].DIMENSIONS.H() ) {\r\n BUTTONS[x].TAP()\r\n }\r\n else {\r\n \r\n }\r\n } \r\n \r\n \r\n \r\n //0000000000000000\r\n //0000000000000000\r\n \r\n if (typeof window[\"JFT_FS\"] ==='undefined') {\r\n window[\"JFT_FS\"] = 0;\r\n //launchIntoFullscreen(document.documentElement);\r\n \r\n }\r\n \r\n \r\n }", "function click_gameopts()\n{\n var fast_btn = spr[sn_btn_fastgame];\n var pt = fast_btn.globalToLocal(stage.mouseX, stage.mouseY);\n if (Math.abs(pt.x) < sz(70) && Math.abs(pt.y) < sz(20)) {\n fast_play.value = !fast_play.value;\n stage.update();\n }\n}", "function init(){\nvar canvas=document.getElementById(\"board\");\ncanvas.width=document.body.clientWidth;\ncanvas.height=document.body.clientHeight;\ncw=canvas.width;\nch=canvas.height;\ncon=canvas.getContext(\"2d\");\ncon.fillStyle=\"#dddddd\"//\"#fffaf0\"//\"#efdfbb\";\ncon.fillRect(0,0,cw,ch);\nif(\"ontouchstart\" in window)\ncanvas.addEventListener(\"touchstart\", touchHandler, false);\nelse\ncanvas.addEventListener(\"mousedown\", touchHandler1, false);\n\n//play button\nplay=Object.create(entity);\nplay.ini(pla, con,0,0,100,100,0,0,100,100);\nplay.calWithRatio(\"width\",20);\nplay.x1=cw/2-play.w1/2;\nplay.y1=ch/2-play.h1/2;\nplay.draw();\n\n//help button\nhelp=Object.create(entity);\nhelp.ini(helps, con,0,0,100,100,0,0,100,100);\nhelp.calWithRatio(\"width\",20);\nhelp.x1=cw/2-play.w1/2;\nhelp.y1=play.y1 + play.h1 + 3/100 *ch;\nhelp.draw();\n\n//help button\nsna=Object.create(entity);\nsna.ini(snake, con,0,0,100,100,0,0,100,100);\nsna.calWithRatio(\"width\",40);\nsna.x1=cw/2-sna.w1/2;\nsna.y1=play.y1 -sna.h1 -3/100 *ch;\nsna.draw();\n\n\n}", "[pointerDown](e) {\n if (isTouch(e)) {\n this.show();\n }\n }", "function addKeyboardEvents(){\n\t// Arrow keys and WASD both work for input\n\tdocument.addEventListener(\"keydown\", function(e){\n\t\tswitch(e.keyCode){\n\t\t\t// Up\n\t\t\tcase 87:\n\t\t\tcase 38:\n\t\t\t\tgs.player.isPressingUp = true;\n\t\t\t\tbreak;\n\t\t\t// Down\n\t\t\tcase 83:\n\t\t\tcase 40:\n\t\t\t\tgs.player.isPressingDown = true;\n\t\t\t\tbreak;\n\t\t\t// Left\n\t\t\tcase 65:\n\t\t\tcase 37:\n\t\t\t\tgs.player.isPressingLeft = true;\n\t\t\t\tbreak;\n\t\t\t// Right\n\t\t\tcase 68:\n\t\t\tcase 39:\n\t\t\t\tgs.player.isPressingRight = true;\n\t\t\t\tbreak;\n\t\t\t// E\n\t\t\tcase 69:\n\t\t\t\tif (wm.gameMode === \"Scavenge\"){\n\t\t\t\t\tgs.enterBuilding();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t// I\n\t\t\tcase 73:\n\t\t\t\tif (wm.gameMode === \"Scavenge\"){\n\t\t\t\t\twm.gameMode = \"Inventory\";\n\t\t\t\t} else if (wm.gameMode === \"Inventory\"){\n\t\t\t\t\twm.gameMode = \"Scavenge\";\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}, false);\n\tdocument.addEventListener(\"keyup\", function(e){\n\t\tswitch(e.keyCode){\n\t\t\t// Up\n\t\t\tcase 87:\n\t\t\tcase 38:\n\t\t\t\tgs.player.isPressingUp = false;\n\t\t\t\tbreak;\n\t\t\t// Down\n\t\t\tcase 83:\n\t\t\tcase 40:\n\t\t\t\tgs.player.isPressingDown = false;\n\t\t\t\tbreak;\n\t\t\t// Left\n\t\t\tcase 65:\n\t\t\tcase 37:\n\t\t\t\tgs.player.isPressingLeft = false;\n\t\t\t\tbreak;\n\t\t\t// Right\n\t\t\tcase 68:\n\t\t\tcase 39:\n\t\t\t\tgs.player.isPressingRight = false;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t}, false);\n\n\t$(\"canvas\")[0].addEventListener(\"click\", function(e){\n\t\tif (wm.gameMode === \"Base\" || \n\t\t\t\twm.gameMode === \"Upgrade\" ||\n\t\t\t\twm.gameMode === \"Dialog\"){\n\t\t\twm.handleMousePress($(\"#canvas\")[0].getContext(\"2d\"), new Coord(e.clientX, e.clientY));\n\t\t}\n\t}, false);\n}", "function mousePressed() { \n \n mousePress = true;\n if (mode == 0) {\n startGame = true;\n }\n \n//Detection if the click was within the menu rectangle\n if (mode == 2 && mouseX > width/2 - 75 && \n mouseX < width/2 + 75 &&\n mouseY > 461 &&\n mouseY < 499) {\n startGame = true;\n }\n}", "function mouseClicked(e) {\n mouseX = e.pageX - canvasBg.offsetLeft;\n mouseY = e.pageY - canvasBg.offsetTop;\n if (isPlaying!=true) {\n if (btnPlay.checkClicked())\n playGame();\n //setTimeout(function(){playGame()},1000);\n }\n }", "sketchpad_mouseUp() {\n this.mouseDown = 0\n }", "click(btn) {\r\n\r\n canvas.addEventListener(\"click\",\r\n function buttonClick(e) {\r\n \r\n let x = fix_X(e.clientX);\r\n let y = fix_Y(e.clientY);\r\n \r\n // Check for collision.\r\n if (x >= btn.x - btn.w / 2 & x <= btn.x + btn.w / 2) {\r\n if (y >= btn.y - btn.h / 2 & y <= btn.y + btn.h / 2) {\r\n btn.action();\r\n canvas.removeEventListener(\"click\", buttonClick);\r\n }\r\n \r\n }\r\n });\r\n }", "function mysketchpad_mouseUp() {\n mouseDown = 0;\n lastX=-1;\n lastY=-1;\n }", "startTouching() {\n var that = this;\n //touch screen event\n this.canvas.addEventListener(\"touchstart\", function(e) {\n //we need to get exact position of canvas on page to get position of touch\n var rect = that.canvas.getBoundingClientRect();\n var touchX = e.touches[0].clientX - rect.left;\n var touchY = e.touches[0].clientY - rect.top;\n document.getElementById(\"station-confirmer-btn\").style.display = \"initial\";\n document.getElementById(\"canvas\").style.borderColor = \"#5CB85C\";\n //switch on\n that.test = true;\n that.context.beginPath();\n that.context.moveTo(touchX, touchY);\n //call by event to touch move methode\n that.canvas.addEventListener(\"touchmove\", that.draw.bind(that));\n });\n //event of stop touching screen\n this.canvas.addEventListener(\"touchend\", function() {\n //swich off\n that.test = false;\n });\n }", "control(){\n document.addEventListener(\"mousemove\", (e) => {\n this.mouse_x = e.clientX;\n this.mouse_y = e.clientY;\n })\n\n document.addEventListener(\"touchmove\", (e) => {\n this.mouse_x = e.touches[0].clientX+30; //Ajuste para a nave ficar a frente do dedo\n this.mouse_y = e.touches[0].clientY;\n })\n\n document.addEventListener(\"click\", (e) => {\n if(e.button == 0){\n this.shotFire();\n }\n })\n\n document.addEventListener(\"touchstart\", (e) => {\n this.shotFire();\n })\n }", "function sketchpad_mouseUp () {\n mouseDown = 0\n}", "function onClick(event) {\n var pos = new vec2d(event.clientX, event.clientY);\n var coords = \"X coords: \" + pos.x + \", Y coords: \" + pos.y;\n document.getElementById(\"demo\").innerHTML = coords;\n\t//var bleep = new Audio();\n //bleep.src = \"dustyroom_multimedia_positve_correct_complete_ping.mp3\";\n if (!Buttons.map && pos.dist(new vec2d(center_w - 240, center_h + 260)) < 40) {\n \tButtons.map = true;\n \tButtons.engi = false;\n \tunactivate_butts(ctx);\n \tdraw_map_butt(ctx, true);\n\t //bleep.play();\n }\n else if (!Buttons.engi && center_w-350<pos.x && pos.x<center_w-300 && center_h+213<pos.y && pos.y<center_h+300) {\n \tButtons.engi = true;\n \tButtons.map = false;\n \tunactivate_butts(ctx);\n \tdraw_engi_butt(ctx, true);\n\t //bleep.play();\n }\n}", "function KEYBOARD(c){var L=this;L.CAPTURE_CHAR=\"\";L.LAST_CAPTURE_CHAR=\"\";L.ACTION_ON_KEY_DOWN=function(){};this.CANVAS=c;this.PROGRAM_NAME=c.id;c.addEventListener(\"\\x6B\\x65\\x79\\x64\\x6F\\x77\\x6E\",function(e){switch(e.keyCode){case 8:e.preventDefault();SYS.DEBUG.LOG(\"\\x70\\x72\\x65\\x76\\x65\\x6E\\x74\\x20\\x64\\x65\\x66\\x61\\x75\\x6C\\x74\\x20\\x66\\x6F\\x72\\x20\\x62\\x61\\x63\\x6B\\x73\\x70\\x61\\x63\\x65\\x2E\");;};SYS.DEBUG.LOG(\"\\x20\\x47\\x41\\x4D\\x45\\x20\\x52\\x55\\x4E\\x4E\\x49\\x4E\\x47\\x20\\x2C\\x20\\x6B\\x65\\x79\\x20\\x70\\x72\\x65\\x73\\x73\\x65\\x64\\x3A\\x20\"+e.keyCode);if( typeof PLAYER!=\"\\x75\\x6E\\x64\\x65\\x66\\x69\\x6E\\x65\\x64\"){if(PLAYER.TYPE==\"\\x50\\x4C\\x41\\x54\\x46\\x4F\\x52\\x4D\\x45\\x52\"){PLAYER.FREEZ=false;switch(e.keyCode){case 121:SYS.DEBUG.LOG(\"\\x46\\x31\\x30\\x20\\x63\\x6F\\x6D\\x6D\\x61\\x6E\\x64\\x20\\x2D\\x2D\\x3E\\x3E\\x20\\x53\\x68\\x6F\\x77\\x20\\x63\\x6F\\x6D\\x6D\\x61\\x6E\\x64\\x20\\x6C\\x69\\x6E\\x65\\x20\");;case 69:;case 37:PLAYER.CONTROL.LEFT=true;PLAYER.X=PLAYER.SPEED;if(PLAYER.CONTROL.JUMP===false){setTimeout(function(){PLAYER.POSITION.TRANSLATE_BY_Y(100)},50)};break ;;case 38:if(PLAYER.CONTROL.JUMP===false){PLAYER.BREAK_AT_MOMENT_STATUS=false;PLAYER.CONTROL.JUMP=true;PLAYER.Y=PLAYER.SPEED*10;console.log(\"\\x3E\\x3E\\x3E\\x3E\\x3E\\x3E\\x3E\"+PLAYER.Y);setTimeout(function(){while(PLAYER.Y>0){PLAYER.Y=PLAYER.Y-PLAYER.SPEED/5};PLAYER.Y= -1;},100);};break ;;case 39:PLAYER.CONTROL.RIGHT=true;PLAYER.X=-PLAYER.SPEED;if(PLAYER.CONTROL.JUMP===false){setTimeout(function(){PLAYER.POSITION.TRANSLATE_BY_Y(100)},50)};break ;;case 40:break ;;};}else {if(PLAYER.TYPE==\"\\x4E\\x4F\\x52\\x4D\\x41\\x4C\"){switch(e.keyCode){case 121:SYS.DEBUG.LOG(\"\\x46\\x31\\x30\\x20\\x63\\x6F\\x6D\\x6D\\x61\\x6E\\x64\\x20\\x2D\\x2D\\x3E\\x3E\\x20\\x53\\x68\\x6F\\x77\\x20\\x63\\x6F\\x6D\\x6D\\x61\\x6E\\x64\\x20\\x6C\\x69\\x6E\\x65\\x20\");;case 69:;case 37:PLAYER.X=PLAYER.X-PLAYER.SPEED;PLAYER.POSITION.TRANSLATE_BY_X(PLAYER.X);break ;;case 38:PLAYER.Y=PLAYER.Y-PLAYER.SPEED;PLAYER.POSITION.TRANSLATE_BY_Y(PLAYER.Y);break ;;case 39:PLAYER.X=PLAYER.X+PLAYER.SPEED;PLAYER.POSITION.TRANSLATE_BY_X(PLAYER.X);break ;;case 40:PLAYER.Y=PLAYER.Y+PLAYER.SPEED;PLAYER.POSITION.TRANSLATE_BY_Y(PLAYER.Y);break ;;}}}};SYS.DEBUG.LOG(\"\\x4B\\x45\\x59\\x42\\x4F\\x41\\x52\\x44\\x2D\\x2D\\x3E\\x3E\\x20\\x53\\x68\\x6F\\x77\\x20\\x75\\x73\\x65\\x72\\x73\\x20\\x74\\x79\\x70\\x65\\x73\\x20\\x3A\\x20\"+e.keyCode);var M;if(window.event){M=e.keyCode}else {if(e.which){M=e.which}};if(e.keyCode==8){SYS.DEBUG.LOG(\"\\x74\\x65\\x78\\x74\\x62\\x6F\\x78\\x20\\x64\\x65\\x6C\\x65\\x74\\x65\\x20\\x6C\\x61\\x73\\x74\\x20\\x63\\x68\\x61\\x72\\x21\");L.CAPTURE_CHAR=remove_last(L.CAPTURE_CHAR);}else {L.CAPTURE_CHAR+=(String.fromCharCode(M));L.LAST_CAPTURE_CHAR=(String.fromCharCode(M));};L.ACTION_ON_KEY_DOWN();if( typeof L.TARGET_MODUL!=\"\\x75\\x6E\\x64\\x65\\x66\\x69\\x6E\\x65\\x64\"&& typeof L.TARGET!=\"\\x75\\x6E\\x64\\x65\\x66\\x69\\x6E\\x65\\x64\"){window[L.PROGRAM_NAME].ENGINE.MODULES.ACCESS(L.TARGET_MODUL).GAME_OBJECTS.ACCESS(L.TARGET).TEXTBOX.TEXT=L.CAPTURE_CHAR};},false);c.addEventListener(\"\\x6B\\x65\\x79\\x75\\x70\",function(e){SYS.DEBUG.LOG(\"\\x20\\x47\\x41\\x4D\\x45\\x20\\x52\\x55\\x4E\\x4E\\x49\\x4E\\x47\\x20\\x2C\\x20\\x6B\\x65\\x79\\x20\\x75\\x70\\x20\\x3A\\x20\"+e.keyCode);if( typeof PLAYER!=\"\\x75\\x6E\\x64\\x65\\x66\\x69\\x6E\\x65\\x64\"){if(PLAYER.TYPE==\"\\x50\\x4C\\x41\\x54\\x46\\x4F\\x52\\x4D\\x45\\x52\"){switch(e.keyCode){case 121:SYS.DEBUG.LOG(\"\\x46\\x31\\x30\\x20\\x63\\x6F\\x6D\\x6D\\x61\\x6E\\x64\\x20\\x2D\\x2D\\x3E\\x3E\\x20\\x53\\x68\\x6F\\x77\\x20\\x63\\x6F\\x6D\\x6D\\x61\\x6E\\x64\\x20\\x6C\\x69\\x6E\\x65\\x20\");;case 69:;case 37:PLAYER.CONTROL.LEFT=false;while(PLAYER.X>0){PLAYER.X=PLAYER.X-PLAYER.SPEED/5};PLAYER.X=0;break ;;case 38:while(PLAYER.Y>0){PLAYER.Y=PLAYER.Y-PLAYER.SPEED/5};break ;;case 39:PLAYER.CONTROL.LEFT=false;while(PLAYER.X<0){PLAYER.X=PLAYER.X+PLAYER.SPEED/5};PLAYER.X=0;break ;;case 40:break ;;}}else {if(PLAYER.TYPE==\"\\x4E\\x4F\\x52\\x4D\\x41\\x4C\"){switch(e.keyCode){case 121:SYS.DEBUG.LOG(\"\\x46\\x31\\x30\\x20\\x63\\x6F\\x6D\\x6D\\x61\\x6E\\x64\\x20\\x2D\\x2D\\x3E\\x3E\\x20\\x53\\x68\\x6F\\x77\\x20\\x63\\x6F\\x6D\\x6D\\x61\\x6E\\x64\\x20\\x6C\\x69\\x6E\\x65\\x20\");;case 69:;case 37:PLAYER.X=PLAYER.X-PLAYER.SPEED;PLAYER.POSITION.TRANSLATE_BY_X(PLAYER.X);break ;;case 38:PLAYER.Y=PLAYER.Y-PLAYER.SPEED;PLAYER.POSITION.TRANSLATE_BY_Y(PLAYER.Y);break ;;case 39:PLAYER.X=PLAYER.X+PLAYER.SPEED;PLAYER.POSITION.TRANSLATE_BY_X(PLAYER.X);break ;;case 40:PLAYER.Y=PLAYER.Y+PLAYER.SPEED;PLAYER.POSITION.TRANSLATE_BY_Y(PLAYER.Y);break ;;}}}};},false);}", "function init() {\n //On récupère le canvas\n canvas = document.querySelector(\"#Pong\");\n\n //On récupère la largeur et la hauteur du canvas\n largeurCanvas = canvas.width;\n hauteurCanvas = canvas.height;\n\n //Récupération du contexte\n ctx = canvas.getContext('2d');\n ctx.font = \"150px Calibri,Geneva,Arial\";\n\n //On crée les objets du jeu\n raquetteJ1 = new Raquette(10, hauteurCanvas / 2 - 100, 15, 120, 20, 20, couleurJ1);\n raquetteJ2 = new Raquette(largeurCanvas - 30, hauteurCanvas / 2 - 100, 15, 120, 20, 20, couleurJ2);\n balle = new Balle(largeurCanvas / 2, hauteurCanvas / 2, 8, 0, 0, 0, couleurBalle);\n\n //On capte les déplacements clavier des joueurs\n window.addEventListener('keydown', function (event) {\n switch (event.keyCode) {\n //Controle du joueur 1 : Touches Z et S\n case 90: //Z\n touches.hautJ1 = true;\n break;\n case 83: //S \n touches.basJ1 = true;\n break;\n //Controle du joueur 2 : Touches Haut et Bas\n case 38: //Haut\n touches.hautJ2 = true;\n break;\n case 40: //Bas\n touches.basJ2 = true;\n break;\n }\n }, false);\n\n window.addEventListener('keyup', function (event) {\n switch (event.keyCode) {\n //Controle du joueur 1 : Touches Z et S\n case 90: //Z\n touches.hautJ1 = false;\n break;\n case 83: //S \n touches.basJ1 = false;\n break;\n //Controle du joueur 2 : Touches Haut et Bas\n case 38: //Haut\n touches.hautJ2 = false;\n break;\n case 40: //Bas\n touches.basJ2 = false;\n break;\n }\n }, false);\n\n //On capte le click droit de la souris qui signale le début de la partie\n canvas.addEventListener('click', function () {\n if (balle.vitesseX === 0 && balle.vitesseY === 0) {\n balle.vitesseX = balle.vitesseY = 20;\n }\n }, false);\n\n //On capte la touche espace qui marque le lancement de la balle\n window.addEventListener('keydown', function (event) {\n if (balle.vitesseX === 0 && balle.vitesseY === 0) {\n switch (event.keyCode) {\n case 13:\n case 32:\n balle.vitesseX = balle.vitesseY = 20;\n break;\n }\n }\n\n }, false);\n\n //Déplacement de la balle\n dessinerJeu(deltaBalleX);\n dplctRaquette();\n }", "function clickOnGameButton(event)\n{\n // Hier coderen we alles wat moet worden gedaan zodra een speler op de game button clicked\n // @TODO: Click event van de game button programmeren. Wat moet er allemaal gebeuren na een klik?\n}", "function sketchpad_mouseUp() {\n mouseDown=0;\n}", "function sketchpad_mouseUp() {\n mouseDown=0;\n}", "function sketchpad_mouseUp() {\n mouseDown=0;\n}", "function main(){\n canvas = document.getElementById('myCanvas');\n\n width = window.innerWidth;\n height = window.innerHeight;\n \n if(!mobilecheck()){\n type = \"click\"; \n width = 375;\n height = 667;\n }\n \n document.addEventListener( type, onpress, false);\n \n canvas.width = width;\n canvas.height = height;\n\n ctx = canvas.getContext(\"2d\");\n\n currentstate = states.Start;\n\n var img = new Image();\n img.onload = function() {\n initSprites(this);\n initBtns();\n run();\n };\n img.src = \"sheet.png\";\n \n flap = new Audio(\"flap.mp3\"); \n point = new Audio(\"point.mp3\"); \n fail = new Audio(\"fail.mp3\"); \n}", "function handleTouch(e) {\n var touch = {\n x: e.touches[0].pageX - ctx.canvas.offsetParent.offsetLeft - ctx.canvas.offsetLeft,\n y: e.touches[0].pageY - ctx.canvas.offsetParent.offsetTop - ctx.canvas.offsetTop - 70\n };\n var move;\n\n if (touch.x < game.player.x &&\n touch.y > game.player.y &&\n touch.y < game.player.y + CONST.PLAYER.MASK.y) {\n move = 'left';\n } else if (touch.y < game.player.y &&\n touch.x > game.player.x &&\n touch.x < game.player.x + CONST.PLAYER.MASK.x) {\n move = 'up';\n } else if (touch.x > game.player.x + CONST.PLAYER.MASK.x &&\n touch.y > game.player.y &&\n touch.y < game.player.y + CONST.PLAYER.MASK.y) {\n move = 'right';\n } else if (touch.y > game.player.y + CONST.PLAYER.MASK.y &&\n touch.x > game.player.x &&\n touch.x < game.player.x + CONST.PLAYER.MASK.x) {\n move = 'down';\n }\n\n /* condition needed to detect button click on the Restart button */\n if (!game.gameOver && move !== undefined){\n e.preventDefault();\n }\n\n game.player.handleInput(move);\n}", "function onPress(e){\n\t\tconsole.log(e);\n\t\tif(e.keyCode == 37){\n\n\t\t\tvx =- 3;\n\t\t}\n\t\tif(e.keyCode == 38){\n\n\n\t\t\tvy =- 3;\n\t\t}\n\t\tif(e.keyCode == 39){\n\n\n\t\t\tvx = 3;\n\t\t}\n\t\tif(e.keyCode == 40){\n\n\n\t\t\tvy = 3;\n\t\t}\n\n\n\t}", "static touchControl(e) {\n // stop default behavior\n // e.preventDefault();\n e = e || window.event;\n // get accurate x,y values\n let a = Game.canvas.getBoundingClientRect();\n const x = e.touches[0].pageX - a.left;\n const y = e.touches[0].pageY - a.top;\n //! detect event type\n let status = (e.type == 'touchstart') ? true : false;\n\n //? EVENTS\n if (status) { //* touchstart\n Game.startX = x;\n Game.startY = y;\n } else { //* touchmove\n //? get walk \n Game.walkX = x - Game.startX;\n Game.walkY = y - Game.startY;\n\n // swipe left\n if (Game.walkX < 0 && Game.jump == false) {\n bird.dy -= 30;\n bird.dx -= 10;\n Game.jump = true;\n }\n // swipe right\n if (Game.walkX > 0 && Game.jump == false) {\n bird.dy -= 30;\n bird.dx += 10;\n Game.jump = true;\n }\n\n // gravity\n bird.dy += 0.5;\n // move bird\n bird.x += bird.dx;\n bird.y += bird.dy;\n // elasticity\n bird.dx *= 0.9;\n bird.dy *= 0.9;\n\n //! detect walls\n // bottom\n if (bird.y > Game.height - ground.h - bird.h) {\n Game.jump = false;\n bird.y = Game.height - ground.h - bird.h;\n bird.dy = 0;\n }\n // left\n if (bird.x < 0) {\n bird.x = 0;\n bird.dx = 0;\n } else if (bird.x > Game.width - bird.w) { // right\n bird.x = Game.width - bird.w;\n bird.dx = 0;\n }\n\n }\n\n }", "click(btn) {\r\n\r\n canvas.addEventListener(\"click\",\r\n function buttonClick(e) {\r\n\r\n let x = fix_X(e.clientX);\r\n let y = fix_Y(e.clientY);\r\n\r\n // Check for collision.\r\n if (x >= btn.x - btn.w / 2 & x <= btn.x + btn.w / 2) {\r\n if (y >= btn.y - btn.h / 2 & y <= btn.y + btn.h / 2) {\r\n btn.click_extra();\r\n btn.action();\r\n }\r\n\r\n }\r\n });\r\n }", "canvasClick() {\n\t\tthis.bird.jumpBird();\n\t}", "function keyPressed(e)\n{\n\tconsole.log(\"keyPressed()\");\n\tvar key = e.keyCode ? e.keyCode : e.which;\n\n\tif ((key == \"97\" || key == \"65\") && app.tileEnabled[0])\n\t{ \n\t\tconsole.log(\"A KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[0]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[0]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"98\" || key == \"66\") && app.tileEnabled[1]) \n\t{\n\t\tconsole.log(\"B KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[1]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[1]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"99\" || key == \"67\") && app.tileEnabled[2]) \n\t{\n\t\tconsole.log(\"C KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[2]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[2]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"100\" || key == \"68\") && app.tileEnabled[3]) \n\t{\n\t\tconsole.log(\"D KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[3]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[3]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"101\" || key == \"69\") && app.tileEnabled[4]) \n\t{\n\t\tconsole.log(\"E KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[4]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[4]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"102\" || key == \"70\") && app.tileEnabled[5]) \n\t{\n\t\tconsole.log(\"F KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[5]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[5]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"103\" || key == \"71\") && app.tileEnabled[6]) \n\t{\n\t\tconsole.log(\"G KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[6]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[6]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"104\" || key == \"72\") && app.tileEnabled[7]) \n\t{\n\t\tconsole.log(\"H KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[7]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[7]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"105\" || key == \"73\") && app.tileEnabled[8]) \n\t{\n\t\tconsole.log(\"I KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[8]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[8]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"106\" || key == \"74\") && app.tileEnabled[9]) \n\t{\n\t\tconsole.log(\"J KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[9]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[9]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"107\" || key == \"75\") && app.tileEnabled[10]) \n\t{\n\t\tconsole.log(\"K KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[10]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[10]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"108\" || key == \"76\") && app.tileEnabled[11]) \n\t{\n\t\tconsole.log(\"L KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[11]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[11]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"109\" || key == \"77\") && app.tileEnabled[12]) \n\t{\n\t\tconsole.log(\"M KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[12]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[12]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"110\" || key == \"78\") && app.tileEnabled[13]) \n\t{\n\t\tconsole.log(\"N KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[13]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[13]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"111\" || key == \"79\") && app.tileEnabled[14]) \n\t{\n\t\tconsole.log(\"O KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[14]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[14]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n\telse if ((key == \"112\" || key == \"80\") && app.tileEnabled[15]) \n\t{\n\t\tconsole.log(\"P KEY PRESSED\");\n\t\tif(app.numClick == 1)\n\t\t{\n\t\t\tfirstClick(app.coverImgArr[15]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.firstCover.id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsecondClick(app.coverImgArr[15]);\n\t\t\tconsole.log(\"\tcover clicked: \"+app.secondCover.id);\n\t\t}\n\t}\n}", "function main() {\n\t// create canvas and set width/height\n\tcanvas = document.createElement(\"canvas\");\n\n\twidth = window.innerWidth;\n\theight = window.innerHeight;\n\n\tvar evt = \"touchstart\";\n\tif (width >= 500) {\n\t\twidth = 320;\n\t\theight = 480;\n\t\tcanvas.style.border = \"1px solid #000\";\n\t\tevt = \"mousedown\";\n\t}\n\n\t// listen for input event\n\tdocument.addEventListener(evt, onpress);\n\n\tcanvas.width = width;\n\tcanvas.height = height;\n\tif (!(!!canvas.getContext && canvas.getContext(\"2d\"))) {\n\t\talert(\"Your browser doesn't support HTML5, please update to latest version\");\n\t}\n\tctx = canvas.getContext(\"2d\");\n\tcurrentstate = states.Splash;\n\t// append canvas to document\n\tdocument.body.appendChild(canvas);\n\n\t// initate graphics and okbtn\n\tvar img = new Image();\n\timg.onload = function() {\n\t\tinitSprites(this);\n\t\tctx.fillStyle =\"blue\";\n\t\tokbtn = {\n\t\t\tx: (width - s_buttons.Ok.width)/2,\n\t\t\ty: height - 200,\n\t\t\twidth: s_buttons.Ok.width,\n\t\t\theight: s_buttons.Ok.height\n\t\t}\n\t\trun();\n\t}\n\timg.src = \"res/sheet.png\";\n\n}", "externalClick() {\n this._strikeClick();\n this._localPointer.x = this.getPointer().x;\n this._localPointer.y = this.getPointer().y;\n }", "function CALCULATE_TOUCH_DOWN_OR_MOUSE_DOWN() {\r\n \r\nif (GLOBAL_CLICK.CLICK_TYPE == \"right_button\") {\r\n \r\nfor (var x=0;x<HOLDER.length;x++){\r\n \r\n\tif (GET_DISTANCE_FROM_OBJECT.VALUE(x) < HOLDER[x].FI ) {\r\n\t\r\n\tHOLDER[x].FOKUS('R');\r\n HOLDER[x].SHOW_MENU();\r\n GLOBAL_CLICK.CLICK_PRESSED = true;\r\n \r\n E(\"NAME_OF_SELECTED\").value = HOLDER[x].NAME;\r\n E(\"NAME_OF_SELECTED\").dataset.index_ = x;\r\n \r\n VOICE.SPEAK(\"Object \" + HOLDER[x].NAME + \" SELECTED . \");\r\n \r\n }else {\r\n HOLDER[x].HIDE_MENU(x);\r\n }\r\n \r\n}\r\n/////////////\r\n//right\r\n//////////// \r\n}\r\nelse if (GLOBAL_CLICK.CLICK_TYPE == \"left_button\"){\r\n\r\nfor (var x=0;x<HOLDER.length;x++){\r\n if (GET_DISTANCE_FROM_OBJECT.VALUE(x) < HOLDER[x].FI ) {\r\n \r\n\t\r\n\tHOLDER[x].FOKUS('L');\r\n\t HOLDER[x].SHOW_MENU('L');\r\n HOLDER[x].SELECTED = true;\r\n \r\n \r\n \r\n \r\n GLOBAL_CLICK.CLICK_PRESSED = true;\r\n \r\n \r\n \r\n E(\"NAME_OF_SELECTED\").value = HOLDER[x].NAME;\r\n E(\"NAME_OF_SELECTED\").dataset.index_ = x;\r\n \r\n //VOICE.SPEAK(\"Object \" + HOLDER[x].NAME + \" SELECTED . \");\r\n \r\n }else {\r\n \r\n HOLDER[x].HIDE_MENU(x);\r\n \r\n \r\n }\r\n }\r\n}\r\n \r\n\r\n\r\n\r\n\r\n }", "onButtonDown() {\n\t\tif(!character.isClicked) {\n\t\t\tcharacter.sprite.y -= 100;\n\t\t\tcharacter.isClicked = true;\n\t\t\tsetup();\n\t\t}\n\t}", "function draw_one_frame()\n{\n var gamepads=null;\n if(port1 != 'none' && port1 !='keys' && port1 !='touch')\n {\n gamepads = navigator.getGamepads(); \n var joy1= gamepads[port1];\n \n if(timestampjoy1 != joy1.timestamp)\n {\n timestampjoy1 = joy1.timestamp;\n handleGamePad('1', joy1);\n }\n }\n if(port2 != 'none' && port2 !='keys' && port2 !='touch')\n {\n if(gamepads==null)\n {\n gamepads = navigator.getGamepads(); \n }\n var joy2= gamepads[port2];\n \n if(timestampjoy2 != joy2.timestamp)\n {\n timestampjoy2 = joy2.timestamp;\n handleGamePad('2', joy2);\n }\n }\n if(port1 == 'touch')\n {\n handle_touch(\"1\");\n }\n else if(port2 == 'touch')\n {\n handle_touch(\"2\");\n }\t\n}", "function sketchpad_mouseUp() {\n mouseDown=0;\n }", "function mousePressed() {\n // Only look for mouse presses during the actual test\n if (draw_finger_arm) {\n // Check if mouse click happened within the touch input area\n if (\n mouseClickWithin(\n width / 2 - 2.0 * PPCM,\n height / 2 - 1.0 * PPCM,\n 4.0 * PPCM,\n 3.0 * PPCM\n )\n ) {\n // Check if mouse click was on left arrow (2D keyboard)\n //if (mouseClickWithin(width/2 - ARROW_SIZE, height/2, ARROW_SIZE, ARROW_SIZE))\n //{\n //current_letter = getPreviousChar(current_letter);\n //if (current_letter.charCodeAt(0) < '_'.charCodeAt(0)) current_letter = 'z'; // wrap around to z\n //}\n //// Check if mouse click was on right arrow (2D keyboard)\n //else if (mouseClickWithin(width/2, height/2, ARROW_SIZE, ARROW_SIZE))\n //{\n //current_letter = getNextChar(current_letter);\n //if (current_letter.charCodeAt(0) > 'z'.charCodeAt(0)) current_letter = '_'; // wrap back to space (i.e., the underscore)\n //}\n //else\n //{\n //// Click in whitespace indicates a character input (2D keyboard)\n //if (current_letter == '_') currently_typed += \" \"; // if underscore, consider that a space bar\n //else if (current_letter == '`' && currently_typed.length > 0) // if `, treat that as delete\n //currently_typed = currently_typed.substring(0, currently_typed.length - 1);\n //else if (current_letter != '`') currently_typed += current_letter; // if not any of the above cases, add the current letter to the entered phrase\n //}\n\n if (mouseClickWithin(BASE_WIDTH, BASE_HEIGHT, BT_WIDTH, BT_HEIGHT))\n buttonPressed(0);\n else if (\n mouseClickWithin(\n BASE_WIDTH + BT_WIDTH,\n BASE_HEIGHT,\n BT_WIDTH,\n BT_HEIGHT\n )\n )\n buttonPressed(1);\n else if (\n mouseClickWithin(\n BASE_WIDTH + 2 * BT_WIDTH,\n BASE_HEIGHT,\n BT_WIDTH,\n BT_HEIGHT\n )\n )\n buttonPressed(2);\n else if (\n mouseClickWithin(\n BASE_WIDTH,\n BASE_HEIGHT + BT_HEIGHT,\n BT_WIDTH,\n BT_HEIGHT\n )\n )\n buttonPressed(3);\n else if (\n mouseClickWithin(\n BASE_WIDTH + BT_WIDTH,\n BASE_HEIGHT + BT_HEIGHT,\n BT_WIDTH,\n BT_HEIGHT\n )\n )\n buttonPressed(4);\n else if (\n mouseClickWithin(\n BASE_WIDTH + 2 * BT_WIDTH,\n BASE_HEIGHT + BT_HEIGHT,\n BT_WIDTH,\n BT_HEIGHT\n )\n )\n buttonPressed(5);\n else if (\n mouseClickWithin(\n BASE_WIDTH,\n BASE_HEIGHT + 2 * BT_HEIGHT,\n BT_WIDTH,\n BT_HEIGHT\n )\n )\n buttonPressed(6);\n else if (\n mouseClickWithin(\n BASE_WIDTH + BT_WIDTH,\n BASE_HEIGHT + 2 * BT_HEIGHT,\n BT_WIDTH,\n BT_HEIGHT\n )\n )\n buttonPressed(7);\n else if (\n mouseClickWithin(\n BASE_WIDTH + 2 * BT_WIDTH,\n BASE_HEIGHT + 2 * BT_HEIGHT,\n BT_WIDTH,\n BT_HEIGHT\n )\n )\n buttonPressed(8);\n else if (\n mouseClickWithin(\n width / 2 - 2.0 * PPCM,\n height / 2 - 1.0 * PPCM,\n (4.0 * PPCM) / 3,\n 0.592 * PPCM\n )\n )\n wordPressed(0);\n else if (\n mouseClickWithin(\n width / 2 - (2.0 * PPCM) / 3,\n height / 2 - 1.0 * PPCM,\n (4.0 * PPCM) / 3,\n 0.592 * PPCM\n )\n )\n wordPressed(1);\n else if (\n mouseClickWithin(\n width / 2 + (2.0 * PPCM) / 3,\n height / 2 - 1.0 * PPCM,\n (4.0 * PPCM) / 3,\n 0.592 * PPCM\n )\n )\n wordPressed(2);\n }\n\n // Check if mouse click happened within 'ACCEPT'\n // (i.e., submits a phrase and completes a trial)\n else if (\n mouseClickWithin(\n width / 2 - 2 * PPCM,\n height / 2 - 5.1 * PPCM,\n 4.0 * PPCM,\n 2.0 * PPCM\n )\n ) {\n // Saves metrics for the current trial\n letters_expected += target_phrase.trim().length;\n letters_entered += currently_typed.trim().length;\n errors += computeLevenshteinDistance(\n currently_typed.trim(),\n target_phrase.trim()\n );\n entered[current_trial] = currently_typed;\n trial_end_time = millis();\n\n current_trial++;\n\n // Check if the user has one more trial/phrase to go\n if (current_trial < 2) {\n // Prepares for new trial\n currently_typed = \"\";\n target_phrase = phrases[current_trial];\n } else {\n // The user has completed both phrases for one attempt\n draw_finger_arm = false;\n attempt_end_time = millis();\n\n printAndSavePerformance(); // prints the user's results on-screen and sends these to the DB\n attempt++;\n\n // Check if the user is about to start their second attempt\n if (attempt < 2) {\n second_attempt_button = createButton(\"START 2ND ATTEMPT\");\n second_attempt_button.mouseReleased(startSecondAttempt);\n second_attempt_button.position(\n width / 2 - second_attempt_button.size().width / 2,\n height / 2 + 200\n );\n }\n }\n }\n }\n}", "addEvents() {\n var self = this;\n\n this.canvas.oncontextmenu = function () { return false; };\n\n this.canvas.addEventListener(\"touchstart\", onTouchStart);\n\n /**\n * @param {Event} evt\n * @private\n */\n function onTouchStart(evt) {\n // remove the focus of the controls\n window.focus();\n document.activeElement.blur();\n\n self.click = 1;\n self.evaluator.setVariable(self.id + \".mouse_pressed\", 1);\n\n // deactivate the graphic controls\n self.parent.deactivateGraphicControls();\n\n self.posAnte = descartesJS.getCursorPosition(evt, self.container);\n self.oldMouse.x = self.getRelativeX(self.posAnte.x);\n self.oldMouse.y = self.getRelativeY(self.posAnte.y);\n\n onSensitiveToMouseMovements(evt);\n\n window.addEventListener(\"touchmove\", onMouseMove);\n window.addEventListener(\"touchend\", onTouchEnd);\n\n // if ((!self.fixed) || (self.sensitive_to_mouse_movements)) {\n evt.preventDefault();\n // }\n }\n\n /**\n *\n * @param {Event} evt\n * @private\n */\n function onTouchEnd(evt) {\n // remove the focus of the controls\n window.focus();\n document.activeElement.blur();\n\n self.click = 0;\n self.evaluator.setVariable(self.id + \".mouse_pressed\", 0);\n\n window.removeEventListener(\"touchmove\", onMouseMove, false);\n window.removeEventListener(\"touchend\", onTouchEnd, false);\n\n evt.preventDefault();\n\n self.parent.update();\n }\n\n ///////////////////////////////////////////////////////////////////////////\n //\n ///////////////////////////////////////////////////////////////////////////\n this.canvas.addEventListener(\"mousedown\", onMouseDown);\n\n /**\n *\n * @param {Event} evt\n * @private\n */\n function onMouseDown(evt) {\n // remove the focus of the controls\n document.body.focus();\n\n self.click = 1;\n\n // deactivate the graphic controls\n self.parent.deactivateGraphicControls();\n\n self.whichBtn = descartesJS.whichBtn(evt);\n\n if (self.whichBtn === \"R\") {\n window.addEventListener(\"mouseup\", onMouseUp);\n\n self.posObserver = (descartesJS.getCursorPosition(evt, self.container)).x;\n self.posObserverNew = self.posObserver;\n\n self.posZoom = (descartesJS.getCursorPosition(evt, self.container)).y;\n self.posZoomNew = self.posZoom;\n\n // if fixed add a zoom manager\n if (!self.fixed) {\n self.tempScale = self.scale;\n self.tempObserver = self.observer;\n window.addEventListener(\"mousemove\", onMouseMoveZoom);\n }\n }\n\n else if (self.whichBtn == \"L\") {\n self.evaluator.setVariable(self.id + \".mouse_pressed\", 1);\n\n self.posAnte = descartesJS.getCursorPosition(evt, self.container);\n self.oldMouse.x = self.getRelativeX(self.posAnte.x);\n self.oldMouse.y = self.getRelativeY(self.posAnte.y);\n\n onSensitiveToMouseMovements(evt);\n\n window.addEventListener(\"mousemove\", onMouseMove);\n window.addEventListener(\"mouseup\", onMouseUp);\n }\n\n evt.preventDefault();\n }\n\n /**\n *\n * @param {Event} evt\n * @private\n */\n function onMouseUp(evt) {\n // remove the focus of the controls\n document.body.focus();\n\n self.click = 0;\n self.evaluator.setVariable(self.id + \".mouse_pressed\", 0);\n evt.preventDefault();\n\n if (self.whichBtn === \"R\") {\n window.removeEventListener(\"mousemove\", onMouseMoveZoom, false);\n\n // show the external space\n if ((self.posZoom == self.posZoomNew) && (descartesJS.showConfig)) {\n self.parent.externalSpace.show();\n }\n }\n\n window.removeEventListener(\"mousemove\", onMouseMove, false);\n window.removeEventListener(\"mouseup\", onMouseUp, false);\n\n self.parent.update();\n }\n\n /**\n *\n * @param {Event} evt\n * @private\n */\n function onSensitiveToMouseMovements(evt) {\n self.posAnte = descartesJS.getCursorPosition(evt, self.container);\n self.mouse_x = self.getRelativeX(self.posAnte.x);\n self.mouse_y = self.getRelativeY(self.posAnte.y);\n self.evaluator.setVariable(self.id + \".mouse_x\", self.mouse_x);\n self.evaluator.setVariable(self.id + \".mouse_y\", self.mouse_y);\n\n // limit the number of updates in the lesson\n self.parent.update();\n }\n\n /**\n *\n * @param {Event} evt\n * @private\n */\n function onMouseMoveZoom(evt) {\n evt.preventDefault();\n\n self.posZoomNew = (descartesJS.getCursorPosition(evt, self.container)).y;\n self.evaluator.setVariable(self.scaleStr, self.tempScale + (self.tempScale/45)*((self.posZoom-self.posZoomNew)/10));\n\n self.posObserverNew = (descartesJS.getCursorPosition(evt, self.container)).x;\n self.evaluator.setVariable(self.obsStr, self.tempObserver - (self.posObserver-self.posObserverNew)*2.5);\n\n self.parent.update();\n }\n\n this.disp = {x: 0, y: 0};\n\n /**\n *\n * @param {Event} evt\n * @private\n */\n function onMouseMove(evt) {\n if ((!self.fixed) && (self.click)) {\n dispX = (self.getAbsoluteX(self.oldMouse.x) - self.getAbsoluteX(self.mouse_x))/4;\n dispY = (-self.getAbsoluteY(self.oldMouse.y) + self.getAbsoluteY(self.mouse_y))/4;\n\n if ((dispX !== self.disp.x) || (dispY !== self.disp.y)) {\n self.alpha = descartesJS.degToRad( self.evaluator.getVariable(self.rotZStr));\n self.beta = descartesJS.degToRad(-self.evaluator.getVariable(self.rotYStr));\n\n self.alpha = descartesJS.radToDeg(self.alpha) - dispX;\n self.beta = descartesJS.radToDeg(self.beta) - dispY;\n\n // set the value to the rotation variables\n self.evaluator.setVariable(self.rotZStr, self.alpha);\n self.evaluator.setVariable(self.rotYStr, -self.beta);\n\n self.disp.x = dispX;\n self.disp.y = dispY;\n\n self.oldMouse.x = self.getRelativeX(self.posAnte.x);\n self.oldMouse.y = self.getRelativeY(self.posAnte.y);\n }\n\n onSensitiveToMouseMovements(evt);\n\n evt.preventDefault();\n }\n }\n\n document.addEventListener(\"visibilitychange\", function(evt) {\n onMouseUp(evt);\n });\n\n document.addEventListener(\"mouseleave\", function(evt) {\n onMouseUp(evt);\n });\n }", "function winScreenButtonClick (e) {\n\t\tlet getMousePos = function (canvas, evt) {\n var rect = canvas.getBoundingClientRect();\n return {\n x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,\n y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height\n };\n\t\t}\n\n\t\tlet pos = getMousePos(canvas, e);\n if (pos.x > WIDTH/2 - 100 && pos.x < WIDTH/2 + 100 && pos.y > HEIGHT*2/3 - 30 && pos.y < HEIGHT*2/3 + 20) {\n \t\tscores = [0, 0]\n\t \twindow.removeEventListener(\"mousedown\", winScreenButtonClick, false)\n \t\tmain();\n }\n}", "function fullScreenClick(){\r\n if (game.scale.isFullScreen)\r\n {\r\n game.scale.stopFullScreen();\r\n }\r\n else\r\n {\r\n game.scale.startFullScreen(false);\r\n }\r\n}", "function touchstart(e) {\n\tx_finger_bak = e.changedTouches[0].screenX\n\ty_finger_bak = e.changedTouches[0].screenY\n\tshow_ctrl(true)\n\treturn false\n}", "function onBoardClick() {\n if (!hasStarted) {\n startGame();\n } else {\n startPause();\n }\n }", "function draw() {\n if (GAMEMODE == \"MENU\") {\n //draw the backgroud\n background(45, 40, 60);\n strokeWeight(1);\n stroke(0);\n //draw the game logo\n (() => {\n fill(200);\n textSize(height * width * 0.00015);\n text('GONKA', (width / 2) - textWidth('GONKA') / 2, height / 3);\n })();\n //draw the play btn\n (() => {\n let [w, h] = [width * 0.2, height * 0.1];\n let [x, y] = [(width / 2) - w / 2, (height / 2)];\n push();\n if (!(mouseX >= x && mouseX <= x + w && mouseY >= y && mouseY <= y + h)) {\n noStroke();\n rect(x, y, w, h, 20);\n fill(45, 40, 60);\n rect(x + 5, y + 5, w - 10, h - 10, 20);\n fill(220);\n textSize(h * 0.5);\n text('PLAY', x + (w / 2) - textWidth('PLAY') / 2, y + (h / 2) + textSize() / 3);\n } else {\n noStroke();\n rect(x, y, w, h, 20);\n fill(220);\n rect(x + 5, y + 5, w - 10, h - 10, 20);\n fill(230, 20, 20);\n fill(45, 40, 60);\n textSize(h - 10);\n text('PLAY', x + (w / 2) - textWidth('PLAY') / 2, y + (h / 2) + textSize() / 3);\n }\n pop();\n })();\n //draw the credits of the game\n (() => {\n let credits = 'Coded by Stiliyan Kushev.\\nSprites, animations and soundtrack by Vencislav Nikolov';\n textSize(10);\n text(credits, 0, height - textSize() * 2);\n })();\n //draw the links buttons with the credits\n (() => {\n let scl = 50;\n let offset = 10;\n let x = width - scl / 2 - offset;\n let y = height - scl / 2 - offset;\n let w = textWidth('f');\n let h = textSize();\n if (mouseX >= x - scl / 2 && mouseX <= x + scl / 2 && mouseY >= y - scl / 2 && mouseY <= y + scl / 2) {\n if (mouseIsPressed) {\n strokeWeight(4);\n fill(200);\n stroke(200);\n ellipse(x, y, scl, scl);\n textSize(30);\n stroke(220);\n fill(66, 52, 193);\n text(\"f\", x - textWidth('f') / 2, y + textSize() / 3);\n window.location.href = \"https://www.facebook.com/stel.kushev\";\n } else {\n strokeWeight(4);\n fill(200);\n stroke(200);\n ellipse(x, y, scl, scl);\n textSize(30);\n stroke(220);\n fill(66, 52, 193);\n text(\"f\", x - textWidth('f') / 2, y + textSize() / 3);\n }\n } else {\n stroke(220);\n strokeWeight(4);\n fill(66, 52, 193);\n ellipse(x, y, scl, scl);\n textSize(30);\n stroke(200);\n fill(200);\n text(\"f\", x - textWidth('f') / 2, y + textSize() / 3);\n }\n })();\n } else if (GAMEMODE == \"RUNNING\") {\n //drawing the spots of the map\n (() => {\n translate(width / 2 - player.pos.x - player.scl / 2, height / 2 - player.pos.y - player.scl / 2);\n (() => {\n for (let rowIndex = 0; rowIndex < roomMap.length; rowIndex++) {\n for (let colIndex = 0; colIndex < roomMap[rowIndex].length; colIndex++) {\n let [x, y] = [rowIndex * SPOT_SCL, colIndex * SPOT_SCL];\n let currentSpot = roomMap[rowIndex][colIndex];\n image(graphix[currentSpot.imgSource], x, y, SPOT_SCL, SPOT_SCL);\n }\n }\n })();\n //draw all other players\n for (let otherPlayer of otherPlayers) {\n if (otherPlayer.name != username)\n rect(otherPlayer.x, otherPlayer.y, player.scl, player.scl);\n }\n\n //draw the player\n player.show();\n })();\n }\n}", "function clickPaint() {\n\tidName('paint-layer').style.pointerEvents = 'auto';\n\tidName('shape-layer').style.pointerEvents = 'none';\n\tclassName('upper-canvas')[0].style.pointerEvents = 'none';\n}", "function onKeyDown(e) {\r\n\t'use strict';\r\n\t\r\n\tswitch(e.keyCode) {\r\n\t\tcase 65: // Tecla A\r\n\t\t\tfor (var i = 0; i < materialArray.length; i++) {\r\n\t\t\t\tmaterialArray[i].wireframe = !materialArray[i].wireframe;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase 97: // Tecla a\r\n\t\t\tfor (var i = 0; i < materialArray.length; i++) {\r\n\t\t\t\tmaterialArray[i].wireframe = !materialArray[i].wireframe;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase 38: // Tecla Cima\r\n\t\t\tstopUP = false;\r\n\t\t\tstopDOWN = false;\r\n\t\t\tcontrolUP = true;\r\n\t\t\tcontrolDOWN = false;\r\n\t\t\tbreak;\r\n\r\n\t\tcase 40: // Tecla Baixo\r\n\t\t\tstopUP = false;\r\n\t\t\tstopDOWN = false;\r\n\t\t\tcontrolUP = false;\r\n\t\t\tcontrolDOWN = true;\r\n\t\t\tbreak;\r\n\r\n\t\tcase 37: // Tecla Esquerda\r\n\t\t\tstopLEFT = false;\r\n\t\t\tstopRIGHT = false;\r\n\t\t\tcontrolLEFT = true;\r\n\t\t\tcontrolRIGHT = false;\r\n\t\t\tbreak;\r\n\r\n\t\tcase 39: // Tecla Direita\r\n\t\t\tstopLEFT = false;\r\n\t\t\tstopRIGHT = false;\r\n\t\t\tcontrolLEFT = false;\r\n\t\t\tcontrolRIGHT = true;\r\n\t\t\tbreak;\r\n\r\n\t\tcase 49: //tecla numero 1\r\n\t\t\tcameraFlag = 0;\r\n\t\t\tbreak;\r\n\r\n\t\tcase 50: //tecla numero 2\r\n\t\t\tcameraFlag = 1;\r\n\t\t\tbreak;\r\n\r\n\t\tcase 51: //tecla numero 3\r\n\t\t\tcameraFlag = 2;\r\n\t\t\tbreak;\r\n\r\n\t}\r\n}", "startMainMenu()\n {\n // We check if the player is on mobile and open fullscreen\n let os = theGame.device.os;\n if(os.android || os.iOS || os.iPad || os.iPhone || os.windowsPhone)\n {\n openFullScreen();\n }\n \n let gameCredits;\n let goat = currentScene.add.image(-100, topBackgroundYOrigin+35, 'GoatMenu');\n let fondo2 = currentScene.add.image(topBackgroundXOrigin, topBackgroundYOrigin, 'Fondo2');\n fondo2.visible = false;\n let logo = currentScene.add.image(topBackgroundXOrigin, topBackgroundYOrigin, 'Logo');\n //logo.visible = false;\n \n // Start Btn\n let startBtn = currentScene.add.image(topBackgroundXOrigin-40, topBackgroundYOrigin+125, 'StartBtn');\n let startHigh = currentScene.add.image(topBackgroundXOrigin-40, topBackgroundYOrigin+125, 'StartHigh');\n startBtn.setInteractive();\n startBtn.on('pointerover', ()=> this.onMenuBtnInteracted(startHigh, true));\n startBtn.on('pointerdown', ()=> this.onMenuBtnInteracted(startHigh, true));\n startBtn.on('pointerup', ()=> this.onMenuBtnInteracted(startHigh, false));\n startBtn.on('pointerout', ()=> this.onMenuBtnInteracted(startHigh, false));\n startBtn.on('pointerup', ()=> interacionManager.interactMenu(\"Start\"));\n\n startBtn.visible = false;\n startHigh.visible = false;\n\n // Continue Btn\n let continueBtn = currentScene.add.image(topBackgroundXOrigin-186, topBackgroundYOrigin+128, 'ContinueBtn');\n let continueHigh = currentScene.add.image(topBackgroundXOrigin-186, topBackgroundYOrigin+128, 'ContinueHigh');\n continueBtn.setInteractive();\n continueBtn.on('pointerover', ()=> this.onMenuBtnInteracted(continueHigh, true));\n continueBtn.on('pointerdown', ()=> this.onMenuBtnInteracted(continueHigh, true));\n continueBtn.on('pointerup', ()=> this.onMenuBtnInteracted(continueHigh, false));\n continueBtn.on('pointerout', ()=> this.onMenuBtnInteracted(continueHigh, false));\n continueBtn.on('pointerup', ()=> interacionManager.interactMenu(\"Continue\"));\n\n continueBtn.visible = false;\n continueHigh.visible = false;\n\n // Credits Btn\n let creditsBtn = currentScene.add.image(topBackgroundXOrigin-308, topBackgroundYOrigin+128, 'CreditsBtn');\n let creditsHigh = currentScene.add.image(topBackgroundXOrigin-308, topBackgroundYOrigin+128, 'CreditsHigh');\n creditsBtn.setInteractive();\n creditsBtn.on('pointerover', ()=> this.onMenuBtnInteracted(creditsHigh, true));\n creditsBtn.on('pointerdown', ()=> this.onMenuBtnInteracted(creditsHigh, true));\n creditsBtn.on('pointerup', ()=> this.onMenuBtnInteracted(creditsHigh, false));\n creditsBtn.on('pointerout', ()=> this.onMenuBtnInteracted(creditsHigh, false));\n creditsBtn.on('pointerup', ()=> enableCredits(this.gameCredits, true));\n\n creditsBtn.visible = false;\n creditsHigh.visible = false;\n\n // Mute Btn\n let muteBtn = currentScene.add.image(topBackgroundXOrigin-395, topBackgroundYOrigin+128, 'MenuMuteBtn');\n let muteHigh = currentScene.add.image(topBackgroundXOrigin-395.9, topBackgroundYOrigin+128, 'MenuMuteHigh');\n muteBtn.setInteractive();\n muteBtn.on('pointerover', ()=> this.onMenuBtnInteracted(muteHigh, true));\n muteBtn.on('pointerdown', ()=> this.onMenuBtnInteracted(muteHigh, true));\n muteBtn.on('pointerup', ()=> this.onMenuBtnInteracted(muteHigh, false));\n muteBtn.on('pointerout', ()=> this.onMenuBtnInteracted(muteHigh, false));\n muteBtn.on('pointerup', ()=> interacionManager.interactMenu(\"Mute\"));\n\n muteBtn.visible = false;\n muteHigh.visible = false;\n\n let timeline = currentScene.tweens.createTimeline();\n\n timeline.add(\n {\n targets: goat,\n x: topBackgroundXOrigin + 175,\n duration: 900\n }\n );\n\n timeline.add( \n {\n targets: fondo2,\n onStart: function()\n {\n fondo2.visible = true;\n let timedEvent = currentScene.time.delayedCall(1300, function()\n {\n musicManager.playThemeSong('Main');\n startBtn.visible = true;\n continueBtn.visible = true;\n creditsBtn.visible = true;\n muteBtn.visible = true;\n\n } , currentScene);\n } \n } \n );\n timeline.play(); \n this.gameCredits = currentScene.add.image(topBackgroundXOrigin, topBackgroundYOrigin, 'GameCredits');\n this.gameCredits.setInteractive();\n this.gameCredits.on('pointerdown', ()=> enableCredits(this.gameCredits, false));\n this.gameCredits.visible = false;\n }", "function onMouseDown(e) {\n //Pega a posição\n var pos = getMousePos(canvas, e);\n //Começa o arrastar\n if (gameState == gameStates.ready && !pause && !gameOver) {\n if (!drag) {\n //Tile sob o mouse\n mt = getMouseTile(pos);\n if (mt.valid) {\n var swapped = false;\n if (level.selectedtile.selected) {\n if (canSwap(mt.x, mt.y, level.selectedtile.column, level.selectedtile.row)) {\n //Pode trocar, mova-os\n mouseSwap(mt.x, mt.y, level.selectedtile.column, level.selectedtile.row);\n swapped = true;\n }\n }\n if (!swapped) {\n //Faz o tile selecionado\n level.selectedtile.column = mt.x;\n level.selectedtile.row = mt.y;\n level.selectedtile.selected = true;\n }\n } else {\n //Tile invalido\n level.selectedtile.selected = false;\n }\n //Começa o arrastar\n drag = true;\n }\n }\n //Verificação de clique nos botões\n if (pos.x >= buttons[0].x && pos.x < buttons[0].x + buttons[0].w && pos.y >= buttons[0].y && pos.y < buttons[0].y + buttons[0].h) {\n if (!gameOver && gameState != gameStates.init) {\n pause = !pause;\n }\n }\n if (gameState == gameStates.init) {\n if (pos.x >= buttons[3].x && pos.x < buttons[3].x + buttons[3].w && pos.y >= buttons[3].y && pos.y < buttons[3].y + buttons[3].h) {\n firsTime = false;\n gameState = gameStates.ready;\n }\n }\n if (pause || gameOver) {\n for (var i = 1; i < buttons.length; i++) {\n if (pos.x >= buttons[i].x && pos.x < buttons[i].x + buttons[i].w && pos.y >= buttons[i].y && pos.y < buttons[i].y + buttons[i].h) {\n switch (i) {\n case 1:\n window.cancelAnimationFrame(vari);\n window.score = Math.floor(score / 4);\n if (score > high) localStorage.high = score;\n canvas.removeEventListener(\"mousemove\", onMouseMove);\n canvas.removeEventListener(\"mousedown\", onMouseDown);\n window.nav = 3;\n window.troca = 2;\n break;\n case 2:\n newGame();\n firsTime = true;\n break;\n case 3:\n pause = false;\n break;\n }\n }\n }\n }\n }", "function click() {\n if ( clickPermission ) { // De if-statement die voorkomt dat je tijdens de animatie en afspelende audio deze opnieuw kunt starten.\n clickPermission = false;\n \n raycaster.setFromCamera( pointer, camera );\n const intersects = raycaster.intersectObjects( buttons );\n if ( intersects.length > 0 ) {\n controls.enabled = false; // Voorkomt dat je tijdens de animatie de scene kunt draaien gezien dit zorgt voor enorm snelle trillingen.\n \n clickedItemName = intersects[ 0 ].object.userData.name;\n if ( clickedItemName == \"buttonPhone\" ) { // Wanneer geklikt wordt op de telefoon button...\n sound.isPlaying = false;\n setTimeout( () => { \n sound.play(); \n }, 1000 );\n // Onderstaande 2 regels animeren de camera positie en perspectief naar de gewenste plek t.o.v. de muur.\n createjs.Tween.get( camera.position )\n .to( { x: -4.5, y: -5, z: 3 }, 3000, createjs.Ease.getPowInOut( 5 ) )\n .wait( 1700 )\n .to( cameraStartPosition, 3000, createjs.Ease.getPowInOut( 5 ) )\n .call( () => { \n controls.enabled = true; clickPermission = true; \n } );\n createjs.Tween.get( controls.target )\n .to( { x: 8, y: 15, z: -20 }, 3000, createjs.Ease.getPowInOut( 5 ) )\n .wait( 1700 )\n .to( { x: 0, y: 0, z: 0 }, 3000, createjs.Ease.getPowInOut( 5 ) );\n createjs.Tween.get( gltfScene.rotation )\n .to( { z: Math.PI * -2.8 }, 3000, createjs.Ease.getPowInOut( 5 ) )\n .wait( 1700 )\n .to( { z: 0 }, 3000, createjs.Ease.getPowInOut( 5 ) );\n // video.play(); // Start de zogenaamde projectie animatie.\n } else if ( clickedItemName == \"buttonPlanes\" ) { // Wanneer geklikt wordt op de vliegtuig button...\n sound2.isPlaying = false;\n setTimeout( () => { \n sound2.play();\n }, 1000 );\n createjs.Tween.get( camera.position )\n .to( { x: 25, y: -5, z: 30 }, 2000, createjs.Ease.getPowInOut(5) )\n .wait( 2100 )\n .to( cameraStartPosition, 2000, createjs.Ease.getPowInOut( 5 ) )\n .call( () => { \n controls.enabled = true; clickPermission = true; \n } );\n createjs.Tween.get( controls.target )\n .to( { x: 35 }, 2000, createjs.Ease.getPowInOut( 5 ) )\n .wait( 2100 )\n .to( { x: 0 }, 2000, createjs.Ease.getPowInOut( 5 ) );\n } \n } else { \n clickPermission = true;\n }\n }\n}", "function CALCULATE_TOUCH_UP_OR_MOUSE_UP() {\r\n \r\n GLOBAL_CLICK.CLICK_PRESSED = false;\r\n \r\n }", "function presionarPantalla(evento)\r\n{\r\n Touch_activo = 1;\r\n xm = evento.touches[0].clientX;\r\n ym = evento.touches[0].clientY;\r\n}", "onButtonUp() {\n\t\tif(character.isClicked) {\n\t\t\tcharacter.sprite.y += 100;\n\t\t\tcharacter.isClicked = false;\n\t\t}\n\t}", "function Update () {\n //Condicion q mira si se esta tocando la pantalla.\n\tif(Input.touches.Length<=0){\n\t\tthis.guiTexture.texture=reanudarOri;\n \t}else{\n \t\n \t\tfor (var i =0 ; i< Input.touchCount; i++) {\n\t\t \t\n\t\t \tif(this.guiTexture!=null&&(this.guiTexture.HitTest(Input.GetTouch(i).position))){\n\t\t \t\n\t \t\t}\n\t \t}\n \t}\t\n }", "function gameMenu(){\n ctx = canvas.getContext(\"2d\");\n createBackground(ctx);\n ctx.fillStyle = \"#000000\";\n ctx.save();\n ctx.font = \"bolder 30px Arial\";\n ctx.fillText(\"Tap Tap Bug\", 110, 200);\n ctx.restore();\n ctx.font = \"15px Arial\";\n var text = \"High Score: \" + prevHighScore;\n ctx.fillText(text, 150,235);\n\n radioHead(ctx);\n startButton(ctx);\n\n canvas.addEventListener(\"mousedown\",\n difficultyPosition, false);\n}", "function onPress(e) {\r\n\t\tif (clickingEnabled) {\r\n\t\t\tif (isRunning) velocity[1] = JUMP;\r\n\t\t\telse { //game just started!\r\n\t\t\t\tisRunning = true;\r\n\r\n\t\t\t\t//////////////////////////////\r\n\t\t\t\t//setup the game's variables//\r\n\t\t\t\txrange = INIT_XRANGE.slice(0);\r\n\t\t\t\tyrange = INIT_YRANGE.slice(0);\r\n\t\t\t\tpos = [map(startPosAsAFraction[0], 0, 1, xrange[0], xrange[1]),\r\n\t\t\t\t\t map(startPosAsAFraction[1], 0, 1, yrange[0], yrange[1])];\r\n\t\t\t\tvelocity = [X_VEL, 0]; //units/second, x velocity shouldn't change\r\n\t\t\t\tcurrentScore = 0;\r\n\r\n\t\t\t\t/////////////////////\r\n\t\t\t\t//generate barriers//\r\n\t\t\t\tbarriers = []; //[[x position, fraction up on the page] ... []]\r\n\t\t\t\tvar barriersUntil = 2*(xrange[1]-xrange[0]); //starting barriers\r\n\t\t\t\tfor (var ai = barriersEveryXUnits; ai < barriersUntil; \r\n\t\t\t\t\t ai+=barriersEveryXUnits) {\r\n\t\t\t\t\tvar vertDisp = getRandReal(\r\n\t\t\t\t\t\tbarrierOpeningRange[0], barrierOpeningRange[1]\r\n\t\t\t\t\t);\r\n\t\t\t\t\tbarriers.push([ai, vertDisp]);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcurrentScreen = 1; //game screen\r\n\t\t\t\tupdateCanvas();\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tclickingEnabled = true; //so the next click will enter the above if\r\n\t\t}\r\n\t}", "function draw(){\r\n drawFusee(\"white\");\r\n if (leftPressed && x_fusee > (hauteur_fusee)){\r\n x_fusee -= 7;\r\n }\r\n if (rightPressed && x_fusee < canvas.width-(hauteur_fusee*3)){\r\n x_fusee += 7;\r\n }\r\n if (upPressed && y_fusee > (hauteur_fusee)){\r\n y_fusee -= 7;\r\n }\r\n if (downPressed && y_fusee < canvas.height-(hauteur_fusee*2)){\r\n y_fusee += 7;\r\n }\r\n drawFusee(\"blue\");\r\n}", "function onCanvasClick(event) {\n let x = event.offsetX;\n let y = event.offsetY;\n var pos = getPosition(x, y);\n var valid = gameBoard.handleClick(pos.x, pos.y);\n if (valid == -1) {\n return;\n }\n updateBoard();\n var result = gameBoard.checkWin(\"b\");\n if(result == -1) {\n return;\n }\n else if (result == \"w\") {\n console.log(\"White wins!\");\n }\n else if (result == \"b\") {\n console.log(\"Black wins!\");\n }\n}", "function ButtonDown(game, index) {\n if(!game.paused) {\n game.buttons[index].pressed.visible = true;\n game.buttons[index].unpressed.visible = false;\n if(index == 0) {\n game.showRadius = true;\n } else if(index == 1) {\n if(game.player.energy > 2) {\n game.player.Shield.visible = true;\n game.shieldActive = true;\n game.player.Shield.animations.play('Start', 28, true);\n }\n } else if(index == 2) {\n if(game.player.energy >= 50) {\n game.player.reduceEnergy(50);\n game.decoyActive = true;\n game.player.createDecoy(game);\n }\n } else if(index == 3) {\n if(game.portalActive) {\n game.player.activePortal(game);\n } else {\n game.player.reduceEnergy(20);\n game.portalActive = true;\n game.player.createPortal(game);\n }\n }\n }\n}", "function keys(){\nif(rightPressed && paddlePl < canvas.width-paddleWidth) {\n paddlePl += 7;\n }\n else if(leftPressed && paddlePl > 0) {\n paddlePl -= 7;\n }\n\n}", "function servostart(e) {\n\tx_finger_bak = e.changedTouches[0].screenX\n\ty_finger_bak = e.changedTouches[0].screenY\n\treturn false\n}", "function showInstructions(e) {\n stage.removeAllChildren();\n\n //add the main screen\n insScreen = new createjs.Bitmap(queue.getResult(\"instructions\"));\n this.stage.addChild(insScreen);\n insScreen.x = 0;\n insScreen.y = 0;\n\n //add the play button\n playButt = new createjs.Bitmap(queue.getResult(\"playButton\"));\n this.stage.addChild(playButt);\n playButt.x = 80;\n playButt.y = 390;\n playButt.addEventListener(\"click\", mainGameStart);\n\n stage.update();\n}", "function onTouch() {\n var card\n\n if (i % 13 === 0) {\n acesClicked[i] = true\n if (acesClicked.filter(function (ace) {\n return ace\n }).length === 4) {\n document.body.removeChild($topbar)\n deck.$el.style.display = 'none'\n setTimeout(function () {\n startWinning()\n }, 250)\n }\n } else if (i % 13 === 12) {\n if (!kingsClicked) {\n return\n }\n kingsClicked[i] = true\n if (kingsClicked.filter(function (king) {\n return king\n }).length === 4) {\n for (var j = 0; j < 3; j++) {\n card = Deck.Card(52 + j)\n card.mount(deck.$el)\n card.$el.style[transform] = 'scale(0)'\n card.enableMoving()\n deck.cards.push(card)\n }\n deck.sort(true)\n kingsClicked = false\n }\n } else {\n acesClicked = []\n if (kingsClicked) {\n kingsClicked = []\n }\n }\n }", "function enableMouseClick() {\n // Add event listener for mouse click events to the canvas\n canvas.addEventListener(\"mousedown\", function (evt) {\n triggerMouseEvent(evt, canvas, connectedGame.mouseClickEvent);\n }, false);\n }", "function showMenu() {\r\n togMenu=true;\r\n togSet=false;\r\n ctx.fillStyle = \"black\";\r\n ctx.globalAlpha = 0.9; \r\n ctx.fillRect(120, 40, 950, 600);\r\n ctx.globalAlpha = 1.0; \r\n ctx.fillStyle = \"white\";\r\n ctx.textAlign = \"center\"; \r\n ctx.font = \"45px Arial\";\r\n ctx.fillText(\"Settings\", w, 100);\r\n ctx.font = \"35px Arial\";\r\n\r\n if (speechOn) {\r\n ctx.fillText(\"Speech: On - press O to change\", w, 210);\r\n if (keys[79]) { //o\r\n speechOn=false;\r\n }\r\n }\r\n\r\n if (!speechOn) {\r\n ctx.fillText(\"Speech: Off - press B to change\", w, 210);\r\n if (keys[66]) { //b\r\n speechOn=true;\r\n }\r\n }\r\n\r\n /*------------------------------------------------------ */\r\n\r\n \r\n if (musicOn) {\r\n ctx.fillText(\"Music: On - press M to change\", w, 310);\r\n if (keys[77]) { //m\r\n musicOn=false;\r\n }\r\n }\r\n\r\n if (!musicOn) {\r\n ctx.fillText(\"Music: Off - press U to change\", w, 310);\r\n if (keys[85]) { //u\r\n musicOn=true;\r\n }\r\n }\r\n\r\n /*------------------------------------------------------ */\r\n\r\n if (picOn) {\r\n ctx.fillText(\"Picture: On - press C to change\", w, 410);\r\n if (keys[67]) { //o\r\n picOn=false;\r\n }\r\n }\r\n\r\n if (!picOn) {\r\n ctx.fillText(\"Colour: On - press I to change\", w, 410);\r\n if (keys[73]) { //f\r\n picOn=true;\r\n }\r\n }\r\n\r\n ctx.font = \"30px Arial\";\r\n ctx.fillText(\"Return to Game\", w, 560);\r\n ctx.fillText(\"Press A\", w, 610);\r\n\r\n if (keys[65]) { //a\r\n togSet=true;\r\n togMenu=false;\r\n }\r\n}", "function keyPressed() {\n // when the up arrow is pressed it increases the size\n if (keyCode === UP_ARROW) {\n size += 10;\n // when the down arrow is pressed it decreaces the size\n } else if (keyCode === DOWN_ARROW) {\n size -= 10;\n }\n // when the left arrow is pressed the type is set as a square\n if (keyCode === LEFT_ARROW) {\n type = 1;\n // when the right arrow is pressed the type is set as a circle\n } else if (keyCode === RIGHT_ARROW) {\n type = 2;\n }\n // when shift is pressed it clears the canvas\n else if (keyCode === SHIFT){\n clear();\n background(230);\n }\n}", "function doCanvasDown()\n{\n\t// Random color generation\n\tfill = {\n\t\tred: Math.round( Math.random() * 255 ),\n\t\tgreen: Math.round( Math.random() * 255 ),\n\t\tblue: Math.round( Math.random() * 255 )\n\t};\n\t\n\t// Event listeners for drawing\n\t// Conditional check for tablets\n\tcanvas.addEventListener( touch ? 'touchmove' : 'mousemove', doCanvasMove );\n\tcanvas.addEventListener( touch ? 'touchend' : 'mouseup', doCanvasUp );\n}", "function setup_event_handlers()\n{\n var canvas = document.getElementById( \"game_canvas\" );\n \n if( !mobile_version )\n {\n canvas.addEventListener( \"mousemove\", on_mouse_move );\n canvas.addEventListener( \"mouseout\", on_mouse_out );\n canvas.addEventListener( \"mouseover\", on_mouse_over );\n }\n else\n {\n if( is_mobile.windows() )\n {\n canvas.addEventListener( 'pointerdown', on_mouse_move );\n canvas.addEventListener( 'pointermove', on_mouse_move );\n canvas.addEventListener( 'pointerup', on_mouse_move );\n }\n \n canvas.addEventListener( 'touchstart', function(e)\n {\n mouse_x = e.changedTouches[0].pageX;\n mouse_y = e.changedTouches[0].pageY;\n //e.preventDefault();\n mouse_click = true;\n }, false );\n canvas.addEventListener( 'touchmove', function(e)\n {\n mouse_x = e.changedTouches[0].pageX;\n mouse_y = e.changedTouches[0].pageY;\n e.preventDefault();\n }, false );\n canvas.addEventListener( 'touchend', function(e)\n {\n mouse_x = e.changedTouches[0].pageX;\n mouse_y = e.changedTouches[0].pageY;\n e.preventDefault();\n }, false );\n \n }\n}", "function mousedownForCanvas(event)\n{\n global_mouseButtonDown = true;\n event.preventDefault(); //need? (maybe not on desktop)\n}", "function drawSongSelectScreen(ctx,screenWidth,screenHeight){\n menuScroll(songButtons);\n let x = 75, y = screenHeight/2;\n ctx.fillStyle = \"white\";\n ctx.fillRect(0,0,screenWidth,screenHeight);\n\n drawBackgroundImage(ctx);\n\n let drawPos = 0;\n \n let btnNum = currentPos;\n drawPos = -2;\n\n for(let i = 0; i < songButtons.length; i++){ \n if(btnNum > songButtons.length - 1){\n btnNum = 0;\n }\n \n if(drawPos == 0){\n x = 75;\n y = screenHeight/2;\n }\n else if(drawPos == 1){\n x = 45;\n y = screenHeight/2 + 85;\n }\n else if(drawPos == 2){\n x = 15;\n y = screenHeight/2 + 170;\n }\n else if(drawPos == -2){\n x = 15;\n y = screenHeight/2 - 170;\n }\n else if(drawPos == -1){\n x = 45;\n y = screenHeight/2 - 85;\n }\n \n if(drawPos <= 2){\n if(drawPos == 0) songButtons[btnNum].setFillColor(\"cornflowerblue\");\n else songButtons[btnNum].setFillColor(\"lightblue\");\n songButtons[btnNum].setRectPos(x,y);\n songButtons[btnNum].draw(ctx);\n drawPos++;\n btnNum++;\n }\n }\n\n // // draw around the center position \n // let centerButton = new ButtonSprite(75,screenHeight/2 - 5,\"none\",\"gold\",\"black\",380,75,\"\",0,0,10);\n // centerButton.draw(ctx);\n // ctx.restore();\n\n let tempPos = currentPos; \n tempPos += 2;\n currentSong = songs[tempPos % songButtons.length];\n \n drawSongSelectText(ctx,screenWidth,screenHeight);\n}", "function prepareCanvas()\r\n{\r\n\t// Create the canvas (Neccessary for IE because it doesn't know what a canvas element is)\r\n\tvar canvasDiv = document.getElementById('canvasDiv');\r\n\tcanvas = document.createElement('canvas');\r\n\r\n\tcanvas.setAttribute('width', canvasWidth);\r\n\tcanvas.setAttribute('height', canvasHeight);\r\n\tcanvas.setAttribute('id', 'canvas');\r\n\tcanvasDiv.appendChild(canvas);\r\n\tif(typeof G_vmlCanvasManager != 'undefined') {\r\n\t\tcanvas = G_vmlCanvasManager.initElement(canvas);\r\n\t}\r\n\t//canvas.position(200, 100);\r\n\tcontext = canvas.getContext(\"2d\");\r\n\r\n\r\n\tcontext.fillStyle = \"#00bfff\";\r\n\tcontext.fillRect(0, 0, canvas.width, canvas.height);\r\n\r\n\tcrayonTextureImage.onload = function() { resourceLoaded();\r\n\t};\r\n\tcrayonTextureImage.src = \"assets/images/crayon-texture-update3.png\";\r\n\r\n\tplaneImage.onload = function() { resourceLoaded();\r\n\t};\r\n\tplaneImage.src = \"assets/images/skywrite-cursor1.png\";\r\n\r\n\t// Add mouse events\r\n\t// ----------------\r\n\tconsole.log($('#canvas'));\r\n\t$('#canvas').on(\"touchstart\", function(e){\r\n\t\tif(window.isPilot){\r\n\t\t\tconsole.log(e);\r\n\t\t\tvar mouseX = e.originalEvent.touches[0].pageX - $('#canvas').get(0).offsetLeft;\r\n\t\t\tvar mouseY = e.originalEvent.touches[0].pageY - $('#canvas').get(0).offsetTop;\r\n\t\t\tpaint = true;\r\n\t\t\t\r\n\t\t\taddClick(e.originalEvent.touches[0].pageX - $('#canvas').get(0).offsetLeft, e.originalEvent.touches[0].pageY - $('#canvas').get(0).offsetTop, false);\r\n\t\t\te.originalEvent.preventDefault();\r\n\t\t\treturn false;\r\n\t\t}\r\n\t});\r\n\t$('#canvas').on(\"mousedown\", function(e){\r\n document.querySelector(\"#sfx1\").play();\r\n if (window.isPilot) {\t\r\n\tvar mouseX = e.pageX - $('#canvas').get(0).offsetLeft;\r\n\tvar mouseY = e.pageY - $('#canvas').get(0).offsetTop;\r\n paint = true;\r\n \taddClick(e.pageX - $('#canvas').get(0).offsetLeft, e.pageY - $('#canvas').get(0).offsetTop, false);\r\n }\r\n $\r\n redraw();\r\n});\r\n\r\n\t$('#canvas').on(\"touchmove\",function(e){\r\n\t\tif (window.isPilot) {\r\n\t\t\tconsole.log(e);\r\n\t\t\taddClick(e.originalEvent.touches[0].pageX - $('#canvas').get(0).offsetLeft, e.originalEvent.touches[0].pageY - $('#canvas').get(0).offsetTop, paint);\r\n\t\t\tplaneX = e.originalEvent.touches[0].pageX - $('#canvas').get(0).offsetLeft;\r\n\t\t\tplaneY = e.originalEvent.touches[0].pageY - $('#canvas').get(0).offsetTop;\r\n\t\t\t\r\n\t\t\tredraw();\r\n\t\t\te.originalEvent.preventDefault();\r\n\t\t\treturn false;\r\n\t\t}\r\n\t});\r\n\r\n\t$('#canvas').on(\"mousemove\",function(e){\r\n\t\tif (window.isPilot) {\r\n\t\t\taddClick(e.pageX - $('#canvas').get(0).offsetLeft, e.pageY - $('#canvas').get(0).offsetTop, paint);\r\n\t\t\tplaneX = e.pageX - $('#canvas').get(0).offsetLeft;\r\n\t\t\tplaneY = e.pageY - $('#canvas').get(0).offsetTop;\r\n\t\t\tredraw();\r\n\t\t}\r\n\t});\r\n\r\n\t$('#canvas').on(\"mouseup touchend\",function(e){\r\n\t\tif (window.isPilot) {\r\n\t\t\tpaint = false;\r\n\t\t redraw();\r\n\t\t}\r\n\t});\r\n\r\n\t$('#canvas').on(\"mouseleave touchleave\",function(e){\r\n\t\tif (window.isPilot) {\r\n\t\t\tpaint = false;\r\n\t\t}\r\n\t});\r\n}", "function startScreen() {\n fill(255, 56, 115, opacity);\n rect(0,0,width,height);\n textSize(12);\n if (frameCount%2 == 0){\n fill(255,opacity);\n textAlign(CENTER);\n textSize(12);\n text(\"CLICK TO PLAY\", width/2, height/2);\n }\n}", "function mousePressed(e) {\n\n\t// Define variables.\n\tvar parent = e.target.parentElement,\n\t\tparentID = parent ? parent.id : '';\n\n\t// Only add objects if the click/touch is not on the controls or swatches. \n\tif (parentID.toUpperCase() != 'CONTROLSBACKGROUND' && parentID.toUpperCase() != 'SWATCHES') {\n\t\n\t\t// Add player control enabled.\n\t\tif (board.addPlayer) {\n\t\t\taddObject('player');\t\n\t\t}\n\t\n\t\t// Add ball control enabled.\n\t\tif (board.addBall) {\n\t\t\taddObject('ball');\n\t\t}\n\n\t\t// Draw control enabled.\n\t\tif (board.drawing) {\n\t\t\tboard.draw(false);\n\t\t}\t\t\n\t\t\n\t\t// Set coordinates of mouse/touch.\n\t\tboard.x = mouseX;\n\t\tboard.y = mouseY;\n\t\tboard.px = mouseX;\n\t\tboard.py = mouseY;\t\t\n\t\t\n\t}\n\t\n\t// Prevent default functionality.\n\treturn false;\t\n\t\n}", "function onMouseDown (e){\n mousePressed=true;\n butt.value=1;\n butt.addEventListener(\"mouseup\", onMouseUp, true);\n butt.addEventListener(\"touchend\", touch2Mouse.touchHandler, true);\n butt.fire(e);\n }", "function doTouchout(e) {\n console.log(e.type);\n //ctx.closePath();\n dragging = false;\n}", "createMenu()\n {\n currentScene.add.image(topBackgroundXOrigin, topBackgroundYOrigin, 'Fondo');\n\n // The first button that will enable audio\n let firstBtn = currentScene.add.image(topBackgroundXOrigin, topBackgroundYOrigin, 'FirstStart');\n\n firstBtn.setInteractive();\n firstBtn.on('pointerdown',function()\n {\n this.setScale(1.05);\n });\n firstBtn.on('pointerup',function()\n {\n firstBtn.disableInteractive();\n // We play the Button pressed SFX \n sfxManager.playSupahStar();\n firstBtn.destroy();\n });\n firstBtn.on('pointerup', () => this.startMainMenu());\n\n // We set the fonts according to the browser\n if(theGame.device.browser.firefox)\n {\n boldFontName = 'Asap-Bold';\n regularFontName = 'Asap';\n }\n else\n {\n boldFontName = 'Asap-Bold';\n regularFontName = 'Asap';\n }\n }", "function startScreen() {\n draw();\n startBtn.draw();\n}", "function canvasTouchHandler(){\n canvas.addEventListener('touchstart', function(event){\n event.preventDefault();},false);\n canvas.addEventListener('touchmove', function(event){\n event.preventDefault();},false);\n}", "function touch(){\n\tfor (var i=0; i<objects.length; i++){\n\t\tobjects[i].addEventListener(\"click\", function(){\n\t\t\tif (this.style.background === trans_color)\n\t\t\t\tclear();\n\t\t});\n\t}\n}", "function KinkyDungeonClickGame(Level) {\n\t// First we handle buttons\n\tif (KinkyDungeonHandleHUD()) {\n\t\t\n\t}\n\t// beep\n\t\n\t// If no buttons are clicked then we handle move\n\telse if (KinkyDungeonTargetingSpell) {\n\t\tif (MouseIn(canvasOffsetX, canvasOffsetY, KinkyDungeonCanvas.width, KinkyDungeonCanvas.height)) {\n\t\t\tif (KinkyDungeonSpellValid) {\n\t\t\t\tKinkyDungeonCastSpell(KinkyDungeonTargetX, KinkyDungeonTargetY, KinkyDungeonTargetingSpell)\n\t\t\t\tKinkyDungeonAdvanceTime(1)\n\t\t\t\tKinkyDungeonTargetingSpell = null\n\t\t\t}\n\t\t} else KinkyDungeonTargetingSpell = null\n\t} else if (MouseIn(canvasOffsetX, canvasOffsetY, KinkyDungeonCanvas.width, KinkyDungeonCanvas.height)) {\n\t\tKinkyDungeonMove(KinkyDungeonMoveDirection)\n\t}\n}", "function initGraphics() {\n stage.addChild(howToPlay);\n howToPlay.on(\"click\", function (event) {\n startGame(event);\n initMuteUnMute();\n });\n}", "function clickImage(e){\n mouse.x = event.x;\n mouse.y = event.y;\n var toggle = pauseandplay.check();\n pauseandplay.update();\n if(toggle){\n canvasElement.removeEventListener('click', removeOnClick);\n if(pauseandplay.state == 0){ //pause\n clearInterval(myGameArea.interval);\n clearInterval(timer);\n // var c = myGameArea.context;\n c.fillStyle = \"rgba(1,1,1,0.7)\";\n c.fillRect(myGameArea.canvas.width/2 - 150, myGameArea.canvas.height/2-50, 300, 100);\n c.font = \"40px Consolas\";\n c.fillStyle = \"white\";\n c.textContent = \"center\";\n c.fillText(\"Paused\", myGameArea.canvas.width/2, myGameArea.canvas.height/2-10);\n c.font = \"15px Consolas\";\n c.fillText(\"Click the icon again to resume\", myGameArea.canvas.width/2, myGameArea.canvas.height/2+20);\n }else{ //play\n setTimeout(function(){\n canvasElement.addEventListener('click', removeOnClick);\n myGameArea.intervalFunction();\n if(timer){\n endTimer();\n }\n \n }, 300);\n }\n }\n if(gauntlet.check() && gauntletCount == 1){\n // particles.splice(0, parseInt(particles.length/2));\n particles.forEach((particle, index) =>{\n if(index < particles.length/2){\n particles[index].removeArea();\n }\n })\n particles.splice(0, parseInt(particles.length/2));\n gauntletCount--;\n }\n if(felixFelicis.check()){\n var count = 5;\n bubbleGenration = 300;\n felixFelicisCount--;\n var interval = setInterval(() => {\n count--;\n bubbleGenration = 300;\n }, 1000);\n if(count == 0){\n clearInterval(interval);\n }\n }\n}", "StartButPress(){\n this.refHolder.getComponent('AudioController').PlayTap();\n this.refHolder.getComponent('UIAnimManager').MainMenuOut();\n this.refHolder.getComponent(\"GamePlay\").CreatePuzzle();\n\n this.refHolder.getComponent('UIAnimManager').GameMenuIn();\n }", "function Start () {\n\nlarguraBotao = 120;//largura predefinida do botao\nalturaBotao = 30;//altura predefinida do botao\n\nposiX = (Screen.width - Screen.width);//Tratando o eixo x\nposiY = (Screen.height - Screen.height);//Tratando o eixo y\n\n}", "function gamePlay(ctx){\n createBackground(ctx);\n createPauseButton(ctx);\n countdownTimer = setInterval(\"timer()\", 1000);\n foodGenerator(ctx);\n scoreDisplay();\n ctx.save();\n myReq = requestAnimationFrame(bugAnimation);\n\n canvas.addEventListener(\"mousedown\",\n getPosition, false);\n}", "function sketchpad_mouseDown() {\n g_mouseDown = 1;\n drawDot(g_ctx, g_mouseX, g_mouseY, 12);\n}", "function clickEvent(){ \r\n const execCode = new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnDoublePickTrigger, (event) => {\r\n if(event.meshUnderPointer.value === null ){\r\n console.log(board.indexOf(event.meshUnderPointer));\r\n if(canPlay){ \r\n if (turn){\r\n event.meshUnderPointer.value = 'x';\r\n makeX(event.meshUnderPointer); \r\n win();\r\n }else{\r\n event.meshUnderPointer.value = 'o';\r\n makeO(event.meshUnderPointer);\r\n win();\r\n }\r\n }\r\n }\r\n });\r\n return execCode;\r\n }", "gamePadClicked () {\n this.SceneManager.switchToUsingTransaction('Gamepad/Level1', Transition.named('ScrollFrom', { direction: 'right' }))\n }", "function main_menu(){\n createCanvas(1270, 580); \n background(255,0,0);\n play_button(); \n textSize(100); \n fill(0);\n textFont(\"Impact\");\n text(\"Haunted House Escape!\", 160,120);\n textSize(60); \n textFont(\"Impact\");\n text(\"a game by Lenay Demetrious\", 265, 200);\n //if the user hits the play button, they will begin the game \n if (mouse_bool == true){\n if((mouseX > 480) && (mouseX < 780) && (mouseY > 300) && (mouseY < 400)){\n enter_house_bool = true; \n mouse_bool = false; \n main_menu_bool = false;\n }\n }\n}", "externalTouchDown() {\n this._strikeTouchDown();\n }", "function enableKeyPress() {\n // Add event listener for keyboard press events to the canvas\n window.addEventListener(\"keydown\", function (evt) {\n connectedGame.keyPressEvent(evt);\n }, false);\n }", "function canvasClicked() {\r\n setTimeout(canvasClicked, fps / drawParams.two);\r\n n++\r\n\r\n a = n * nltLIB.dtr(divergence);\r\n r = c * Math.sqrt(n);\r\n\r\n x = mouseX + r * Math.cos(a) + canvasWidth / drawParams.two;\r\n y = mouseY + r * Math.sin(a) + canvasHeight / drawParams.two;\r\n }", "function acrosticKeyHandler(event) {\n pencilToggle(event, '.pencil-mode-toggle', 'pencil');\n pauseToggle(event, '.pause-button', '#pzm-pause button.review-button', '#portal-game-modals.pzm-active');\n }", "function clickShape() {\n\tidName('shape-layer').style.pointerEvents = 'auto';\n\tclassName('upper-canvas')[0].style.pointerEvents = 'auto';\n\tidName('paint-layer').style.pointerEvents = 'none';\n}", "_onScreenTouch() {\n let state = this.state;\n const time = new Date().getTime();\n const delta = time - state.lastScreenPress;\n\n if ( delta < 300 ) {\n // this.methods.toggleFullscreen();\n }\n\n state.lastScreenPress = time;\n\n this.setState( state );\n }", "function keyPressed() {\n // toggle fullscreen mode\n if( key === 'f') {\n fs = fullscreen();\n fullscreen(!fs);\n return;\n } \n\n adventureManager.keyPressed(key); \n}", "function mouseClicked() {\n //i cant figure out how to do mouse controls\n //player.mouseControls *= -1\n\n for (b = 0; b < buttons.length; b++){\n switch (buttons[b].shape) {\n case \"rect\":\n if (mouseX >= (buttons[b].x + camOffsetX) * canvasScale &&\n mouseX <= (buttons[b].x + camOffsetX + buttons[b].w) * canvasScale &&\n mouseY >= (buttons[b].y + camOffsetY) * canvasScale &&\n mouseY <= (buttons[b].y + camOffsetY + buttons[b].h) * canvasScale){\n if (options.optionsMenuHidden === -1 && buttons[b].tab === options.optionsMenuTab){\n buttons[b].testClick();\n return;\n }\n }\n break;\n case \"circle\":\n if (Math.sqrt(Math.pow(mouseX - ((buttons[b].x + camOffsetX) * canvasScale), 2)+Math.pow(mouseY - ((buttons[b].y + camOffsetY) * canvasScale),2) < buttons[b].w)){\n if (options.optionsMenuHidden === -1 && buttons[b].tab === options.optionsMenuTab){\n buttons[b].testClick();\n return;\n }\n }\n default:\n break;\n }\n \n }\n}", "function keyClickDetection(){\n if (state === 'piano'){\n if (mouseIsPressed){\n if (mouseX > width - 475 && mouseX < width - 325 &&\n mouseY > 195 && mouseY < 595){\n playPianoNote(noteG,0.5);\n }\n else if (mouseX > width - 625 && mouseX < width - 475 &&\n mouseY > 195 && mouseY < 595){\n playPianoNote(noteF,0.5);\n }\n else if (mouseX > width - 775 && mouseX < width - 625 &&\n mouseY > 195 && mouseY < 595){\n playPianoNote(noteE,0.5);\n }\n else if (mouseX > width - 925 && mouseX < width - 775 &&\n mouseY > 195 && mouseY < 595){\n playPianoNote(noteD,0.5);\n } \n else if (mouseX > width - 1075 && mouseX < width - 925 &&\n mouseY > 195 && mouseY < 595){\n playPianoNote(noteC,0.5);\n }\n else if (mouseX > width - 1225 && mouseX < width - 1075 &&\n mouseY > 195 && mouseY < 595){\n playPianoNote(noteB,0.5);\n } \n else if (mouseX > width - 1375 && mouseX < width - 1225 &&\n mouseY > 195 && mouseY < 595){\n playPianoNote(noteA,0.5);\n } \n }\n }\n }", "function gameInitial(){\n // game title\n let title = new LTextField();\n title.size = 30;\n title.text = '是男人就下100层';\n title.x = (LGlobal.width - title.getWidth())/2;\n title.y = 100;\n \n title.color = '#ffffff';\n \n \n backLayer.addChild(title);\n\n // show the instro text\n backLayer.graphics.drawRect(1,'#ffffff',\n [(LGlobal.width - 220 )/2,240,220,40]);\n\n // add start button\n let textClick = new LTextField();\n textClick.size = 18;\n textClick.color = '#ffffff';\n textClick.text = '点击开始';\n textClick.x = (LGlobal.width - textClick.getWidth())/2;\n textClick.y = 250;\n\n backLayer.addChild(textClick);\n\n // add click event, click the rect of text named 'start',\n // and start game\n backLayer.addEventListener(LMouseEvent.MOUSE_UP, gameStart);\n}", "draw() {\n //condition to get exact position of moving finger\n if (this.test === true) {\n var rect = this.canvas.getBoundingClientRect();\n var x = event.touches[0].clientX - rect.left;\n var y = event.touches[0].clientY - rect.top;\n this.context.lineTo(x, y);\n this.context.stroke();\n }\n //this alows us to stop screen\n event.preventDefault();\n }" ]
[ "0.70594984", "0.68947816", "0.68403137", "0.68271595", "0.6802393", "0.67657787", "0.66740894", "0.6669814", "0.66688263", "0.6647324", "0.65812474", "0.65748274", "0.6573092", "0.6565624", "0.649676", "0.648754", "0.6466395", "0.6432844", "0.6421616", "0.6419846", "0.6411446", "0.64108604", "0.6404658", "0.6404658", "0.6404658", "0.640179", "0.6398335", "0.6393742", "0.63559496", "0.6342473", "0.63329405", "0.6325447", "0.63249385", "0.6312634", "0.6306275", "0.6301904", "0.6282714", "0.62814635", "0.62721723", "0.62697154", "0.62692493", "0.6263994", "0.6263679", "0.6242874", "0.6237773", "0.6232826", "0.62314445", "0.6225834", "0.62224054", "0.6215181", "0.62139326", "0.62075174", "0.61944115", "0.61792624", "0.61755556", "0.61731577", "0.61694163", "0.61613256", "0.61516833", "0.6148299", "0.6147039", "0.6145677", "0.6140851", "0.6124344", "0.6122676", "0.61196303", "0.6119459", "0.61174", "0.6108326", "0.6106519", "0.6102258", "0.6093465", "0.60855067", "0.6079385", "0.6076244", "0.60711837", "0.6070102", "0.6062176", "0.60586405", "0.605723", "0.6048343", "0.6043238", "0.60369676", "0.6034591", "0.6025305", "0.6022734", "0.60226166", "0.60223407", "0.6008137", "0.60022354", "0.6000946", "0.60008824", "0.59993416", "0.5996108", "0.59953874", "0.59931624", "0.5992444", "0.5988567", "0.5986219", "0.5982389" ]
0.61073357
69
====================== GESTIONE DELLA PRESSIONE DEI TASTI DELLA TASTIERA ======================
function doKeyDown(e){ //==================== // THE W KEY //==================== if (e.keyCode == 87) { if(!modalitaGara) cameraInteraction.moveForward = true; else key[0]=true; } //==================== // THE S KEY //==================== if (e.keyCode == 83) { if(!modalitaGara) cameraInteraction.moveBackward = true; else key[2]=true; } //==================== // THE A KEY //==================== if (e.keyCode == 65) { if(!modalitaGara) cameraInteraction.moveLeft = true; else key[1]=true; } //==================== // THE D KEY //==================== if (e.keyCode == 68) { if(!modalitaGara) cameraInteraction.moveRight = true; else key[3]=true; } // RIGHT ARROW if (e.keyCode == 39){ if(!modalitaGara) cameraInteraction.rotateRight = true; } // LEFT ARROW if (e.keyCode == 37){ if(!modalitaGara) cameraInteraction.rotateLeft = true; } // UP ARROW if (e.keyCode == 38){ if(!modalitaGara) cameraInteraction.moveUp = true; } // DOWN ARROW if (e.keyCode == 40){ if(!modalitaGara) cameraInteraction.moveDown = true; } // NUM 8 if (e.keyCode == 104){ if(!modalitaGara) cameraInteraction.rotateUp = true; } // NUM 5 if (e.keyCode == 101){ if(!modalitaGara) cameraInteraction.rotateDown = true; } // SPACEBAR if (e.keyCode == 32 && modalitaGara){ lancio(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "xToOverpressure(xTNT){\n const a1 = -0.214362789151;\n const b1 = 1.35034249993;\n const c01 = 2.78076916577;\n const c11 = -1.6958988741;\n const c21 = -0.154159376846;\n const c31 = 0.514060730593;\n const c41 = 0.0988554365274;\n const c51 = -0.293912623038;\n const c61 = -0.0268112345019;\n const c71 = 0.109097496421;\n const c81 = 0.001628467556311;\n const c91 = -0.0214631030242;\n const c101 = 0.0001456723382;\n const c111 = 0.00167847752266;\n \n //Calculo de Masa equivalente de TNT\n let masaEQTNT = (this.fe*this.hCombKJKG*this.mass)/DHCTNT;\n \n //Distancia Escalada (m/kg^1/3)\n let z = xTNT/Math.pow(masaEQTNT, 1.0/3.0);\n \n let ablog = a1+b1*Math.log10(z);\n let c = c01+c11*ablog+c21*Math.pow(ablog, 2)+c31*Math.pow(ablog, 3)+c41*Math.pow(ablog, 4)+c51*Math.pow(ablog, 5)+c61*Math.pow(ablog, 6)+c71*Math.pow(ablog, 7)+c81*Math.pow(ablog, 8)+c91*Math.pow(ablog, 9)+c101*Math.pow(ablog, 10)+c111*Math.pow(ablog, 11);\n let pres = Math.pow(10, c);\n return pres;\n\n }", "function onMotionRawValueChanged(event) {\r\n var v = event.target.value;\r\n\r\n // accel: 6Q10\r\n var _ax = cnvtEndian16(v, 0).getInt16(0);\r\n var ax = toFixedPoint(_ax, 10);\r\n var _ay = cnvtEndian16(v, 2).getInt16(2);\r\n var ay = toFixedPoint(_ay, 10);\r\n var _az = cnvtEndian16(v, 4).getInt16(4);\r\n var az = toFixedPoint(_az, 10);\r\n document.querySelector('#ax').value = ax;\r\n document.querySelector('#ay').value = ay;\r\n document.querySelector('#az').value = az;\r\n\r\n // gyro: 11Q5\r\n var _gx = cnvtEndian16(v, 6).getInt16(6);\r\n var gx = toFixedPoint(_gx, 5);\r\n var _gy = cnvtEndian16(v, 8).getInt16(8);\r\n var gy = toFixedPoint(_gy, 5);\r\n var _gz = cnvtEndian16(v, 10).getInt16(10);\r\n var gz = toFixedPoint(_gz, 5);\r\n document.querySelector('#gx').value = gx;\r\n document.querySelector('#gy').value = gy;\r\n document.querySelector('#gz').value = gz;\r\n\r\n // compass: 12Q4\r\n var _cx = cnvtEndian16(v, 12).getInt16(12);\r\n var cx = toFixedPoint(_cx, 4);\r\n var _cy = cnvtEndian16(v, 14).getInt16(14);\r\n var cy = toFixedPoint(_cy, 4);\r\n var _cz = cnvtEndian16(v, 16).getInt16(16);\r\n var cz = toFixedPoint(_cz, 4);\r\n\r\n document.querySelector('#cx').value = cx;\r\n document.querySelector('#cy').value = cy;\r\n document.querySelector('#cz').value = cz;\r\n\r\n var accel = { x: ax, y: ay, z: az };\r\n appendAccelData(accel);\r\n var gyro = { x: gx, y: gy, z: gz };\r\n appendGyroData(gyro);\r\n var compass = { x: cx, y: cy, z: cz };\r\n appendCompassData(compass);\r\n frames.a += 1;\r\n frames.g += 1;\r\n frames.c += 1;\r\n\r\n save(accel.x.toString() + ',' + accel.y.toString() + ',' + accel.z.toString() +\r\n gyro.x.toString() + ',' + gyro.y.toString() + ',' + gyro.z.toString() +\r\n compass.x.toString() + ',' + compass.y.toString() + ',' + compass.z.toString());\r\n}", "x1(t) {\n return (\n Math.sin(t / 200) * 125 + Math.sin(t / 20) * 125 + Math.sin(t / 30) * 125\n );\n }", "function convertTemp(t){\n\n return Math.round(((parseFloat(t)-273.15)*1.8)+32);\n\n}", "function tras_tsg_tmg(TSG_DEC){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy). dicembre 2009\n // TSG_DEC: Tempo siderale a Greenwich in ore decimali.\n // restituisce il valore numerico TMG in ore decimali.\n // calcolo effettuato per la data corrente.\n\n var data=new Date();\n var anno =data.getYear(); // anno.\n\n if (anno<1900) { anno=anno+1900; } // correzione anno per il browser.\n\n var valore_jda=calcola_jda(); // giorno giuliano 0.0 gennaio anno corrente.\n\n // calcolare il valore di B\n\n var S=valore_jda-2415020;\n var T=S/36525;\n var R=6.6460656+(2400.051262*T)+(0.00002581*T*T);\n var U=R-(24*(anno-1900));\n var B=24-U;\n\n B=ore_24(B); // riporta l'intervallo di B tra 0-24 ore.\n\n// valore di B\n\nvar valore_jd=calcola_jd(); // valore del giorno giuliano per la data corrente U.T. GREENWICH.\nvar num_day=Math.floor(valore_jd-valore_jda);\n\n\n var TO=(num_day*0.0657098)-B;\n\n TO= ore_24(TO); // intervallo 0-24 ore.\n\nvar TMG=TSG_DEC-TO; // valore del tempo medio a Greenwich\n\n TMG= ore_24(TMG); // intervallo 0-24 ore.\n\nTMG=TMG*0.997270;\n\nreturn TMG;\n}", "calcRisingPositons() {\n this.risingPositions = []\n let max = 120; //Per my decision: \"Highest\" point should be at 70 + buffer 50 for gradient\n let min = 500;\n let interval = (min - max) / this.risingSunColors.length - 1;\n let nextPosition = min - interval;\n while(nextPosition >= max) {\n this.risingPositions.push(nextPosition);\n nextPosition -= interval * 1;\n } \n }", "x2(t) {\n return (\n Math.sin(t / 15) * 125 + Math.sin(t / 25) * 125 + Math.sin(t / 35) * 125\n );\n }", "linear(t) {\n return t;\n }", "onSensorMove(event) {\n // Alpha = z axis [0 ,360]\n // Beta = x axis [-180 , 180]\n // Gamma = y axis [-90 , 90]\n this.data.alpha = event.alpha;\n this.data.beta = event.beta;\n this.data.gamma = event.gamma;\n }", "function getAccelerometerValues() {\n acc.onreading = () => {\n xval.innerHTML = acc.x.toFixed(3);\n yval.innerHTML = acc.y.toFixed(3);\n zval.innerHTML = acc.z.toFixed(3);\n // Data must be sent on reading!\n this.sendValues();\n }\n acc.start();\n}", "function CalculMélangeRGB() {\n \n //valeurs des curseurs\n valCurseurR = document.querySelector(\"#curseurRouge\").getElementsByTagName('input')[0].value;\n valCurseurG = document.querySelector(\"#curseurVert\").getElementsByTagName('input')[0].value;\n valCurseurB = document.querySelector(\"#curseurBleu\").getElementsByTagName('input')[0].value;\n //valeurs des curseurs en %\n pCurseurR = valCurseurR / 100;\n pCurseurB = valCurseurB / 100;\n pCurseurG = valCurseurG / 100;\n\n //recuperer les valeurs X Y Z\n XBleu = data.XYZ.B.X;\n YBleu = data.XYZ.B.Y;\n ZBleu = data.XYZ.B.Z;\n //XYZ du Vert\n XVert = data.XYZ.G.X;\n YVert = data.XYZ.G.Y;\n ZVert = data.XYZ.G.Z;\n //XYZ du rouge\n XRouge = data.XYZ.R.X;\n YRouge = data.XYZ.R.Y;\n ZRouge = data.XYZ.R.Z;\n\n //calcul du X,Y,Z pour le mélange\n\n Xmelange = (XBleu * pCurseurB) + (XVert * pCurseurG) + (XRouge * pCurseurR);\n Ymelange = (YBleu * pCurseurB) + (YVert * pCurseurG) + (YRouge * pCurseurR);\n Zmelange = (ZBleu * pCurseurB) + (ZVert * pCurseurG) + (ZRouge * pCurseurR);\n\n //calcul du melange du x et y\n xMelange = Xmelange / (Xmelange + Ymelange + Zmelange);\n yMelange = Ymelange / (Xmelange + Ymelange + Zmelange);\n\n const cieChart = document.querySelector('cie-xy-chart'); // Tu récupère le premier diagramme de ton DOM (par exemple.)\n cieChart.inputs.xy.x.value = xMelange; // Tu définis la valeur du champ x.\n cieChart.inputs.xy.x.dispatchEvent(new InputEvent('input')); // Tu déclenches l'événement \"input\" correspondant à x.\n cieChart.inputs.xy.y.value = yMelange; // Tu définis la valeur du champ y.\n cieChart.inputs.xy.y.dispatchEvent(new InputEvent('input')); // Tu déclenches l'événement \"input\" correspondant à y.\n // Déclencher les événements input devrait rafraîchir le diagramme.\n \n}", "function adapt(delta, numPoints, firstTime) {\n \t\t\t\tvar k = 0;\n \t\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n \t\t\t\tdelta += floor(delta / numPoints);\n \t\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n \t\t\t\t\tdelta = floor(delta / baseMinusTMin);\n \t\t\t\t}\n \t\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n \t\t\t}", "adaptPoints(control){\n var buffer = [];\n /*Se pasa al plano XZ*/\n for (var i = 0; i < 7; i++){ //La curva tiene siempre 7 puntos de control\n var point = new Point((control[i].x - 200)/15, 0, (control[i].y - 212)/15);\n buffer.push(point);\n }\n return buffer;\n }", "function accelReadDataX(error, data){\n if (error){\n console.log(\"Error reading the data!\");\n }\n else{ \n var time = new Date();\n //IMPORTANT THE VALUE IS IN HEXADECIMAL.\n messageToPublish = \"\" + time.getDate() + \"/\" + (time.getMonth()+1) + \"/\" + time.getFullYear() + \"/\" + time.getHours() + \":\" + time.getMinutes() + \":\" + time.getSeconds() + \", X = \" + data.toString('hex');\n a1.mqttClient.publish(\"kemalA/accel\", messageToPublish);\n console.log(\"Accel, \" + messageToPublish);\n fileToWriteAccel.write(messageToPublish+'\\n', accelWriteCallback);\n }\n}", "function eq_tempo(){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) ottobre 2011.\n // funzione per il calcolo del valore dell'equazione del tempo per la data odierna.\n // algoritmo di P.D. SMITH.\n \nvar njd=calcola_jd(); // giorno giuliano in questo istante a Greenwich.\n njd=jdHO(njd)+0.5; // g. g. a mezzogiorno di Greenwich.\n\nvar ar_sole=pos_sole(njd); // calcolo dell'ascensione retta del sole.\nvar anno=jd_data(njd); // anno di riferimento.\n\nvar Tempo_medio_Greenw=tsg_tmg_data(ar_sole[0],anno[2],njd); // tempo medio di Greenwich.\nvar valore_et=12-Tempo_medio_Greenw; // valore dell'equazione del tempo.\n\n valore_et=valore_et*60; // valore in minuti.\n\n valore_et=valore_et.toFixed(6);\n\n\n\nreturn valore_et\n\n}", "overpressureToDistance(overPressurekPa)\n{\n const a1 = -0.214362789151;\n const b1 = 1.35034249993;\n const c01 = 2.78076916577;\n const c11 = -1.6958988741;\n const c21 = -0.154159376846;\n const c31 = 0.514060730593;\n const c41 = 0.0988554365274;\n const c51 = -0.293912623038;\n const c61 = -0.0268112345019;\n const c71 = 0.109097496421;\n const c81 = 0.001628467556311;\n const c91 = -0.0214631030242;\n const c101 = 0.0001456723382;\n const c111 = 0.00167847752266;\n \n //Tolerancia del cálculo\n const tolerance = 0.001;\n\n //Valor de inicio del calculo de dsitancia x a la de sobrepresion overPressureTNT;\n let xTNT = 0;\n \n //Presion inicial para el cálculo este numero es el maximo reportado por EPA en kPA\n var pres = 33000;\n \n //Calculo de Masa equivalente de TNT\n let masaEQTNT = (this.fe*this.hCombKJKG*this.mass)/DHCTNT;\n \n //Calculo de la distancia por iteracion\n for (xTNT = 1; pres > overPressurekPa; xTNT = xTNT + tolerance)\n {\n //Distancia Escalada (m/kg^1/3)\n const z = xTNT/Math.pow(masaEQTNT, 1.0/3.0);\n \n let ablog = a1+b1*Math.log10(z);\n let c = c01+c11*ablog+c21*Math.pow(ablog, 2)+c31*Math.pow(ablog, 3)+c41*Math.pow(ablog, 4)+c51*Math.pow(ablog, 5)+c61*Math.pow(ablog, 6)+c71*Math.pow(ablog, 7)+c81*Math.pow(ablog, 8)+c91*Math.pow(ablog, 9)+c101*Math.pow(ablog, 10)+c111*Math.pow(ablog, 11);\n pres = Math.pow(10, c);\n }\n return xTNT;\n\n}", "function stampa(cosa_voglio_stampare) {\r\n console.log(cosa_voglio_stampare);\r\n}", "function stampa(cosa_voglio_stampare) {\r\n console.log(cosa_voglio_stampare);\r\n}", "function thermostatPointerTempToDeg(temp){\n return (temp * 2) + 20;\n}", "function adapt(delta, numPoints, firstTime) {\n var k = 0;\n delta = firstTime ? floor(delta / damp) : delta >> 1;\n delta += floor(delta / numPoints);\n for (\n ;\n /* no initialization */ delta > (baseMinusTMin * tMax) >> 1;\n k += base\n ) {\n delta = floor(delta / baseMinusTMin);\n }\n return floor(k + ((baseMinusTMin + 1) * delta) / (delta + skew));\n }", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}", "function onAnalogRead(x) { \n if (!x.err && typeof x.value == 'number') {\n pushData(x.value); // <10>\n }\n setTimeout(drawGraph, 20); // <11>\n }", "y1(t) {\n return (\n Math.cos(t / 10) * -125 + Math.cos(t / 20) * 125 + Math.cos(t / 30) * 125\n );\n }", "function getAccelBetweenPoints(prev, curr, prevTick) {\n let tick = new Date();\n let delta = tick - prevTick;\n let accel = (curr - prev) / delta;\n return accel;\n}", "function tsg_tmg_data(TSG_DEC,anno,njd){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy). dicembre 2009\n // TSG_DEC: Tempo siderale a Greenwich in ore decimali.\n // restituisce il valore numerico TMG in ore decimali.\n // calcolo effettuato per la data indicata nel parametro njd.\n // njd non sono necessarie le ore\n // funzione da utilizzare nelle effemeridi. \n\n var valore_jda=calcola_jd_anno(anno); // giorno giuliano 0.0 gennaio dell'anno indicato.\n\n // calcolare il valore di B\n\n var S=valore_jda-2415020; // 0.0 gennaio 1900.\n var T=S/36525;\n var R=6.6460656+(2400.051262*T)+(0.00002581*T*T);\n var U=R-(24*(anno-1900));\n var B=24-U;\n\n B=ore_24(B); // intervallo 0-24 ore.\n\n// valore di B\n\nvar valore_jd=njd; // valore del giorno giuliano per la data indicata nel parametro.\nvar num_day=Math.floor(valore_jd-valore_jda);\n\nvar TO=(num_day*0.0657098)-B;\n TO= ore_24(TO)*1; // intervallo 0-24 ore.\n\nvar TMG=TSG_DEC-TO; // valore del tempo medio a Greenwich\n\n TMG= ore_24(TMG)*1; // intervallo 0-24 ore.\n\nTMG=TMG*0.997270;\n\nreturn TMG;\n}", "function gps(s, x) {\n if(x.length <= 1) return 0\n\n let newArr = [];\n for(let i = 0; i < x.length-1; i++) {\n newArr.push(3600 * (x[i+1]-x[i]) / s)\n }\n // Better to Use spread operator \n return Math.floor(Math.max(...newArr))\n // Than sort and picking up first index\n // return Math.floor(newArr.sort((a, b) => b - a)[0])\n}", "function handleAcceleration(data) {\n t = new Date().getTime()\n ax = data.getFloat32(0, true);\n ay = data.getFloat32(4, true);\n az = data.getFloat32(8, true);\n\n var accel = {'type': 'accel', 'data': [{'time': t, 'ax': ax, 'ay': ay, 'az': az}]}\n //console.log(JSON.stringify(accel))\n ws.send(JSON.stringify(accel))\n //$.post('/arduino_csv_accel_raw', JSON.stringify(accel))\n}", "function adapt(delta, numPoints, firstTime) {\n var k = 0;\n delta = firstTime ? floor(delta / damp) : delta >> 1;\n delta += floor(delta / numPoints);\n for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n delta = floor(delta / baseMinusTMin);\n }\n return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n }", "static smoothValue(min, max, t) {\n return Interp.smoothstep(0, 1, t) * (max - min) + min;\n }", "function getTimeVals(cell, index) {\r\n //Zapamatuju si, kdy je treba preskocit na dalsi bunku\r\n t1 = casy2[index][0].split(\":\");\r\n t2 = casy2[index+getSpan(cell)][1].split(\":\");\r\n \r\n\r\n //Ulozim si rozmezi pro procenta\r\n range = [t1[0]*60+1*t1[1], t2[0]*60+1*t2[1]];\r\n console.log(range);\r\n }", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(; /* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(; /* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(; /* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "static adapt(delta, numPoints, firstTime) {\n var k = 0;\n delta = firstTime ? settings.floor(delta / settings.damp) : delta >> 1;\n delta += settings.floor(delta / numPoints);\n for ( /* no initialization */; delta > settings.baseMinusTMin * settings.tMax >> 1; k += settings.base) {\n delta = settings.floor(delta / settings.baseMinusTMin);\n }\n return settings.floor(k + (settings.baseMinusTMin + 1) * delta / (delta + settings.skew));\n }", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function telemetry() {\n\tlet status = document.getElementById('status');\n\tvar newMeasurement = {};\n\tlet sensor = new Accelerometer();\n\tsensor.addEventListener('reading', function(e) {\n\t\tstatus.innerHTML = 'x: ' + e.target.x + '<br> y: ' + e.target.y + '<br> z: ' + e.target.z;\n\t\tnewMeasurement.x = e.target.x;\n\t\tnewMeasurement.y = e.target.y;\n\t\tnewMeasurement.z = e.target.z;\n\t});\n\tsensor.start();\n\treturn newMeasurement;\n}", "function mousePreciona (eventos) \n{\n\t\n\t//guarda la ubicacion el puntero\n\tx = eventos.layerX;\n\ty = eventos.layerY;\n\t\n\testado = EstadoDeEstadoXd();\n\n}", "function xData(e) {\n return xScale(timeAccessor(e));\n }", "function xData(e) {\n return xScale(timeAccessor(e));\n }", "function unit_speed_trajectory(t,x_center,rgb) {\n p.fill(rgb[0],rgb[1],rgb[2]);\n r = p.sqrt(x_center*x_center+1);\n t_0 = p.log(r - x_center); // the \"time\" (0,1) is supposed to be at\n t_shifted = t + t_0;\n e2t = p.exp(2*t_shifted);\n et = p.exp(t_shifted);\n tanht = (e2t - 1)/(e2t + 1);\n secht = (2*et)/(e2t + 1);\n return dot(p, [x_center+r*tanht, r*secht]);\n }", "function temp_sensor() {\r\n var celsius = temp.value();\r\n var fahrenheit = celsius * 9.0/5.0 + 32.0;\r\n console.log(celsius + \" degrees Celsius, or \" +\r\n Math.round(fahrenheit) + \" degrees Fahrenheit\");\r\n\r\n deviceClient.publish(\"status\",\"json\",'{\"d\" : { \"temperature\" : '+ celsius +'}}');\r\n setTimeout(temp_sensor,1000);\r\n\r\n}", "function audfunc()\r\n{\r\n inr.value = parseFloat(aud.value) * 2.29964;\r\n usd.value = parseFloat(aud.value) * 1.13262;\r\n eur.value = parseFloat(aud.value) * 1.60329;\r\n cad.value = parseFloat(aud.value) * 0.88297; \r\n}", "function Correcto(acceleration){\n\tvar element=document.getElementById('acelerometro');\n\t\n\telement.innerHTML='Aceleracion en X;'+acceleration.x+'<br/>'+\n\t'Aceleracion en Y:'+acceleration.y+'<br/>'+\n\t'intervalo:'+acceleration.timestamp+'<br/>';\n}", "function getTemperature (event) {\n // read variables from the event\n let ev = JSON.parse(event.data);\n let evData = ev.data; // the data from the argon event: \"pressed\" or \"released\"\n let evDeviceId = ev.coreid; // the device id\n let evTimestamp = Date.parse(ev.published_at); // the timestamp of the event\n let alrtDevice = 0;\n\n // helper variables that we need to build the message to be sent to the clients\n let message = \"Verbindung zu deinem smarten Brandmelder ist aktiv.\";\n var floatValue = parseFloat(evData);\n var correctednewTempValue = ((floatValue - 4)*10)/10;\n let difference = correctednewTempValue-correctedoldTempValue;\n correctedoldTempValue = correctednewTempValue;\n let newTempValue = correctednewTempValue;\n if( difference > 0.5 ){\n alrtDevice = 1;\n }\n else{\n alrtDevice = 0;\n }\n // send data to all connected clients\n sendData(\"temperature\", newTempValue, message, evDeviceId, evTimestamp, alrtDevice);\n}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "_calcMovePrecision() {\n let precision = (this.o.maxVal - this.o.minVal) / 127;\n return precision;\n }", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function adapt(delta, numPoints, firstTime) {\n\t\t\tvar k = 0;\n\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\t\tdelta += floor(delta / numPoints);\n\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t\t}\n\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t\t}", "function temposid (njd){\n\n // funzione per il calcolo del tempo siderale di GREENWICH.\n // by Salvatore Ruiu Irgoli-Sardegna (Italy). 10 2011.\n // PARAMETRO njd --- numero dei giorni giuliani della data corrente riferita al T.U. di Greenwich.\n // fuso= fuso orario della località è già considerato nel calcolo del giorno giuliano.\n // restituisce il valore numerico SIDERAL_TIMEG in ore decimali \n \n //var time_zg=parseInt(njd)+0.5; // giorno giuliano all'ora zero di Greenwich.\n var time_zg=jdHO(njd);\n var T=(time_zg-2415020.0)/36525; \n // data di riferimento :2415020 = 0.0:1900\n\t var int_time=0.276919398+100.0021359*T+0.000001075*T*T; // numero rivoluzioni; utilizzare la parte decimale del valore int_time.\n\t \n int_time=(int_time-parseInt(int_time))*24; // tempo siderale a Greenwich alle ore zero UT\n\t \n\t var TSG=int_time // tempo siderale a Greenwich alle ore zero UT.\n\t \n// TEMPO SIDERALE PER QUALUNQUE INTERVALLO DI ORE A GREENWICH\n \n\t var time_qi=(njd-time_zg)*24; // qualunque intervallo per Greenwich.\n\t var intervallo_ts=time_qi*1.002737908;\n\t \t \n\t var SIDERAL_TIMEG=TSG+intervallo_ts; // TEMPO SIDERALE PER QUALSIASI INTERVALLO (ore decimali).\n\n SIDERAL_TIMEG=ore_24(SIDERAL_TIMEG); // intervallo 0-24 (ore decimali).\n\nreturn SIDERAL_TIMEG;}", "function getGasValue2 (event) {\n // read variables from the event\n let ev = JSON.parse(event.data);\n var evData = ev.data; // the data from the argon event: \"pressed\" or \"released\"\n let evDeviceId = ev.coreid; // the device id\n let evTimestamp = Date.parse(ev.published_at);\n let alrtDevice = 0;\n if( evData > 100 ){\n alrtDevice = 1;\n }\n else{\n alrtDevice = 0;\n }\n // helper variables that we need to build the message to be sent to the clients\n let message = \"Verbindung zu deinem smarten Brandmelder ist aktiv.\";\n // send data to all connected clients\n sendData(\"gasValue2\", evData, message, evDeviceId, evTimestamp, alrtDevice);\n}", "function adapt(delta, numPoints, firstTime) {\n var k = 0;\n delta = firstTime ? floor(delta / damp) : delta >> 1;\n delta += floor(delta / numPoints);\n\n for (;\n /* no initialization */\n delta > baseMinusTMin * tMax >> 1; k += base) {\n delta = floor(delta / baseMinusTMin);\n }\n\n return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n }", "function onCalibrate(){\r\n var slider = document.getElementById(\"myRange\");\r\n var toSend = JSON.stringify(slider.value)\r\n client.send(\"IC.embedded/jhat/sensors/calibration\", toSend, 1, true)\r\n}", "function adapt(delta, numPoints, firstTime) {\n\t var k = 0;\n\t delta = firstTime ? floor(delta / damp) : delta >> 1;\n\t delta += floor(delta / numPoints);\n\t for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base$1) {\n\t delta = floor(delta / baseMinusTMin);\n\t }\n\t return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}", "updateTemp(e) {\n var newTemp = this.state.targTemp;\n if (e.detail.angleStatus === \"VALID\") {\n var tempOffset = Math.round(Constants.TEMP_CHANGE_PER_DEG * (e.detail.deg - Constants.ANGLE_OFFSET_DEG) * 2) / 2; //only display at intervals of 0.5\n newTemp = e.detail.targTemp + tempOffset;\n } else if (e.detail.angleStatus === \"MAXBUFF\") {\n newTemp = Constants.HIGHEST_TEMP_SLIDER;\n } else if (e.detail.angleStatus === \"MINBUFF\") {\n newTemp = Constants.LOWEST_TEMP_SLIDER;\n } else {\n\n }\n this.setState({targTemp: newTemp});\n this.service.send({ type: 'UPDATETARGTEMP', targetTemp: newTemp });\n }", "function adapt(delta, numPoints, firstTime) {\n\t\tvar k = 0;\n\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\tdelta += floor(delta / numPoints);\n\t\tfor (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t}\n\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}", "function adapt(delta, numPoints, firstTime) {\n\t\tvar k = 0;\n\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\tdelta += floor(delta / numPoints);\n\t\tfor (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t}\n\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}", "getNonTransitTime ({x, y}) {\n let relx = x - this.x\n let rely = y - this.y\n\n if (Math.abs(relx) <= this.radius && Math.abs(rely) <= this.radius) {\n // make them nonnegative so they can be used as offsets\n relx += this.radius\n rely += this.radius\n\n // we can possibly walk to this pixel\n // the index of the pixel, plus one because the radius is recorded at the start of the array\n let timeSecs = this.data[rely * (this.radius * 2 + 1) + relx + 1] / 60\n let timeMins = timeSecs / 60 | 0\n if (timeSecs !== -1 && timeMins < 255) return timeMins\n }\n\n return 255\n }", "get temperature() {\n // convertimos los grados F a C\n this.temperature_F = 5 / 9 * (this.temperature_F - 32)\n return this.temperature_F;\n }", "adjustHighAndLow() {\n if (this.red + this.green > 510 - MAX_DATABITS) {\n this.red = 255 - (MAX_DATABITS >>> 1)\n this.green = 255 - (MAX_DATABITS - (MAX_DATABITS >>> 1))\n } else if (this.red + this.green < MAX_DATABITS) {\n this.red = MAX_DATABITS >>> 1\n this.green = MAX_DATABITS - (MAX_DATABITS >>> 1)\n }\n }", "function Sensor() {\n this.adapters = []\n this.fanSpeed = \"\"\n this.xAxis = ['0']\n this.grid = undefined\n}", "function adapt(delta, numPoints, firstTime) {\n\t var k = 0;\n\t delta = firstTime ? floor(delta / damp) : delta >> 1;\n\t delta += floor(delta / numPoints);\n\t for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t delta = floor(delta / baseMinusTMin);\n\t }\n\t return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}", "function adapt(delta, numPoints, firstTime) {\n\t var k = 0;\n\t delta = firstTime ? floor(delta / damp) : delta >> 1;\n\t delta += floor(delta / numPoints);\n\t for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t delta = floor(delta / baseMinusTMin);\n\t }\n\t return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}", "function computerTimeIncrements() {\n time_increments = [];\n for (var i = 0; i < curves.length; i++) {\n if (params.ArcLength) {\n time_increments.push(\n Math.round((params.Speed / curves[i].getLength()) * 200)\n );\n } else {\n time_increments.push(params.Speed);\n }\n }\n}", "function adapt(delta, numPoints, firstTime) {\n var k = 0;\n delta = firstTime ? floor(delta / damp) : delta >> 1;\n delta += floor(delta / numPoints);\n for (;delta > baseMinusTMin * tMax >> 1; k += base) {\n delta = floor(delta / baseMinusTMin);\n }\n return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n }", "function bindPortaitEvent() {\n var enterDirection = \"\";\n var portait = document.getElementById('portait');\n var offOut = portait.querySelector('.offset-outer');\n var offIn = portait.querySelector('.offset-inner');\n var front = offIn.querySelector('.sticker-front');\n var back = offIn.querySelector('.sticker-back');\n\n function portaitAnimate(hW,relaLeft,relaTop) {\n offOut.style[hW] = 50 + (hW == 'width'?relaLeft:relaTop)/2 + 'px';\n back.classList.remove('up','right','left','down');\n back.classList.add(enterDirection);\n back.style.transform = 'translate'+ (hW == 'width'?'X':'Y') +'(-' + (100 - (hW == 'width'?relaLeft:relaTop)) + 'px) scale'+ (hW == 'width'?'X':'Y') +'(-1)';\n back.querySelector('.sticker-shadow').style[hW = 'width' ? 'height' : 'width'] = \"100%\";\n back.querySelector('.sticker-shadow').style[hW] = 55 - (hW == 'width'?relaLeft:relaTop)/2 + 'px';\n }\n function portaitAnimate2(hW,relaLeft,relaTop) {\n offOut.style[hW] = (100 - (hW == 'width'?relaLeft:relaTop)/2) + 'px';\n offOut.style.transform = 'translate'+ (hW == 'width'?'X':'Y') +'(' + (hW == 'width'?relaLeft:relaTop)/2 + 'px)';\n offIn.style.transform = 'translate'+ (hW == 'width'?'X':'Y') +'(-' + (hW == 'width'?relaLeft:relaTop)/2 + 'px)';\n back.classList.remove('up','right','left','down');\n back.classList.add(enterDirection);\n back.style.transform = 'translate'+ (hW == 'width'?'X':'Y') +'(' + (hW == 'width'?relaLeft:relaTop) + 'px) scale'+ (hW == 'width'?'X':'Y') +'(-1)';\n back.querySelector('.sticker-shadow').style[hW = 'width' ? 'height' : 'width'] = '100%';\n back.querySelector('.sticker-shadow').style[hW] = (hW == 'width'?relaLeft:relaTop)/2 + 5 + 'px';\n }\n\n portait.onmousemove = function(e) {\n var relaTop = e.clientY - this.getBoundingClientRect().top;\n var relaLeft = e.clientX - this.getBoundingClientRect().left;\n switch (enterDirection) {\n case 'right':\n portaitAnimate('width', relaLeft, relaTop);\n break;\n case 'down':\n portaitAnimate('height', relaLeft, relaTop);\n break;\n case 'left':\n portaitAnimate2('width', relaLeft, relaTop);\n break;\n case 'up':\n portaitAnimate2('height', relaLeft, relaTop);\n break;\n default:\n console.log(\"default\");\n break;\n }\n };\n portait.onmouseenter = function(e) {\n offOut.style.transition = offIn.style.transition = back.style.transition = 'none';\n var relaTop = e.clientY - this.getBoundingClientRect().top;\n var relaLeft = e.clientX - this.getBoundingClientRect().left;\n enterDirection = getEnterDirection(relaTop, relaLeft, this);\n // portaitState = true;\n };\n portait.onmouseleave = function(e) {\n offOut.style.transition = offIn.style.transition = 'all .4s linear';\n back.style.transition = 'transform .4s linear';\n // portaitState = false;\n offOut.style.height = offOut.style.width = '100px';\n offOut.style.transform = offIn.style.transform = 'translateX(0) translateY(0)';\n // 'translateX(0) translateY(0)';\n switch(enterDirection) {\n case 'right':\n case 'left':\n back.style.transform = 'translateX(0) translateY(0) scaleX(-1)';\n break;\n case 'up':\n case 'down':\n back.style.transform = 'translateX(0) translateY(0) scaleY(-1)';\n break;\n default:\n break;\n }\n };\n}", "function jd_data(njd){\n // funzione per il calcolo della data dal numero del giorno giuliano.\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) novembre 2011.\n // restituisce i valori numerici gg/mm/yy.\n // il valore gg è in giorni e ore decimali. Moltiplicare la parte decimale di qq. x24.per avere le ore.\n // njd=numero del giorno giuliano.\n \n var I=parseInt(njd+0.50);\n var F=(njd+0.50)-I;\n var A=0;\n var B=0;\n\n if (I>=2229160){A=parseInt((I-1867216.25)/36524.25); B=I+1+A-parseInt(A/4);}\nelse {B=I;}\n\nvar C=B+1524;\nvar D=parseInt((C-122.1)/365.25);\nvar E=parseInt(365.25*D);\nvar G=parseInt((C-E)/30.6001);\n\n// recupero del giorno.\n\nvar giorno=C-E+F-parseInt(30.6001*G); // giorno con ore decimali.\n giorno=giorno; // toFixed(6)\n\n // recupero del mese.\n\nvar mese=0;\n\n if (G<13.5) {mese=G-1; }\nelse if (G>13.5) {mese=G-13; }\n\n // recupero dell'anno.\n\nvar anno=0;\n\n if (mese>2.5) {anno=D-4716; }\nelse if (mese<2.5) {anno=D-4715; }\n\n njd=jdHO(njd); // riporta il giorno giuliano (njd), alle ore 0(zero) del giorno.\n\nvar gio_sett=(njd+1.5)%7; // recupera il resto: calcola il numero del giorno della settimana (0=domenica, 1=lunedì....)\nvar gio_sett_n=gio_sett; // giorno della settimana numerico.\n \nvar gio_sett_en=\"\"; // giorno della settimana in inglese.\n\n if(gio_sett==0){gio_sett=\"Do\"; gio_sett_en=\"Su\"; }\nelse if(gio_sett==1){gio_sett=\"Lu\"; gio_sett_en=\"Mo\"; }\nelse if(gio_sett==2){gio_sett=\"Ma\"; gio_sett_en=\"Tu\"; }\nelse if(gio_sett==3){gio_sett=\"Me\"; gio_sett_en=\"We\"; }\nelse if(gio_sett==4){gio_sett=\"Gi\"; gio_sett_en=\"Th\"; }\nelse if(gio_sett==5){gio_sett=\"Ve\"; gio_sett_en=\"Fr\"; }\nelse if(gio_sett==6){gio_sett=\"Sa\"; gio_sett_en=\"Sa\"; }\n\nvar data_calendario=new Array(giorno,mese,anno,gio_sett,gio_sett_en,gio_sett_n);\n // array 0 1 2 3 4 5 \n\nreturn data_calendario;\n\n\n}", "snapToGrip (val) {\n return parseFloat((this.gridResolution * Math.round(val / this.gridResolution)).toFixed(2));\n }", "function fahrenheitConversion(event) {\n let temperatureElement = document.querySelector(\"#temperature\");\n let temperature = temperatureElement.innerHTML;\n temperatureElement.innerHTML = Math.round((temperature * 9) / 5 + 32);\n}", "function deCasteljau(b, t){\n var temp = [];\n for(var i = 0; i < b.length; i++){\n temp.push(b[i]);\n }\n\n for(var i = 0; temp.length > 1; i++){\n var m = temp.shift();\n var n = temp[0];\n\n temp.push({x: (m.x*(1-t) + n.x*t).toFixed(4), y: (m.y*(1-t) + n.y*t).toFixed(4)});\n\n if(i == temp.length-2){\n temp.shift();\n i = -1;\n }\n }\n return temp[0];\n }" ]
[ "0.61321664", "0.58022934", "0.5716744", "0.56321055", "0.5621674", "0.5478601", "0.5472039", "0.5283669", "0.5261521", "0.5229616", "0.5218887", "0.5192626", "0.516904", "0.5161146", "0.51399", "0.51247704", "0.5121781", "0.5121781", "0.51205933", "0.5106364", "0.5100934", "0.50979894", "0.50916344", "0.50844884", "0.5081474", "0.50740236", "0.5061076", "0.5061072", "0.5059064", "0.5058066", "0.5056322", "0.5056322", "0.5056322", "0.5055883", "0.50535804", "0.50535804", "0.50535804", "0.50535804", "0.50535804", "0.5042153", "0.50349355", "0.501922", "0.501922", "0.5016809", "0.50079125", "0.5005382", "0.5004507", "0.50034004", "0.49954137", "0.49954137", "0.49954137", "0.49954137", "0.49592417", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49590108", "0.49547535", "0.49464607", "0.4942843", "0.49402583", "0.49385956", "0.49312794", "0.49277598", "0.49277598", "0.4922062", "0.49186125", "0.49165648", "0.491558", "0.49136508", "0.49136508", "0.49107027", "0.4908692", "0.49081698", "0.49046412", "0.48980168", "0.48971623", "0.48920763" ]
0.0
-1
====================== GESTIONE DELLE FUNZIONALITA' DEL PANNELLO UI ====================== Modalita' scena/gara
function changeMod(radioButton){ if(radioButton.value == "scena"){ modalitaGara = false; initCamera(); touchCanvas2.addEventListener("mousedown", doMouseDown); touchCanvas2.addEventListener("mouseup", doMouseUp); touchCanvas2.addEventListener("mousemove", doMouseMove2); document.getElementById("sceltaVisuale").hidden = true; document.getElementById('touchCanvas2').hidden = false; } else{ modalitaGara = true; //nascondo e disabilito la canvas di rotazione visuale che non serve document.getElementById('touchCanvas2').hidden = true; touchCanvas2.removeEventListener("mousedown", doMouseDown); touchCanvas2.removeEventListener("mouseup", doMouseUp); touchCanvas2.removeEventListener("mousemove", doMouseMove2); document.getElementById("sceltaVisuale").hidden = false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function nuevo_producto(){\t\t\n\t\tllama_formulario('NUEVA CIUDAD','nuevo');\t \n\t\tVentana_modal.show();\t\t\t\n\t}", "function mostrarDevoluciones(){ // Cuando toque el boton \"devoluciones\" voy a ver la seccion (hacer devoluciones)\r\n limpiar(); //limpio campos de texto y mensajes al usuario\r\n document.querySelector(\"#homeDocente\").style.display = \"block\"; // habilito division docente\r\n document.querySelector(\"#bodyHome\").style.display = \"none\"; // oculto body bienvenida\r\n document.querySelector(\"#divAsignarNivel\").style.display = \"none\"; // oculto plantear ejercicios a alumnos\r\n document.querySelector(\"#divPlantearEje\").style.display = \"none\"; // oculto plantear tarea\r\n document.querySelector(\"#divEntregas\").style.display = \"none\"; // oculto tabla\r\n document.querySelector(\"#divDevoluciones\").style.display = \"block\"; // muestro redactar devoluciones a tareas\r\n document.querySelector(\"#divEstadisticas\").style.display = \"none\"; // oculto visualizar estadisticas\r\n}", "function mostrarAsignarNivel(){ // Cuando toque el boton \"asignar nivel\" voy a ver la seccion (Asignar nivel a alumnos)\r\n limpiar(); //limpio campos de texto y mensajes al usuario\r\n document.querySelector(\"#divMostrarTablaXDocente\").innerHTML = \"\"; //limpio tabla por posible interaccion anterior\r\n document.querySelector(\"#homeDocente\").style.display = \"block\"; //Habilito division docente\r\n document.querySelector(\"#divAsignarNivel\").style.display = \"block\"; // muestro asignar nivel\r\n document.querySelector(\"#bodyHome\").style.display = \"none\"; //Oculto body bienvenida\r\n document.querySelector(\"#divPlantearEje\").style.display = \"none\"; // oculto plantear ejercicios a alumnos\r\n document.querySelector(\"#divDevoluciones\").style.display = \"none\"; // oculto redactar devoluciones a tareas\r\n document.querySelector(\"#divEstadisticas\").style.display = \"none\"; // oculto visualizar estadisticas\r\n}", "function mostrarPlantearEje(){ // Cuando toque el boton \"plantear ejercicios\" voy a ver la seccion (plantear tarea a alumnos)\r\n limpiar(); //limpio campos de texto y mensajes al usuario\r\n document.querySelector(\"#divDevoluciones\").style.display = \"none\"; // oculto redactar devoluciones a tareas\r\n document.querySelector(\"#homeDocente\").style.display = \"block\"; //Habilito division docente\r\n document.querySelector(\"#bodyHome\").style.display = \"none\"; //Oculto body bienvenida\r\n document.querySelector(\"#divAsignarNivel\").style.display = \"none\"; // oculto plantear ejercicios a alumnos\r\n document.querySelector(\"#divPlantearEje\").style.display = \"block\"; // muestro plantear tarea\r\n document.querySelector(\"#divEntregas\").style.display = \"none\"; // oculto redactar devoluciones a tareas\r\n document.querySelector(\"#divEstadisticas\").style.display = \"none\"; // oculto visualizar estadisticas\r\n}", "function mostrarPrimPantalla(){\n\n \t\t$('#cuadro-preguntas').addClass(\"hidden\");//ocultar\n\t\t$('#segunda-pantalla').removeClass(\"hidden\");//mostrar\n \t}", "function abreModalAceiteParcela(cd_projeto, cd_proposta, cd_parcela, tx_sigla_projeto, ni_parcela) {\r\n\r\n\tvar jsonData = {'cd_projeto':cd_projeto,\r\n\t\t\t\t\t'cd_proposta': cd_proposta,\r\n\t\t\t\t\t'cd_parcela': cd_parcela,\r\n\t\t\t\t\t'ni_parcela': ni_parcela,\r\n\t\t\t\t\t'tx_sigla_projeto': tx_sigla_projeto\r\n\t\t\t\t };\r\n\teval('var buttons = {\"'+i18n.L_VIEW_SCRIPT_BTN_CANCELAR+'\": '+function(){closeDialog( 'dialog_aceite_parcela' );}+', \"'+i18n.L_VIEW_SCRIPT_BTN_SALVAR+'\": '+function(){salvarAceiteParcela();}+'};');\r\n loadDialog({\r\n id : 'dialog_aceite_parcela',\t\t//id do pop-up\r\n title : i18n.L_VIEW_SCRIPT_TITLE_DIALOG_ACEITE_PARCELA,\t\t\t// titulo do pop-up\r\n url : systemName + '/aceite-parcela',\t// url onde encontra-se o phtml\r\n data : jsonData,\t\t\t\t\t\t\t// parametros para serem transferidos para o pop-up\r\n height : 300,\t\t\t\t\t\t\t\t\t// altura do pop-up\r\n buttons : buttons\r\n });\r\n}", "function gestioneSoggettoAllegato() {\n var overlay = $('#sospendiTuttoAllegatoAtto').overlay('show');\n // Pulisco i dati\n $(\"#datiSoggettoModaleSospensioneSoggettoElenco\").html('');\n $(\"#modaleSospensioneSoggettoElenco\").find('input').val('');\n // Nascondo gli alert\n datiNonUnivociModaleSospensioneSoggetto.slideUp();\n alertErroriModaleSospensioneSoggetto.slideUp();\n\n $.postJSON('aggiornaAllegatoAtto_ricercaDatiSospensioneAllegato.do')\n .then(handleRicercaDatiSoggettoAllegato)\n .always(overlay.overlay.bind(overlay, 'hide'));\n }", "function VentanaModal(valor, ruta)\n\t{\n\t\t\t\t\t\t\t\n\t\tdocument.getElementById(\"bg_ventana_modal\").style.display=valor;\t\t\n\t\tdocument.getElementById(\"ventana_modal\").style.display=valor;\t\t\n\t\t\n\t\n\t\tdocument.getElementById(\"ventana_modal\").style.marginLeft=\"6%\";\n\t\tdocument.getElementById(\"ventana_modal\").style.marginRight=\"6%\";\n\t\tdocument.getElementById(\"ventana_modal\").style.marginTop=\"2%\";\n\t\tdocument.getElementById(\"ventana_modal\").style.marginBottom=\"2%\";\n\t\t\n\t\tdocument.getElementById(\"ventana_modal\").style.width=\"90%\";\n\t\tdocument.getElementById(\"ventana_modal\").style.height=\"90%\";\n\t\t\n\t\tdocument.getElementById(\"ventana_modal\").style.backgroundImage=ruta;\n\t\t\n\t\t\n\t\t\t\n\t}", "function leggiCapitoliNellaVariazione(){\n \t$('#tabellaGestioneVariazioni').overlay('show');\n\n \treturn $.postJSON(\"leggiCapitoliNellaVariazione_aggiornamento.do\", {})\n \t.then(function(data) {\n\t\t\tvar errori = data.errori;\n\t\t\tvar messaggi = data.messaggi;\n\t\t\tvar informazioni = data.informazioni;\n\t\t\tvar alertErrori = alertErrori;\n\t\t\tvar alertMessaggi = $(\"#MESSAGGI\");\n\t\t\tvar alertInformazioni = $(\"#INFORMAZIONI\");\n\n\t\t\t\t// Controllo gli eventuali errori, messaggi, informazioni\n\t\t\tif(impostaDatiNegliAlert(errori, alertErrori)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(impostaDatiNegliAlert(messaggi, alertMessaggi)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(impostaDatiNegliAlert(informazioni, alertInformazioni)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t//chiamo dataTable SI\n\t\t\timpostaDataTableCapitoliNellaVariazione($(\"#tabellaGestioneVariazioni\"));\n\n\t\t\timpostaTotaliInDataTable(data.totaleStanziamentiEntrata, data.totaleStanziamentiCassaEntrata, data.totaleStanziamentiResiduiEntrata, data.totaleStanziamentiEntrata1, data.totaleStanziamentiEntrata2,\n\t\t\t\t\tdata.totaleStanziamentiSpesa, data.totaleStanziamentiCassaSpesa, data.totaleStanziamentiResiduiSpesa, data.totaleStanziamentiSpesa1, data.totaleStanziamentiSpesa2);\n\t\t}).always(rimuoviOverlay.bind(this));\n }", "function abreModalFechamentoParcelaDetalhe(cd_projeto, cd_proposta, cd_parcela, tx_sigla_projeto, ni_parcela) {\r\n\r\n\tvar jsonData = {'cd_projeto':cd_projeto,\r\n\t\t\t\t\t'cd_proposta': cd_proposta,\r\n\t\t\t\t\t'cd_parcela': cd_parcela,\r\n\t\t\t\t\t'ni_parcela': ni_parcela,\r\n\t\t\t\t\t'tx_sigla_projeto': tx_sigla_projeto\r\n\t\t\t\t };\r\n\teval('var buttons = {\"'+i18n.L_VIEW_SCRIPT_BTN_CANCELAR+'\": '+function(){closeDialog( 'dialog_detalhe_fechamento_parcela' );}+'};');\r\n loadDialog({\r\n id : 'dialog_detalhe_fechamento_parcela',\t\t//id do pop-up\r\n title : i18n.L_VIEW_SCRIPT_TITLE_DIALOG_FECHAR_PARCELA,\t// titulo do pop-up\r\n url : systemName + '/controle-parcela/fechamento-parcela',\t// url onde encontra-se o phtml\r\n data : jsonData,\t\t\t\t\t\t\t// parametros para serem transferidos para o pop-up\r\n height : 230,\t\t\t\t\t\t\t\t\t// altura do pop-up\r\n buttons : buttons\r\n });\r\n}", "function ver_paciente(id_paciente) {\n\t var modal_pacientes_name = document.getElementById('modal_pacientes_name');\n\t var actionAddEdit = document.getElementById('actionAddEdit');\n\n\t $.ajax({\n\t type: 'post',\n\t url: base_url + '../Usuario/ver_paciente',\n\t data: {\n\t id_paciente: id_paciente\n\t },\n\t beforeSend: function() {\n\n\t },\n\t success: function(response) {\n\t actionAddEdit.setAttribute('onclick', 'paciente_formulario_editar(\\'' + id_paciente + '\\')');\n\t actionAddEdit.innerHTML = '<i class=\"fa fa-pencil\" aria-hidden=\"true\"></i> Editar';\n\t modal_pacientes_name.innerHTML = 'Visualizar paciente';\n\t document.getElementById('load_action_paciente').innerHTML = response;\n\n\t function cuantosAnios(dia, mes, anio) {\n\t var hoy = new Date();\n\t var nacido = new Date(anio, mes - 1, dia);\n\t var tiempo = hoy - nacido;\n\t var unanio = 1000 * 60 * 60 * 24 * 365;\n\t var tienes = parseInt(tiempo / unanio);\n\t return tienes;\n\t }\n\t }\n\t });\n\n\t}", "function voltarEtapa3() {\n msgTratamentoEtapa4.innerHTML = \"\";\n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"3º Etapa - Colaborador\";\n\n document.getElementById('selecionarPacotes').style.display = 'none'; //desabilita a etapa 4\n document.getElementById('selecionarFuncionarios').style.display = ''; //habilita a etapa 3\n }", "function etapa4() {\n \n //recebe a quantidade de funcionario selecionado\n var qtdFuncionario = document.getElementById('qtdFuncioanrio').value;\n \n //verifica se tem pelo menos 1 funcionario\n if(qtdFuncionario == 0){\n \n msgTratamentoEtapa3.textContent = \"Não foi possível seguir para a 4º Etapa! É obrigatório adicionar no mínimo um animador. =)\" \n \n }else{\n \n msgTratamentoEtapa3.innerHTML = \"\";\n \n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"4º Etapa - Pacote & Adicionais\"; \n \n document.getElementById('selecionarPacotes').style.display = ''; //habilita a etapa 4\n document.getElementById('selecionarFuncionarios').style.display = 'none'; //desabilita a etapa 3 \n }\n \n }", "function detallesFactura(idventa){\n document.getElementById(\"detallesFacModalLabel\").innerHTML=\"Detalles de la Factura con ID .v[\"+idventa+\"]\";\n cargardetalleFac(idventa); \n}", "function mostrarVentanaCajero(){\n\tnav = 20;\n\tvar nombre = datosUsuario[0][\"nombre\"];\n\tvar txt= forPantallaCajero('Cajero', nombre);\n\t$('#contenedor').html(txt);\n\t$('#contenedor').append(cargarModal());//Agrega HTML del formulario modal\n\tvar parametros ={\"opc\": nav};\n\tejecutarAjax(parametros, nav);\n}", "function abrirModalAlta(){\r\n cargaSelectAlta();\r\n $(\"#formularioAlta\").css(\"visibility\",\"visible\");\r\n $(\"#doc\").addClass(\"contenedorDesactivado\");\r\n}", "function popUpDistribucionJurisdiccion() {\n\t\tvar montoTotal = window.document.forms[0].montoFinanciamientoTotal.value;\n\t\t\n\t\tif (!IsBlank(montoTotal) && !IsNull(montoTotal) && isDouble(montoTotal)) { \n\t\t\tvar type = getCheckedValue(window.document.forms[0].tipoDistribucionFinanciamiento);\n\t\t\tvar asignacion = window.document.forms[0].codigoTipoFinanciamientoAsignacion.value;\n\t\t\tvar url= \"DistribucionFinanciamiento.do?tipo=\"+ type + \"&asignacion=\" + asignacion + \"&montoTotal=\" + montoTotal;\n\t\t\tvar scroll = true;\n\t\t\tif (type=='REGIONAL') {\n\t\t\t\tAbrirPopup(url,'350','400',scroll);\n//\t\t\t\tAbrirPopupBloqueante(url,'350','400');\n\t\t\t}\n\t\t\tif (type=='JURISDICCIONAL') {\n\t\t\t\tAbrirPopup(url,'400','750',scroll);\n//\t\t\t\tAbrirPopupBloqueante(url,'400','750');\n\t\t\t}\n\t\t} else {\n\t\t\talert('Debe ingresar un importe en Monto Total Instrumento');\t\t\n\t\t}\n\t}", "function datosTablaVigencia(val){\n var nombre = $(\"input[name ^= vigenciaNombre\"+val+\"]\").val(),\n paterno = $(\"input[name ^= vigenciaPaterno\"+val+\"]\").val(),\n materno = $(\"input[name ^= vigenciaMaterno\"+val+\"]\").val(),\n nacimiento = $(\"input[name ^= vigenciaNacimiento\"+val+\"]\").val(),\n curp = $(\"input[name ^= vigenciaCurp\"+val+\"]\").val(),\n agregado = $(\"input[name ^= vigenciaAgregado\"+val+\"]\").val(),\n vigencia = $(\"input[name ^= vigencia\"+val+\"]\").val(),\n delegacion = $(\"input[name ^= vigenciaDelegacion\"+val+\"]\").val(),\n umf = $(\"input[name ^= vigenciaUmf\"+val+\"]\").val(),\n sexo = $(\"input[name ^= vigenciaSexo\"+val+\"]\").val(),\n colonia = $(\"input[name ^= vigenciaColonia\"+val+\"]\").val(),\n direccion = $(\"input[name ^= vigenciaDireccion\"+val+\"]\").val(),\n /*Se cuenta el numero de caracteres de la direccion para tomar los ultimos 5 digitos correspondientes\n al codigo postal del paciente*/\n longituddireccion = direccion.length,\n cpostal = direccion.substring(longituddireccion-5,longituddireccion);\n if(sexo == \"F\"){\n sexo = \"MUJER\";\n }else if(sexo == \"M\"){\n sexo = \"HOMBRE\";\n }\n // Verifica la vigencia del usuario para indicar un estado de color verde si esta activo o rojo en caso contrario\n if(vigencia == \"NO\"){\n $(\"input[name = pia_vigencia]\").css('background-color', 'rgb(252, 155, 155)');\n }else if(vigencia == \"SI\"){\n $(\"input[name = pia_vigencia]\").css('background-color', 'rgb(144, 255, 149)');\n }\n //Se agrega los datos seleccionados del modal al formulario principal\n $(\"input[name = pum_nss_agregado]\").val(agregado);\n $(\"input[name = pia_vigencia]\").val(vigencia);\n $(\"input[name = pum_delegacion]\").val(delegacion);\n $(\"input[name = pum_umf]\").val(umf);\n $(\"input[name = triage_paciente_curp]\").val(curp);\n $(\"input[name = triage_nombre_ap]\").val(paterno);\n $(\"input[name = triage_nombre_am]\").val(materno);\n $(\"input[name = triage_nombre]\").val(nombre);\n $(\"input[name = triage_fecha_nac]\").val(nacimiento);\n $(\"select[name = triage_paciente_sexo]\").val(sexo);\n $(\"input[name = directorio_colonia]\").val(colonia);\n $(\"input[name = directorio_cp]\").val(cpostal);\n}", "function mostrarEstDocente(){ // Cuando toque el boton \"estadisticas\" voy a ver la seccion (ver estadisticas)\r\n limpiar(); //limpio campos de texto y mensajes al usuario\r\n document.querySelector(\"#homeDocente\").style.display = \"block\"; //Habilito division docente\r\n document.querySelector(\"#bodyHome\").style.display = \"none\"; //Oculto body bienvenida\r\n document.querySelector(\"#divAsignarNivel\").style.display = \"none\"; // oculto plantear ejercicios a alumnos\r\n document.querySelector(\"#divPlantearEje\").style.display = \"none\"; // oculto plantear tarea\r\n document.querySelector(\"#divDevoluciones\").style.display = \"none\"; // oculto redactar devoluciones a tareas\r\n document.querySelector(\"#divEstadisticas\").style.display = \"block\"; // muestro visualizar estadisticas\r\n generarListaAlumnos();\r\n}", "function ouvrir() {\n creationModal();\n }", "function setFullPosit(titulo, cuerpo) {\n var textoTitulo = document.getElementById(\"texto-titulo\");\n var textoCuerpo = document.getElementById(\"texto-cuerpo\");\n textoTitulo.innerText = titulo;\n textoCuerpo.innerText = cuerpo;\n //Mostramos el modal\n document.getElementById(\"modal-postit\").style.display = \"block\";\n}", "function verdetalle(idventa_d) {\n\t// alert(idventa);\n\tlistar_detalle_modal(idventa_d)\n\t$(\"#myModal_detalles .modal-title\").html('<i class=\"fa fa-list-ol\" aria-hidden=\"true\"></i> Detalle de Venta 00'+idventa_d);\n\t$('#myModal_detalles').modal('show');\n\n}", "function abrir_modal_seccion(tipo_modal_, tipo_, idseccion_) {\n $(\"#modal_load\").modal(\"show\");\n limpiar_modal_secciones();\n idseccion_UID = idseccion_;\n\n \n if (tipo_modal_ == 1) {\n cargar_datos_seccion(tipo_modal_);\n cargar_texto_imagen_seccion1();\n $(\"#modal_seccion_editar1\").modal(\"show\");\n }\n else if (tipo_modal_ == 2) {\n cargar_datos_seccion(tipo_modal_);\n cargar_texto_imagen_seccion2();\n $(\"#modal_seccion_editar2\").modal(\"show\");\n }\n else if (tipo_modal_ == 3) {\n cargar_datos_seccion(tipo_modal_);\n cargar_texto_seccion3();\n $(\"#modal_seccion_editar3\").modal(\"show\");\n }\n else if (tipo_modal_ == 4) {\n obj_gallery = {};\n $(\"#ul_imagenes\").html('');\n cargar_datos_seccion(tipo_modal_);\n cargar_texto_seccion4();\n cargar_imgs_galeria4();\n $(\"#modal_seccion_editar4\").modal(\"show\");\n }\n else if (tipo_modal_ == 5) {\n cargar_datos_seccion(tipo_modal_);\n cargar_texto_seccion5();\n $(\"#modal_seccion_editar5\").modal(\"show\");\n }\n \n $(\"#modal_load\").modal(\"hide\");\n}", "function apriModaleRicercaFattura() {\n var modale = $(\"#modaleRicercaFattura\");\n // Chiudo l'alert di errore\n alertErroriModale.slideUp();\n // Cancello tutti i campi\n modale.find(\":input\").val(\"\");\n // Apro il modale\n modale.modal(\"show\");\n }", "function seleccionarfila(tr){\n \n\n \n var sigla= $(\"tr #sigla\").text();\n\n var id= $('#id_organizacion').val();\n \n $(\"#titlee\").html(sigla);\n \n $(\"#superidOrganizacion\").val(id);\n // El Codigo Malandro Super Tukki ..!\n // Gracias stackoverflow ...\n\n $(\"#tabla\").removeClass(\"in\");\n $(\".modal-backdrop\").remove();\n $('#tabla').modal('hide');\n\n}", "function payerPanier(){\n \n // On cache le panier\n document.getElementById('panierModal').style.display='none';\n\n // On détruit le contenu du panier (car on va réutiliser la Somme, et on ne veut pas l'avoir 2 fois !)\n $(\"#panierModal\").remove();\n\n // On affiche la facture\n displayFacture();\n\n // On vide le panier\n panier.length = 0;\n \n // Nb article dans le panier\n refreshButtonPanier();\n\n // On affiche que le paiement a été effectué\n dipslaySnackbar(\"Paiement effectué. Merci !\");\n}", "function abreModalAceiteParcelaDetalhe(cd_projeto, cd_proposta, cd_parcela, tx_sigla_projeto, ni_parcela) {\r\n\r\n\tvar jsonData = {'cd_projeto':cd_projeto,\r\n\t\t\t\t\t'cd_proposta': cd_proposta,\r\n\t\t\t\t\t'cd_parcela': cd_parcela,\r\n\t\t\t\t\t'tx_sigla_projeto': tx_sigla_projeto,\r\n\t\t\t\t\t'ni_parcela': ni_parcela\r\n\t\t\t\t };\r\n\teval('var buttons = {\"'+i18n.L_VIEW_SCRIPT_BTN_CANCELAR+'\": '+function(){closeDialog( 'dialog_detalhe_aceite_parcela' );}+'};');\r\n loadDialog({\r\n id : 'dialog_detalhe_aceite_parcela',\t\t\t\t\t//id do pop-up\r\n title : i18n.L_VIEW_SCRIPT_TITLE_DIALOG_ACEITE_PARCELA,\t// titulo do pop-up\r\n url : systemName + '/controle-parcela/aceite-parcela',\t// url onde encontra-se o phtml\r\n data : jsonData,\t\t\t\t\t\t\t// parametros para serem transferidos para o pop-up\r\n height : 250,\t\t\t\t\t\t\t\t\t// altura do pop-up\r\n buttons : buttons\r\n });\r\n}", "function notificaInfo()\n{\n\t$('#modalHeader').html('Preventivo accettato');\n\t$('#modalBody').html('<p>Un cliente ha accettato il tuo preventivo. Attende che lo contatti, vuoi visualizzare i suoi dati?</p>');\n\t$('#modalFooter').html('<a href=\"javascript:accendiSeNotifica()\" class=\"btn\" data-dismiss=\"modal\">Annulla</a>'+\n\t\t\t\t\t\t '<a href=\"mostraQualcosa.html\" class=\"btn btn-primary\">Visualizza</a>');\n\t$('#panelNotifiche').modal('show');\n\tspegniSeNotifica();\n}", "function ClickGerarPontosDeVida(modo) {\n GeraPontosDeVida(modo);\n AtualizaGeral();\n}", "function displayPanier(){\n\n // S'il existe déjà, on le détruit\n $(\"#panierModal\").remove();\n\n /**********************************************\n Header avec titre + bouton de fermeture\n ***********************************************/\n // Titre\n var titre = document.createElement(\"h2\");\n titre.innerHTML = \"Mon Panier\";\n \n // Bouton de fermeture\n var boutonFermeture = document.createElement(\"span\");\n boutonFermeture.setAttribute(\"onClick\", \"document.getElementById('panierModal').style.display='none'\");\n boutonFermeture.setAttribute(\"class\", \"w3-button w3-display-topright w3-red w3-round header-close\");\n boutonFermeture.innerHTML = \"x\";\n \n // Header\n var modalHeader = document.createElement(\"header\");\n modalHeader.setAttribute(\"class\", \"w3-container w3-teal\");\n modalHeader.appendChild(boutonFermeture);\n modalHeader.appendChild(titre);\n \n /**********************************************\n Liste des éléments\n ***********************************************/\n // Liste principale\n var listeUl = document.createElement(\"ul\");\n listeUl.setAttribute(\"class\", \"w3-ul\");\n \n // Éléments\n var nblements = panier.length;\n if(nblements > 0){\n // On construit chaque élément\n for(var i = 0 ; i < nblements ; i++){ \n var article = panier[i];\n var element = createNewListElement(\n livres[article.id].id,\n livres[article.id].titre, \n livres[article.id].auteur, \n livres[article.id].image, \n livres[article.id].prix, \n article.nombre);\n listeUl.appendChild(element);\n }\n }else{\n // Panier vide\n var element = getMsgPanierVide();\n listeUl.appendChild(element);\n }\n\n /**********************************************\n Partie Somme des achats\n ***********************************************/\n var sumZone = document.createElement(\"div\");\n sumZone.setAttribute(\"class\", \"w3-container light-teal-bgd w3-card-4\");\n sumZone.appendChild(createSumZone());\n\n /**********************************************\n Footer avec le bouton \"Payer\" et \"Magasiner\"\n ***********************************************/ \n var boutonPayer = document.createElement(\"button\");\n boutonPayer.setAttribute(\"id\", \"panierBoutonPayer\");\n boutonPayer.setAttribute(\"class\", \"w3-button w3-round-large w3-margin w3-white w3-ripple\");\n boutonPayer.setAttribute(\"onClick\", \"payerPanier();\"); \n boutonPayer.innerHTML = \"Payer\";\n var boutonContinuer = document.createElement(\"button\");\n boutonContinuer.setAttribute(\"id\", \"panierBoutonContinuer\");\n boutonContinuer.setAttribute(\"class\", \"w3-button w3-round-large w3-margin w3-white w3-ripple\");\n boutonContinuer.setAttribute(\"onClick\", \"document.getElementById('panierModal').style.display='none'\"); \n boutonContinuer.innerHTML = \"Magasiner\";\n var footer = document.createElement(\"footer\");\n footer.setAttribute(\"class\", \"w3-center w3-teal\");\n footer.appendChild(boutonPayer);\n footer.appendChild(boutonContinuer);\n\n\n /**********************************************\n div Modal conteneur\n ***********************************************/\n // Séparateur\n var separator = document.createElement(\"div\");\n separator.setAttribute(\"class\", \"line-separator\");\n\n // Div de conteneur\n var divModalContent = document.createElement(\"div\");\n divModalContent.setAttribute(\"class\", \"w3-modal-content w3-card-4 w3-animate-top\");\n divModalContent.appendChild(modalHeader); // L'entête\n divModalContent.appendChild(listeUl); // La liste des éléments\n divModalContent.appendChild(separator); // Séparateur\n divModalContent.appendChild(sumZone); // Le prix final\n divModalContent.appendChild(footer); // Bouton Payer\n\n /**********************************************\n Div principal\n ***********************************************/\n var divMain = document.createElement(\"div\");\n divMain.setAttribute(\"id\", \"panierModal\");\n divMain.setAttribute(\"class\", \"w3-modal\");\n divMain.appendChild(divModalContent);\n\n // Ajout à la page web\n document.getElementById('panier').appendChild(divMain);\n\n // Affichage\n document.getElementById('panierModal').style.display='block';\n\n // Total du panier\n refreshSomme();\n\n // Si le panier est vide, on cache le bouton \"Payer\", sinon on l'affiche\n displayButtonPayer();\n}", "function ClickAbrir() {\n var nome = ValorSelecionado(Dom('select-personagens'));\n if (nome == '--') {\n Mensagem('Nome \"--\" não é válido.');\n return;\n }\n var eh_local = false;\n if (nome.indexOf('local_') == 0) {\n eh_local = true;\n nome = nome.substr(6);\n } else {\n nome = nome.substr(5);\n }\n var handler = {\n nome: nome,\n f: function(dado) {\n if (nome in dado) {\n gEntradas = JSON.parse(dado[nome]);\n CorrigePericias();\n AtualizaGeralSemLerEntradas();\n SelecionaValor('--', Dom('select-personagens'));\n Mensagem(Traduz('Personagem') + ' \"' + nome + '\" ' + Traduz('carregado com sucesso.'));\n } else {\n Mensagem(Traduz('Não encontrei personagem com nome') + ' \"' + nome + '\"');\n }\n DesabilitaOverlay();\n },\n };\n HabilitaOverlay();\n AbreDoArmazem(nome, eh_local, handler.f);\n}", "function mostrarFechasResultantes (infoFechaInmunidad, infoFechaRevacunacion){\n //levanto el modal donde están las cajas de mensaje donde\n //cargo la información de las fechas\n $('#modalInfo').modal();\n //asigno la información de las fechas a las cajas de texto\n const infoFechaInmune = document.getElementById(\"fInmune\");\n infoFechaInmune.innerHTML = `${infoFechaInmunidad}`;\n const infoFechaRevacunar = document.getElementById(\"fRevacunacion\");\n infoFechaRevacunar.innerHTML = `${infoFechaRevacunacion}`;\n\n\n}", "function modals_supernumerario_admin(titulo,mensaje){\n\n\tvar modal='<!-- Modal -->';\n\t\t\tmodal+='<div id=\"myModal4\" class=\"modal2 hide fade\" style=\"margin-top: -1%; background-color: rgb(41, 76, 139); color: #fff; z-index: 900000; behavior: url(../../css/PIE.htc);width: 60%; left: 50%;\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\" data-backdrop=\"true\">';\n\t\t\tmodal+='<div class=\"modal-header\" style=\"border-bottom: 0px !important;\">';\n\t\t\tmodal+='<button type=\"button\" class=\"close\" style=\"color:#fff !important;\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>';\n\t\t\tmodal+='<h4 id=\"myModalLabel\">'+titulo+'</h4>';\n\t\t\tmodal+='</div>';\n\t\t\tmodal+='<div class=\"modal-body\" style=\"max-height: 560px; max-width: 92% !important; background-color:#fff; margin: 0 auto; margin-bottom: 1%; border-radius: 8px; behavior: url(../../css/PIE.htc);\">';\n\t\t\tmodal+='<p id=\"msj_modal\">'+mensaje+'</p>';\n\t\t\tmodal+='</div>';\n\t\t\n\t\t\tmodal+='</div>';\n\t$(\"#main\").append(modal);\n\t\n\t$('#myModal4').modal({\n\t\tkeyboard: false,\n\t\tbackdrop: \"static\" \n\t});\n\t\n\t$('#myModal4').on('hidden', function () {\n\t\t$(this).remove();\n\t});\n\t\n}", "function mostrarJogada (e){\n\n escolha.style.display = \"none\"\n containerPlay.style.display = \"none\"\n containerJogada.style.display = \"flex\"\n containerRegras.style.display = \"flex\"\n\n nivelDificuldade = e.target.id\n\n return geracaoTorreHanoi(nivelDificuldade)\n\n}", "function cargarDatosModalDetalleNecesidad( necesidad ){\n $('.detalleNecesidadModal').html(\n `<div class=\"card necesidad ${necesidad.nombreCategoria.toLowerCase()}\">\n <div class=\"card-body\">d\n <div class=\"container-fluid\">\n <div class=\"datosNecesidad\">\n <p class=\"font-weight-bold\">${necesidad.nombreCategoria}</p>\n <p>${necesidad.descripcionNecesidad}</p>\n <p>Cantidad: ${necesidad.cantidadNecesidad}</p>\n <p>Fecha limite: ${ new Date(necesidad.fechaLimiteNecesidad).toLocaleDateString('es-AR') }</p>\n <p>Estado: en proceso</p>\n <p>Colaboradores: 5</p>\n </div>\n </div>\n <button type=\"button\" class=\"btn btnColaborar btn-block btn-outline-primary mt-4\" data-toggle=\"modal\" data-target=\"#modalColaborar\"><i class=\"far fa-handshake\"></i>COLABORAR</button>\n </div>\n </div>`)\n}", "function telaIngrediente(tipoRequisicao, id) {\r\n let codigoHTML = ``;\r\n\r\n codigoHTML += `<div class=\"modal\" id=\"modaltelaingrediente\">\r\n <div class=\"modal-dialog modal-lg modal-dialog-scrollable\">\r\n <div class=\"modal-content\">\r\n <div class=\"modal-header\">\r\n <h5 class=\"modal-title\"><span class=\"fas fa-carrot\"></span> Dados do ingrediente</h5>\r\n <button type=\"button\" class=\"close btn-outline-danger\" data-dismiss=\"modal\" aria-label=\"Close\">\r\n <span aria-hidden=\"true\">&times;</span>\r\n </button>\r\n </div>\r\n <div class=\"modal-body\">`\r\n if (tipoRequisicao == 'cadastrar') {\r\n codigoHTML += `<h4 class=\"text-center\"><span class=\"fas fa-carrot\"></span> Criar ingrediente</h4>`\r\n } else {\r\n codigoHTML += `<h4 class=\"text-center\"><span class=\"fas fa-carrot\"></span> Atualizar ingrediente</h4>`\r\n }\r\n codigoHTML += `<form class=\"card-deck col-11 mx-auto d-block\" style=\"margin-top:30px;\">\r\n <div class=\"row shadow-lg p-3 mb-4 bg-white rounded\">\r\n <div class=\"col-6\">\r\n <label>Nome do ingrediente: </label>\r\n <input id=\"nomeingrediente\" type=\"text\" class=\"form-control mousetrap\" placeholder=\"Nome do ingrediente\">\r\n </div>\r\n <div class=\"col-6\">\r\n <label>Preço de custo (total): </label>\r\n <div class=\"input-group\">\r\n <div class=\"input-group-prepend\">\r\n <span class=\"input-group-text\">R$</span>\r\n </div>\r\n <input id=\"precocustoingrediente\" type=\"Number\" class=\"form-control mousetrap\" placeholder=\"Preço de custo\">\r\n </div>\r\n </div>\r\n </div>\r\n <div class=\"row shadow-lg p-3 mb-4 bg-white rounded\">\r\n <div class=\"col-6\">\r\n <label>Quantidade: </label>\r\n <input id=\"quantidadeingrediente\" type=\"Number\" class=\"form-control mousetrap\" placeholder=\"Quantidade\">\r\n </div>\r\n <div class=\"col-6\">\r\n <div class=\"form-group\">\r\n <label for=\"unidademedidaingrediente\">Unidade de medida: </label>\r\n <select class=\"form-control\" id=\"unidademedidaingrediente\">\r\n <option value=\"g\">G (Grama)</option>\r\n <option value=\"ml\">ML (Mililitro)</option>\r\n <option value=\"u\">Unid. (Unidade)</option>\r\n </select>\r\n </div>\r\n </div>\r\n </div>\r\n <div class=\"row shadow-lg p-3 mb-4 bg-white rounded\">\r\n <div class=\"col\">\r\n <label>Descrição: </label>\r\n <textArea type=\"text\" id=\"descricaoingrediente\" class=\"form-control mousetrap\" placeholder=\"Descrição\" rows=\"5\">Nenhuma.</textArea>\r\n </div>\r\n </div>\r\n </form>\r\n </div>\r\n <div class=\"modal-footer\">`\r\n if (tipoRequisicao == 'cadastrar') {\r\n codigoHTML += `<button onclick=\"if(validaDadosCampo(['#nomeingrediente','#precocustoingrediente','#quantidadeingrediente','#descricaoingrediente']) && validaValoresCampo(['#precocustoingrediente','#quantidadeingrediente'])){cadastrarIngrediente(); $('#modaltelaingrediente').modal('hide');}else{mensagemDeErro('Preencha os campos nome e preço com valores válidos!'); mostrarCamposIncorrreto(['nomeingrediente','precocustoingrediente','quantidadeingrediente','descricaoingrediente']);}\" type=\"button\" class=\"btn btn-primary\">\r\n <span class=\"fas fa-save\"></span> Salvar\r\n </button>`\r\n } else {\r\n codigoHTML += `<button onclick=\"if(validaDadosCampo(['#nomeingrediente','#precocustoingrediente','#quantidadeingrediente','#descricaoingrediente']) && validaValoresCampo(['#precocustoingrediente','#quantidadeingrediente'])){confirmarAcao('Atualizar os dados do produto!', 'atualizaIngrediente(this.value)','${id}'); $('#modaltelaingrediente').modal('hide');}else{mensagemDeErro('Preencha todos os campos com valores válidos!'); mostrarCamposIncorrreto(['nomeingrediente','precocustoingrediente','quantidadeingrediente','descricaoingrediente']);}\" type=\"button\" class=\"btn btn-success\">\r\n <span class=\"fas fa-pencil-alt\"></span> Atualizar\r\n </button>\r\n <button onclick=\"confirmarAcao('Excluir os dados do produto permanentemente!', 'deletarIngrediente(this.value)', '${id}'); $('#modaltelaingrediente').modal('hide');\" type=\"button\" class=\"btn btn-outline-danger\">\r\n <span class=\"fas fa-trash-alt\"></span> Excluir\r\n </button>`\r\n }\r\n codigoHTML += `</div>\r\n </div>\r\n </div>\r\n </div>`\r\n\r\n\r\n document.getElementById('modal').innerHTML = codigoHTML;\r\n $('#modaltelaingrediente').modal('show')\r\n}", "function addAgenmento() {\n var pop = $('#md-editar-agendamento');\n\n if (pop) {\n loadClientes().then(() => {\n onNovoAgendamento();\n setPopAgendamentoTitle(\"Criar Agendamento\");\n pop.draggable();\n pop.modal();\n });\n }\n }", "function displayFacture(){\n\n // Si elle existe déjà, on la détruit\n $(\"#factureDetail\").empty();\n $(\"#factureSomme\").empty();\n\n // Titre\n var titre = document.createElement(\"h2\");\n titre.setAttribute(\"class\", \"w3-center\");\n titre.innerHTML= \"La Livrairie vous remercie !\";\n\n // Si la personne a fournie ses coordonnées, on les affiches (Pas de vérification demandée dans le TP)\n if(coordonnees.nom){\n $(\"#factureCoord\").show();\n $(\"#factureNom\").text(\"Nom : \" + coordonnees.nom);\n $(\"#facturePrenom\").text(\"Prénom : \" + coordonnees.prenom);\n $(\"#factureAdresse\").text(\"Adresse : \" + coordonnees.address);\n }\n\n // On crée les éléments correspondants aux achats\n for(var p in panier){\n $(\"#factureDetail\").append(createFactureElement(panier[p]));\n }\n\n // On crée la zone somme\n var somme = createSumZone(); \n \n // Ajout de la somme\n var list = $(\"#factureSomme\").append(somme);\n\n\n // On affiche\n document.getElementById(\"factureModal\").style.display='block';\n\n // On remplie les montants de la somme\n refreshSomme();\n}", "function cadastrarDespesa() {\n\n let ano = document.getElementById('ano')\n let mes = document.getElementById('mes')\n let dia = document.getElementById('dia')\n let tipo = document.getElementById('tipo')\n let descricao = document.getElementById('descricao')\n let valor = document.getElementById('valor')\n\n //atruir os valores dos inputs instanciando o objeto Despesa\n let despesa = new Despesa(\n ano.value,\n mes.value,\n dia.value,\n tipo.value,\n descricao.value,\n valor.value\n )\n\n //Validacão\n if(despesa.validarDados()) {\n //Executar o método de gravação na instancia do objeto bd\n bd.gravar(despesa) \n\n //cor do header\n let header = document.getElementById('headerRegistro')\n header.classList.add(\"text-success\")\n\n //Conteudo do cabeçalho\n document.getElementById('tituloRegistro').innerHTML = 'Registrado com sucesso!'\n\n //Conteudo do corpo\n document.getElementById('corpoRegistro').innerHTML = 'Seus dados foram salvos.'\n\n //Botão cor\n let btn = document.getElementById('btnRegistro')\n btn.classList.add(\"btn-success\")\n\n //Botao Conteudo\n btn.innerHTML = 'Finalizar'\n\n //dialog de sucesso\n $('#registraDespesa').modal('show')\n\n //reset\n ano.value = ''\n mes.value = ''\n dia.value = ''\n tipo.value = ''\n descricao.value = ''\n valor.value = ''\n \n } else {\n //dialog de erro\n $('#registraDespesa').modal('show')\n \n //Cabeçalho cor\n let header = document.getElementById('headerRegistro')\n header.classList.add(\"text-danger\")\n\n //Conteudo do cabeçalho\n document.getElementById('tituloRegistro').innerHTML = 'Erro no registro!'\n\n //Conteudo do corpo\n document.getElementById('corpoRegistro').innerHTML = 'Dados vazios ou incorretos.'\n\n //Botão cor\n let btn = document.getElementById('btnRegistro')\n btn.classList.add(\"btn-danger\")\n\n //Botao Conteudo\n btn.innerHTML = 'Refazer'\n \n }\n\n}", "function fnAgregar(){\n\t//$(\"button\").removeAttr('disabled');\n\tvar id_identificacion = $('#selectFuenteRecurso').val();\n\tvar clave = $('#txtClave').val();\n\tvar descripcion = $('#txtDescripcion').val();\n\tvar msg = \"\";\n\n\t/*if (id_identificacion == \"\" || id_identificacion == 0 || clave == \"\" || descripcion == \"\") {\n\t\t$('#ModalUR').modal('hide');\n\t\tmuestraMensaje('Agregar Finalidad, Función y Descripción para realizar el proceso', 3, 'msjValidacion', 5000);\n\t\treturn false;\n\t}*/\n\t/*if (clave == \"\" && descripcion == \"\") {\n\t\t\n\t\t$('#ModalUR').modal('hide');\n\t\tmuestraMensaje('Debe agregar Función y Descripción para realizar el proceso', 3, 'msjValidacion', 5000);\n\t\treturn false;\n\t\t\n\t}else if (clave == \"\") {\n\t\t$('#ModalUR').modal('hide');\n\t\tmuestraMensaje('Debe agregar Función para realizar el proceso', 3, 'msjValidacion', 5000);\n\t\treturn false;\n\t}else if (descripcion == \"\") {\n\t\t$('#ModalUR').modal('hide');\n\t\tmuestraMensaje('Debe agregar Descripción para realizar el proceso', 3, 'msjValidacion', 5000);\n\t\t\n\t\treturn false;\n\t}*/\n\n\tif (clave == \"\" || descripcion == \"\") {\n\t\tif (clave == \"\" ) {\n\t\t\tmsg += '<p>Falta capturar la clave </p>';\n\t\t}\n\t\tif (descripcion==\"\" ) {\n\t\t\tmsg += '<p>Falta capturar el Descripción </p>';\n\t\t}\n\n\t\t$('#divMensajeOperacion').removeClass('hide');\n\t\t$('#divMensajeOperacion').empty();\n\t\t$('#divMensajeOperacion').append('<div class=\"alert alert-danger alert-dismissable\">' + msg + '<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button></div>');\n\t\t\n\t}else{\n\t\t$('#ModalUR').modal('hide');\n\t\tdataObj = { \n\t\t option: 'AgregarCatalogo',\n\t\t id_identificacion: id_identificacion,\n\t\t clave: clave,\n\t\t descripcion: descripcion,\n\t\t proceso: proceso\n\t\t };\n\t\t//Obtener datos de las bahias\n\t\t$.ajax({\n\t\t\t async:false,\n\t cache:false,\n\t\t method: \"POST\",\n\t\t dataType:\"json\",\n\t\t url: url,\n\t\t data:dataObj\n\t\t })\n\t\t.done(function( data ) {\n\t\t if(data.result){\n\t\t \tmuestraMensaje(data.contenido, 1, 'divMensajeOperacion', 5000);\n\n\t\t \tfnLimpiarTabla('divTabla', 'divContenidoTabla');\n\t\t \tfnMostrarDatos('','');\n\t\t }else{\n\t\t \tmuestraMensaje(data.contenido, 3, 'divMensajeOperacion', 5000);\n\t\t }\n\t\t})\n\t\t.fail(function(result) {\n\t\t\tconsole.log(\"ERROR\");\n\t\t console.log( result );\n\t\t});\n\t}\n}", "function logo_click() {\n if (pasos.paso1.aseguradoraSeleccionada != null && pasos.paso1.aseguradoraSeleccionada.id == pasos.paso1.listaAseguradoras[$(this).index()].id) {\n componentes.progreso.porcentaje = 0;\n componentes.progreso.barra.css({width: '0px'});\n pasos.paso1.aseguradoraSeleccionada = null;\n $(this).removeClass(\"seleccionada\");\n componentes.pasos.paso1.numero_siniestro.prop('readonly', true);\n } else {\n if (pasos.paso1.aseguradoraSeleccionada == null) {\n componentes.progreso.porcentaje = 5;\n componentes.progreso.barra.css({width: '5%'});\n }\n pasos.paso1.aseguradoraSeleccionada = pasos.paso1.listaAseguradoras[$(this).index()];\n $.get('http://localhost:8080/ReForms_Provider/wr/perito/buscarPeritoPorAseguradora/' + pasos.paso1.aseguradoraSeleccionada.id, respuesta_buscarPeritoPorAseguradora, 'json');\n $(this).siblings(\".seleccionada\").removeClass(\"seleccionada\");\n $(this).addClass(\"seleccionada\");\n componentes.pasos.paso1.numero_siniestro.prop('readonly', false);\n }\n componentes.pasos.paso1.numero_siniestro.val('').focus();\n componentes.pasos.paso1.numero_siniestro.keyup();\n }", "function jogar() {\n //variáveis globais\n img_count = 1;\n pal_count = 0;\n al_tam = 0;\n\n //sorteando a palavra para o jogo\n obj = _geraPalavras(Math.floor(Math.random() * 11));\n\n //inserindo imagem do boneco\n document.getElementsByTagName('img')[0].style.display = 'block';\n document.getElementsByTagName('img')[0].src = `../public/image/stc_${img_count++}.png`;\n\n //preparando os botões do jogo\n document.getElementById('jogar').style.display = 'none';\n\n document.getElementById('letra').style.display = 'inline';\n document.getElementById('chute').style.display = 'inline';\n document.getElementById('inp-palavra').style.display = 'inline';\n document.getElementById('btn-palavra').style.display = 'inline';\n document.getElementById('desistir').style.display = 'inline';\n\n //limpando letras utilizadas e exibindo\n document.getElementById('letrasUtilizadas').innerHTML = '';\n document.getElementById('letrasUtilizadas').style.display = 'block';\n\n //inserindo dica\n document.getElementById('p-txt').innerHTML = obj.dica;\n\n //criando caixinhas da palavra\n let str = '<form id=\"formJogo\">';\n\n for (let i = 0; i < obj.palavra.length; i++) \n str += `<button type=\"button\" value=\"${obj.palavra[i]}\"></button>`;\n str += '</form>'\n\n //inserindo as caixinhas na view\n document.getElementById('div-palavra').innerHTML = str;\n\n //armazenando os dados referentes a palavra sorteada\n pal_tam = pal_count = document.forms['formJogo'].length;\n}", "function apriModaleSoggetto(e) {\n e.preventDefault();\n $(\"#codiceSoggetto_modale\").val($(\"#codiceSoggetto\").val());\n $(\"#modaleGuidaSoggetto\").modal(\"show\");\n }", "function carritoVacio() {\n\n $(\".modal-body-aviso\").text(\"Debes tener al menos un producto en el carrito para poder registrarte y confirmar la compra.\");\n $(\".btnRevisar\").hide();\n $(\"#modalAviso\").modal(\"show\");\n\n}", "function msj(titulo, contenido, idioma) {\n var padre = document.createElement('div');\n padre.id = 'modal';\n document.body.appendChild(padre);\n var bc = idioma ? idioma : 'Aceptar';\n var ModalData = document.getElementById(\"modal\");\n var boton = \"\";\n ModalData.innerHTML = '<div id=\"modal-back\"></div><div class=\"modal\"><div id=\"modal-c\"><h3>'+titulo+'</h3><span id=\"mc\">'+contenido+'</span><div id=\"buttons\"><a id=\"mclose\" href=\"#\">'+bc+'</a>'+boton+'</div></div></div>';\n document.querySelector(\".modal\").style.height = document.getElementById(\"mc\").offsetHeight+100 + 'px';\n document.getElementById('mclose').onclick=function(){ borrar('modal'); };\n document.getElementById('modal-back').onclick=function(){ borrar('modal'); }\n }", "function forSeleccionarMesa(){\nvar txt='<div class=\"div-center\"><div class=\"content\"><div id=\"head\"><img src=\"img/logo1.png\" alt=\"logo\" id=\"imgLogin\"><h2></h2>';\ntxt += '<hr /></div><div id=\"asignar\"><table class=\"table table-bordered table-light\" ><thead><tr class=\"table-active\">';\ntxt += '<th scope=\"col\">Mesa</th><th scope=\"col\">Capacidad</th><th scope=\"col\"></th></tr></thead><tbody><tr><td scope=\"row\">15</td>';\ntxt += '<td>4</td><td><button onClick=\"mostrarCategoriaProduto()\" class=\"btn btn-info\"><span class=\"glyphicon glyphicon-ok\"></span></button></td></tr><tr><td scope=\"row\">8</td>';\ntxt += '<td>2</td><td><button onClick=\"mostrarCategoriaProduto()\" class=\"btn btn-info\"><span class=\"glyphicon glyphicon-ok\"></span></button></td></tr><tr><td scope=\"row\">12</td>';\ntxt += '<td>8</td><td><button onClick=\"mostrarCategoriaProduto()\" class=\"btn btn-info\"><span class=\"glyphicon glyphicon-ok\"></span></button></td></tr></tbody></table></div>';\ntxt += '<hr/><div id=\"campoBtn\"></div></div></div>';\n/*<button class=\"btn btn-info pull-left\" onClick=\"regresar()\" id=\"btnRegreso\"><span class=\"glyphicon glyphicon-chevron-left\"></span></button>*/\n\treturn txt;\t\n}", "function mostrarVentanaChef1(nombre){\n\tnav = 10;\n\tvar parametros ={\"opc\": nav};\n\tejecutarAjax(parametros, nav);\n\n\tvar txt= forPantallaChef1('COCINA', nombre);\n\t$('#contenedor').html(txt);\n\t$('#contenedor').append(cargarModalChef1());//Agrega HTML del formulario modal\n}", "function nuvoInscPreli(){ \n $(\".modal-title\").html(\"Nueva incripción\"); \n $('#formIncPreliminar').modal('show');\n}", "function modal(){\n this.mostrarModal = function(){\n var estados = \"\";\n var i=0;\n var contador = 8;\n var elem='https://reporte2.atentus.com/simbologia.php';\n var enlace = elem.replace(elem,\"<a href='\"+elem+\"' target='_blank'>\"+elem+\"</a>\"); \n var ayuda = [\n \"Url \",\n \"Estado: \",\n \"Bytes: \",\n \"Segundos: \",\n \"Ip: \",\n \"Latencia\",\n \"Dns\",\n \"Descarga\"\n ];\n var descripcion = [ \n \"Hace referencia la URL del elemento actual.\",\n \"Indica el código del elemento HTTP que devolvió el servidor WEB o el error de red que detecto el atentubot, más información de códigos en: \"+enlace+\".\",\n \"Columna que indica el tamaño de los elementos.\",\n \"Columna que indica el tiempo total que tardo un elemento en descargar.\",\n \"Muestra la dirección IP del elemento actual.\",\n \"Tiempo que transcurrio entre la petición del elemento hasta que empezo la descarga del primer byte.\",\n \"Tiempo que demora el servidor DNS en resolver.\",\n \"Tiempo que transcurrio entre la descarga del primer byte y el termino de la descarga completa.\"\n ]; \n //recorre los array para posicionarlos en tablas separadas\n for ( i=0; i<contador; i++){\n estados = estados + '<table class=\"definicion\" width=\"100%\" ><tr><th>' + ayuda[i] + '</th></tr><tr><td>' + descripcion[i] + '</td></tr></table></br>';\n }\n dojo.byId(\"contenido\").innerHTML = estados;\n dijit.byId(\"ModalAyuda\").show();\n };\n//Destruye identificador si esta no ha sido definida\n this.cerrarAyuda= function(){\n if(typeof dijit.byId(\"ModalAyuda\") != \"undefined\"){\n dijit.byId(\"ModalAyuda\").destroyRecursive();\n }\n };\n //Destruye identificador si esta ha sido definida\n this.cerrarElemento= function(){\n if(typeof dijit.byId(\"ModalMuestra\") != \"undefined\"){\n dijit.byId(\"ModalMuestra\").destroyRecursive();\n }\n };\n \n}", "function compruebaFin() {\r\n if( oculta.indexOf(\"_\") == -1 ) {\r\n document.getElementById(\"msg-final\").innerHTML = \"Felicidades !!\";\r\n document.getElementById(\"msg-final\").className += \"zoom-in\";\r\n document.getElementById(\"palabra\").className += \" encuadre\";//className obtine y establece el valor del atributo de la clase del elemento especificado\r\n for (var i = 0; i < buttons.length; i++) {\r\n buttons[i].disabled = true;\r\n }\r\n document.getElementById(\"reset\").innerHTML = \"Empezar\";\r\n btnInicio.onclick = function() { location.reload() };\r\n }else if( cont == 0 ) {\r\n document.getElementById(\"msg-final\").innerHTML = \"Juego Finalizado\";\r\n document.getElementById(\"msg-final\").className += \"zoom-in\";\r\n document.getElementById(\"dibujo_ahorcado\").style.display=\"none\";\r\n document.getElementById(\"segundo\").style.display=\"block\";\r\n\r\n for (var i = 0; i < buttons.length; i++) {\r\n buttons[i].disabled = true; //Desactiva el boton despues de precionarlo\r\n }\r\n document.getElementById(\"reset\").innerHTML = \"Empezar\";\r\n btnInicio.onclick = function () { location.reload() }; // el reload me sirve para volver a cargar el juego o una nueva palabra en menos palabra\r\n }\r\n}", "function mostrarPalabra(){\n \n}", "function visProdukt(produkt) {\n console.log(produkt);\n\n\n /**** KLON PRODUKT_TEMPLATE ****/\n var klon = document.querySelector(\"#produkt_template\").content.cloneNode(true);\n\n\n /**** INDSÆTTER DATA I KLON I .ret ****/\n klon.querySelector(\".data_navn\").innerHTML = produkt.navn;\n klon.querySelector(\".data_kort_beskrivelse\").innerHTML = produkt.kortbeskrivelse;\n klon.querySelector(\".data_allergener\").innerHTML = produkt.allergener;\n klon.querySelector(\".data_pris\").innerHTML = produkt.pris;\n\n\n /**** INDSÆTTER DATA I KLON I MODAL ****/\n klon.querySelector(\".modal_overskrift\").innerHTML = produkt.navn;\n klon.querySelector(\".modal_lang_beskrivelse\").innerHTML = produkt.langbeskrivelse;\n klon.querySelector(\".modal_allergener\").innerHTML = produkt.allergener;\n klon.querySelector(\".modal_data_pris\").innerHTML = produkt.pris;\n\n\n /**** SE DETALJER-KNAP ****/\n klon.getElementById(\"modal_menukort\").setAttribute(\"id\", \"modal_menukort_\" + produkt.id);\n klon.getElementById(\"se_detaljer_knap\").setAttribute(\"data-target\", \"#modal_menukort_\" + produkt.id);\n\n\n /**** HENTER KORT BESKRIVELSE IND I MODAL, HVIS LANG BESKRIVELSE IKKE ER I DATA HOS SPECIFIKT PRODUKT ****/\n if (produkt.langbeskrivelse == \"\") {\n klon.querySelector(\".modal_lang_beskrivelse\").innerHTML = produkt.kortbeskrivelse;\n }\n\n\n /**** RABAT-BEREGNING I .ret ****/\n var rabatpris = Math.ceil(produkt.pris - (produkt.pris * produkt.rabatsats / 100));\n klon.querySelector(\".data_rabatpris\").innerHTML = rabatpris;\n\n\n /**** RABAT-BEREGNING I MODAL ****/\n var rabatpris = Math.ceil(produkt.pris - (produkt.pris * produkt.rabatsats / 100));\n klon.querySelector(\".modal_data_rabatpris\").innerHTML = rabatpris;\n\n\n /**** BILLEDER ****/\n klon.querySelector(\".data_billede\").src = \"./Billeder/imgs/Large/\" + produkt.billede + \".jpg\";\n\n\n /**** ALLERGENER I .ret ****/\n if (produkt.allergener == false) {\n var allergener = klon.querySelector(\".allergener_tekst\");\n allergener.parentNode.removeChild(allergener);\n } else {\n klon.querySelector(\".data_allergener\").innerHTML = produkt.allergener;\n }\n\n\n /**** ALLERGENER I MODAL ****/\n if (produkt.allergener == false) {\n var allergener = klon.querySelector(\".modal_allergener_tekst\");\n allergener.parentNode.removeChild(allergener);\n } else {\n klon.querySelector(\".modal_allergener\").innerHTML = produkt.allergener;\n }\n\n\n /**** VEGETAR I .ret ****/\n if (produkt.vegetar == false) {\n var vegetaregnet = klon.querySelector(\".vegetaregnet_tekst\");\n vegetaregnet.parentNode.removeChild(vegetaregnet);\n } else {\n var ikke_vegetaregnet = klon.querySelector(\".ikke_vegetaregnet_tekst\");\n ikke_vegetaregnet.parentNode.removeChild(ikke_vegetaregnet);\n }\n\n\n /**** VEGETAR I MODAL ****/\n if (produkt.vegetar == false) {\n var vegetaregnet = klon.querySelector(\".modal_vegetaregnet_tekst\");\n vegetaregnet.parentNode.removeChild(vegetaregnet);\n } else {\n var ikke_vegetaregnet = klon.querySelector(\".modal_ikke_vegetaregnet_tekst\");\n ikke_vegetaregnet.parentNode.removeChild(ikke_vegetaregnet);\n }\n\n\n /**** UDSOLGT I .ret ****/\n if (produkt.udsolgt == false) {\n //produktet er ikke udsolge\n //udsolgt_tekst skal fjernes\n var udsolgt_tekst = klon.querySelector(\".udsolgt_tekst\");\n udsolgt_tekst.parentNode.removeChild(udsolgt_tekst);\n } else {\n klon.querySelector(\".pris\").classList.add(\"udsolgt\");\n }\n\n\n /**** UDSOLGT I MODAL ****/\n if (produkt.udsolgt == false) {\n //produktet er ikke udsolge\n //udsolgt_tekst skal fjernes\n var modal_udsolgt_tekst = klon.querySelector(\".modal_udsolgt_tekst\");\n modal_udsolgt_tekst.parentNode.removeChild(modal_udsolgt_tekst);\n } else {\n klon.querySelector(\".modal_pris\").classList.add(\"udsolgt\");\n }\n\n\n /**** RABAT i .ret ****/\n if (produkt.udsolgt == true || produkt.rabatsats == 0) {\n //der er ikke rabat. Rabatprisen skal fjernes\n var rabatpris = klon.querySelector(\".rabatpris\");\n rabatpris.parentNode.removeChild(rabatpris);\n } else {\n klon.querySelector(\".pris\").classList.add(\"rabat\");\n }\n\n\n /**** RABAT I MODAL ****/\n if (produkt.udsolgt == true || produkt.rabatsats == 0) {\n //der er ikke rabat. Rabatprisen skal fjernes\n var modal_rabatpris = klon.querySelector(\".modal_rabatpris\");\n modal_rabatpris.parentNode.removeChild(modal_rabatpris);\n } else {\n klon.querySelector(\".modal_pris\").classList.add(\"rabat\");\n }\n\n\n var visMåskeProdukt = true;\n\n\n /**** FILTRERER PRODUKTER MED ALLERGENER FRA ****/\n if (udenAllergener) {\n visMåskeProdukt = visMåskeProdukt && produkt.allergener == \"\";\n }\n\n\n /**** FILTRERER IKKE VEGETAREGNEDE PRODUKTER FRA ****/\n if (vegetaregnet_filtrer) {\n visMåskeProdukt = visMåskeProdukt && produkt.vegetar;\n }\n\n\n /**** FILTRERER UDSOLGTE PRODUKTER FRA ****/\n if (påLager) {\n visMåskeProdukt = visMåskeProdukt && !produkt.udsolgt;\n }\n\n\n /**** FILTRERER PRODUKTER UDEN RABAT FRA ****/\n if (rabat) {\n visMåskeProdukt = visMåskeProdukt && produkt.rabatsats != 0;\n }\n\n\n /**** TILFØJER klon TIL KATEGORI ****/\n if (visMåskeProdukt) {\n document.querySelector(\".\" + produkt.kategori).appendChild(klon);\n }\n}", "function ClickGastarFeitico() {\n AtualizaGeral();\n}", "function handleRicercaDatiSoggettoAllegato(data) {\n var modal = $(\"#modaleSospensioneSoggettoElenco\");\n\n // Prepopolo i dati se applicabile\n if(data.datiSoggettoAllegatoDeterminatiUnivocamente && data.datiSoggettoAllegato) {\n // Ripeto pe sicurezza\n datiNonUnivociModaleSospensioneSoggetto.slideUp();\n // TODO: dinamicizzare\n $('#dataSospensioneDatiSoggettoAllegato').val(data.datiSoggettoAllegato.dataSospensione);\n $('#causaleSospensioneDatiSoggettoAllegato').val(data.datiSoggettoAllegato.causaleSospensione);\n $('#dataRiattivazioneDatiSoggettoAllegato').val(data.datiSoggettoAllegato.dataRiattivazione);\n } else {\n // Mostro il div di dati non univoci\n datiNonUnivociModaleSospensioneSoggetto.slideDown();\n }\n\n $(\".datepicker\", modal).each(function() {\n var $this = $(this);\n var value = $this.val();\n $this.datepicker(\"update\", value);\n });\n\n $(\"#pulsanteConfermaModaleSospensioneSoggettoElenco\").substituteHandler(\"click\", handleConfermaSospensioneSoggetto);\n // Apro il modale\n modal.modal(\"show\");\n }", "function seleccionePersona(tipo){\n elementos.mensajePanel.find('h3').text('Seleccione un '+tipo+' para ver las devoluciones disponibles');\n elementos.mensajePanel.removeClass('hide');\n elementos.devolucionesTabla.addClass('hide');\n elementos.mensajePanel.find('.overlay').addClass('hide');\n }", "function abreAviso(texto, modo, cor){ \n modo = ((modo === undefined) || (modo === ''))? 'ok': modo;\n cor = ((cor === undefined) || (cor === ''))? 'ok': cor;\n \n $(\"#popFundo\").fadeIn();\n $(\"#avisoTexto\").html(texto);\n $(\"#aviso\").addClass(\"avisoEntrada\");\n \n\n}", "function pop_up_ubicar_geograficamente(id_div,id_boton_abrir) {\n \n //modificar estos parametros\n var posicion_actual=$('#nom_artic').val();\n\n var dataString='tipo=cargar_atractivos';\n $.ajax({\n type: \"GET\",\n dataType:\"json\",\n url: \"/guayapp/data/F_ingresar_datos.php\",\n data: dataString,\n\n success: function(data) {\n if(data.items!=null){\n //mensaje que indica que esta todo bien\n \n }\n\n }\n });\n \n \n //$('#progressbar_img').css('display','none');\n document.getElementById('sombra').className='sombraLoad';\n document.getElementById(id_div).className='windowLoadubicacion_geo';\n \n}", "function pop_up_ubicar_geograficamente(id_div,id_boton_abrir) {\n \n //modificar estos parametros\n var posicion_actual=$('#nom_artic').val();\n\n var dataString='tipo=cargar_atractivos';\n $.ajax({\n type: \"GET\",\n dataType:\"json\",\n url: \"/guayapp/data/F_ingresar_datos.php\",\n data: dataString,\n\n success: function(data) {\n if(data.items!=null){\n //mensaje que indica que esta todo bien\n \n }\n\n }\n });\n \n \n //$('#progressbar_img').css('display','none');\n document.getElementById('sombra').className='sombraLoad';\n document.getElementById(id_div).className='windowLoadubicacion_geo';\n \n}", "function siguienteSeccion(){\n document.getElementById('segundaParte').style.display='block';\n document.getElementById('primeraParte').style.display='none';\n document.getElementById('Errores').style.display='none';\n document.getElementById('Exitoso').style.display='none';\n}", "function mostrar_formulario_juntar_y_derivar(id_derivacion){\r\n var urlraiz=$(\"#url_raiz_proyecto\").val();\r\n $(\"#capa_modal\").show();\r\n $(\"#capa_formularios\").show();\r\n var screenTop = $(document).scrollTop();\r\n $(\"#capa_formularios\").css('top', screenTop);\r\n $(\"#capa_formularios\").html($(\"#cargador_empresa\").html());\r\n //Pasamos el id_derivacion para manterer el cite\r\n var miurl=urlraiz+\"/form_juntar_y derivar_correspondencia/\"+id_derivacion;\r\n $.ajax({\r\n url: miurl\r\n }).done( function(resul)\r\n {\r\n $(\"#capa_formularios\").html(resul);\r\n\r\n }).fail( function()\r\n {\r\n $(\"#capa_formularios\").html('<span>...ATENCION Ha ocurrido un error, revise su conexión y vuelva a intentarlo...</span>');\r\n }) ;\r\n\r\n}", "function tipoatributo()\n{\n var selecvalue = tipo_atributo.options[tipo_atributo.selectedIndex].value;\n //var selectext = catalogo.options[catalogo.selectedIndex].text;\n if (selecvalue=='Especiales') {\n $(\"#boton_tipo_atributo\").show();\n\n /* var base_url= 'http://localhost/sistema_monedas/';\n $.ajax({\n url: base_url + \"collectionm/form_moneda/\",\n type:\"POST\",\n beforeSend: function() {\n $('#gif_carga').html(\"<center><img src='\"+base_url+\"/public/images/loader.gif' /></center>\");\n },\n success:function(resp){\n //$(\"#input_creado\").append(resp);\n $(\"#precio_moneda\").html(resp);\n //alert(resp);\n },\n error:function(){\n $('#gif_carga').html(\"\");\n $('#precio_moneda').html(\"<center><h4 style='color:red;'>ERROR EN EL SERVIDOR.POR FAVOR ENVIE UN MENSAJE AL ADMINISTRADOR</h4></center>\");\n }\n\n });*/\n }else{\n $(\"#boton_tipo_atributo\").hide();\n /* $('#precio_billete').html(\"\");*/\n }\n \n}", "function Minuta_Deposito_Banco(){\n \tdb_smart_sales.metodos.Obtener_Banco_Deposito(function (item) {\n \t\tif( item.rows.length == 0){\n \t\t\talert(\"La ruta no tiene configurado banco de deposito\");\n \t\t}\n \t\telse{\n \t\t\tvar banco_txt= item.rows.item(0).Banco.trim()\n\t\t\t\t\t\tvar cadena_espaciada = banco_txt.split(\"\")\n\t\t\t\t\t\tvar url=\"../img/\"+ banco_txt +\".png\"\n\t\t\t\t\t\tif (banco_txt.toUpperCase() ==\"BAC\"){url= \"../img/\"+ banco_txt +\".gif\"}\n\n\t\t\t\t\t\tvar html_imagen=\"<img src='\"+ url +\"' class=img_banco width='89' height='34'> Minuta \"+ banco_txt\n\t\t\t\t\t\t$('#banco_deposito').attr(\"onclick\",\"imprimeminuta('\"+ cadena_espaciada.join(\" \") +\"')\")\n\n\n\t\t\t\t\t\t//imprimeResumenPago\n\t\t\t\t\t\t$('#banco_deposito').html(html_imagen)\n \t\t}\n\t\t\t\t}, function(error){\n\t\t\t\t\tvar conf= confirm(\"Ocurrio un error al obtener el Banco de Desposito. Desea volver a consultar el banco?\");\n\t\t\t\t\tif(conf){ Minuta_Deposito_Banco() }\n\t\t\t\t})\n }", "function mostrar_formulario_archivar(id_derivacion){\r\n var urlraiz=$(\"#url_raiz_proyecto\").val();\r\n $(\"#capa_modal\").show();\r\n $(\"#capa_formularios\").show();\r\n var screenTop = $(document).scrollTop();\r\n $(\"#capa_formularios\").css('top', screenTop);\r\n $(\"#capa_formularios\").html($(\"#cargador_empresa\").html());\r\n //Pasamos el id_derivacion para manterer el cite\r\n var miurl=urlraiz+\"/form_archivar_correspondencia/\"+id_derivacion;\r\n $.ajax({\r\n url: miurl\r\n }).done( function(resul)\r\n {\r\n $(\"#capa_formularios\").html(resul);\r\n\r\n }).fail( function()\r\n {\r\n $(\"#capa_formularios\").html('<span>...ATENCION Ha ocurrido un error, revise su conexión y vuelva a intentarlo...</span>');\r\n }) ;\r\n}", "function onyeshaYaliyomo(kiungo, e, rangi, id) {\n e.preventDefault();\n let viungo, yaliyomo;\n viungo = document.getElementsByClassName(\"kiungo\");\n yaliyomo = document.getElementsByClassName(\"yaliyomo\");\n\n // ficha 'yaliyomo' zote kabla ya yote\n for (let index = 0; index < yaliyomo.length; index++) {\n const element = yaliyomo[index];\n element.style.display = \"none\";\n }\n\n // Ondoa darasa la 'hai' kwenye viungo vyote\n for (let index = 0; index < viungo.length; index++) {\n const kiungo = viungo[index];\n kiungo.className = kiungo.className.replace(\" hai\", \"\");\n kiungo.style.backgroundColor = \"transparent\";\n }\n\n // Onyesha kiungo hai na Yaliyomo yake\n kiungo.className += \" hai\";\n kiungo.style.backgroundColor = rangi;\n let yaliyomoHai = document.getElementById(id);\n let seksheni = document.getElementById(\"tabu-kurasa-nzima\");\n yaliyomoHai.style.display = \"block\";\n // yaliyomoHai.style.backgroundColor = rangi;\n seksheni.style.backgroundColor = rangi;\n}", "function agregaNuevaPropiedadAlFinal(){\n\t\tvar dad = $(this).prev();\n\t\tdad.append( \"<tr>\" +\n\t\t\t\t\t\t\"<td><a></a><input></input></td>\" +\n\t\t\t\t\t\t\"<td>:</td>\" +\n\t\t\t\t\t\t\"<td><a></a><input></input></td>\" +\n\t\t\t\t\t\"</tr>\" );\n\t\tvar hijos = dad.children().first().children().last().children();\n\t\tvar textNode = document.createTextNode(\"\");\n\t\t//textNode.nodeValue = \"nuevo Valor :)\";\n\t\t\n\t\tvar styleSheet = jQuery.data(dad.parent().parent()[0],\"styleSheet\");\n\t\t//alert(dad.next().prop('class'));\n\t\tstyleSheet.style.insertBefore(textNode, jQuery.data(dad.next()[0],\"endingKey\"));\n\t\t//styleSheet.style.appendChild(textNode);\n\t\t\n\t\tjQuery.data(hijos.parent()[0],\"textNode\", textNode);\n\t\tvar link = hijos.first().children().first();\n\t\tlink.parent().click(desapareceLinkApareceInput);\n\t\tlink.next()\n\t\t\t.blur(desapareceInputApareceLink)\n\t\t\t.keydown(controlDeTabulacionYEnter);\n\t\tlink.parent()[0].click();\n\t\tlink = hijos.last().children().first();\n\t\tlink.parent().click(desapareceLinkApareceInput);\n\t\tlink.next()\n\t\t\t.blur(desapareceInputApareceLink)\n\t\t\t.keydown(controlDeTabulacionYEnter);\n\t\t//alert(jQuery.data(hijos.parent()[0],\"textNode\").value);\n\t}", "function initPopupFormular() {\r\n $(\"#\" + global.Element.PopupFormular).modal({\r\n keyboard: false,\r\n show: false\r\n });\r\n $(\"#\" + global.Element.PopupFormular + \" button[save]\").click(function () {\r\n saveFormular();\r\n global.Data.ClientId = document.getElementById(\"ClientName\").innerHTML;\r\n var realTimeHub = $.connection.realTimeJTableDemoHub;\r\n realTimeHub.server.sendUpdateEvent(\"jtableFormular\", global.Data.ClientId, \"Cập nhật loại dịch vụ\");\r\n $.connection.hub.start();\r\n });\r\n $(\"#\" + global.Element.PopupFormular + \" button[cancel]\").click(function () {\r\n $(\"#\" + global.Element.PopupFormular).modal(\"hide\");\r\n });\r\n }", "function ClickGerarAleatorioComum() {\n GeraAleatorioComum();\n AtualizaGeral();\n}", "function mostrarFormulario(){\n var acum; \n //variable que permite saber que es un registrar\n encontrado=0; \n if(ventana==null) \n ventana = Ext.create ('App.miVentanaBanco')\n limpiar();\n ventana.show();\n }", "function cnsFrn_editar(acao){\n\tvar actpos = $(\"#cnsFornec_position\").val();\n\tif(actpos === 'null'){\n swal({\n title:'Atenção',\n text:'É necessário selecionar uma linha',\n type:'warning',\n timer:3000\n },\n function(){\n swal.close();\n setTimeout(function(){$('#cnsFornec_pesquisa').focus();},30);\n }\n );\n\t\treturn;\n\t}\n \n var aux = objTabelaFornec.registros[actpos];\n\tswitch(acao){\n\t\tcase 'A': //AGENDA\n\t\t\twindow.open(encodeURI(\"../utility/Agenda.Layout.php?nome=\"+aux.fo_abrev+\"&ord=1\" ));\n\t\treturn;\n\n\t\tcase 'S': // SOMA DEBITOS\n\t\t\tloading.show(\"Buscando Dados...\");\n\t\t\tajax(\"funcao=somaDebitos&fo_number=\"+aux.fo_number, CNSFORNEC_EXEC, function(retorno){\n loading.close();\n\t\t\t\tswal({\n title: 'Soma Débitos',\n text: retorno,\n type: \"info\",\n html: true\n\t\t\t\t }\n );\n\t\t\t});\n\t\treturn;\n\t}\n}", "function viewFR(id){\n var pel=$('#tahunlulusS').val();\n $.Dialog({\n shadow:true,\n overlay:true,\n draggable:true,\n height:'auto',\n width:'35%',\n padding:20,\n onShow: function(){\n var titlex;\n var contentFR;\n $('#departemenH').val($('#departemenS').val());\n $('#tahunlulusH').val($('#tahunlulusS').val());\n if (id!='') { // edit mode\n // alert('masuk edit'); return false;\n titlex='<span class=\"icon-pencil\"></span> Ubah ';\n $.ajax({\n url:dir,\n data:'aksi=ambiledit&replid='+id,\n type:'post',\n dataType:'json',\n success:function(dt){\n $('#idformH').val(id);\n // $('#departemenTB').val(dt.departemen);\n $('#nisnTB').val(dt.nisn); \n $('#tahunlulusTB').val(dt.tahunlulus); \n $('#tahunlulusH').val(dt.idtahunlulus); \n $('#siswa2TB').val(dt.siswa); \n $('#siswaH').val(dt.siswak); \n $('#keteranganTB').val(dt.ket);\n // cmbdepartemen('form',$('#departemenS').val());\n // cmbtahunlulus2('form',dt.iddepartemen,dt.idtahunlulus);\n }\n });contentFR=contentEdit;\n }else{ //add mode\n titlex='<span class=\"icon-plus-2\"></span> Tambah ';\n $.ajax({\n url:dir2,\n data:'aksi=cmbdepartemen',\n type:'post',\n dataType:'json',\n success:function(dt){\n cmbdepartemen('form',$('#departemenS').val());\n cmbtahunlulus2('form',$('#tahunlulusS').val());\n }\n });\n contentFR=contentAdd;\n }\n $.Dialog.title(titlex+' '+mnu);\n $.Dialog.content(contentFR);\n\n $(\"#siswaTB\").combogrid({\n debug:true,\n width:'400px',\n colModel: [{\n 'align':'left',\n 'columnName':'nisn',\n 'hide':true,\n 'width':'55',\n 'label':'NISN'\n },{ \n 'columnName':'nama',\n 'width':'40',\n 'label':'NAMA'\n }],\n // url: dir+'?aksi=autocomp',\n url: dir+'?aksi=autocomp&tahunlulus='+pel,\n select: function( event, ui ) { // event setelah data terpilih \n // $('#gruruH').val(ui.item.replid);\n \n siswaAdd(ui.item.replid,ui.item.nisn,ui.item.nama);\n // alert(ui.item.replid);\n \n // $('#barangTB').combogrid( \"option\", \"url\", dir+'?aksi=autocomp&tahunlulus='+pel+'&siswa='+siswaArr() );\n // $(this).combogrid( \"option\", \"url\", dir+'?aksi=autocomp&lokasi='+$('#lokasiTB').val() );\n // $('#siswaTB').combogrid( \"option\", \"url\", dir+'?aksi=autocomp');\n return false;\n }\n \n });\n\n }\n });\n}", "function mossa(pos)\n{\n//reset in casella statistiche e messaggi a sinistra dello schermo\n\tdocument.getElementById(\"faccia\").innerHTML=\"(• ‿ •)\";\n\tif(colturno=='n')\n\t\tdocument.getElementById(\"messaggi\").innerHTML=\"tocca ai neri\";\n\telse\n\t\tdocument.getElementById(\"messaggi\").innerHTML=\"tocca ai bianchi\";\n\n/*_________________________PRIMO CLICK___________________________________*/\n\n\tif(cont%2==0)\n\t{\n\t\tprimo=document.getElementById(pos).innerHTML;\n\t\tvecchiaPos=pos;\n\t\t//ottengo colore giocatore\n\t\tvar lenstr=primo.length;\n\t\tvar colp=primo.charAt(lenstr-7);\n\t\t//controllo se la selezione corrisponde al colore della mossa\n\t\tif(colp!=colturno)\n\t\t{\n\t\t\tdocument.getElementById(\"messaggi\").innerHTML=\"mossa non valida...\";\n\t\t\tdocument.getElementById('faccia').innerHTML=\"(ಠ╭╮ಠ)\";\n\t\t\t\treturn;//esce dalla funzione in caso di selezione colore sbagliato\n\t\t}\n\n\t\t//cambia colore selezionato\n\t\tdocument.getElementById(pos).className=\"selezionato\";\n\t\t//controllo pedina + selezione mosse possibili\n\t\tSeleziona(primo, colp, colturno, pos);\n\t\t\n\t}\n//_____________________________SECONDO CLICK___________________________//\n\n\telse\n\t{\n\t\t//SE LA MOSSA E' VALIDA\n\t\tif(document.getElementById(pos).className==\"selezionato\"&&pos!=vecchiaPos)\n\t\t{\n\t\t\t//se viene mangiata una pedian avversaria, la faccia si stupisce e viene salvata la pedina mangiata in un array\n\t\t\tif(document.getElementById(pos).innerHTML!='<img src=\"imm/vuota.png\">')\n\t\t\t{\n\t\t\t\tdocument.getElementById('faccia').innerHTML=\"(^ ‿ ^)\";\n\t\t\t\tif(colturno=='b')//se era nera\n\t\t\t\t\tmangiate_n.push(document.getElementById(pos).innerHTML);\n\t\t\t\telse\t//se era bianca\n\t\t\t\t\tmangiate_b.push(document.getElementById(pos).innerHTML);\n\t\t\t}\n\t\t\t//se viene mangiato il re finisce il gioco\n\t\t\tif(document.getElementById(pos).innerHTML=='<img src=\"imm/re_b.png\">')//vincono i neri\t\t\t\n\t\t\t\tfine(true);\n\t\t\telse if(document.getElementById(pos).innerHTML=='<img src=\"imm/re_n.png\">')//vincono i bianchi\t\t\t\n\t\t\t\tfine(false);\n\t\t\t\n\t\t\t/*_____________________CONTROLLO ARROCCO____________________*/\n\t\t\tif(pos==\"13\" && isArrocco==true)//nero sx\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"14\").innerHTML='<img src=\"imm/torre_n.png\">'; //assegna alla nuova casella la pedina\n\t\t\t\tdocument.getElementById(\"11\").innerHTML=\"<img src='imm/vuota.png'>\"; //cancella la pedina nella vecchia casella\n\t\t\t\tarrocco[0]=false;\n\t\t\t}\n\t\t\telse if(pos==\"17\" && isArrocco==true)//nero dx\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"16\").innerHTML='<img src=\"imm/torre_n.png\">'; //assegna alla nuova casella la pedina\n\t\t\t\tdocument.getElementById(\"18\").innerHTML=\"<img src='imm/vuota.png'>\"; //cancella la pedina nella vecchia casella\n\t\t\t\tarrocco[0]=false;\n\t\t\t}\n\t\t\telse if(pos==\"83\" && isArrocco==true)//bianco sx\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"84\").innerHTML='<img src=\"imm/torre_b.png\">'; //assegna alla nuova casella la pedina\n\t\t\t\tdocument.getElementById(\"81\").innerHTML=\"<img src='imm/vuota.png'>\"; //cancella la pedina nella vecchia casella\n\t\t\t\tarrocco[3]=false;\n\t\t\t}\n\t\t\telse if(pos==\"87\" && isArrocco==true)//bianco dx\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"86\").innerHTML='<img src=\"imm/torre_b.png\">'; //assegna alla nuova casella la pedina\n\t\t\t\tdocument.getElementById(\"88\").innerHTML=\"<img src='imm/vuota.png'>\"; //cancella la pedina nella vecchia casella\n\t\t\t\tarrocco[3]=false;\n\t\t\t}\n\t\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t//se è stato mossa una pedina per l'arrocco, ma non è stato fatto (quindi l'arrocco non è più possibile per quelle pedine)\n\t\t\tvar sum=[\"15\", \"11\", \"18\", \"85\", \"81\", \"88\"]\n\t\t\tfor(var i=0; i<6; i++)\n\t\t\t{\n\t\t\t\tif(vecchiaPos==sum[i])\n\t\t\t\t\tarrocco[i]=false;\n\t\t\t\t\t\n\t\t\t}\n\t\t\t//spostamento pedine\n\t\t\tdocument.getElementById(pos).innerHTML=primo; //assegna alla nuova casella la pedina\n\t\t\tdocument.getElementById(vecchiaPos).innerHTML=\"<img src='imm/vuota.png'>\"; //cancella la pedina nella vecchia casella\n\t\t\t//cambiamenti finali\n\t\t\tcontrolloPedoneFinal(pos,primo);//controlla se la pedina spostata era un pedone è arrivato alla parte opposta della scacchiera\n\t\t\tturno++;\n\t\t\ttimersec=300;\n\t\t\tdocument.getElementById(\"mosse\").innerHTML=\"mossa numero: \"+turno;\n\t\t\t//indica a chi tocca il turno successivo\n\t\t\tif(colturno=='b')\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"messaggi\").innerHTML=\"tocca ai neri\";\n\t\t\t\tcolturno='n';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"messaggi\").innerHTML=\"tocca ai bianchi\";\n\t\t\t\tcolturno='b';\n\t\t\t}\n\t\t}\n\t\t//SE LA MOSSA NON E' VALIDA\n\t\telse\n\t\t\tdocument.getElementById(\"messaggi\").innerHTML=\"mossa non valida!!!\";\n\t\t\n\t\tDeseleziona();//deseleziona tutto\n\t\tvisualEaten();//visualizza le pedine mangiate\t\n\t}\n\tcont++;\n}", "function voltarEtapa5() {\n \n msgTratamentoEtapa6.innerHTML = \"\";\n \n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"5º Etapa - Valores Adicionais & Desconto\";\n\n document.getElementById('inserirValorAdicional').style.display = ''; //habilita a etapa 5\n document.getElementById('inserirDespesas').style.display = 'none'; //desabilita a etapa 6\n }", "function montarModalEdicao(posicao) {\n\n // LIMPAR TODAS MENSAGENS\n limparMensagens();\n\n // OBTEM O ID DA EDITORA NA LINHA DA TABELA SELECIONADA\n let i = posicao.parentNode.parentNode.rowIndex;\n let id = (document.getElementById(\"tabela-pessoas\").rows[i].cells[0].innerHTML);\n\n // replace para remover espaco vazio antes do id\n let referenciaBd = firebase.database().ref(`pessoas/ ${id}`.replace(/\\s/g, ''));\n\n let pessoa = [];\n referenciaBd.on('value', function(snapshot) {\n\n if (!!snapshot) {\n pessoa = {\n id: snapshot.val().id,\n nome: snapshot.val().nome,\n perfil: snapshot.val().perfil,\n telefone: snapshot.val().telefone,\n email: snapshot.val().email,\n curso: snapshot.val().curso,\n instituicao: snapshot.val().instituicao,\n escolaridade: snapshot.val().escolaridade,\n endereco: snapshot.val().endereco,\n cpf: snapshot.val().cpf,\n rg: snapshot.val().rg,\n responsavel: snapshot.val().responsavel,\n usuario: snapshot.val().usuario,\n senha: snapshot.val().senha\n }\n\n //VARIAVEL USADA NO METODO gravarAlteracao, NECESSARIO PARA SABER QUAL POSICAO SERA EDITADA\n posicaoGravar = i;\n\n // PREENCHER MODAL COM DADOS PARA EDICAO\n document.getElementById(\"editar-id-pessoa\").value = pessoa.id;\n document.getElementById(\"editar-nome-pessoa\").value = pessoa.nome;\n document.getElementById(\"editar-perfil-pessoa\").value = pessoa.perfil;\n document.getElementById(\"editar-telefone-pessoa\").value = pessoa.telefone;\n document.getElementById(\"editar-email-pessoa\").value = pessoa.email;\n document.getElementById(\"editar-curso-pessoa\").value = pessoa.curso;\n document.getElementById(\"editar-instituicao-pessoa\").value = pessoa.instituicao;\n document.getElementById(\"editar-escolaridade-pessoa\").value = pessoa.escolaridade;\n document.getElementById(\"editar-endereco-pessoa\").value = pessoa.endereco;\n document.getElementById(\"editar-cpf-pessoa\").value = pessoa.cpf;\n document.getElementById(\"editar-rg-pessoa\").value = pessoa.rg;\n document.getElementById(\"editar-responsavel-pessoa\").value = pessoa.responsavel;\n document.getElementById(\"editar-usuario-pessoa\").value = pessoa.usuario;\n document.getElementById(\"editar-senha-pessoa\").value = pessoa.senha;\n }\n });\n}", "function showPopupFormular() {\r\n $(\"#\" + global.Element.PopupFormular).modal(\"show\");\r\n }", "function modificarDOMPantallaPlantilla() {\r\n\t// Obtenemos la tabla de jugadores y todas sus filas.\r\n\tvar tablaJugadores = document.getElementById(\"content\").getElementsByTagName(\"table\")[0];\r\n\tvar filasTablaJugadores = tablaJugadores.getElementsByTagName(\"tr\");\r\n\t\r\n\t// Recorremos todas las filas de la tabla de jugadores (excepto la primera, que es la cabecera).\r\n\tfor (var fila = 1; fila < filasTablaJugadores.length; fila++) {\r\n\t\t// Obtenemos el id del jugador actual.\r\n\t\tvar columnasFila = filasTablaJugadores[fila].getElementsByTagName(\"td\");\r\n\t\tvar columnaIdJugador = columnasFila[3];\r\n\t\tvar idJugador = extraerIdJugador(columnaIdJugador.getElementsByTagName(\"a\")[0]);\r\n\t\t// Actualizamos el valor de las stats del jugador actual.\r\n\t\tprocesarCambioValorStat(columnasFila[5], idJugador, \"calidad\");\r\n\t\tprocesarCambioValorStat(columnasFila[6], idJugador, \"resistencia\");\r\n\t\tprocesarCambioValorStat(columnasFila[7], idJugador, \"velocidad\");\r\n\t\tprocesarCambioValorStat(columnasFila[8], idJugador, \"pase\");\r\n\t\tprocesarCambioValorStat(columnasFila[9], idJugador, \"remate\");\r\n\t\tprocesarCambioValorStat(columnasFila[10], idJugador, \"tiro\");\r\n\t\tprocesarCambioValorStat(columnasFila[11], idJugador, \"entradas\");\r\n\t\tprocesarCambioValorStat(columnasFila[12], idJugador, \"agresividad\");\r\n\t\tprocesarCambioValorStat(columnasFila[13], idJugador, \"conduccion\");\r\n\t\tprocesarCambioValorStat(columnasFila[14], idJugador, \"desmarque\");\r\n\t\tprocesarCambioValorStat(columnasFila[16], idJugador, \"mediareal\");\r\n\t}\r\n\t\r\n\t// Ajustamos estilos de tabla y contenedores.\r\n\teliminarAnchosColumnaTablaJugadores(filasTablaJugadores[0]);\r\n\tajustarEstilosContenedores();\r\n\t\r\n\t// Cuando tenemos todo el DOM modificado, mostramos la tabla.\r\n\tmostrarJugadores();\r\n}", "function mostrarIngresar(){ \r\n limpiar();\r\n document.querySelector(\"#auxLanding\").style.display = \"none\"; //Oculto botones de registrar e ingresar\r\n document.querySelector(\"#bodyHome\").style.display = \"none\"; //Oculto el body de la landing page\r\n document.querySelector(\"#registro\").style.display = \"none\"; //Oculto formulario registrar\r\n document.querySelector(\"#ingreso\").style.display = \"block\"; //Muestro el formulario\r\n document.querySelector(\"#pagPrincipal\").style.display = \"block\"; //Muestro pag principal\r\n}", "function cercaCapitoloNellaVariazione(e){\n \tvar prefissoOggetto = 'capitolo';\n \tvar oggettoPerChiamataAjax = {};\n \t//Campi hidden da leggere\n var tipoApplicazione = $(\"#HIDDEN_tipoApplicazione\").val();\n var annoVariazione = $(\"#HIDDEN_annoVariazione\").val();\n // Spinner\n var spinner = $(\"#SPINNER_CapitoloNellaVariazione\");\n\n //input selezionati dall'utente\n var tipoCapitolo = $('input[name=\"specificaImporti.tipoCapitoloNellaVariazione\"]:checked').val();\n var annoCapitolo = $('#annoCapitoloNellaVariazione').val();\n var numeroCapitolo = $('#numeroCapitoloNellaVariazione').val();\n var numeroArticolo = $('#numeroArticoloNellaVariazione').val();\n \n //Wrapper per il tipo capitolo e tipo applicazione: e.g. SpesaGestione, reduced:UG\n var wrapTipoCapitoloApplicazione = tipoCapitolo + ottieniTipoApplicazioneCapitolo(tipoApplicazione);\n // Dati per la creazione della chiamata AJAX\n var capitoloDaRichiamare = prefissoOggetto + wrapTipoCapitoloApplicazione + 'NellaVariazione';\n \n //validazione dei campi\n var erroriArray = controllaCampiRicercaCapitolo(annoCapitolo, numeroCapitolo,numeroArticolo,tipoCapitolo);\n var url = 'effettuaRicercaNellaVariazioneCap' + wrapTipoCapitoloApplicazione + '_aggiornamento.do';\n \n e.preventDefault();\n \n if(impostaDatiNegliAlert(erroriArray, alertErrori)){\n \treturn;\n }\n //i campi sono tutti stati compilati correttamente\n alertErrori.slideUp();\n spinner.addClass(\"activated\");\n \n //creo oggetto da passare al server e.g. capitoloDaRichiamare = \"capitoloEntrataGestione\"\n oggettoPerChiamataAjax[capitoloDaRichiamare + \".annoCapitolo\"] = annoCapitolo.trim();\n oggettoPerChiamataAjax[capitoloDaRichiamare + \".numeroCapitolo\"] = numeroCapitolo.trim();\n oggettoPerChiamataAjax[capitoloDaRichiamare + \".numeroArticolo\"] = numeroArticolo.trim();\n oggettoPerChiamataAjax[capitoloDaRichiamare + \".numeroUEB\"] = 1;\n oggettoPerChiamataAjax.annoImporti = annoVariazione;\n \n return $.postJSON(url, oggettoPerChiamataAjax).then(function(data){\n \tvar errori = data.errori;\n var elementoCapitolo = data.elementoCapitoloVariazioneTrovatoNellaVariazione;\n if(impostaDatiNegliAlert(errori,alertErrori)){\n \treturn;\n }\n apriEPopolaModaleModificaImporti(elementoCapitolo);\n $('#editStanziamenti').modal('show');\n }).always(spinner.removeClass.bind(spinner, \"activated\"));\n \n }", "function mostrarContenidoBitacora() {\n ppActividades.style.display = \"block\";\n let idBitacora = this.dataset._id;\n inputIdBitacora.value = idBitacora;\n let infoBitacora = buscarBitacora(idBitacora);\n // Este titulo se adquiere del curso al que pertenece la bitacora\n let tituloBitacora = document.querySelector('#sct_actividades>div>h1');\n tituloBitacora.textContent = 'Bitácora de: ' + infoBitacora['curso_bitacora'];\n\n // Esto crea el boton de agregar actividad\n let btnAgregarActividad = document.querySelector('#btnAgregarActividad');\n if (rolUsuarioActual == 'Asistente' || rolUsuarioActual == 'Administrador') {\n btnAgregarActividad.addEventListener('click', function () {\n ppActividades.style.display = \"none\";\n ppRegistrarActividad.style.display = \"block\";\n });\n btnAgregarActividad.addEventListener('click', cambiarDatosFormularioActividad);\n } else {\n btnAgregarActividad.hidden = true;\n document.querySelector('#sct_actividades .popup-content').style.display = 'block';\n }\n\n let table = document.querySelector('#tblActividades');\n let msgNoActividad = document.querySelector('#msjActividad');\n\n let listaActividades = infoBitacora['actividades_bitacora'];\n\n if (infoBitacora['actividades_bitacora'].length == 0 || infoBitacora['actividades_bitacora'].length == null || infoBitacora['actividades_bitacora'].length == undefined) {\n table.style.display = \"none\";\n document.querySelector('#sct_actividades .popup-content').style.width = '60%';\n msgNoActividad.style.display = \"block\";\n } else {\n table.style.display = \"table\";\n document.querySelector('#sct_actividades .popup-content').style.width = '90%';\n msgNoActividad.style.display = \"none\";\n }\n\n let tbody = document.querySelector('#tblActividades tbody');\n\n tbody.innerHTML = '';\n\n for (let i = 0; i < listaActividades.length; i++) {\n\n let fila = tbody.insertRow();\n let celdaFechaRegistro = fila.insertCell();\n let celdaFechaActividad = fila.insertCell();\n let celdaHoraInicio = fila.insertCell();\n let celdaHoraFin = fila.insertCell();\n let celdaHorasTrabajadas = fila.insertCell();\n let celdaAccionActividad = fila.insertCell();\n let celdaEstudianteAtendido = fila.insertCell();\n let celdaDescripcion = fila.insertCell();\n\n celdaFechaRegistro.innerHTML = formatDate(listaActividades[i]['fecha_registro_actividad']);\n celdaFechaActividad.innerHTML = formatDate(listaActividades[i]['fecha_actividad_actividad']);\n celdaHoraInicio.innerHTML = listaActividades[i]['hora_inicio_actividad'];\n celdaHoraFin.innerHTML = listaActividades[i]['hora_fin_actividad'];\n if (listaActividades[i]['horas_trabajadas_actividad'] != undefined || listaActividades[i]['horas_trabajadas_actividad'] != \"\") {\n celdaHorasTrabajadas.innerHTML = listaActividades[i]['horas_trabajadas_actividad'].toFixed(2);\n } else {\n celdaHorasTrabajadas.innerHTML = '-';\n }\n\n celdaAccionActividad.innerHTML = listaActividades[i]['accion_actividad'];\n\n if (listaActividades[i]['estudiantes_atendidos_actividad'] != \"\") {\n celdaEstudianteAtendido.innerHTML = listaActividades[i]['estudiantes_atendidos_actividad'];\n } else {\n celdaEstudianteAtendido.innerHTML = \"-\";\n }\n\n celdaDescripcion.innerHTML = listaActividades[i]['descripcion_actividad'];\n\n // Imprime la columna de opciones si el usuario no es asistente\n if (rolUsuarioActual == 'Asistente' || rolUsuarioActual == 'Administrador') {\n\n let cOpciones = document.querySelector('#cOpcionesActividad');\n cOpciones.hidden = false;\n let celdaOpciones = fila.insertCell();\n\n // Este es el boton de editar\n let botonEditar = document.createElement('span');\n botonEditar.classList.add('fas');\n botonEditar.classList.add('fa-cogs');\n\n botonEditar.dataset.id_actividad = listaActividades[i]['_id'];\n botonEditar.name = \"btnEditarActividad\"\n\n if (rolUsuarioActual == 'Asistente' || rolUsuarioActual == 'Administrador') {\n botonEditar.addEventListener('click', function () {\n ppActividades.style.display = \"none\";\n ppRegistrarActividad.style.display = \"block\";\n });\n botonEditar.addEventListener('click', cambiarDatosFormularioActividad);\n botonEditar.addEventListener('click', llenarFormularioActualizar);\n }\n\n celdaOpciones.appendChild(botonEditar);\n\n\n let botonEliminar = document.createElement('span');\n botonEliminar.classList.add('fas');\n botonEliminar.classList.add('fa-trash-alt');\n botonEliminar.dataset.id_actividad = listaActividades[i]['_id'];\n\n celdaOpciones.appendChild(botonEliminar);\n botonEliminar.addEventListener('click', eliminar_actividad);\n\n celdaOpciones.appendChild(botonEliminar);\n }\n\n }\n displayActividadesScroll();\n\n\n}", "function LeEntradas() {\n // Modo mestre ligado ou nao.\n gEntradas.modo_mestre = Dom('input-modo-mestre').checked;\n\n // nome\n gEntradas.nome = Dom('nome').value;\n // raca\n gEntradas.raca = ValorSelecionado(Dom('raca'));\n // template\n gEntradas.template = ValorSelecionado(Dom('template'));\n // tamanho\n gEntradas.tamanho = ValorSelecionado(Dom('tamanho')) || tabelas_raca[gEntradas.raca].tamanho;\n // alinhamento\n gEntradas.alinhamento = ValorSelecionado(Dom('alinhamento'));\n // divindade\n gEntradas.divindade = Dom('divindade-patrona').value;\n // classes.\n gEntradas.classes.length = 0;\n var div_classes = Dom('classes');\n for (var i = 0; i < div_classes.childNodes.length; ++i) {\n var elemento = div_classes.childNodes[i];\n if (elemento.tagName == \"DIV\") {\n var select = elemento.getElementsByTagName(\"SELECT\")[0];\n var input = elemento.getElementsByTagName(\"INPUT\")[0];\n gEntradas.classes.push({\n classe: ValorSelecionado(select),\n nivel: parseInt(input.value)});\n }\n }\n // Dominios de clerigo.\n _LeDominios();\n // Familiares.\n _LeFamiliar();\n _LeCompanheiroAnimal();\n gEntradas.niveis_negativos = parseInt(Dom('niveis-negativos').value) || 0;\n // pontos de vida e ferimentos.\n gEntradas.pontos_vida = parseInt(Dom('pontos-vida-dados').value) || 0;\n gEntradas.pontos_vida_temporarios = parseInt(Dom('pontos-vida-temporarios').value) || 0;\n gEntradas.ferimentos = Math.abs(parseInt(Dom('ferimentos').textContent)) || 0;\n gEntradas.ferimentos_nao_letais = Math.abs(parseInt(Dom('ferimentos-nao-letais').textContent)) || 0;\n // Experiencia.\n gEntradas.experiencia = parseInt(Dom('pontos-experiencia').value) || 0;\n // atributos\n var span_bonus_atributos = Dom('pontos-atributos-gastos');\n if (span_bonus_atributos.textContent.length > 0) {\n var array_bonus = span_bonus_atributos.textContent.split(',');\n for (var i = 0; i < array_bonus.length; ++i) {\n // Trim direita.\n var nome_atributo = AjustaString(array_bonus[i]);\n array_bonus[i] = tabelas_atributos_invertidos[nome_atributo];\n }\n gEntradas.bonus_atributos = array_bonus;\n } else {\n gEntradas.bonus_atributos = [];\n }\n var atributos = [\n 'forca', 'destreza', 'constituicao', 'inteligencia', 'sabedoria', 'carisma' ];\n for (var i = 0; i < atributos.length; ++i) {\n gEntradas[atributos[i]] =\n parseInt(Dom(atributos[i] + '-valor-base').value);\n }\n\n // Estilos de luta.\n gEntradas.estilos_luta = [];\n var div_estilos_luta = Dom('div-estilos-luta');\n for (var i = 0; i < div_estilos_luta.childNodes.length; ++i) {\n gEntradas.estilos_luta.push(\n _LeEntradaEstiloLuta(div_estilos_luta.childNodes[i]));\n }\n\n _LeHabilidadesEspeciais();\n\n _LeEquipamentos();\n\n _LeTalentos();\n\n // Pericias.\n _LePericias();\n\n // Feiticos.\n _LeFeiticos();\n\n gEntradas.notas = Dom('text-area-notas').value;\n}", "function LeEntradas() {\n // Modo mestre ligado ou nao.\n gEntradas.modo_mestre = Dom('input-modo-mestre').checked;\n\n // nome\n gEntradas.nome = Dom('nome').value;\n // raca\n gEntradas.raca = ValorSelecionado(Dom('raca'));\n // template\n gEntradas.template = ValorSelecionado(Dom('template'));\n // tamanho\n gEntradas.tamanho = ValorSelecionado(Dom('tamanho')) || tabelas_raca[gEntradas.raca].tamanho;\n // alinhamento\n gEntradas.alinhamento = ValorSelecionado(Dom('alinhamento'));\n // divindade\n gEntradas.divindade = Dom('divindade-patrona').value;\n // classes.\n gEntradas.classes.length = 0;\n var div_classes = Dom('classes');\n for (var i = 0; i < div_classes.childNodes.length; ++i) {\n var elemento = div_classes.childNodes[i];\n if (elemento.tagName == \"DIV\") {\n var select = elemento.getElementsByTagName(\"SELECT\")[0];\n var input = elemento.getElementsByTagName(\"INPUT\")[0];\n gEntradas.classes.push({\n classe: ValorSelecionado(select),\n nivel: parseInt(input.value)});\n }\n }\n // Dominios de clerigo.\n _LeDominios();\n // Familiares.\n _LeFamiliar();\n _LeCompanheiroAnimal();\n gEntradas.niveis_negativos = parseInt(Dom('niveis-negativos').value) || 0;\n // pontos de vida e ferimentos.\n gEntradas.pontos_vida = parseInt(Dom('pontos-vida-dados').value) || 0;\n gEntradas.pontos_vida_temporarios = parseInt(Dom('pontos-vida-temporarios').value) || 0;\n gEntradas.ferimentos = Math.abs(parseInt(Dom('ferimentos').textContent)) || 0;\n gEntradas.ferimentos_nao_letais = Math.abs(parseInt(Dom('ferimentos-nao-letais').textContent)) || 0;\n // Experiencia.\n gEntradas.experiencia = parseInt(Dom('pontos-experiencia').value) || 0;\n // atributos\n var span_bonus_atributos = Dom('pontos-atributos-gastos');\n if (span_bonus_atributos.textContent.length > 0) {\n var array_bonus = span_bonus_atributos.textContent.split(',');\n for (var i = 0; i < array_bonus.length; ++i) {\n // Trim direita.\n var nome_atributo = AjustaString(array_bonus[i]);\n array_bonus[i] = tabelas_atributos_invertidos[nome_atributo];\n }\n gEntradas.bonus_atributos = array_bonus;\n } else {\n gEntradas.bonus_atributos = [];\n }\n var atributos = [\n 'forca', 'destreza', 'constituicao', 'inteligencia', 'sabedoria', 'carisma' ];\n for (var i = 0; i < atributos.length; ++i) {\n gEntradas[atributos[i]] =\n parseInt(Dom(atributos[i] + '-valor-base').value);\n }\n\n // Estilos de luta.\n gEntradas.estilos_luta = [];\n var div_estilos_luta = Dom('div-estilos-luta');\n for (var i = 0; i < div_estilos_luta.childNodes.length; ++i) {\n gEntradas.estilos_luta.push(\n _LeEntradaEstiloLuta(div_estilos_luta.childNodes[i]));\n }\n\n _LeHabilidadesEspeciais();\n\n _LeEquipamentos();\n\n _LeTalentos();\n\n // Pericias.\n _LePericias();\n\n // Feiticos.\n _LeFeiticos();\n\n gEntradas.notas = Dom('text-area-notas').value;\n}", "function aggiornaConto(e) {\n alertErrori.slideUp();\n alertInformazioni.slideUp();\n\n // Popolo i dati\n var elementoStruttura = e.data[0];\n var idx = e.data[1];\n\n // Popolo i dati del conto\n var dareAvere = elementoStruttura.contoTipoOperazione.operazioneSegnoConto._name;\n var importo = elementoStruttura.movimentoDettaglio && elementoStruttura.movimentoDettaglio.importo || 0;\n $(\"input[type='radio'][data-\" + dareAvere + \"]\").prop('checked', true);\n // Disabilito i radio se e' da causale\n $(\"input[type='radio'][data-DARE], input[type='radio'][data-AVERE]\").prop('disabled', $(\"#HIDDEN_contiCausale\").val() === \"true\");\n\n $(\"#segnoConto\").val(elementoStruttura.contoTipoOperazione.operazioneSegnoConto._name);\n $(\"#importoModale\").val(importo.formatMoney());\n\n // Imposto l'indice\n $(\"#indiceContoModale\").val(idx);\n // Apro il modale\n alertErroriModale.slideUp();\n $(\"#modaleAggiornamentoConto\").modal(\"show\");\n }", "function etapa8() {\n \n //verifica se o usuário já inseriu as formas de pagamento corretamente\n if(valorTotalFestaLocal == 0 && countPrimeiraVezAdd !== 0){\n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"8º Etapa - Horários do Evento\";\n\n document.getElementById('inserirHorarios').style.display = ''; //habilita a etapa 8\n document.getElementById('valoresEformaPagamento').style.display = 'none'; //desabilita a etapa 7\n \n msgTratamentoEtapa7.innerHTML = \"\";\n \n //DEFINI O TEXTO DE CONFIRMAÇÃO DO VALOR A PEGAR COM CONTRATANTE\n \n //apaga o paragrafo do valor a pegar com contratante , pois vai criar outro\n if(criouPegarContratante > 0){\n document.getElementById('pValorPegarContratante').remove();\n }\n criouPegarContratante++;\n \n //recebe o elemento html da ultima etapa (confirmação) e salva em uma variavel \n var confirmacaoInfValoresFinais = document.querySelector(\"#valoresFinalInf\");\n \n //cria os elementos <h6> para todos os valores\n var paragrafoValorPegarContratante = document.createElement(\"h5\");\n\n //define o atributo\n paragrafoValorPegarContratante.class = \"card-title\"; \n paragrafoValorPegarContratante.id = \"pValorPegarContratante\"; \n \n //define o texto\n paragrafoValorPegarContratante.textContent = \"Receber com contrante: R$\"+valorPegarContratante; \n \n //coloca os <p> criados dentro do elemento html da etapa de confirmação\n confirmacaoInfValoresFinais.appendChild(paragrafoValorPegarContratante);\n \n //DEFINI O VALOR DO INPUT DO PEGAR COM CONTRATANTE\n document.getElementById('valorReceberContratante').value = valorPegarContratante;\n \n }else{\n msgTratamentoEtapa7.textContent = \"Não foi possível seguir para a 8º Etapa! Para seguir o valor total adicionado deve ser igual ao Valor Total. =)\"\n }\n \n }", "function fnAgregarCatalogoModal(){\n\t$('#divMensajeOperacion').addClass('hide');\n\n\tproceso = \"Agregar\";\n\n\t//$(\"#selectFuenteRecurso\").multiselect('rebuild');\n\t$(\"#txtClave\").prop(\"readonly\", false);\n\t$('#txtClave').val(\"\");\n\t$('#txtDescripcion').val(\"\");\n\t$('#selectFuenteRecurso').multiselect('enable');\n\n\tvar titulo = '<h3><span class=\"glyphicon glyphicon-info-sign\"></span> Agregar Fuente de Recurso</h3>';\n\t$('#ModalUR_Titulo').empty();\n $('#ModalUR_Titulo').append(titulo);\n\t$('#ModalUR').modal('show');\n}", "function crear_mapa_gopi_expedientes_tecnicos()\n{\n var aux_haburb_gopi_perfiles=0;\n $(\"#inp_habilitacion\").show();\n $(\"#btn_busqueda_gopi_exp_tecnico\").show();\n $(\"#inp_habilitacion\").val('');\n $(\"#hidden_inp_habilitacion\").val('');\n $(\"#anio_pred\").hide();\n \n \n if(aux_haburb_gopi_perfiles==0)\n {\n aux_haburb_gopi_perfiles=1;\n autocompletar_haburb('inp_habilitacion');\n }\n MensajeDialogLoadAjaxFinish('map'); \n}", "function recuperarDadosPopup(codigoRegistro, descricaoRegistro, tipoConsulta) {\r\n\r\n\tvar form = document.ImovelOutrosCriteriosActionForm;\r\n\r\n\tif (tipoConsulta == 'localidadeOrigem') {\r\n form.localidadeOrigemID.value = codigoRegistro;\r\n\t form.nomeLocalidadeOrigem.value = descricaoRegistro;\r\n\t form.nomeLocalidadeOrigem.style.color = \"#000000\";\r\n\t \r\n\t form.localidadeDestinoID.value = codigoRegistro;\r\n form.nomeLocalidadeDestino.value = descricaoRegistro;\r\n form.nomeLocalidadeDestino.style.color = \"#000000\";\r\n form.setorComercialOrigemCD.focus();\r\n\t}\r\n\r\n\tif (tipoConsulta == 'localidadeDestino') {\r\n form.localidadeDestinoID.value = codigoRegistro;\r\n form.nomeLocalidadeDestino.value = descricaoRegistro;\r\n \t form.setorComercialDestinoCD.focus();\r\n\t \t\t \r\n\t}\r\n\r\n\tif(tipoConsulta == 'municipio'){\r\n\t\tform.idMunicipio.value = codigoRegistro;\r\n\t\tform.nomeMunicipio.value = descricaoRegistro;\r\n\t\tform.nomeMunicipio.style.color = \"#000000\";\r\n\t\tform.idBairro.focus();\r\n\t}\r\n\r\n\tif(tipoConsulta == 'cep'){\r\n\t\tform.CEP.value = codigoRegistro;\r\n\t\tform.descricaoCep.value = descricaoRegistro;\r\n\t\tform.descricaoCep.style.color = \"#000000\";\r\n \t form.idLogradouro.focus();\r\n\t}\r\n\r\n\t\r\n\tif(tipoConsulta == 'bairro'){\r\n\t\tform.idBairro.value = codigoRegistro;\r\n\t\tform.nomeBairro.value = descricaoRegistro;\r\n\t\tform.nomeBairro.style.color = \"#000000\";\r\n\t form.CEP.focus();\r\n\t}\r\n\t\r\n\tif(tipoConsulta == 'logradouro'){\r\n\t\tform.idLogradouro.value = codigoRegistro;\r\n\t\tform.nomeLogradouro.value = descricaoRegistro;\r\n\t\tform.nomeLogradouro.style.color = \"#000000\";\r\n\t}\r\n\tform.action = 'exibirFiltrarImovelOutrosCriteriosConsumidoresInscricao.do?menu=sim&gerarRelatorio=RelatorioCadastroConsumidoresInscricao&limpar=S';\r\n\tform.submit();\r\n}", "function posarBoleta(e) {\r\n// console.log(\"has clicat el \"+ e.target.getAttribute('id'));\r\n if (numDeClics==0) {\r\n //si guanya\r\n if (e.target.getAttribute('id')==aleatorio) {\r\n resultat(\"guany\", \"Felicitats :)\");\r\n // resultat(\"Felicitats :)\");\r\n //si perd\r\n }else{\r\n // resultat(\"Torna a provar! :S\");\r\n resultat(\"perd\", \"Torna a provar! :S\");\r\n\r\n }\r\n numDeClics=numDeClics+1;\r\n }\r\n}", "function etapa3() {\n countListaNomeCrianca = 0; //count de quantas vezes passou na lista de crianças\n\n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"3º Etapa - Colaborador\";\n\n document.getElementById('selecionarFuncionarios').style.display = ''; //habilita a etapa 3\n document.getElementById('selecionarAniversariantes').style.display = 'none'; //desabilita a etapa 2\n \n //seta a quantidade de criança que foi definida no input de controle \"qtdCrianca\"\n document.getElementById('qtdCrianca').value = quantidadeCrianca2;\n \n //percorre a lista de nomes das crianças e monta o texto de confirmação para as crianças\n var tamanhoListaNomeCrianca = listaNomeCrianca.length; //recebe o tamanho da lista em uma variavel\n\n listaNomeCrianca.forEach((valorAtualLista) => {\n if(countListaNomeCrianca == 0){\n textoConfirmacaoCrianca = \"Aniversariantes: \";\n }\n countListaNomeCrianca++;\n \n if(countListaNomeCrianca == tamanhoListaNomeCrianca){\n textoConfirmacaoCrianca = textoConfirmacaoCrianca + valorAtualLista;\n }else{\n textoConfirmacaoCrianca = textoConfirmacaoCrianca + valorAtualLista + \" / \";\n }\n \n }); \n countListaNomeCrianca = 0;\n \n if(tamanhoListaNomeCrianca == 0){\n textoConfirmacaoCrianca = \"Evento não possui aniversariante.\";\n }\n \n //seta o texto informação da crianças na ultima etapa\n var confirmacaoInfCrianca = document.querySelector(\"#criancasInf\");\n confirmacaoInfCrianca.textContent = textoConfirmacaoCrianca; \n \n }", "function alumnoIngreso(){ \r\n document.querySelector(\"#bodyHome\").style.display = \"block\"; //Muestro interfaz bienvenida\r\n document.querySelector(\"#h1TitBienvenida\").innerHTML = `Bienvenido/a ${usuarioLoggeado}`;//Bienvenida usuario\r\n document.querySelector(\"#navAlumno\").style.display = \"block\"; //Muestro interfaz alumno\r\n document.querySelector(\"#auxUsuario\").style.display = \"block\"; //Muestro div auxiliar de usuarios\r\n document.querySelector(\"#auxLanding\").style.display = \"none\"; //Oculto botones de registrar e ingresar\r\n document.querySelector(\"#pagPrincipal\").style.display = \"none\"; //Oculto boton pagina principal\r\n document.querySelector(\"#registro\").style.display = \"none\"; //Oculto el formulario\r\n document.querySelector(\"#ingreso\").style.display = \"none\"; //Oculto formulario de ingreso\r\n}", "function populaModal(pokemon) {\n //TO-DO:\n // 1. CRIAR COMPONENTES PARA MOSTRAR NO MODAL \n // SEGUINDO O PADRÃO DO BOOTSTRAP\n // (http://getbootstrap.com/docs/4.0/components/modal/#modal-components)\n // 2. LINKAR TODOS OS COMPONENTES COM O MODAL .modal\n // 3. SEMPRE QUE FECHAR O MODAL LIMPAR O CONTEUDO ADICIONADO\n const modal = document.querySelector('.modal');\n\n while(modal.firstChild) {\n modal.removeChild(modal.firstChild);\n }\n\n //estrutura modal\n const dialog = document.createElement('div');\n dialog.classList.add('modal-dialog');\n\n const content = document.createElement('div');\n content.classList.add('modal-content');\n \n const header = document.createElement('div');\n header.classList.add('modal-header');\n content.appendChild(header);\n \n //id\n const id = document.createElement('h5');\n id.classList.add('modal-title');\n id.innerText = `#${pokemon.id}`;\n header.appendChild(id);\n\n const body = document.createElement('div');\n body.classList.add('modal-body');\n content.appendChild(body);\n\n //nome\n const nome = document.createElement('h1');\n nome.innerText = pokemon.name;\n body.appendChild(nome);\n\n //tipos\n const div = document.createElement('div');\n div.innerText = \"Tipos\";\n body.appendChild(div);\n const tipos = document.createElement('ul');\n pokemon.types.map(type => {\n const tipo = document.createElement('li');\n tipo.innerText = type.type.name;\n tipos.appendChild(tipo);\n });\n body.appendChild(tipos);\n\n //peso\n const peso = document.createElement('div');\n peso.innerText = `Peso: ${pokemon.weight}`;\n body.appendChild(peso);\n\n //altura\n const altura = document.createElement('div');\n altura.innerText = `Altura: ${pokemon.height}`;\n body.appendChild(altura);\n\n //imagem\n const img = document.createElement('img');\n img.src = pokemon.sprites.front_default; \n body.appendChild(img);\n\n\n dialog.appendChild(content);\n modal.appendChild(dialog);\n}", "function ujebTomu(x) {\r\n //ulozi id tuknuteho luda\r\n let pes = document.getElementById(x);\r\n\r\n //ak uz nie je otvoreny nejaky iny zamestnanec\r\n if (otvoreny == \"nikto\") {\r\n //ulozi aktualne otvoreneho luda\r\n otvoreny = pes;\r\n x = '#' + x;\r\n\r\n //zmaze css pre zatvorenu tablicku - ci uz pc alebo mobil\r\n $(x).removeClass(\"mobileLudo\");\r\n $(x).removeClass(\"normLudo\");\r\n\r\n //prida css pre otvorenu tablicku\r\n if ($(window).width() < 1000) {\r\n //pre mobil otvori \"fullscreen\" zobrazenie luda\r\n $('body div').hide();\r\n //vypne moznost kliknut na logo v mavbare kym je otvoreny nejaky ludo\r\n $('.mavbar a').attr(\"onclick\", \"\");\r\n\r\n let picus = \"#BL\" + pes.id;\r\n $(picus).show();\r\n $(picus).find(\"div\").show();\r\n $('.mavbar').show();\r\n $('.mavbar #menuButton').hide();\r\n } else {\r\n //pre pc\r\n $(x).addClass(\"bigLudo\");\r\n $(x).find('.dlhyOpis').show();\r\n }\r\n\r\n //ukaze kontakt danej osoby\r\n $(x).find(\".bengoroKontakt\").show();\r\n //ukaze tlacitka pre email a zatvorenie tablicky\r\n $(x).find(\".miniButtony\").show();\r\n //ukaze zvysok opisneho textu\r\n $(x).find(\".quiestce\").find(\"span\").removeClass(\"hidden\");\r\n } else {\r\n //ak uz bol nejaky ludo otvoreny v momente kliknutia tak ho zavre\r\n //a otvori aktualne tuknuteho luda\r\n odjebTomu(otvoreny.id);\r\n ujebTomu(pes.id);\r\n otvoreny = pes\r\n }\r\n\r\n //riesi marginy medzi ludo divmi - obdlzniky nalavo maju mat margin right\r\n if ($(x).hasClass(\"lavo\")) {\r\n $('.lavo').each(function() {\r\n if ($(this).index() > $(x).index() &&\r\n $(this).parent().attr(\"id\") == $(x).parent().attr(\"id\")) {\r\n $(this).removeClass(\"medzeraNapravo\");\r\n }\r\n })\r\n\r\n $('.pravo').each(function() {\r\n if ($(this).index() > $(x).index() &&\r\n $(this).parent().attr(\"id\") == $(x).parent().attr(\"id\")) {\r\n $(this).addClass('medzeraNapravo');\r\n }\r\n })\r\n }\r\n}", "function mostrar_formulario_derivar(id_derivacion){\r\n var urlraiz=$(\"#url_raiz_proyecto\").val();\r\n $(\"#capa_modal\").show();\r\n $(\"#capa_formularios\").show();\r\n var screenTop = $(document).scrollTop();\r\n $(\"#capa_formularios\").css('top', screenTop);\r\n $(\"#capa_formularios\").html($(\"#cargador_empresa\").html());\r\n //Pasamos el id_derivacion para manterer el cite\r\n var miurl=urlraiz+\"/form_derivar_correspondencia/\"+id_derivacion;\r\n $.ajax({\r\n url: miurl\r\n }).done( function(resul)\r\n {\r\n $(\"#capa_formularios\").html(resul);\r\n\r\n }).fail( function()\r\n {\r\n $(\"#capa_formularios\").html('<span>...ATENCION Ha ocurrido un error, revise su conexión y vuelva a intentarlo...</span>');\r\n }) ;\r\n\r\n}", "function viewFR(id){\n // $.Dialog({\n $.Dialog({\n shadow: true,\n overlay: true,\n draggable: true,\n width: 500,\n padding: 10,\n onShow: function(){\n var titlex='';\n\n // form :: departemen (disabled field) -----------------------------\n $.ajax({\n url:dir2,\n data:'aksi=cmb'+mnu2+'&replid='+$('#departemenS').val(),\n type:'post',\n dataType:'json',\n success:function(dt){\n titlex+='';\n $('#departemenH').val($('#departemenS').val());\n $('#tahunajaranH').val($('#tahunajaranS').val());\n $('#tingkatH').val($('#tingkatS').val());\n var out;\n if(dt.status!='sukses'){\n out=dt.status;\n }else{\n out=dt.departemen[0].nama;\n }$('#departemenTB').val(out);\n \n // form :: tahun ajaran (disabled field) --------------\n $.ajax({\n url:dir3,\n // data:'aksi=cmbtahunajaran&departemen='+$('#departemenS').val()+'&replid='+$('#tahunajaranS').val(),\n data:'aksi=cmbtahunajaran&replid='+$('#tahunajaranS').val(),\n dataType:'json',\n type:'post',\n success:function(dt2){\n // alert(titlex+' ok');\n var out2;\n if(dt.status!='sukses'){\n out2=dt2.status;\n }else{\n out2=dt2.tahunajaran[0].tahunajaran;\n }$('#tahunajaranTB').val(out2);\n \n // form :: tingkat (disabled field) --------------\n $.ajax({\n url:dir4,\n data:'aksi=cmbtingkat&replid='+$('#tingkatS').val(),\n dataType:'json',\n type:'post',\n success:function(dt3){\n // alert(titlex+' ok');\n var out3;\n if(dt3.status!='sukses'){\n out3=dt3.status;\n }else{\n out3=dt3.tingkat[0].tingkat;\n }$('#tingkatTB').val(out3);\n \n if (id!='') { // edit mode\n // form :: edit :: tampilkan data \n $.ajax({\n url:dir,\n data:'aksi=ambiledit&replid='+id,\n type:'post',\n dataType:'json',\n success:function(dt3){\n $('#idformH').val(id);\n $('#kelasTB').val(dt3.kelas);\n $('#kapasitasTB').val(dt3.kapasitas);\n $('#waliTB').val(dt3.wali);\n $('#keteranganTB').val(dt3.keterangan);\n }\n });\n // end of form :: edit :: tampilkan data \n // titlex='<span class=\"icon-pencil\"></span> Ubah ';\n titlex+='<span class=\"icon-pencil\"></span> Ubah ';\n }else{ //add mode\n // alert('judul ='+titlex);\n titlex+='<span class=\"icon-plus-2\"></span> Tambah ';\n // titlex='<span class=\"icon-plus-2\"></span> Tambah ';\n }\n }\n });\n\n }\n });\n // alert(titlex);\n //end of form :: tahun ajaran (disabled field) --------------\n }\n });\n //end of form :: departemen (disabled field) -----------------------------\n $.Dialog.title(titlex+' '+mnu);\n $.Dialog.content(contentFR);\n }\n });\n }", "function initPopupElementFormular() {\r\n $(\"#\" + global.Element.PopupElementFormular).modal({\r\n keyboard: false,\r\n show: false\r\n });\r\n $(\"#\" + global.Element.PopupElementFormular + \" button[save]\").click(function () {\r\n saveElementFormular();\r\n global.Data.ClientId = document.getElementById(\"ClientName\").innerHTML;\r\n var realTimeHub = $.connection.realTimeJTableDemoHub;\r\n realTimeHub.server.sendUpdateEvent(\"jtableElementFormular\", global.Data.ClientId, \"Cập nhật loại dịch vụ\");\r\n $.connection.hub.start();\r\n });\r\n $(\"#\" + global.Element.PopupElementFormular + \" button[cancel]\").click(function () {\r\n $(\"#\" + global.Element.PopupElementFormular).modal(\"hide\");\r\n });\r\n }", "function modal_detalle(garantia) \r\n{\r\n /*Recuperar el id de la garantia que se desea actualizar*/\r\n var garantia_id = garantia;\r\n $('#modal_detalle').modal('toggle');\r\n \r\n return false;\r\n}", "function onClickBtnModif(e) {\n e.preventDefault();\n\n //On recupere l'identifiant de l'equipe stocker en attribut\n let idEquipe = $(this).attr(\"idequipe\");\n\n //On execute la requete sur le serveur distant\n let request = constructRequest(\"index.php?page=equipemodifws&id=\" + idEquipe);\n\n //En cas de succe de la requete\n request.done(function( infos ) {\n //si les informations sur l'equipe sont definis\n if(infos.element_infos !== undefined) {\n //on modifie la valeur de tout les champ\n $(\"#modif-id\").val(infos.element_infos.id);\n $(\"#modif-libelle\").val(infos.element_infos.libelle);\n $(\"#modif-responsable\").val(infos.element_infos.idResponsable);\n\n //et on affiche le modal modif\n $(\"#modal-modif\").modal(\"show\");\n } else {\n //sinon on affiche un popup avec le message recu\n showPopup(infos.popup_message, infos.popup_type);\n }\n });\n}", "function controlloFrecce(btn) {\n _frecciaDestra.css(\"visibility\", \"visible\");\n _frecciaSinistra.css(\"visibility\", \"visible\");\n if (btn.id == \"frecciaDestra\")\n i++;\n else\n i--;\n if (i == 0)\n _frecciaSinistra.css(\"visibility\", \"hidden\");\n if (i == max - 1)\n _frecciaDestra.css(\"visibility\", \"hidden\");\n for (let i = 0; i < _li.length; i++)\n _li[i].removeAttribute(\"class\");\n _li[0].classList.add(\"active\");\n _informazioneDaVisualizzare = \"btnNome\";\n visualizzaInformazioni(_persone);\n}", "function ClickGerarComum() {\n GeraComum();\n AtualizaGeral();\n}", "function pideLectura()\r\n{\r\n\t$(\"#aviso\").show();\r\n\t$(\"#formulario\").hide();\r\n\tgtimer = setTimeout(cerrar, 10000);\r\n\tPoneModoI('c', revisaLectura);\r\n}", "function modal_verformulario(obj){\n // SECTION CABECERA\n $('.vusuario').text(obj.usuario);\n $('.vnumero').text(obj.numero);\n $('.vfecha').text(obj.fecha);\n $('.vestado').text(obj.estado?\"No Aprobado\":\"Aprobado\");\n \n // SECTION GENERAL\n $('.vlugar').text(obj.lugar);\n $('.vfecha_salida').text(obj.fecha_salida);\n $('.vfecha_llegada').text(obj.fecha_llegada);\n $('.vnumero_memo').text(obj.numero_memo);\n $('.vresolucion_administrativa').text(obj.resolucion_administrativa);\n $('.vdescripcion').text(obj.descripcion);\n $('.vobservacion').text(obj.observacion);\n \n // SECTION VEHICULO\n $('.vvehiculoestado small').text(obj.vehiculo.estado?\"Activo\":\"Inactivo\");\n $('.vcombustible small').text(obj.combustible);\n $('.vplaca small').text(obj.vehiculo.placa);\n $('.vtipo').text(obj.vehiculo.tipo);\n $('.vmarca').text(obj.vehiculo.marca);\n $('.vmodelo').text(obj.vehiculo.modelo);\n $('.vkilometraje small').text(obj.kilometraje);\n $('.vkilometraje_viaje small').text(obj.kilometraje_viaje);\n $('.vrendimiento small').text(obj.vehiculo.rendimiento);\n $('#verformulariomodal .modal-footer .btn-info').attr('onclick', 'ver_formulario_ajax('+obj.id+',\"formulario\",\"modificar\");');\n $('#verformulariomodal .modal-footer .btn-primary').attr('onclick', 'ver_formulario_ajax('+obj.id+',\"formulario\",\"pdf\");');\n \n var tabla1=0,tabla2=0;\n partida=obj.partida;recurso=obj.recurso;\n for (let i = 0; i < recurso.length; i++) {\n const element = recurso[i];\n var totalfila=recurso[i].cantidad*recurso[i].precio_unitario;\n var porcentaje=(totalfila*0.13).toFixed(1);\n tabla1=tabla1+totalfila;\n tabla2=tabla2+(totalfila-porcentaje);\n $('#section_recurso tbody').append('<tr><th scope=\"row\">'+partida[i].numero+'</th><td>'+partida[i].glosa_dos+'</td><td>'+recurso[i].cantidad+'</td><td>'+partida[i].unidad+'</td><td>'+recurso[i].precio_unitario+'</td><td>'+totalfila+'</td></tr>');\n $('#section_liquidacion tbody').append('<tr><th scope=\"row\">'+partida[i].numero+'</th><td>'+partida[i].glosa_uno+'</td><td>'+recurso[i].unidad_liquidacion+'</td><td>'+recurso[i].cantidad+'</td><td>'+recurso[i].precio_unitario+'</td><td>'+totalfila+'</td><td>'+porcentaje+'</td><td>'+(totalfila-porcentaje)+'</td></tr>'); \n }\n $('#section_recurso tbody').append('<tr><td colspan=\"6\" style=\"text-align:right\"><h4 style=\"margin:0\">TOTAL: <small>'+tabla1+'</small></h4></td></tr>');\n $('#section_liquidacion tbody').append('<tr><td colspan=\"8\" style=\"text-align:right\"><h4 style=\"margin:0\">TOTAL: <small>'+tabla2+'</small></h4></td></tr>');\n}", "function showPopupElementFormular() {\r\n $(\"#\" + global.Element.PopupElementFormular).modal(\"show\");\r\n }", "function mostrarDevoluciones() {\n elementos.mensajePanel.addClass('hide');\n elementos.devolucionesTabla.removeClass('hide');\n\n NumberHelper.mascaraMoneda('.mascaraMoneda');\n }" ]
[ "0.71202886", "0.7016336", "0.70131487", "0.6987887", "0.697702", "0.6911901", "0.6880727", "0.6829409", "0.6793059", "0.6792487", "0.67830306", "0.6769643", "0.6768539", "0.67561066", "0.67536664", "0.6716652", "0.6702014", "0.6701383", "0.6684609", "0.6684311", "0.66788584", "0.6671985", "0.66532016", "0.66445327", "0.6629723", "0.6624436", "0.6624399", "0.6624303", "0.66204673", "0.6609775", "0.6605175", "0.6598088", "0.658907", "0.6579984", "0.65788895", "0.6576452", "0.6575267", "0.6575207", "0.6561932", "0.65499896", "0.65468746", "0.65275407", "0.65189177", "0.6503912", "0.6499833", "0.64978576", "0.64961565", "0.64932907", "0.6488577", "0.6486832", "0.6485804", "0.64849347", "0.6481668", "0.6479424", "0.6479092", "0.6478532", "0.64767283", "0.64767283", "0.6463108", "0.6453389", "0.64517", "0.645139", "0.64468086", "0.6439974", "0.64375776", "0.64299464", "0.64250344", "0.6424855", "0.64237934", "0.6417078", "0.64104027", "0.6406514", "0.6404728", "0.6395341", "0.6378207", "0.6378199", "0.6374256", "0.6374073", "0.636972", "0.636972", "0.63693166", "0.6365868", "0.6363772", "0.6361798", "0.63566244", "0.63554436", "0.6353914", "0.6353133", "0.6350734", "0.6350605", "0.634989", "0.6349249", "0.634764", "0.63459986", "0.6345953", "0.63384956", "0.6334797", "0.6331973", "0.63264966", "0.6319177", "0.6318848" ]
0.0
-1
Attiva/disattiva movimento del sole
function activeLightMovement(checkbox){ if(checkbox.checked) lightMoveOpt = true; else lightMoveOpt = false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function verRepeticion(cadena) {\n cargarCadenaMovimientos(cadena);\n // Muestro el primer movimiento de la partida\n crearEventosMovRepeticion();\n cargarTablero(1);\n estilosMovActualRep(0);\n}", "function actualizarCantidadMovimientos() {\n limiteMovimientos -= 1;\n}", "function vermovimientos() {\n\t $http.get(url_server+\"movimientos_extern/\"+$scope.usuario.USUCEL).then(function(response){\n\t\t\tif(response.data.status){\n\t\t\t\t//$scope.movimientos = response.data.movimientos;\n\t\t\t\tfor (var i = 0 ; i < response.data.movimientos.length ; i++) {\n\t\t\t\t\tnewFecha = response.data.movimientos[i].MOVFEC.split(\"T\");\n\t\t\t\t\tresponse.data.movimientos[i].MOVFEC = newFecha[0];\n\t \t}\n\t \t$scope.movimientos = response.data.movimientos;\n\t\t\t}else{\n\t\t\t\t$scope.movimientos = null;\n\t\t\t\tif (response.data.message) {\n\t\t\t\t\t$scope.message = response.data.message;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function puedo_moverme(){\r\n Puntaje(1,'#movimientos-text')\r\n var X_adonde = info_movido.columna - info_arrastrado.columna\r\n var Y_adonde = info_movido.fila - info_arrastrado.fila\r\n if (Math.abs(X_adonde)==1 && Y_adonde==0) {\r\n animar_dulce(-X_adonde,Y_adonde)\r\n }\r\n else if (Math.abs(Y_adonde)==1 && X_adonde==0) {\r\n animar_dulce(X_adonde,Y_adonde)\r\n } else {\r\n $('.col-'+info_arrastrado.columna+' .fila'+info_arrastrado.fila+' img').animate({\r\n top: 0,\r\n left: 0\r\n },200)\r\n }\r\n }", "recibirDisparo(potencia) {\n this.escudo = this.escudo - potencia;\n return this.escudo;\n }", "actualizarAuto() {\n let se = this.informacion_vehiculos.find(\n automovil => this.automovil.placa == automovil.placa \n );\n this.enEdicion = false;\n this.informacion_vehiculos.splice(se, 1, this.automovil);\n this.automovil = Object.assign({}, se);\n localStorage.setItem('automoviles', JSON.stringify(this.informacion_vehiculos));\n }", "function sumarACuenta(movimiento) {\t\n\tsaldoCuenta += movimiento;\n\tactualizarSaldoEnPantalla();\n}", "procMorreu()\n\t// retorna se jah foi usado\n\t{\n\t\tthis._personagemJahPegou = true;\n\n\t\tif (this._informacoesPocao.ativadoInstant)\n\t\t\tControladorJogo.pers.controladorPocoesPegou.adicionarPocaoUsando(this);\n\t\telse\n\t\t\tControladorJogo.pers.controladorPocoesPegou.adicionarPocao(this);\n\n\t\treturn this._informacoesPocao.ativadoInstant;\n\t}", "moverAbajo(){\n this.salaActual.jugador = false;\n this.salaActual = this.salaActual.abajo;\n this.salaActual.entradaAnteriorSala = posicionSala.abajo;\n this.salaActual.jugador = true;\n\n }", "moverIzquierda(){\n this.salaActual.jugador = false;\n this.salaActual = this.salaActual.izquierda;\n this.salaActual.entradaAnteriorSala = posicionSala.izquierda;\n this.salaActual.jugador = true;\n }", "movimientochamp()\n {\n \n if(this.disminuyendoVelocidad && this.speed > -this.limitspeed){\n this.speed -= this.aceleracion; //Disminuye Vel\n this.disminuyendoVelocidad = false;\n }\n\n if(this.aumentandoVelocidad){\n this.speed += this.aceleracion; //Aumenta vel.\n this.aumentandoVelocidad = false;\n }\n this.moverse();\n }", "moverDerecha(){\n this.salaActual.jugador = false;\n this.salaActual = this.salaActual.derecha;\n this.salaActual.entradaAnteriorSala = posicionSala.derecha;\n this.salaActual.jugador = true;\n }", "function presionar() {\t\n\n\tmostrarDuracion(medio.duration, duracion)\n\t// if ( medio.canPlayType(\"mp4\")) { // BUSCAR COMO USAR EL METODO ==> canPlayType\n\tif( !medio.paused && !medio.ended ) {\n\t\tmedio.pause()\n\t\treproducir.innerHTML = \"Reproducir\"\n\t\twindow.clearInterval(bucle)\n\t} else {\t\t\n\t\tmedio.play()\n\t\treproducir.innerHTML = \"Pausar\"\n\t\tbucle = setInterval(estado, 1000)\n\t}\n\t// } else {\n\t// \talert(\"El video no se puede reproducir. Formato no válido\")\n\t// }\n}", "function atirar(){\n\tif(jogoEmAndamento==true){\n\t\tif(jogador.getMunicao()>0){\n\t\t\tvar audio = new Audio('tiro.wav');\n\t\t\taudio.play();\n\t\t\tjogador.setMunicao(jogador.getMunicao()-1);\n\t\t\tbalas.push(new bala);\n\t\t}\n\t}\n}", "function moverse(){\r\n $('.col-'+info_arrastrado.columna+' .fila'+info_arrastrado.fila).find('img').detach()\r\n $('.col-'+info_movido.columna+' .fila'+info_movido.fila).find('img').detach()\r\n $('.col-'+info_arrastrado.columna+' .fila'+info_arrastrado.fila).append('<img src=\"'+info_movido.imagen+'\">')\r\n $('.col-'+info_movido.columna+' .fila'+info_movido.fila).append('<img src=\"'+info_arrastrado.imagen+'\">')\r\n actualizar_puntaje()\r\n }", "function cumpleanosModificadonObjeto(persona) {\n persona.edad += 1;\n}", "function onClickDisk(e) {\n if(Tocadiscos.moverAguja == 1 && player.paused){\n let newCurrentTime = 0;\n screenX = e.x,\n screenY = e.y,\n offsetLeft = disk.offsetParent.offsetLeft + disk.offsetLeft,\n //clientRect = disk.of,\n minX = ([2,4].indexOf(Tocadiscos.disco) === -1) ? 136 : 146,\n maxX = ([2,4].indexOf(Tocadiscos.disco) === -1) ? disk.offsetWidth : disk.offsetWidth - 10,\n minY = 61,\n maxY = disk.offsetHeight - 61,\n moveMaxX = offsetLeft + minX,\n moveMinX = offsetLeft + maxX,\n distance = {\n x: screenX - offsetLeft,\n y: screenY - (disk.offsetParent.offsetTop + disk.offsetTop)\n };\n\n // Obtener la duración total\n let duration = (Tocadiscos.reproductorTipo == ReproductorTipo.Playlist) ? player.duration : getSecondsTime(Tocadiscos.valorTiempoGeneral);\n\n duration = (Tocadiscos.mostrarTiempoGeneral == 1) ? getSecondsTime(Tocadiscos.valorTiempoGeneral) : duration;\n //console.log(distance, minY, maxY);\n\n // Si los valores de X y Y del cursor están dentro del rango permitido\n if((distance.x >= minX && distance.x <= maxX) && (distance.y >= minY && distance.y <= maxY)){\n distance = Math.abs((distance.x - minX) - (maxX - minX));\n maxX = maxX - minX;\n\n newCurrentTime = Math.floor(distance * duration / maxX);\n newCurrentTime = (newCurrentTime > duration) ? duration : (newCurrentTime < 0) ? 0 : newCurrentTime;\n //console.log(newCurrentTime, distance, `min: ${minX}`, `max: ${maxX}`);\n\n if(Tocadiscos.mostrarTiempoGeneral === 1){\n updateIndicators(newCurrentTime, duration);\n timeArmMoving = newCurrentTime;\n }else{\n player.currentTime = newCurrentTime;\n currentTime = newCurrentTime;\n }\n }\n }\n}", "function mover_cero(t, ya_realizados, mov_ant, direccion = null) { //mov_ant = Movimientos ya realizados en ese nivel de profunddida + movimiento del que vengo\n\n var index = t.indexOf(\"0\");\n var mov_restantes = calcular_mov_restantes(index, ya_realizados, mov_ant);\n\n if (direccion === null) {\n if (mov_restantes.length === 0) {\n return 0;\n }\n if (mov_restantes.includes(6)) {\n var aux = t[index + 4];\n t[index + 4] = t[index];\n t[index] = aux;\n return 6;\n\n } else if (mov_restantes.includes(9)) {\n var aux = t[index - 1];\n t[index - 1] = t[index];\n t[index] = aux;\n return 9;\n } else if (mov_restantes.includes(12)) {\n var aux = t[index - 4];\n t[index - 4] = t[index];\n t[index] = aux;\n return 12;\n\n } else if (mov_restantes.includes(3)) {\n var aux = t[index + 1];\n t[index + 1] = t[index];\n t[index] = aux;\n return 3;\n\n }\n } else {\n switch (direccion) {\n case 12:\n var aux = t[index - 4];\n t[index - 4] = t[index];\n t[index] = aux;\n return 12;\n case 3:\n var aux = t[index + 1];\n t[index + 1] = t[index];\n t[index] = aux;\n return 3;\n case 6:\n var aux = t[index + 4];\n t[index + 4] = t[index];\n t[index] = aux;\n return 6;\n case 9:\n var aux = t[index - 1];\n t[index - 1] = t[index];\n t[index] = aux;\n return 9;\n }\n }\n\n}", "function IA_Actualizador() {\n IA.call(this);\n\n //\n this.actualizacion = function() {\n\n // Mientras la serpiente este viva el juego seguira.\n if(!victoria) clearInterval(jugando);\n\n Tablero.prototype.limpiar(tablero);\n muros.dibujarTodo();\n\n // Dibujo la serpiente.\n for(var i=0; i<serpiente.obtenerCant();i++) {\n if(i==0) {\n\n if(!serpiente.obtenerPos(0).giro) serpiente.obtenerPos(i).movimiento();\n\n // Verificamos la nueva posicion.\n var puntoi = serpiente.obtenerPos(0).obtenerPI();\n var pos_actual = esc.obtenerPos(puntoi.obtenerX()/esc.multiplicador, puntoi.obtenerY()/esc.multiplicador);\n\n if(victoria && pos_actual.obtenerPared()) victoria=false;\n else if(victoria && pos_actual.obtenerManzana()) {\n // Removemos la posicion actual de la manzana.\n var pos = pos_actual.obtenerObjManzana();\n pos_actual.desactivarManzana();\n pos_actual.establecerManzana(null);\n manzanas.obtenerPos(pos).posAleatoria();\n\n serpiente.extender(serpiente);\n\n // Agregamos la nueva posicion.\n var x = manzanas.obtenerPos(pos).obtenerCentro().obtenerX();\n var y = manzanas.obtenerPos(pos).obtenerCentro().obtenerY();\n esc.obtenerPos(x/esc.multiplicador, y/esc.multiplicador).activarManzana();\n esc.obtenerPos(x/esc.multiplicador, y/esc.multiplicador).establecerManzana(pos);\n }\n }\n else {\n\n var puntoi = serpiente.obtenerPos(i-1).obtenerPF().clone();\n var puntof = serpiente.obtenerPos(i).obtenerPI().clone();\n\n serpiente.obtenerPos(i).establecerPI(puntoi);\n serpiente.obtenerPos(i).establecerPF(puntof);\n }\n serpiente.obtenerPos(i).dibujar();\n }\n\n // Verficamos que la cabeza de la serpiente no coma su propio cuerpo.\n var puntoi = serpiente.obtenerPos(0).obtenerPI();\n var j=1;\n while(j<serpiente.obtenerCant() && victoria) {\n if(serpiente.obtenerPos(j).obtenerPF().equals(puntoi)) victoria=false;\n j++;\n }\n\n\n serpiente.obtenerPos(0).giro = false;\n\n // Dibujo de manzanas.\n for(var i=0; i<manzanas.obtenerCant(); i++) {\n manzanas.obtenerPos(i).dibujar();\n }\n\n }\n}", "function guardaDadosCena(){\nconsole.log(\"guardaDadosCena\");\n\tvar $stringIdEtiquetasCena = '';\n\t$.each($idEtiquetasCena, function (index, value){\n\t\t$stringIdEtiquetasCena += value + \", \";\n\t});\n\n\tvar $stringIdTipoActividadeCena = '';\n\tvar $stringNumeroRepeticaoGestos = '';\n\n\tif(opcaoActividade == \"Gesto\"){\n\t\t$.each($idTipoActividadeCena, function (index, value){\n\t\t\t$stringIdTipoActividadeCena += value + \", \";\n\t\t});\n\t\t$.each($nrVezesGesto, function (index, value){\n\t\t\t$stringNumeroRepeticaoGestos += value + \", \";\n\t\t});\n\t}else{\n\t\t$.each($idTipoActividadeCena, function (index, value){\n\t\t\t$stringIdTipoActividadeCena += value + \", \";\n\t\t\t$stringNumeroRepeticaoGestos += '0, ';\n\t\t});\n\t}\n\t//converte os ficheiros para mp4 e webm\n\tif($mimeIntroducaoCena == \"video\"){\n\t\tthumbnailRequest(null, 'convertFile', null, \"tempFolderIntroducaoActividadeFile\", null, $urlIntroducaoCena, null);\n\t\tif(!$alterarCena || $modificouIntroducao){\n\t\t\t//grava a introducao da cena\t\n\t\t\tvar $arrayIntro = $urlIntroducaoCena.split('.');\n\t\t\tvar $intro = '..';\n\t\t\tvar i = 0;\n\t\t\twhile (i < $arrayIntro.length-1){\n\t\t\t\tif($arrayIntro[i] != '')\n\t\t\t\t\t$intro = $intro + $arrayIntro[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\t$urlIntroducaoCena = $intro;\n\t\t}\n\t\tthumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderIntroducaoActividadeFile\", \"introducaoActividade\", $urlIntroducaoCena + '.mp4', 'gravar');\n\t\t$urlIntroducaoCena = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderIntroducaoActividadeFile\", \"introducaoActividade\", $urlIntroducaoCena + '.webm', 'gravar');\n\t\tvar $arrayIntro = $urlIntroducaoCena.split('.');\n\t\tvar $intro = '..';\n\t\tvar i = 0;\n\t\twhile (i < $arrayIntro.length-1){\n\t\t\tif($arrayIntro[i] != '')\n\t\t\t\t$intro = $intro + $arrayIntro[i];\n\t\t\ti++;\n\t\t}\n\t\t$urlIntroducaoCena = $intro;\n\t} else {\n\t\t//grava a introducao da cena\t\n\t\t$urlIntroducaoCena = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderIntroducaoActividadeFile\", \"introducaoActividade\", $urlIntroducaoCena, 'gravar');\n\t}\n\t//grava o thumbnail da cena\n\t$imagemCena = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderThumbsCena\", \"thumbsCena\", $imagemCena, 'gravar');\n\n\n\t//converte os ficheiros para mp4 e webm\n\tif($mimeReforcoPositivo == \"video\"){\n\t\tthumbnailRequest(null, 'convertFile', null, \"tempFolderReforcoPositivo\", null, $urlReforcoPositivo, null);\n\t\t//grava o reforço positivo\n\t\tif(!$alterarCena || $modificouReforcoPositivo){\n\t\t\tvar $arrayIntro = $urlReforcoPositivo.split('.');\n\t\t\tvar $intro = '..';\n\t\t\tvar i = 0;\n\t\t\twhile (i < $arrayIntro.length-1){\n\t\t\t\tif($arrayIntro[i] != '')\n\t\t\t\t\t$intro = $intro + $arrayIntro[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\t$urlReforcoPositivo = $intro;\n\t\t}\n\t\tthumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderReforcoPositivo\", \"reforcoPositivo\", $urlReforcoPositivo + '.mp4', 'gravar');\n\t\t$urlReforcoPositivo = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderReforcoPositivo\", \"reforcoPositivo\", $urlReforcoPositivo + '.webm', 'gravar');\n\t\t\n\t\tvar $arrayIntro = $urlReforcoPositivo.split('.');\n\t\tvar $intro = '..';\n\t\tvar i = 0;\n\t\twhile (i < $arrayIntro.length-1){\n\t\t\tif($arrayIntro[i] != '')\n\t\t\t\t$intro = $intro + $arrayIntro[i];\n\t\t\ti++;\n\t\t}\n\t\t$urlReforcoPositivo = $intro;\n\t} else {\n\t\t//grava o reforço positivo\n\t\t$urlReforcoPositivo = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderReforcoPositivo\", \"reforcoPositivo\", $urlReforcoPositivo, 'gravar');\n\t}\n\t//grava o thumbnail do reforço positivo\n\t$urlReforcoPositivoThumb = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderThumbsReforcoPositivo\", \"thumbsReforcoPositivo\", $urlReforcoPositivoThumb, 'gravar');\n\n\tif($urlReforcoNegativo != ''){\n\t\t//converte os ficheiros para mp4 e webm\n\t\tif($mimeReforcoNegativo == \"video\"){\n\t\t\tthumbnailRequest(null, 'convertFile', null, \"tempFolderReforcoNegativo\", null, $urlReforcoNegativo, null);\n\t\t\t//grava o reforço negativo\n\t\t\tif(!$alterarCena || $modificouReforcoNegativo){\n\t\t\t\tvar $arrayIntro = $urlReforcoNegativo.split('.');\n\t\t\t\tvar $intro = '..';\n\t\t\t\tvar i = 0;\n\t\t\t\twhile (i < $arrayIntro.length-1){\n\t\t\t\t\tif($arrayIntro[i] != '')\n\t\t\t\t\t\t$intro = $intro + $arrayIntro[i];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\t$urlReforcoNegativo = $intro;\n\t\t\t}\n\t\t\tthumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderReforcoNegativo\", \"reforcoNegativo\", $urlReforcoNegativo + '.mp4', 'gravar');\n\t\t\t//grava o reforço negativo\n\t\t\t$urlReforcoNegativo = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderReforcoNegativo\", \"reforcoNegativo\", $urlReforcoNegativo + '.webm', 'gravar');\n\n\t\t\tvar $arrayIntro = $urlReforcoNegativo.split('.');\n\t\t\tvar $intro = '..';\n\t\t\tvar i = 0;\n\t\t\twhile (i < $arrayIntro.length-1){\n\t\t\t\tif($arrayIntro[i] != '')\n\t\t\t\t\t$intro = $intro + $arrayIntro[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\t$urlReforcoNegativo = $intro;\n\t\t} else {\n\t\t\t//grava o reforço negativo\n\t\t\t$urlReforcoNegativo = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderReforcoNegativo\", \"reforcoNegativo\", $urlReforcoNegativo, 'gravar');\n\t\t}\n\t} \n\t//grava o thumbnail do reforço negativo\nconsole.log(\"$urlReforcoNegativoThumb antes: \" + $urlReforcoNegativoThumb);\n\t$urlReforcoNegativoThumb = thumbnailRequest(null, 'saveFile', $nomeCena, \"tempFolderThumbsReforcoNegativo\", \"thumbsReforcoNegativo\", $urlReforcoNegativoThumb, 'gravar');\nconsole.log(\"$urlReforcoNegativoThumb depois: \" + $urlReforcoNegativoThumb);\n\n\n\t//adiciona a cena\nconsole.log(\"urlIntroducaoCenaurlIntroducaoCenaurlIntroducaoCena: \" + $urlIntroducaoCena);\nconsole.log(\"urlReforcoPositivourlReforcoPositivourlReforcoPositivo: \" + $urlReforcoPositivo);\nconsole.log(\"urlReforcoNegativourlReforcoNegativourlReforcoNegativo: \" + $urlReforcoNegativo);\n\t$idCena = adicionaNovaCena($imagemCena, $nomeCena, $descricaoCena, $stringIdEtiquetasCena, $urlIntroducaoCena, $mimeIntroducaoCena, $stringIdTipoActividadeCena, $stringNumeroRepeticaoGestos, opcaoActividade, $urlReforcoPositivo, $mimeReforcoPositivo, $urlReforcoPositivoThumb, $urlReforcoNegativo, $mimeReforcoNegativo, $urlReforcoNegativoThumb, $nrVezesCena, $pontuacaoCena);\n\n\tif(Number($idCena)){\n\t\t//adiciona Cena à historia\n\t\tconsole.log(\"$idCena: \" + $idCena);\n\n\t\t$idCenasHistoria.push($idCena);\n\t\tif($pontuacaoCena == 1)\n\t\t\t$idCenasPontuacao.push($idCena);\n\t\t$('#terminarBibliotecaCenasButton').attr(\"disabled\", false);\n\t\tgetCenaById($idCena, \"adicionaNovaCenaSeleccionadaHistoria\");\n\t\t$('#seguinteCenaButton').attr('disabled', 'true');\n\t} else {\n\t\talert(\"Não foi possível adicionar a cena\");\n\t}\n}", "function _AtualizaAtaque() {\n ImprimeSinalizado(gPersonagem.bba, DomsPorClasse('bba'));\n ImprimeNaoSinalizado(gPersonagem.numero_ataques,\n DomsPorClasse('numero-ataques'));\n // Corpo a corpo.\n var span_bba_cac = Dom('bba-corpo-a-corpo');\n ImprimeSinalizado(gPersonagem.bba_cac, span_bba_cac);\n var titulo_span_bba_cac = {};\n titulo_span_bba_cac[Traduz('bba')] = gPersonagem.bba;\n titulo_span_bba_cac[Traduz('força')] = gPersonagem.atributos['forca'].modificador;\n titulo_span_bba_cac[Traduz('tamanho')] = gPersonagem.tamanho.modificador_ataque_defesa;\n TituloChaves(titulo_span_bba_cac, span_bba_cac);\n\n // Distancia.\n var span_bba_distancia = Dom('bba-distancia');\n ImprimeSinalizado(gPersonagem.bba_distancia, span_bba_distancia);\n var titulo_span_bba_distancia = {};\n titulo_span_bba_distancia[Traduz('bba')] = gPersonagem.bba;\n titulo_span_bba_distancia[Traduz('destreza')] = gPersonagem.atributos['destreza'].modificador;\n titulo_span_bba_distancia[Traduz('tamanho')] = gPersonagem.tamanho.modificador_ataque_defesa;\n TituloChaves(titulo_span_bba_distancia, span_bba_distancia);\n\n // Agarrar\n var span_bba_agarrar = Dom('bba-agarrar');\n ImprimeSinalizado(gPersonagem.agarrar, span_bba_agarrar);\n var titulo_span_bba_agarrar = {};\n titulo_span_bba_agarrar[Traduz('bba')] = gPersonagem.bba;\n titulo_span_bba_agarrar[Traduz('força')] = gPersonagem.atributos['forca'].modificador;\n titulo_span_bba_agarrar[Traduz('tamanho especial')] = gPersonagem.tamanho.modificador_agarrar;\n TituloChaves(titulo_span_bba_agarrar, span_bba_agarrar);\n}", "function do_click(reserva) {\n\tvar v = document.getElementById(reserva);\n\tif (v.alt != 2) {\n\t\tif (fila == 0) { // Comprobacion de que es la primera fila que se\n\t\t\t\t\t\t\t// escoje\n\t\t\tfila = parseInt(reserva / 100);\n\t\t\tif (v.alt == 0) {\n\t\t\t\tv.src = 'images/butacas/iconoLibre.ico';\n\t\t\t\tv.alt = 1;\n\t\t\t\tsetSeat(reserva);\n\t\t\t} else if (v.alt == 1) {\n\t\t\t\tv.src = 'images/butacas/iconoElegido.ico';\n\t\t\t\tv.alt = 0;\n\t\t\t\tdeleteSeat(reserva);\n\t\t\t}\n\t\t} else if (parseInt(reserva / 100) == fila) {\n\t\t\tif (v.alt == 0) {\n\t\t\t\tif (contador < 10) {\n\t\t\t\t\tv.src = 'images/butacas/iconoLibre.ico';\n\t\t\t\t\tv.alt = 1;\n\t\t\t\t\tsetSeat(reserva);\n\t\t\t\t} else\n\t\t\t\t\talert(\"No se puede comprar mas de 10 entradas\");\n\t\t\t} else if (v.alt == 1) {\n\t\t\t\tv.src = 'images/butacas/iconoElegido.ico';\n\t\t\t\tv.alt = 0;\n\t\t\t\tdeleteSeat(reserva);\n\t\t\t}\n\t\t} else\n\t\t\talert(\"Las entradas deben pertenecer a la misma fila\");\n\t}\n}", "avancer() {\n\t\tlet fermee = this.cellule.ouverture(this.direction);\n\t\tif (fermee) { //il y a un mur\n\t\t\treturn this.finMouvement();\n\t\t} else if (this.verifierBlocage()===true) { //la porte est bloquee\n return this.finMouvement();\n }\n\t\tthis.visuel.style.transitionDuration = (this.animMouvement) + \"ms\";\n\t\tthis.cellule = this.cellule.voisine(this.direction);\n\n console.log(\"Déplacement: \"+[\"↑\",\"→\",\"↓\",\"←\"][this.direction]+\" / \"+this.cellule.infoDebogage());\n\n\t\tthis.visuel.addEventListener('transitionend', this.evt.visuel.transitionend);\n\t}", "cambiaContatto(index){\n this.contattoAttivo = index;\n }", "mov(){\n if (!this.pausa) {\n switch (this.game.nivel) {\n case 1:\n if (this.cambiaAnim) {\n this.animacion.play(this.animIzq);\n this.cambiaAnim = false;\n }\n this.setPosition(this.t * 25, this.n + 150 * Math.sin(this.t/7));\n this.animacion.setPosition(this.t * 25, this.n + 150 * Math.sin(this.t/7));\n this.t -= 0.1;\n if (this.t <= 10) { this.pausa = true; this.animacion.anims.stop(); }\n break;\n case 2:\n //DISPONEMOS DE 2 CAMINOS EN ESTE NIVEL (DIR)\n //CADA CAMINO ESTÁ FORMADO POR 2 FUNCIONES CADA UNO\n if (this.funcion == 0) {\n if (this.cambiaAnim) {\n if (this.dir == 0) { \n this.animacion.play(this.animDer);\n this.t = 7;\n }\n if (this.dir == 1) {\n this.animacion.play(this.animIzq);\n this.t = -7;\n }\n this.cambiaAnim = false;\n }\n let y0 = Math.sqrt(1 - (Math.pow(Math.abs(this.t/7) - 1, 2)));\n if (!isNaN(y0)) {\n this.setPosition(this.m + this.t * 25, this.r - 200 * y0);\n this.animacion.setPosition(this.m + this.t * 25, this.r - 200 * y0);\n }\n else {\n if (this.dir == 0) this.t = 14;\n if (this.dir == 1) this.t = -14;\n this.funcion = 1;\n this.cambiaAnim = true;\n }\n if (this.dir == 0) this.t += 0.1;\n if (this.dir == 1) this.t -= 0.1;\n }\n if (this.funcion == 1) {\n if (this.cambiaAnim) {\n if (this.dir == 0) this.animacion.play(this.animIzq);\n if (this.dir == 1) this.animacion.play(this.animDer);\n this.cambiaAnim = false;\n }\n let y1 = -2.5 * Math.sqrt(1 - Math.sqrt(Math.abs(this.t/7) / 2));\n if (!isNaN(y1)) {\n this.setPosition(this.m + this.t * 25, this.r - 200 * y1);\n this.animacion.setPosition(this.m + this.t * 25, this.r - 200 * y1);\n }\n if (this.dir == 0) this.t -= 0.1;\n if (this.dir == 1) this.t += 0.1;\n }\n if (this.y >= 700) { this.pausa = true; this.animacion.anims.stop(); }\n break;\n }\n }\n }", "function onObligatorioMonto() {\n\t// Si obligatorio activar la obligatoriedad de los relacionados.\n\tif (get(FORMULARIO + '.ObligatorioMonto') == 'S') {\n\t\tset(FORMULARIO + '.ObligatorioPeriodoInicioV', 'S');\t\t\n\t\tset(FORMULARIO + '.ObligatorioPeriodoFinV', 'S');\n\t}\t\t\n}", "addNuevo(auditoria){\n // al agregar un elemento unico, se debe ubicar: DESPUES de los inventarios sin fecha, y ANTES que los inventarios con fecha\n // buscar el indice del primer inventario con fecha\n let indexConFecha = this.lista.findIndex(auditoria=>{\n let dia = auditoria.aud_fechaProgramada.split('-')[2]\n return dia!=='00'\n })\n if(indexConFecha>=0){\n // se encontro el indice\n this.lista.splice(indexConFecha, 0, auditoria)\n }else{\n // no hay ninguno con fecha, agregar al final\n this.lista.push(auditoria)\n }\n }", "function executaDisparo() {\n somDisparo.play();\n posicaoX = parseInt($(\"#disparo\").css(\"left\"));\n $(\"#disparo\").css(\"left\",posicaoX+15); \n \n if (posicaoX>900) { \n window.clearInterval(tempoDisparo);\n tempoDisparo = null;\n $(\"#disparo\").remove();\n podeAtirar = true; \n }\n }", "function vacio(contenido)\n {\n\t var nombre;\n//\t document.form1.titulo.value = contenido.length;\n\t if (contenido.length == 0){\n\t\tdocument.getElementById('aviso').style.display='inline';\n\t\tdocument.getElementById('aviso').style.visibility='visible';\t\t \n\t\tdocument.form1.publicar.disabled=true;\n\t\tdocument.form1.titulo.style.backgroundColor='#f66';\n\t }\n\t else{\n\t\t document.getElementById('aviso').style.display='none';\n\t\t document.form1.publicar.disabled=false;\n\t }\n }", "function _AtualizaPontosVida() {\n // O valor dos ferimentos deve ser <= 0.\n var pontos_vida_corrente =\n gPersonagem.pontos_vida.total_dados + gPersonagem.pontos_vida.bonus.Total() + gPersonagem.pontos_vida.temporarios\n - gPersonagem.pontos_vida.ferimentos - gPersonagem.pontos_vida.ferimentos_nao_letais;\n ImprimeNaoSinalizado(\n pontos_vida_corrente, Dom('pontos-vida-corrente'));\n Dom('pontos-vida-dados').value = gPersonagem.pontos_vida.total_dados ?\n gPersonagem.pontos_vida.total_dados : '';\n ImprimeSinalizado(\n gPersonagem.pontos_vida.bonus.Total(), Dom('pontos-vida-bonus'), false);\n ImprimeSinalizado(\n gPersonagem.pontos_vida.temporarios, Dom('pontos-vida-temporarios'), false);\n ImprimeSinalizado(\n -gPersonagem.pontos_vida.ferimentos, Dom('ferimentos'), false);\n ImprimeSinalizado(\n -gPersonagem.pontos_vida.ferimentos_nao_letais, Dom('ferimentos-nao-letais'), false);\n\n // Companheiro animal.\n if (gPersonagem.canimal != null) {\n Dom('pontos-vida-base-canimal').value = gPersonagem.canimal.pontos_vida.base;\n Dom('pontos-vida-temporarios-canimal').value = gPersonagem.canimal.pontos_vida.temporarios;\n var pontos_vida_canimal = gPersonagem.canimal.pontos_vida;\n ImprimeSinalizado(-pontos_vida_canimal.ferimentos, Dom('ferimentos-canimal'), false);\n ImprimeSinalizado(-pontos_vida_canimal.ferimentos_nao_letais, Dom('ferimentos-nao-letais-canimal'), false);\n var pontos_vida_corrente_canimal =\n pontos_vida_canimal.base + pontos_vida_canimal.bonus.Total() + pontos_vida_canimal.temporarios\n - pontos_vida_canimal.ferimentos - pontos_vida_canimal.ferimentos_nao_letais;\n Dom('pontos-vida-corrente-canimal').textContent = pontos_vida_corrente_canimal;\n Dom('notas-canimal').textContent = gPersonagem.canimal.notas;\n Dom('canimal-raca').value = gPersonagem.canimal.raca;\n }\n\n // Familiar.\n if (gPersonagem.familiar == null ||\n !(gPersonagem.familiar.chave in tabelas_familiares) ||\n !gPersonagem.familiar.em_uso) {\n return;\n }\n Dom('pontos-vida-base-familiar').textContent = gPersonagem.familiar.pontos_vida.base;\n Dom('pontos-vida-temporarios-familiar').value = gPersonagem.familiar.pontos_vida.temporarios;\n var pontos_vida_familiar = gPersonagem.familiar.pontos_vida;\n ImprimeSinalizado(-pontos_vida_familiar.ferimentos, Dom('ferimentos-familiar'), false);\n ImprimeSinalizado(-pontos_vida_familiar.ferimentos_nao_letais, Dom('ferimentos-nao-letais-familiar'), false);\n var pontos_vida_corrente_familiar =\n pontos_vida_familiar.base + pontos_vida_familiar.bonus.Total() + pontos_vida_familiar.temporarios\n - pontos_vida_familiar.ferimentos - pontos_vida_familiar.ferimentos_nao_letais;\n Dom('pontos-vida-corrente-familiar').textContent = pontos_vida_corrente_familiar;\n}", "function ClickGerarPontosDeVida(modo) {\n GeraPontosDeVida(modo);\n AtualizaGeral();\n}", "executarPocao() {\n\t\tlet tempoPocaoResta = null; //quanto tempo a pocao fica ativo ateh desaparecer de novo (em milisegundos)\n\t\tlet pocaoMudaPers; //soh obrigatorio para pocoes que tenham desexecutar\n\n\t\tswitch (this._codPocao) {\n\t\t\tcase TipoPocao.DiminuirTamanhoPers:\n\t\t\t\ttempoPocaoResta = 7500;\n\t\t\t\tpocaoMudaPers = true;\n\t\t\t\tControladorJogo.pers.mudarTamanho(porcentagemSetTam); //50% do tamanho\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.MatarObjetos1Tiro:\n\t\t\t\t//mudanca na propria classe Obstaculo e Inimigo\n\t\t\t\ttempoPocaoResta = 3000;\n\t\t\t\tpocaoMudaPers = false;\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.RUIMPersPerdeVel:\n\t\t\t\ttempoPocaoResta = 5000;\n\t\t\t\tpocaoMudaPers = true;\n\t\t\t\tControladorJogo.pers.mudarVelocidade(porcentagemSetVelRuim);\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.TiroPersMaisRapidoMortal:\n\t\t\t\ttempoPocaoResta = 8500;\n\t\t\t\tpocaoMudaPers = true;\n\n\t\t\t\t//porque depende do aviao do personagem, qual o index que vai ter o tiro bom\n\t\t\t\tconst indexTiroMelhor = ControladorJogo.pers.indexTiroMelhor;\n\t\t\t\t//mudar frequencia\n\t\t\t\tconst freqFuncAtual = ControladorJogo.pers.getFreqFuncAtirar(indexTiroMelhor);\n\t\t\t\tthis._frequenciaAtirarAntigo = freqFuncAtual.freq;\n\t\t\t\tfreqFuncAtual.freq = freqAtirarMaisRapidoMortal;\n\t\t\t\t//mudar infoTiro\n\t\t\t\tControladorJogo.pers.getControladorTiros(indexTiroMelhor).colocarInfoTiroEspecial(ArmazenadorInfoObjetos.infoTiro(\"TiroForte\", true));\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.MatarInimigosNaoEssenc:\n\t\t\t\tControladorJogo.controladoresInimigos.forEach(controladorInims => {\n\t\t\t\t\tif (!controladorInims.ehDeInimigosEssenciais)\n\t\t\t\t\t\t//soh mata os inimigos nao essenciais\n\t\t\t\t\t\tcontroladorInims.matarTodosInim();\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.ReverterTirosJogoInimDirInim:\n\t\t\t\tthis._reverterTirosContraInimigos(false);\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.GanharPoucaVida:\n\t\t\t\tControladorJogo.pers.mudarVida(qtdGanhaPoucaVida);\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.RUIMPersPerdeVida:\n\t\t\t\tControladorJogo.pers.mudarVida(-qtdPerdeVida);\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.ReverterTirosJogoInimSeguirInim:\n\t\t\t\tthis._reverterTirosContraInimigos(true);\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.DeixarTempoMaisLento:\n\t\t\t\ttempoPocaoResta = 5000;\n\t\t\t\tpocaoMudaPers = false;\n\t\t\t\t/* para deixar tempo mais lento:\n\t\t\t\t -> tiros tela. OK\n\t\t\t\t -> inimigos (incluindo tiros deles, atirar e inimigosSurgindo). OK\n\t\t\t\t -> obstaculos. OK\n\t\t\t\t -> Timers (aqui soh os que jah existem). OK\n\t\t\t\t ps1: verificar se nao existem Timers no PersonagemPrincipal\n\t\t\t\t ps2: verificar se nao podem ser criados freqFuncs sem ser do pers durante esse tempo\n\t\t\n\t\t\t\tresto:\n\t\t\t\t -> quando Timers forem criados. OK\n\t\t\t\t -> quando tiros(sem ser do personagem), obstaculos ou inimigos(freqFuncAtirar tambem) forem criados. OK\n\t\t\t\t*/\n\t\t\t\t//tiros sem dono\n\t\t\t\tControladorJogo.controladorOutrosTirosNaoPers.mudarTempo(porcentagemDeixarTempoLento);\n\t\t\t\t//suportes aereos\n\t\t\t\tControladorJogo.controladorSuportesAereos.suportesAereos.forEach(suporteAereo => suporteAereo.mudarTempo(porcentagemDeixarTempoLento));\n\t\t\t\t//inimigos (incluindo tiros deles e freqFuncAtirar)\n\t\t\t\tControladorJogo.controladoresInimigos.forEach(controladorInims =>\n\t\t\t\t\tcontroladorInims.mudarTempo(porcentagemDeixarTempoLento));\n\t\t\t\t//obstaculos\n\t\t\t\tControladorJogo.controladoresObstaculos.forEach(controladorObsts =>\n\t\t\t\t\tcontroladorObsts.mudarTempo(porcentagemDeixarTempoLento));\n\t\t\t\t//escuridao\n\t\t\t\tif (ControladorJogo.escuridao !== undefined)\n\t\t\t\t\tControladorJogo.escuridao.mudarTempo(porcentagemDeixarTempoLento);\n\t\t\t\t//Timers\n\t\t\t\tConjuntoTimers.mudarTempo(porcentagemDeixarTempoLento);\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.RUIMTirosPersDirEle:\n\t\t\t\t//virar tiros contra criador\n\t\t\t\tControladorJogo.pers.virarTirosContraCriador(false);\n\t\t\t\t//diminuir a velocidade e o dano\n\t\t\t\tControladorJogo.pers.armas.forEach(arma => {\n\t\t\t\t\tarma.controlador.mudarQtdAndarTiros(porcentagemVelTiroSeVoltarPers);\n\t\t\t\t\tarma.controlador.mudarMortalidadeTiros(porcentagemMortalidadeTiroSeVoltarPers, true);\n\t\t\t\t});\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.GanharMuitaVida:\n\t\t\t\tControladorJogo.pers.mudarVida(qtdGanhaMuitaVida);\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.PersMaisRapido:\n\t\t\t\ttempoPocaoResta = 7500;\n\t\t\t\tpocaoMudaPers = true;\n\t\t\t\tControladorJogo.pers.mudarVelocidade(porcentagemSetVel);\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.PersComMissil:\n\t\t\t\ttempoPocaoResta = 4500;\n\t\t\t\tpocaoMudaPers = true;\n\n\t\t\t\t//setar novo tiro\n\t\t\t\tControladorJogo.pers.getControladorTiros(indexArmaMissilPers).colocarInfoTiroEspecial(ArmazenadorInfoObjetos.infoTiro(\"TiroMissil\", true));\n\n\t\t\t\t//guardar frequencia e atirarDireto antigo antes de muda-los\n\t\t\t\tthis._informacoesNaoMissil = {\n\t\t\t\t\tfreq: ControladorJogo.pers.getFreqFuncAtirar(indexArmaMissilPers).freq,\n\t\t\t\t\tatirarDireto: ControladorJogo.pers.getConfigArma(indexArmaMissilPers).atirarDireto\n\t\t\t\t};\n\n\t\t\t\t//mudar freqAtirar e atirarDireto\n\t\t\t\tControladorJogo.pers.getFreqFuncAtirar(indexArmaMissilPers).freq = freqMissilPers;\n\t\t\t\tControladorJogo.pers.getFreqFuncAtirar(indexArmaMissilPers).setContadorUltimaEtapa(); //ele jah vai atirar missil em seguida\n\t\t\t\tControladorJogo.pers.getConfigArma(indexArmaMissilPers).atirarDireto = true;\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.TirarVidaTodosInim:\n\t\t\t\t//passa por todos os controladores de inimigos\n\t\t\t\tControladorJogo.controladoresInimigos.forEach(controladorInims =>\n\t\t\t\t\tcontroladorInims.tirarVidaTodosInim(qtdTiraVidaTodosInim));\n\t\t\t\tbreak;\n\n\t\t\tcase TipoPocao.CongelarInimigos:\n\t\t\t\ttempoPocaoResta = 5000;\n\t\t\t\tpocaoMudaPers = false;\n\t\t\t\t//congelar todos os inimigos\n\t\t\t\tControladorJogo.controladoresInimigos.forEach(controladorInims =>\n\t\t\t\t\tcontroladorInims.mudarCongelarTodosInim(true));\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tthrow \"Esse codigo pocao nao existe!\";\n\t\t}\n\n\t\tif (this.mudaAviaoPersTemp)\n\t\t\t//para mudancas feitas em uma certa nave do personagem nao desexecutar em outra\n\t\t\tthis._numeroAviaoPers = ControladorJogo.pers.numeroAviao;\n\n\t\tif (tempoPocaoResta !== null) //se tem que desexecutar depois de um tempo, programa esse Timer (pode ser soh uma acao pontual)\n\t\t{\n\t\t\t//programa quando quando vai parar com esse pocao\n\t\t\tthis._timerDesexecutar = new Timer(() => { this.desexecutarPocao(); }, tempoPocaoResta, false, false /*pocao transcende o level (mesmo se o level acabar ainda vai ter que desexecutar)*/,\n\t\t\t\tpocaoMudaPers, { obj: this, atr: \"_tempoRestante\" }); //atualiza quanto tempo falta\n\n\t\t\tthis._tempoTotal = tempoPocaoResta;\n\t\t\t//this._tempoRestante = tempoPocaoResta; nao precisa setar tempoRestante porque Timer jah faz isso\n\t\t} else\n\t\t\tdelete this._timerDesexecutar;\n\t}", "function actividade()\n{\n\n estado = 4;\n\n // animacao pacman e monstros\n\n if (flag_vida != 0)\n {\n for(i = 0; i < 5; i++)\n {\n descarta_objecto(i);\n }\n move_pacman();\n move_monstros();\n for(i = 0; i < 5; i++)\n {\n chama_objecto(i);\n }\n animacao_pisca();\n accao();\n\n condicao_vit_derr = setTimeout(\"actividade(); \", velocidade);\n }\n else\n {\n if (jogador_total_comida[jog_activo] > 0)\n {\n clearTimeout(condicao_vit_derr);\n setTimeout(\"morre(); \", 500);\n }\n else\n {\n vidas_jogador[jog_activo]++;\n clearTimeout(condicao_vit_derr);\n setTimeout(\"vitoria(); \", 500);\n }\n }\n}", "function aplicarDescuento(){\n if (numeroDeClases >= 12) {\n console.log(\"El total a abonar con su descuento es de \" + (totalClase - montoDescontar));\n } else if (numeroDeClases <= 11) {\n console.log(\"Aún NO aplica el descuento, el valor total a abonar es de \" + totalClase);\n }\n }", "moverArriba(){\n this.salaActual.jugador = false;\n this.salaActual = this.salaActual.arriba;\n this.salaActual.entradaAnteriorSala = posicionSala.arriba;\n this.salaActual.jugador = true;\n }", "function FimJogo(){\n\t\tswitch(_vitoria){\n\t\t\tcase 1:AnunciarVitoria(1);p1.Vencer();break;\n\t\t\tcase 2:AnunciarVitoria(2);p2.Vencer();break;\n\t\t\tcase 4:AnunciarVitoria(3);p3.Vencer();break;\n\t\t\tcase 8:AnunciarVitoria(4);p4.Vencer();break;\n\t\t\tcase 0:AnunciarVitoria(0);AnimacaoEmpate();break;\n\t\t\tdefault:if(_minutos==0 && _segundos==0){AnunciarVitoria(0);AnimacaoEmpate();}break;\n\t\t}\n\t}", "function actualizarLS(nombre){\n ventas=JSON.parse(localStorage.getItem('carrito'));\n const ventasActualizadas=[];\n ventas.forEach(element => {\n if (element.titulo != nombre){\n ventasActualizadas.push(element)\n }\n });\n localStorage.setItem('carrito',JSON.stringify(ventasActualizadas));\n //actualiza el monto\n actualizaMonto();\n}", "function ChangeAjustarFerimentos(valor) {\n EntradasAdicionarFerimentos(valor, Dom('input-ferimento-nao-letal').checked);\n AtualizaGeralSemLerEntradas();\n}", "async function filtrarProvisorio(solicitudAdopciones, sexo, tamañoFinal, tipoMascota, usuario) {\n \n let animales = [] \n let desde = solicitudAdopciones.length\n // if (solicitudAdopciones.length == undefined )\n // {\n // let filterProv = filter\n // console.log(filterProv)\n // filterProv._id = mongosee.Types.ObjectId(solicitudAdopciones.mascotaId)\n // console.log(filterProv)\n // desde = 0 \n // let animal = await Animal.find(filterProv)\n // if (!animal) return animales\n // if (usuario.tipoUsuario != 1 && usuario.Direccion.barrio != barrioNew && barrioNew) return animales\n // animales.push(animal)\n // }\n \n for (let i = 0 ; i < desde ; i ++ ){\n \n \n let animal = await Animal.findById(solicitudAdopciones[i].mascotaId)\n if(sexo && sexo != animal.sexo) continue\n if(tamañoFinal && tamañoFinal != animal.tamañoFinal) continue\n if(tipoMascota && tipoMascota != animal.tipoMascota) continue\n // if (usuario.tipoUsuario != 1 && usuario.Direccion.barrio != barrioNew && barrioNew) continue\n \n \n // console.log(\"entro al for\", filterProv)\n // if (!animal) continue\n // console.log(\"animales\")\n // if (usuario.tipoUsuario != 1 && usuario.Direccion.barrio != barrioNew && barrioNew) continue\n animales.push(animal)\n \n }\n return (animales)\n }", "imprimirMayorAMenor() {\n\t\tthis.vehiculos.sort((v1, v2) => {\n\t\t\treturn v2.precio - v1.precio\n\t\t})\n\n\t\tconsole.log('Vehiculos ordenados de mayor a menor:')\n\n\t\tthis.vehiculos.forEach(vehiculo => {\n\t\t\tconsole.log(`${vehiculo.marca} ${vehiculo.modelo}`)\n\t\t});\n\t}", "function mantenerPosicion()\n{\n if(vaca.cargaOK)\n {\n for(var i=0; i < cantidadVacas; i++)\n {\n var x = aleatorio(0, 25);\n var y = aleatorio(0, 25);\n var x = x * 30;\n var y = y * 20;\n xVaca[i] = x;\n yVaca[i] = y;\n }\n if(cerdo.cargaOK)\n {\n for(var i=0; i < cantidadCerdos; i++)\n {\n var x = aleatorio(0, 25);\n var y = aleatorio(0, 25);\n var x = x * 30;\n var y = y * 20;\n xCerdo[i] = x;\n yCerdo[i] = y;\n }\n }\n if(pollo.cargaOK)\n {\n for(var i=0; i < cantidadPollos; i++)\n {\n var x = aleatorio(0, 25);\n var y = aleatorio(0, 25);\n var x = x * 30;\n var y = y * 20;\n xPollo[i] = x;\n yPollo[i] = y;\n }\n }\n }\n dibujar();\n}", "function cumpleanosDos(persona){\n\n return {\n \n ...persona,\n edad: persona.edad + 1\n\n }\n\n /* Aqui lo que hacemos es retornar un nuevo objeto con los atributos de la\n persona y podremos cambiar los atributos y agregar atributos nuevos\n \n Esto arreglara el problema de que cuando se invoque la funcion tambien se\n cambie el objeto, con este ejemplo retornara un objeto nuevo con la \n edad modificada y si vemos el objeto este no tendra ningun cambio\n \n \n */\n}", "function avancar(tempoEsgotado){\n\tif ($(\"#buttonAvancar\").attr(\"class\") == \"botaoAvancar enable hover\" || tempoEsgotado) { // verifica se o botao esta habilitado.\n\n\t\tdocument.getElementById('divBotao').innerHTML = \"<input type = 'button' id = 'buttonAvancar' value = 'Avançar' class = 'botaoAvancar' onClick = 'avancaCenario()'/>\";\n\t\tdocument.getElementById(\"contadorRegressivo\").innerHTML = tempo; // mostra o tempo que ele passou para concluir uma etapa\n\n\t\tcoloreCelulas(); // colore as celulas marcadas ou nao\n\t\tmostraResultado(); // mostra o resultado das marcacoes na tela\n\t\tmostraScore();\n\t\tcalculaAumentoSalarial();\n\t}\t\n}", "function habilitarMovimento(sentido, casaBaixo){\n\t\t\t\tif(sentido == 'baixo'){ baixo(casaBaixo); }\n\t\t\t\telse{ $('#baixo_btn').off(); }\n\n\t\t\t\tif(sentido == 'direita'){ direita(); }\n\t\t\t\telse{ $('#direita_btn').off(); }\n\n\t\t\t\tif(sentido == 'esquerda'){ esquerda(); }\n\t\t\t\telse{ $('#esquerda_btn').off(); }\n\t\t\t}", "async salva_descarregamento_sqlite_v2({ ID, Unidade, Placa, Dia, Transportadora, Modal, Nome, Materiais }){\n\n const Atualizado = module.exports.agora();\n\n // Procura um item igual no sqlite\n const db_caminhao = await connection('fDescarregamento')\n .select('*')\n .where( \"ID\", \"=\", ID );\n\n // Se não existir esses caminhões no sqlite ainda, criar um novo\n if ( db_caminhao.length === 0 ) {\n\n await connection('fDescarregamento')\n .insert({\n ID,\n Placa,\n Dia,\n Status: \"Aguardando chegada do veículo\",\n Unidade,\n Atualizado,\n Transportadora,\n Modal,\n Nome,\n Materiais: JSON.stringify(Materiais),\n Assinaturas: JSON.stringify([]),\n Atualizado_sys: Atualizado,\n });\n\n // Caso seja a primeira aparição dessa caminhão, inserir seu status na tabela de status\n module.exports.on_status_change({\n ID,\n Status: 'Aguardando chegada do veículo',\n Unidade,\n Placa,\n Dia\n });\n\n } else {\n\n await connection('fDescarregamento')\n .update({\n Placa,\n Dia,\n Unidade,\n Atualizado,\n Transportadora,\n Modal,\n Nome,\n Materiais: JSON.stringify(Materiais),\n Atualizado_sys: Atualizado\n })\n .where('ID', '=', ID);\n\n };\n }", "function intercambiar() {\n const aux = vaso1;\n vaso1 = vaso2;\n vaso2 = aux;\n}", "async function sincronizarPedidos (idVendedor) {\n if (idEmpresa == undefined)\n throw \"No se reconoce el id empresa.\"\n\n var pedidosParaInsertar = []\n var pedidosItemsParaInsertar = []\n var pedidosItemsDescuentosParaInsertar = []\n var eliminados = []\n var paraEliminar = {}\n var r = 0\n var idPedidosRemoto = []\n var eliminadosLocal = []\n var argFecha = process.argv.slice(2).shift();\n var fechaDesde\n var cantidadRegistros = 0\n const bar = new progress.Bar({barsize: 50}, pPreset)\n \n var pedidosRemoto = await PgPedidos.findAll({\n where: {\n idVendedor: {[Op.eq]: idVendedor},\n idEmpresa: idEmpresa,\n DeletedOn: null,\n [Op.or]: [{idRefPedido: null}, {idRefPedido: 0}]\n },\n order: [\n ['idPedido']\n ]\n })\n\n // var localEliminados = await DmllogEliminados.findAll({\n // attributes: ['id'],\n // where: {\n // sTabla: {[Op.in]: ['PedidosItems', 'PedidosItemsDescuentos']},\n // bProcesado: 0,\n // fEliminado: {\n // [Op.gte]: fechaDesde\n // }\n // }\n // })\n\n idPedidosRemoto = _.map(pedidosRemoto, function(pedidosRemoto) { return pedidosRemoto.id.toLowerCase() })\n\n try {\n var pedidosItemsRemoto = await PgPedidosItems.findAll({\n where: {\n PedidoID: { [Op.in]: idPedidosRemoto },\n DeletedOn: null\n }\n })\n var pedidosItemsDescuentosRemoto = await PgPedidosItemsDescuentos.findAll({\n where: {\n PedidoID: { [Op.in]: idPedidosRemoto },\n DeletedOn: null\n }\n })\n } catch (e) {\n log.fatal(e.message)\n }\n\n cantidadRegistros = pedidosRemoto.length + pedidosItemsRemoto.length + pedidosItemsDescuentosRemoto.length\n if (cantidadRegistros > 0) {\n console.log('')\n console.log('Descarga de datos...')\n bar.start(cantidadRegistros, 0, {tabla: `Vendedor ${idVendedor}:`})\n\n await cargaDeDatos(bar, pedidosRemoto, pedidosItemsRemoto, pedidosItemsDescuentosRemoto)\n // eliminarEliminadoEnMovil(paraEliminar)\n }\n }", "function atualizaDados(){\n\t\t\tatendimentoService.all($scope.data).then(function (response) {\n\t\t\t\tlimpar();\n\t\t\t\t$scope.atendimentos = response.data;\n\t\t\t\t$log.info($scope.atendimentos);\n\t\t\t}, function (error) {\n\t\t\t\t$scope.status = 'Unable to load customer data: ' + error.message;\n\t\t\t});\n\t\t\t$scope.usuario={};\n\t\t}", "function mostraNotas(){}", "function mesAnt() {\r\n if (mesActu === 0) {\r\n //si el mes actual es enero, se decrementa en 1 el año y se coloca como mes actual diciembre\r\n anioActu--;\r\n mesActu = 11;\r\n llenarMes();\r\n } else {\r\n mesActu--;\r\n llenarMes();\r\n }\r\n}", "function desclickear(e){\n movible = false;\n figura = null;\n}", "function movimiento0($contenido1){\n\t\t\t//definir posicion de la ventana cuando no hay opcion seleccionado\n\t\t\t$('#forma-carteras-window').css({\"margin-left\": -350,\"margin-top\": -200});\n\t\t\t//definir alto de la ventana cuando no hay opcion seleccionado\n\t\t\t$('#forma-carteras-window').find('.carteras_div_one').css({'height':'190px'});\n\t\t\t\n\t\t\t//ancho de la ventana\n\t\t\t$('#forma-carteras-window').find('.carteras_div_one').css({'width':'913px'});\n\t\t\t$('#forma-carteras-window').find('.carteras_div_two').css({'width':'913px'});\n\t\t\t$('#forma-carteras-window').find('#carteras_div_titulo_ventana').css({'width':'873px'});\n\t\t\t$('#forma-carteras-window').find('.carteras_div_three').css({'width':'903px'});\n\t\t\t//posicion de los botones\n\t\t\t$('#forma-carteras-window').find('#botones').css({'width':'886px'});\n\t\t\t\n\t\t\t\n\t\t\t$contenido1.find('input[name=pagosxguardar]').attr({ 'value' : 0});\n\t\t\t$contenido1.find('input[name=monto_ant_selec]').attr({ 'value' : 0});\n\t\t\t\n\t\t\t$contenido1.find('tr.uno').find('td.oculta_anticipo').show();\n\t\t\t$contenido1.find('tr.uno').find('a[href*=busca_cliente]').show();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.cheque').hide();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.cancelar').remove();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.cancelar_pagos').remove();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.transferencia').hide();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.registros').hide();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.tarjeta').hide();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.pago').hide();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.monto').hide();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.monto_total').hide();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.moneda').hide();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.moneda').find('textarea[name=observaciones]').text('');\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.moneda').find('textarea[name=observaciones]').hide();\n\t\t\t\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.anticipo').remove();\n\t\t\t$contenido1.find('tr.registros').hide();\n\t\t\t$contenido1.find('tr.transaccion').remove();\n\t\t\t$contenido1.find('tr.facturas').remove();\n\t\t\t$contenido1.find('tr.anticipo').remove();\n\t\t\t$contenido1.find('tr.uno').find('tbody tr.pago').find('td:eq(3)').find('div span').remove();\n\t\t\t$('#forma-carteras-window').find('#submit_pago').hide();\n\t\t\t$('#forma-carteras-window').find('#submit_cancel').hide();\n\t\t\t\n\t\t\t\n\t\t\tvar input_json = document.location.protocol + '//' + document.location.host + '/'+controller+'/get_tipos_movimiento.json';\n\t\t\t$arreglo = {};\n\t\t\t$.post(input_json,$arreglo,function(entry){\n\t\t\t\t//carga select con todas las monedas\n\t\t\t\t$contenido1.find('select[name=tipo_mov]').children().remove();\n\t\t\t\tvar tipo_mov_hmtl = '<option value=\"0\" selected=\"yes\">Seleccione una opcion</option>';\n\t\t\t\t$.each(entry['Tiposmov'],function(entryIndex,tm){\n\t\t\t\t\t\ttipo_mov_hmtl += '<option value=\"' + tm['id'] + '\" >' + tm['titulo'] + '</option>';\n\t\t\t\t});\n\t\t\t\t$contenido1.find('select[name=tipo_mov]').append(tipo_mov_hmtl);\n\t\t\t\t\n\t\t\t});//termina llamada json\n\t\t\t\n\t\t\t\n\t\t}", "function SubirImgTaxiActualizada(cMarca, cModelo, cNtaxi, cPlaca, cSitio, cNumeroSerie, addIDColleccion, num) {\n\t\t\t\t\t\tlet imagenASubir = file;\n\t\t\t\t\t\tlet uploadTask = storageRef.child(\"Fotos_taxis/\" + imagenASubir.name).put(imagenASubir);\n\n\t\t\t\t\t\tuploadTask.on(\"state_changed\",\n\t\t\t\t\t\t\tfunction (snapshot) {\n\t\t\t\t\t\t\t\tlet progress =\n\t\t\t\t\t\t\t\t\t(snapshot.bytesTransferred / snapshot.totalBytes) * 100;\n\t\t\t\t\t\t\t\tswitch (snapshot.state) {\n\t\t\t\t\t\t\t\t\tcase firebase.storage.TaskState.PAUSED: // or 'paused'\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"Upload is paused\");\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase firebase.storage.TaskState.RUNNING: // or 'running'\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"Upload is running\");\n\t\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\tfunction (error) {\n\t\t\t\t\t\t\t\t// Handle unsuccessful uploads\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tfunction () {\n\t\t\t\t\t\t\t\tuploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {\n\t\t\t\t\t\t\t\t\t//Aqui va el metodo donde se guarda\n\t\t\t\t\t\t\t\t\tactualizarTaxi(cMarca, cModelo, cNtaxi, cPlaca, cSitio, cNumeroSerie, downloadURL, addIDColleccion, num);\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}", "function fin() {\n //ponemos el contados y el tiempo final a 0\n contador = 0;\n tiempoFinal = 0;\n console.log('fin');\n\n //desbloqueamos el boton de finalizar para que puedan guardar el movimiento\n document.getElementById('siguiente').innerHTML = '<b>FINALIZAR</b>';\n document.getElementById('siguiente').disabled = false;\n document.getElementById('siguiente').style.backgroundColor = 'rgb(3, 119, 25)';\n}", "function municoesAndam(){\n\tif(jogoEmAndamento==true){\n\t\tmunicoes.forEach(andarMunicao);\n\t}\n}", "function ActionMoi(valeur)\r\n{\r\n\tclearInterval(chrono);\r\n\ttemps = 100;\r\n\tSetActionMoi(valeur);\r\n\tTourSuivantVerification();\r\n}", "function restarDinero(monto) {\n saldoCuenta -= monto;\n return saldoCuenta;\n}", "function activarHerramientaPerfil() {\n console.log(\"Activar herramienta perfil\");\n\n crearYCargarCapaLineaPerfil();\n activarControlDibujo();\n\n\n}", "function contadorAtualizacaoThreads(idContadorRemainUnique){\r\n //var segundosFaltando = GM_getValue(\"quikchan_tempo_autoupdate\") - 1;\r\n $(\"#contadorThreads\").html(\"<p><i>Esta página vai se auto atualizar em <span id=\\\"contadorexibitor\\\">\"+parseInt()+\"</span> segundos...</i></p>\");\r\n var segundosFaltando = parseInt($(\"#contadorexibitor\").html());\r\n\r\n if( segundosFaltando == 0){\r\n segundosFaltando = parseInt(GM_getValue(\"quikchan_tempo_autoupdate\"));\r\n }else{\r\n segundosFaltando = segundosFaltando--;\r\n }\r\n $(\"#contadorexibitor\").html(segundosFaltando);\r\n }", "function PersonagemRenovaFeiticos() {\n for (var chave_classe in gPersonagem.feiticos) {\n if (!gPersonagem.feiticos[chave_classe].em_uso) {\n continue;\n }\n var slots_classe = gPersonagem.feiticos[chave_classe].slots;\n for (var nivel in slots_classe) {\n for (var indice = 0; indice < slots_classe[nivel].feiticos.length; ++indice) {\n slots_classe[nivel].feiticos[indice].gasto = false;\n }\n if ('feitico_dominio' in slots_classe[nivel] && slots_classe[nivel].feitico_dominio != null) {\n slots_classe[nivel].feitico_dominio.gasto = false;\n }\n if ('feitico_especializado' in slots_classe[nivel] && slots_classe[nivel].feitico_especializado != null) {\n slots_classe[nivel].feitico_especializado.gasto = false;\n }\n }\n }\n}", "function _AtualizaModificadoresAtributos() {\n // busca a raca e seus modificadores.\n var modificadores_raca = tabelas_raca[gPersonagem.raca].atributos;\n\n // Busca cada elemento das estatisticas e atualiza modificadores.\n var atributos = [\n 'forca', 'destreza', 'constituicao', 'inteligencia', 'sabedoria', 'carisma' ];\n for (var i = 0; i < atributos.length; ++i) {\n var atributo = atributos[i];\n // Valor do bonus sem base.\n var dom_bonus = Dom(atributo + '-mod-bonus');\n ImprimeSinalizado(gPersonagem.atributos[atributo].bonus.Total(['base']), dom_bonus, false);\n Titulo(gPersonagem.atributos[atributo].bonus.Exporta(['base']), dom_bonus);\n\n // Escreve o valor total.\n var dom_valor = Dom(atributo + '-valor-total');\n ImprimeNaoSinalizado(gPersonagem.atributos[atributo].bonus.Total(), dom_valor);\n Titulo(gPersonagem.atributos[atributo].bonus.Exporta(), dom_valor);\n\n // Escreve o modificador.\n ImprimeSinalizado(\n gPersonagem.atributos[atributo].modificador,\n DomsPorClasse(atributo + '-mod-total'));\n }\n}", "function cumpleanos(persona){\n persona.edad += 1\n\n}", "function fazPonto(ponto) {\n\tmarca = new google.maps.Marker({ position : ponto, map : map });\n\tcordenadasAtual = ponto;\n\tsetDocumentoInfo(ponto);\n\tmap.panTo(ponto);\n}", "actualizarUsuario() {\n let calculo = (this.usuario.peso / (this.usuario.estatura * this.usuario.estatura)) * 10000;\n this.x = calculo.toFixed(2)\n this.usuario.IMC = this.x\n let posicion = this.lista_usuario.findIndex(\n usuario => usuario.id == this.usuario.id\n );\n this.lista_usuario.splice(posicion, 1, this.usuario);\n localStorage.setItem(posicion, this.usuario);\n this.usuario = {\n tipoidentificacion: \"\",\n id: \"\",\n nombres: \"\",\n apellidos: \"\",\n correo: \"\",\n peso: \"\",\n estatura: \"\",\n IMC: \"\",\n acciones: true\n };\n this.saveLocalStorage();\n this.enEdicion = false\n }", "function nascer()\n{\n\n estado = 3;\n flag_vida = 1;\n vidas_jogador[jog_activo]--;\n\tsom_inicio.play();\n if(jog_activo == 0)\n move_obj($('jogador_1'),290,320);\n else\n move_obj($('jogador_2'),290,320);\n\n // coloca objectos iniciais\n inicializa_objectos();\n objectos_comida();\n for(i = 0; i < 5; i++)\n {\n chama_objecto(i);\n }\n\n move_obj($('preparado'),320,450);\n setTimeout(\"move_obj($('jogador_1'),-1000,0); move_obj($('jogador_2'),-1000,0); move_obj($('preparado'),-1000,0); actividade(); \", 2143);\n}", "function SubirImgTaxi(mail, cMarca, cModelo, cNtaxi, cPlaca, cSitio, cNumeroSerie) {\n\t\t\t\t\t\tlet imagenASubir = file;\n\t\t\t\t\t\tlet uploadTask = storageRef.child(\"Fotos_taxis/\" + imagenASubir.name).put(imagenASubir);\n\n\t\t\t\t\t\tuploadTask.on(\"state_changed\",\n\t\t\t\t\t\t\tfunction (snapshot) {\n\t\t\t\t\t\t\t\tlet progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;\n\t\t\t\t\t\t\t\tswitch (snapshot.state) {\n\t\t\t\t\t\t\t\t\tcase firebase.storage.TaskState.PAUSED: // or 'paused'\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"Upload is paused\");\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase firebase.storage.TaskState.RUNNING: // or 'running'\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"Upload is running\");\n\t\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\tfunction (error) {\n\t\t\t\t\t\t\t\t// Handle unsuccessful uploads\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tfunction () {\n\t\t\t\t\t\t\t\tuploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {\n\t\t\t\t\t\t\t\t\t//Aqui va el metodo donde se guarda\n\t\t\t\t\t\t\t\t\tGuardarTaxis(mail, downloadURL, cMarca, cModelo, cNtaxi, cPlaca, cSitio, cNumeroSerie);\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}", "atenderTicket( escritorio ) {\n\n // validacion : imaginemos que No tenemos tickets\n if ( this.tickets.length === 0 ) {\n return null; // nada no hay tiket que puede atender\n } \n\n const ticket = this.tickets.shift(); // this.tickets[0]; - el siguiente en cole con antelacion\n\n /* const ticket : es el ticket el que fue borrado del array de tikcets del dia : tickets en cola de espera, que ya no tiene ningun relacion con la coleccion\n * le asigno al objeto Ticket el directorio quien le atendio \n * pues el ticket es el ticket que necesito atender ahora // escriterio pasa de ser null a un directorio asignado \n */\n ticket.escritorio = escritorio;\n\n this.ultimos4.unshift( ticket ); // empujar en posicion index 0 \n\n if ( this.ultimos4.length > 4 ) { // verificar que siempre sean 4\n this.ultimos4.splice(-1,1); // * -1 : la ultima posicion del array , 1 : quiero que cortar un elemento nada mas , puedo cortar 2 0 3 etc..\n }\n\n this.guardarDB();\n\n return ticket; \n }", "addNuevos(auditorias){\n // al agregar un elemento unico, se debe ubicar: DESPUES de los auditorias sin fecha, y ANTES que los auditorias con fecha\n // buscar el indice del primer inventario con fecha\n let indexConFecha = this.lista.findIndex(aud=>{\n let dia = aud.aud_fechaProgramada.split('-')[2]\n return dia!=='00'\n })\n if(indexConFecha>=0){\n // se encontro el indice\n this.lista.splice(indexConFecha, 0, ...auditorias)\n }else{\n // no hay ninguno con fecha, agregar al final\n this.lista = this.lista.concat(auditorias)\n }\n }", "function pasarFoto() {\r\n // se incrementa el indice (posicionActual)\r\n\r\n // ...y se muestra la imagen que toca.\r\n }", "function sacarDeCarrito(e) {\r\n //Obtenemos el elemento desde el cual se disparó el evento\r\n let boton = e.target;\r\n let id = boton.id;\r\n //Nos quedamos solo con el numero del ID\r\n let index = id.substring(3);\r\n\r\n carrito.splice(index, 1);\r\n\r\n //Despues que actulizamos el carrito volvemos a actualizar el DOM\r\n $(`#carrito${index}`).fadeOut(\"slow\", function () {\r\n actualizarCarritoLocal(carrito);\r\n });\r\n}", "function movimientoantesdelanzar() {\n let bola = document.getElementsByClassName('bola')[0];\n let izquierda;\n izquierda = document.getElementById('jugador').style.left;\n izquierda = izquierda.substring(0, izquierda.indexOf('px'));\n izquierda = parseInt(izquierda) + (2 * (document.getElementById('jugador').offsetWidth / 4))\n izquierda = izquierda + \"px\";\n bola.style.left = izquierda;\n }", "actualizarNombre(id, nombre) {\n for (let usuario of this.lista) {\n if (usuario.id === id) {\n usuario.nombre = nombre;\n break;\n }\n //de la lista en cada interaccicon la variable \n //usuario va a ser el elmento de cada intereaccion\n }\n }", "function setIndiceAndPlayRecientes(indice,a_pagina_cancion,recientes){\n sessionStorage.setItem(\"indiceLista\",indice);\n var listaAux;\n //Si actual es distinta a Aux se establece Aux\n if(recientes==1){\n listaAux = sessionStorage.getItem(\"listaRecientes\");\n }\n else{\n listaAux = sessionStorage.getItem(\"listaRecomendadas\");\n }\n var listaActual = sessionStorage.getItem(\"listaActual\");\n if(listaActual != listaAux){\n sessionStorage.setItem(\"listaActual\",listaAux);\n }\n reproducirCancion(a_pagina_cancion);\n}", "function principal() {\n choquecuerpo();\n choquepared();\n dibujar();\n movimiento();\n \n if(cabeza.choque (comida)){\n comida.colocar();\n cabeza.meter();\n } \n}", "function _GeraPontosDeVida(modo, submodo) {\n if (modo != 'personagem' && modo != 'elite' && modo != 'comum') {\n Mensagem(Traduz('Modo') + ' ' + modo + ' ' + Traduz('invalido') + '. ' + Traduz('Deve ser elite, comum ou personagem.'));\n return;\n }\n // Para cada classe, rolar o dado.\n var total_pontos_vida = 0;\n // Primeiro eh diferente na elite e personagem.\n var primeiro = (modo == 'comum') ? false : true;\n for (var i = 0; i < gPersonagem.classes.length; ++i) {\n var info_classe = gPersonagem.classes[i];\n for (var j = 0; j < info_classe.nivel; ++j) {\n var pontos_vida_nivel = 0;\n var template_personagem = PersonagemTemplate();\n var dados_vida = template_personagem != null && 'dados_vida' in template_personagem ?\n template_personagem.dados_vida :\n tabelas_classes[info_classe.classe].dados_vida;\n if (primeiro) {\n if (modo == 'elite') {\n pontos_vida_nivel = dados_vida;\n } else if (modo == 'personagem') {\n // O modificador de constituicao eh subtraido aqui pq sera adicionado\n // no calculo de pontos de vida, nos bonus.\n pontos_vida_nivel = dados_vida +\n gPersonagem.atributos['constituicao'].valor -\n gPersonagem.atributos['constituicao'].modificador;\n } else {\n pontos_vida_nivel = submodo == 'tabelado' ? dados_vida / 2 : Rola(1, dados_vida);\n }\n primeiro = false;\n } else {\n pontos_vida_nivel = submodo == 'tabelado' ? dados_vida / 2 : Rola(1, dados_vida);\n\n }\n // Nunca pode ganhar menos de 1 ponto por nivel.\n if (pontos_vida_nivel < 1) {\n pontos_vida_nivel = 1;\n }\n total_pontos_vida += pontos_vida_nivel;\n }\n }\n gPersonagem.pontos_vida.total_dados = Math.floor(total_pontos_vida);\n}", "function PrecoArmaArmaduraEscudo(tipo, tabela, chave, material, obra_prima, bonus, invertido) {\n var entrada_tabela = tabela[chave];\n if (entrada_tabela == null || entrada_tabela.preco == null) {\n return null;\n }\n // Nao pode usar invertido aqui, pq la embaixo inverte tudo.\n var preco = LePreco(entrada_tabela.preco);\n var preco_adicional = { platina: 0, ouro: 0, prata: 0, cobre: 0 };\n if (bonus && bonus > 0) {\n switch (bonus) {\n case 1: preco.ouro += tipo == 'arma' ? 2000 : 1000; break; \n case 2: preco.ouro += tipo == 'arma' ? 8000 : 4000; break; \n case 3: preco.ouro += tipo == 'arma' ? 18000 : 9000; break; \n case 4: preco.ouro += tipo == 'arma' ? 32000 : 16000; break; \n case 5: preco.ouro += tipo == 'arma' ? 50000 : 25000; break; \n default:\n return null;\n }\n }\n if (obra_prima) {\n // Armas op custam 300 a mais, armaduras e escudos, 150.\n preco_adicional.ouro += tipo == 'arma' ? 300 : 150; \n }\n // Modificadores de materiais.\n if (material != 'nenhum') {\n var preco_material = null;\n var tabela_material = tabelas_materiais_especiais[material];\n if (tabela_material.custo_por_tipo) {\n var custo = tabela_material.custo_por_tipo[tipo];\n if (custo.por_subtipo) {\n // TODO\n } else {\n preco_material = LePreco(custo);\n }\n } else if (tabela_material.custo_por_kg) {\n var peso_kg = LePeso(entrada_tabela.peso);\n preco_material = LePreco(tabela_material.custo_por_kg);\n for (var tipo_moeda in preco_material) {\n preco_material[tipo_moeda] *= peso_kg;\n }\n } else if (material == 'couro_dragao') {\n // Preco da armadura mais obra prima.\n preco_material = SomaPrecos(LePreco(entrada_tabela.preco), { ouro: 150 });\n } else if (material == 'ferro_frio') {\n // Preço da arma normal e cada bonus custa 2000 PO a mais.\n preco_material = LePreco(entrada_tabela.preco);\n preco_material['ouro'] += bonus * 2000;\n } else if (material == 'mitral') {\n // Preco tabelado de acordo com tipo da armadura ou escudo (excluidindo custo de obra prima).\n var custo = 0; // escudo ou leve.\n if (tipo == 'escudo') {\n custo = 850;\n } else {\n var talento_relacionado = entrada_tabela.talento_relacionado;\n if (talento_relacionado == 'usar_armaduras_leves') {\n custo = 850;\n } else if (talento_relacionado == 'usar_armaduras_medias') {\n custo = 3850;\n } else if (talento_relacionado == 'usar_armaduras_pesadas') {\n custo = 8850;\n }\n }\n preco_material = { ouro: custo };\n } else if (material == 'prata_alquimica') {\n var categorias = entrada_tabela.categorias;\n var custo = 0;\n if ('cac_leve' in categorias) {\n custo = 20;\n } else if ('cac' in categorias) {\n custo = 90;\n } else if ('cac_duas_maos' in categorias) {\n custo = 180;\n }\n preco_material = { ouro: custo };\n }\n // Adiciona preco do material.\n preco_adicional = SomaPrecos(preco_adicional, preco_material);\n }\n\n // Soma e se necessario, inverte.\n preco = SomaPrecos(preco, preco_adicional);\n if (invertido) {\n for (var tipo_moeda in preco) {\n preco[tipo_moeda] = -preco[tipo_moeda];\n }\n }\n return preco;\n}", "function CriarRecados(){\n const descri = document.getElementById('inputDescri').value;\n const detalhes = document.getElementById('inputDetalha').value;\n if (indiceUpdate != undefined) {\n const objeto = lista[indiceUpdate];\n objeto.des = descri;\n objeto.deta = detalhes;\n chamaAlert('warning', 'Recado editado com sucesso!');\n } else {\n lista.push({des:descri,deta:detalhes});\n chamaAlert('success', 'Recado salvo com sucesso!');\n } \n salvar();\n mostrar();\n indiceUpdate = undefined;\n document.getElementById(\"inputDescri\").value = \"\"; //deixa campos limpos\n document.getElementById(\"inputDetalha\").value = \"\"; //deixa campos limpos\n}", "function MetodoCruzamento(){\n //Nivel+1 para sabermos que não são os pais, e um o fruto de um cruzamento do nivel 1.\n\tNivel++;\n\tswitch(MetodoCruzamen){\n\t\tcase 1:\n\t\t\tKillError(\"-s [1:Não definido,2]\");\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tconsole.log(\"Cruzamento em andamento!\");\n\t\t\tconsole.log(\"- Crossover PMX\");\n\t\t\tconsole.log(\"- - Geração: \"+Geracao);\n\t\t\tif(Torneio==1){\n\t\t\t\tconsole.log(\"- - - Torneio\");\n\t\t\t}else{\n\t\t\t\tconsole.log(\"- - - Roleta\");\n\t\t\t}\n\t\t\twhile(Geracao>=0){\n\t\t\t\tCrossover_PMX();\n\t\t\t\tGeracao=Geracao-1;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tKillError(\"-s [1,2]\");\n\t}\n\tQualidadeCheck();\n}", "adicionaVoto(id) {\n\t\tif (id == '1') {\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tthis._bd.run(`UPDATE votacao SET total_votos_1 = total_votos_1 + 1`,[],(err,result) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tconsole.log(err)\n\t\t\t\t\t\treject('Não foi possivel incrementar voto do participante 1')\n\t\t\t\t\t}\n\t\t\t\t\t\tresolve(result);\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t\telse if (id == '16'){\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tthis._bd.run(`UPDATE votacao SET total_votos_2 = total_votos_2 + 1`,[],(err,result) => {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tconsole.log(err)\n\t\t\t\t\t\treject('Não foi possivel incrementar voto do participantes 2 ')\n\t\t\t\t\t}\n\t\t\t\t\t\tresolve(result);\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t}", "function cambiarEstado(e) {\r\n e.preventDefault();\r\n var contadore = 0;\r\n if (e.target.classList.contains('mes-Mesa') || e.target.classList.contains('mes-Mesa-circular')) {\r\n if (e.target.classList.contains('activo')) {\r\n e.target.classList.remove('activo');\r\n } else {\r\n for (var x = 0; x < reserva.children.length; x++) {\r\n if (reserva.children[x].classList.contains('activo')) {\r\n contadore++;\r\n }\r\n }\r\n if (contadore === 0 && !e.target.classList.contains('reservado')) {\r\n e.target.classList.add('activo');\r\n } else {\r\n Swal.fire({\r\n icon: 'error',\r\n title: 'No puede reservar mas de una mesa ni reservar una ocupada',\r\n text: 'Error'\r\n });\r\n }\r\n }\r\n }\r\n}", "function solicitar_movimientos() {\r\n\r\n\r\n var fichasJ1 = obtenerArregloFichas(1);\r\n var fichasJ2 = obtenerArregloFichas(2);\r\n\r\n $scope.http_request.endpoint = \"movidasPosibles\";\r\n $scope.http_request.method = \"POST\";\r\n $scope.http_request.body = {\r\n \"size\" : $scope.tam.col,\r\n \"level\" : obtenerDificultad(),\r\n \"posFichasJ1\" : fichasJ1,\r\n \"posFichasJ2\" : fichasJ2,\r\n \"jugadorActual\" : 1\r\n };\r\n\r\n HttpRequest.player_vs_system($scope.http_request,function (response) {\r\n $scope.movidasPosibles = response.data;\r\n apply_style_available_moves(response.data);\r\n });\r\n }", "function avantiDiUno(){\n\t\tvar fotoCorrente = $(\"img.active\");\n var fotoSuccessiva = fotoCorrente.next(\"img\");\n // devo valutare se l img successiva esiste, in caso contrario riparto dalla prima,poi faro l incontrario per il precedente..sfrutto le classi first e last assegnate.. uso .length per valutare l esistenza!!!\n if (fotoSuccessiva.length == 0) {\n fotoSuccessiva = $(\"img.first\");\n }\n fotoCorrente.removeClass(\"active\");\n fotoSuccessiva.addClass(\"active\");\n // faccio la stessa cosa con i pallini\n var pallinoCorrente = $(\"i.active\");\n var pallinoSuccessivo = pallinoCorrente.next(\"i\");\n if (pallinoSuccessivo.length == 0) {\n pallinoSuccessivo = $(\"i.first\");\n }\n pallinoCorrente.removeClass(\"active\");\n pallinoSuccessivo.addClass(\"active\");\n // faccio variare anche qui l avariabile creata sopra per allinere i cambiamenti di frecce e pallini...vorrei tornare indietro nel tempo e dirlo al me stesso di un ora fa!!!\n if(current_img<3)\n\t\t\tcurrent_img++;\n\t\telse\n\t\t\tcurrent_img=0;\n\n\t}", "function edadEvil (persona)\n{\n persona.edad += 1\n}// esta función modificara la edad del objeto en cuestion, esto se hace por si quieres modificar el objecto original ", "function adicionar (){\n const valor = contador + 1\n setContador(valor) \n }", "function estado() {\n\tmostrarDuracion(medio.currentTime,duracion_avance)\n\tif( !medio.ended ) {\t\t\n\t\tvar total = parseInt( medio.currentTime*maximo/medio.duration )\n\t\tprogreso.style.width = total + \"px\"\n\t} else {\n\t\ttotal = parseInt( medio.currentTime*maximo/medio.duration )\n\t\tprogreso.style.width = total + \"px\"\n\t\treproducir.innerHTML = \"Reproducir\"\n\t\twindow.clearInterval(bucle)\n\t}\t\n}", "function cambiarEstado(esMiTurno, resultado) {\n if (esMiTurno) {\n if (!miPartida.estadoActual && resultado === null) {\n iniciarEventosTablero();\n miPartida.estadoActual = true;\n }\n } else {\n if (miPartida.estadoActual) {\n eliminarEventosTablero();\n miPartida.estadoActual = false;\n }\n }\n}", "function extraerNodoP(){\r\n\tvar nuevo = this.raiz;\r\n\tif(!this.vacia()){\r\n\t\tthis.raiz = this.raiz.sig;\r\n\t\t//window.alert(nuevo.nombre);\r\n\t}\r\n\treturn nuevo;\r\n\t\r\n}", "function activaFuncionamientoReloj() {\n let tiempo = {\n hora: 0,\n minuto: 0,\n segundo: 0\n };\n\n tiempo_corriendo = null;\n\n\n tiempo_corriendo = setInterval(function () {\n // Segundos\n tiempo.segundo++;\n if (tiempo.segundo >= 60) {\n tiempo.segundo = 0;\n tiempo.minuto++;\n }\n\n // Minutos\n if (tiempo.minuto >= 60) {\n tiempo.minuto = 0;\n tiempo.hora++;\n }\n\n $horasDom.text(tiempo.hora < 10 ? '0' + tiempo.hora : tiempo.hora);\n $minutosDom.text(tiempo.minuto < 10 ? '0' + tiempo.minuto : tiempo.minuto);\n $segundosDom.text(tiempo.segundo < 10 ? '0' + tiempo.segundo : tiempo.segundo);\n }, 1000);\n corriendo = true;\n\n }", "function moureFantasma(fantasma) {\n novaDireccioFantasma(fantasma);\n\n if (fantasma[3] == 1) {\n tauler[fantasma[2]][fantasma[1]] = 1;\n //guardem les posicions antigues per comprovar colisions\n fantasma[5] = fantasma[1];\n fantasma[6] = fantasma[2];\n //movem el fantasma\n fantasma[2] += 1;\n //modifiquem el tauler\n tauler[fantasma[2]][fantasma[1]] = 3;\n }\n if (fantasma[3] == 2) {\n tauler[fantasma[2]][fantasma[1]] = 1;\n fantasma[5] = fantasma[1];\n fantasma[6] = fantasma[2];\n fantasma[1] += 1;\n tauler[fantasma[2]][fantasma[1]] = 3;\n }\n if (fantasma[3] == 3) {\n tauler[fantasma[2]][fantasma[1]] = 1;\n fantasma[5] = fantasma[1];\n fantasma[6] = fantasma[2];\n fantasma[2] += -1;\n tauler[fantasma[2]][fantasma[1]] = 3;\n }\n if (fantasma[3] == 4) {\n tauler[fantasma[2]][fantasma[1]] = 1;\n fantasma[5] = fantasma[1];\n fantasma[6] = fantasma[2];\n fantasma[1] += -1;\n tauler[fantasma[2]][fantasma[1]] = 3;\n }\n}", "async pesquisarTarefa() {\n printPlanejamentoAtual(this.getPlanejamentoAtual());\n const { tarefa } = await formPesquisarTarefa(this.listaTarefas());\n await this.informacaoTarefa(tarefa);\n }", "function ocultarAviso() {\n aviso.classList.add('ocultar');\n }", "function movimiento(posicion) {\n var fichablanca;\n var fichaescogida;\n var validacion;\n fichablanca = document.getElementsByClassName(\"p9\")[0].id[3];\n fichaescogida = (posicion);\n validacion = fichablanca - fichaescogida;\n if (validacion == -1 || validacion == 1 || validacion == 3 || validacion == -3) {\n document.getElementsByClassName(\"p9\")[0].className = document.getElementById(\"img\" + (posicion)).className;\n document.getElementById(\"img\" + (posicion)).className = \"p9\";\n }\n}", "function asignarManejadores() {\n traerPersonajes();\n}", "function _AtualizaDadosVida() {\n var span_dados = Dom('dados-vida-classes');\n span_dados.textContent =\n gPersonagem.dados_vida.nivel_personagem + ' = ' + PersonagemStringDadosVida();\n}", "function mostrarMovimientosEnPantalla() {\n let cartel = document.getElementById('movimientos');\n let limite = document.getElementById('movimientos-restantes');\n cartel.innerText = movimientos.length;\n limite.innerText = `Movimientos restantes: ${limiteMovimientos}`;\n}", "verificarPerdida(){\n if(this.grillaLlena()){\n let aux = this.clone();\n aux.grafica = new GraficaInactiva();\n //simulo movimiento a derecha\n aux.mover(new MovimientoDerecha(aux));\n if(aux.compareTo(this)){\n //simulo movimiento a izquierda\n aux.mover(new MovimientoIzquierda(aux));\n if(aux.compareTo(this)){\n //simulo movimiento a abajo\n aux.mover(new MovimientoAbajo(aux));\n if(aux.compareTo(this)){ \n //simulo movimiento a arriba\n aux.mover(new MovimientoArriba(aux));\n if(aux.compareTo(this))\n this.grafica.setPerdida();\n }\n } \n }\n }\n }", "function _attivaIsola(){\r\n\t\t\t$('.isola').each(function(){\r\n\t\t\t\tif($(this).is('[id^=\"isola'+isolaIndex+'\"]')){\r\n\t\t\t\t\t$(this).addClass('attiva').removeClass('spenta');\r\n\t\t\t\t}else{\r\n\t\t\t\t\t$(this).removeClass('attiva').addClass('spenta');\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\t$('.testo-isola#t'+isolaIndex).addClass('presente');\r\n\r\n\t\t\tclicking = true;\r\n\t\t}", "function reiniciar() {\n movimentos = 0;\n $('.movimentos').html(movimentos);\n tempo.stopTimer();\n $('#timer').text(\"Tempo: 00:00 \");\n criarCards();\n $('#s1').show();\n $('#s2').show();\n $('#s3').show();\n addEventHandler();\n }", "async function coletar() {\n try {\n console.log(\"Coletando dados do irrigador\");\n\n let res = await axios.get(URL_DISPOSITIVO);\n if (!res?.data?.status)\n throw new Error(\"Erro durante a coleta dos dados do dispositivo\");\n let status = res.data.status;\n\n // Converte a ultima irrigacao para o tempo atual\n if (!status.ultimaIrrigacao) {\n status.ultimaIrrigacao = await getUltimaIrrigacao();\n } else {\n let agora = Date.now();\n status.ultimaIrrigacao = new Date(agora - status.time + status.ultimaIrrigacao);\n }\n status.time = new Date();\n console.log(`Ultima irrigacao: ${status.ultimaIrrigacao}`);\n\n // Armazena e publica os dados\n console.log(`Armazenando Status: ${JSON.stringify(status)}`);\n udb.insert(res.data);\n if (URL_PLANILHA)\n postPlanilha({ timestamp: new Date(), ...status });\n\n } catch (ex) {\n console.error(err); F\n }\n}", "function finalVideo(mensaje)\n{\n\tvideo.pause();\n\t$(\"#video\").css(\"width\",\"0px\").css(\"height\",\"0px\")\n\t$(\"#video\").addClass(\"hidden\");\n\t$(\"#accion\").text(\"Repetir Aventura.\");\n\t$(\"#mensaje\").text(mensaje);\n\t$(\"#mensaje\").removeClass(\"hidden\");\n\t$(\"#accion\").removeClass(\"hidden\");\n}", "updateFantasmas() {\n var that = this;\n that.fantasmas.forEach(function(fantasma, i){\n that.moverFantasma(fantasma);\n that.teletransportarPersonaje(fantasma);\n fantasma.update();\n })\n }" ]
[ "0.6070929", "0.6011335", "0.591213", "0.5807454", "0.579562", "0.5771342", "0.57705873", "0.5764822", "0.57597023", "0.5744459", "0.5723331", "0.5671172", "0.56194365", "0.55685997", "0.5549548", "0.5492684", "0.5449385", "0.5443814", "0.5429616", "0.5421745", "0.5415066", "0.5406013", "0.54040736", "0.5402946", "0.53995144", "0.53871095", "0.53789943", "0.5346622", "0.5344357", "0.53433233", "0.5343075", "0.5335702", "0.53297746", "0.5305578", "0.530385", "0.5299887", "0.5298671", "0.5296387", "0.5287603", "0.52627754", "0.5260645", "0.5252068", "0.52485824", "0.5239927", "0.5226422", "0.5225476", "0.5224348", "0.52212214", "0.52179635", "0.5207482", "0.5194627", "0.5193033", "0.51793796", "0.5179", "0.5178198", "0.5177868", "0.5174985", "0.5156296", "0.5153178", "0.5145803", "0.51427126", "0.514048", "0.51358354", "0.51348925", "0.5127555", "0.5123574", "0.5105279", "0.51042366", "0.51037014", "0.50992334", "0.50977725", "0.5097102", "0.50929886", "0.50863546", "0.50859845", "0.5083805", "0.5078829", "0.50736797", "0.5071665", "0.5068102", "0.5066499", "0.50653917", "0.5063053", "0.506197", "0.5060259", "0.5058052", "0.50525594", "0.5050664", "0.50505877", "0.5050472", "0.5047878", "0.50469035", "0.5046684", "0.50459343", "0.5045599", "0.5042914", "0.50417453", "0.5037864", "0.50356835", "0.5027247", "0.5026847" ]
0.0
-1
fetch stats by country
fetchCountryData() { this.countriesLoaded = false; this.errorCountries = false; fetch(`${this.api}/countries`) .then((res) => res.json()) .then((data) => (this.items = data)) .finally(() => (this.countriesLoaded = true)) .catch((error) => { this.countriesLoaded = false; this.errorCountries = true; console.log(error); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function requestCountrySpecificData() {\n DevSearchStore.getCountryDataFromServer();\n DevSearchStore.getDeveloperCountByCountryFromServer();\n DevSearchStore.getDeveloperCountByLanguageFromServer();\n}", "function fetchdata(country) {\n var data = [];\n for (x in nodes) {\n if (nodes[x].id === country) {\n data.push(nodes[x]);\n }\n }\n return data;\n }", "function getCountryData() {\n Fetcher(countries)\n .then(countryData => drawCountry(countryData))\n}", "getCountryStatistics(countryCode) {\n // If there is no country selected, we do not make a call to the API\n if(countryCode === '-1' || countryCode === undefined) return;\n\n const url = `https://api.openaq.org/v1/measurements?country=${countryCode}&parameter[]=co&parameter[]=pm25`;\n\n fetch(url)\n .then(response => response.json())\n .then(data => {\n // The data comes back as an object with an array called \"results\".\n // We take the first element of this array, as it contains our measurement data.\n this.setState({ measurementData: data.results[0] });\n });\n }", "async function getOfficeStats(country) {\n\t\t\t\t// async function body\n\t\t\t}", "getCities(country) {\n return fetch(`https://api.openaq.org/v1/latest?country=${country}&parameter=pm25`)\n // Parse JSON response\n .then(response => response.json())\n // Sort from the largest by value of first measurement \n .then(response => response.results.sort((a, b) => b.measurements[0].value - a.measurements[0].value))\n // Make results unique by city\n .then(results => Object.values(\n results.reduce((uniqueResults, result) => {\n if (uniqueResults[result.city] === undefined) {\n uniqueResults[result.city] = result\n }\n return uniqueResults\n }, {})\n ))\n // Slice results to 10, because we want only 10 cities\n .then(results => results.slice(0, 10))\n // List results\n .then(results => results.map(result => result.city))\n }", "async function fetchCountries(country) {\n //Fetch the Country\n // in future replace with fullName endpoint to get Guinea\n // might break some of the other countries due to values\n // not being the exact same as full name (.name field)\n if (country !== 'Guinea') {\n await fetch(`https://restcountries.eu/rest/v2/name/${country}`)\n .then((res) => res.json())\n .then((country) => {\n let output = `\n <div class=\"row\">\n <div class=\"col-md-6 name\">\n <img src=\"${country[0].flag}\" class=\"img-thumbnail-lg\"/>\n </div>\n <div class=\"col-md-6 name\">\n <h2><strong><em>${country[0].name}</em></strong></h2>\n <a onclick=\"countrySelected('${country[0].alpha2Code}')\" href=\"country.html\" class=\"btn btn-primary mt-3\">Country Details</a>\n </div>\n </div>\n </div>\n `\n results.innerHTML = ''\n let doc = new DOMParser().parseFromString(output, 'text/html')\n results.appendChild(doc.body)\n })\n\n .catch((err) => err)\n } else {\n checkIfGuinea(country)\n }\n}", "function getWeather(country) {\n // distracting key names from oneCity object to use \n const { lat, lon, display_name } = country;\n fetch(\n `${BASE_URL}/onecall?lat=${lat}&lon=${lon}&exclude=current&cnt=4&appid=${API_KEY}&units=metric&lang=en`\n )\n .then((res) => res.json())\n .then((data) => {\n // assign data for hourly, daily weather forecast\n setWeather({\n current: {\n ...normalizeWeatherData(data.hourly[0]),\n city: display_name.split(',')[0],\n },\n hourly: data.hourly.map((w) => normalizeWeatherData(w)),\n daily: data.daily.map((w) => normalizeWeatherData(w)),\n timeZone: data.timezone \n \n });\n setSearchBar(false);\n timeZone = data.timezone\n });\n }", "function getGdp(country){\n result = null;\n for (i =0; i<gdp_csv.length; i++){\n if (gdp_csv[i][\"Country\"] == country){\n result = gdp_csv[i];\n }\n }\n return result;\n}", "function campaignStatByCountries(callback, id) {\n if (id === undefined) {\n return callback(returnError('Empty book id'));\n }\n sendRequest('campaigns/' + id + '/countries', 'GET', {}, true, callback);\n}", "function getCountries( countries ) {\r\n const countriesMap = _( countries )\r\n .groupBy( 'country' )\r\n .mapValues( data => {\r\n const callIn = _.sum( data, 'callIn' );\r\n const callOut = _.sum( data, 'callOut' );\r\n\r\n return {\r\n in: callIn,\r\n out: callOut,\r\n total: callIn + callOut,\r\n };\r\n } )\r\n .value();\r\n\r\n return countriesMap;\r\n}", "function showTopForCountry() {\n var url = 'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=' + userCountry + '&api_key=a1b827bb5962ea81025679fd8869f5ed&format=json';\n var countryTop = asyncRequest('GET', url, prettyShow);\n return countryTop;\n}", "function countryCheck() {\n var countryLog = document.querySelector(\".country\");\n var country = response.country;\n console.log(country);\n\n countryLog.innerHTML += country;\n }", "function findCountry(country, data){\n var key = country;\n var object = data[0][key];\n return object;\n }", "function getCountryStat(country, data) {\n// let a;\n// for (let i; i < data.length; i++) {\n// if (data[i].country == 'Bahrain') {\n// a.add(data[i].country);\n// }\n// }\n let result = data.filter(value => value.country == country);\n console.log(typeof result);\n if (result.length>0) {\n return result[0];\n } else {\n return alert('Be sure you write the country correctly!');\n }\n //return data.filter(value => value.country == country);\n}", "async function init_stats(){\n let rng = randid(\"v\");\n let countries = null;\n let global = null;\n let diffs = null;\n let global_stats = {cases:0,deaths:0,recovered:0};\n\n await fetch(\"./js/countries.json\")\n .then(response => response.json())\n .then(data => {\n countries = data;\n })\n .catch(err => console.error(\"JSON ERROR: countries |\", err));\n\n\n await fetch(`${site_url}?type=status`)\n .then(response => response.json())\n .then(data => {\n global = data;\n })\n .catch(err => console.error(\"[API ERROR]: init_stats global |\", err));\n\n\n await fetch(`${site_url}?type=diff`)\n .then(response => response.json())\n .then(data => {\n diffs = data;\n })\n .catch(err => console.error(\"[API ERROR]: init_stats diffs |\", err));\n\n\n // Join all data to one\n let info = Object.keys(countries).map(function(code){\n let name = countries[code];\n let g = global.find(el => { return (code == el.country); });\n let d = diffs.find(el => { return (code == el.country); });\n\n if( name && g && d ){\n global_stats.cases += g.cases;\n global_stats.deaths += g.deaths;\n global_stats.recovered += g.recovered;\n\n return {\n \"name\": name,\n \"code\": code,\n \"cases\": g.cases,\n \"new_cases\": d.new_cases,\n \"deaths\": g.deaths,\n \"new_deaths\": d.new_deaths,\n \"recovered\": g.recovered,\n \"new_recovered\": d.new_recovered,\n };\n }\n else{\n return false;\n }\n });\n\n info = info.filter(el => { return (el != false); });\n\n // console.log( info );\n\n return {\n countries: info,\n global: global_stats\n };\n}", "function dataByCountryDate (country, date){\n\tconst endpointUrl = `https://covid-19-data.p.rapidapi.com/report/country/name?name=${country}&date=${date}`;\t\n\tm = moment(date, 'YYYY-MM-DD')\n\tmFormat = m.format('Do MMMM YYYY');\t\n\t// console.log(country) \n\t// console.log(mFormat) \n\tcountryName.textContent = country + \" - \" + mFormat\n\t\n\t//Fetch country data and display it\n\tfetch(endpointUrl, options)\n\t.then(response => {\n\t\treturn response.json();\n\t})\n\t.then((body) => {\n\t\tif (body[0].provinces[0].confirmed) {\n\t\t\trenderChart(body[0].provinces[0].confirmed, body[0].provinces[0].recovered, body[0].provinces[0].deaths );\n\t\t} else {\n\t\t\tremoveCountryAndRender();\n\t\t\t$(\".msg\" && \".refresh\").html (\"There is no data for this date .Please click to refresh\").show()\n\t\t}\n\t})\n\t.catch(() => {\n\t\tremoveCountryAndRender();\n\t\t$(\".msg\" && \".refresh\").html (\"Please click to refresh and search for a valid country & date\").show();\t\n\t\tcountryName.textContent =\"\";\n });\n}", "function get_country_data(world_data, country_name)\n{\n //http://stackoverflow.com/questions/7176908/how-to-get-index-of-object-by-its-property-in-javascript\n country_index = -1;//world_data.map(function(e) { return e.name; }).indexOf(country_name);\n for(i in world_data)\n {\n if(world_data[i].name == country_name)\n {\n country_index = i;\n break;\n }\n }\n\n return world_data[country_index];\n}", "function getData(country) {\n inputCountry = country;\n}", "function getCountries() {\n\tconst endpointUrl = \"https://covid-19-data.p.rapidapi.com/help/countries\";\n\n\tfetch(endpointUrl, options)\n\t.then(response => {\n\t\treturn response.json();\n\t})\n\t.then((body) => {\t\n\t\tfor (var i = 0 ; i < body.length ; i++ ) {\n\t\t\t$(\"#browsers\").append(`<option class=\"option-country\" value=\"${body[i].name}\">`);\t\t\t\t\n\t\t};\t\t\t\n\t})\n\t.catch((error) => {\n\t\t$(\".msg\" && \".refresh\").html (\"Get Countries failed\").show()\t\t\t\t\n\t});\t\t\n}", "async function getCountries () {\n try {\n return (await axios.get(`${backendAPI}/tracker/country`)).data;\n } catch (error) {\n throw generateError(error);\n }\n }", "getCovidInfo(country) {\n if(country.country == 'England'){\n const formated_country= 'UK'\n const urlString = 'https://corona.lmao.ninja/v2/countries/'+ formated_country + '?yesterday&strict&query='\n return axios.get(urlString) \n .catch(function (error) {\n console.log(error);\n });\n } else if (country.country == 'United States'){\n const formated_country = 'USA'\n const urlString = 'https://corona.lmao.ninja/v2/countries/'+ formated_country + '?yesterday&strict&query='\n return axios.get(urlString) \n .catch(function (error) {\n console.log(error);\n });\n } else{\n const formated_country = country.country\n const urlString = 'https://corona.lmao.ninja/v2/countries/'+ formated_country + '?yesterday&strict&query='\n return axios.get(urlString) \n .catch(function (error) {\n console.log(error);\n });\n }\n\n}", "function getCountryDetails(countries) {\n var deferred = Q.defer();\n var bResponseSent = false;\n var counter = 0;\n var countryDetails = [];\n for(var country in countries) {\n request(encodeURI('https://restcountries.eu/rest/v2/name/' + countries[country]), function (error, response, body) {\n if(error && !bResponseSent) {\n bResponseSent = true;\n deferred.reject(error);\n } else {\n counter++;\n countryDetails.push(JSON.parse(body)[0]); \n if(countries.length === counter && !bResponseSent) {\n bResponseSent = true;\n deferred.resolve(countryDetails); \n }\n } \n }); \n }\n return deferred.promise;\n }", "async function getCountries(region) {\n let url = `https://restcountries.eu/rest/v1/region/${region}`;\n let response = await fetch( url );\n let countries = await response.json();\n return countries;\n}", "getCountryCases(country) {\n console.log(\"Inside getCountryCases \", String(country));\n let covidCases = 0;\n let activeCases = 0;\n let deaths = 0;\n let newCases = 0;\n return fetch(\n \"https://covid-193.p.rapidapi.com/statistics?country=\" + String(country),\n {\n method: \"GET\",\n headers: {\n \"x-rapidapi-host\": \"covid-193.p.rapidapi.com\",\n \"x-rapidapi-key\":\n \"7462fc126bmsh61e1b04c8ef6952p1c3ffdjsn332eaa43c91d\",\n },\n }\n )\n .then((response) => response.json())\n .then((data) => {\n covidCases = data.response[\"0\"][\"cases\"][\"total\"];\n activeCases = data.response[\"0\"][\"cases\"][\"active\"];\n deaths = data.response[\"0\"][\"deaths\"][\"total\"];\n newCases = data.response[\"0\"][\"cases\"][\"new\"];\n })\n .then(() => this.setState({ covidCases, activeCases, deaths, newCases }))\n .catch((err) => {\n console.log(err);\n });\n }", "async function allCountriesData(proxy) {\n\n let countryByname = [];\n let continent = {};\n\n const countrySrc = `${proxy}https://restcountries.herokuapp.com/api/v1`;\n const getdata = await fetch(countrySrc);\n let allCountries = await getdata.json();\n // console.log(allCountries);\n\n for (country of allCountries) {\n countryByname.push([country.name.common, country.cca2, country.region]);\n }\n\n for (country of countryByname) {\n if (country[2] in continent) {\n continent[country[2]].push([country[0], country[1]]);\n }\n else {\n continent[country[2]] = [[country[0], country[1]]];\n }\n }\n // console.log(countryByname);\n // console.log(continent);\n return [countryByname, continent];\n}", "function fetchWeatherInfoWithStatAndCountry(city, state, country) {\n let url = \"http://api.openweathermap.org/data/2.5/weather?q=\";\n url = `${url}${city},{state},${country}&appid=${APIKey}`;\n // console.log(\"url is\", url);\n return fetch(url).then(response => response.json());\n}", "getUserCountry() {\n console.log(\"Inside getUserCountry\");\n let country = \"all\";\n return fetch(\"https://extreme-ip-lookup.com/json/\")\n .then((res) => res.json())\n .then((response) => (country = response.country))\n .catch((data, status) => {\n console.log(\"Request failed\");\n });\n }", "function countries() {\n var deferred = $q.defer(),\n cacheKey = \"countries\",\n geoCountryDataCache = self.geoCountryDataCache.get(cacheKey);\n\n if (geoCountryDataCache) {\n //console.log(\"Countries Found in Cache\", geoCountryDataCache);\n $(\"#loadingWidget\").fadeOut('slow');\n deferred.resolve(geoCountryDataCache);\n }\n\n $http.get(apiUrl + 'util/allcountry')\n .success(function(data, status) {\n if ($http.pendingRequests.length < 1) {\n $(\"#loadingWidget\").fadeOut('slow');\n }\n self.geoCountryDataCache.put(cacheKey, data);\n deferred.resolve(data);\n }).error(function() {\n deferred.reject();\n });\n return deferred.promise;\n }", "function searchAllCountries() {\r\n GetAjaxData(\"https://restcountries.eu/rest/v2/all?fields=name;topLevelDomain;capital;currencies;flag\", response => createArrayFromAllCountries(response) , err => console.log(err))\r\n}", "function getData(selectFilter1, selectFilter2) {\n const url = `https://restcountries.eu/rest/v2/${selectFilter1}/${selectFilter2}`;;\n if (selectFilter1 != '' || selectFilter2 != '') {\n const divPai = document.querySelector('#countriesResult')\n let contentHTML1 = ''\n divPai.innerHTML = contentHTML1;\n fetch(url)\n .then(response => response.json())\n .then(data => {\n data.forEach(element => {\n countryFlag = element.flag\n countryCode = element.alpha3Code\n\n drawCountries(countryFlag, countryCode)\n });\n })\n }\n}", "countries(){\n return fetch(`${this.base+this.urls.countries}`).then((response)=> response.json());\n }", "function loadCountryList() {\n\tLookup.all({where: {'lookup_type':'COUNTRY', 'enabled_flag':'Y'}}, function(err, lookups){\n\t this.country_list = lookups;\n\t next(); // process the next tick. If you don't put it here, it will stuck at this point.\n\t}.bind(this));\n}", "async function fetchCountryData(countryCode) {\n const api_url = `https://restcountries.eu/rest/v2/alpha?codes=${countryCode}`;\n const fetchResponse = await fetch(api_url);\n const json = await fetchResponse.json();\n const jsonData = json[0];\n\n let countryData = {\n countryName: jsonData.name,\n capital: jsonData.capital,\n region: jsonData.region,\n population: jsonData.population,\n currency: jsonData.currencies[0].name,\n primaryLanguage: jsonData.languages[0].name,\n flag: jsonData.flag,\n };\n return countryData;\n}", "function getCountryData(searchObject) {\n return CountrySearchService.getCountryData(searchObject);\n }", "function getStats(type, countryCode, SummaryData) {\n let covidData = []\n switch (type) {\n case \"NewConfirmed\":\n covidData = SummaryData.filter(data => data.CountryCode === countryCode)\n .map(x => x.NewConfirmed)\n return (covidData.toLocaleString());\n\n case \"TotalConfirmed\":\n covidData = SummaryData.filter(data => data.CountryCode === countryCode)\n .map(x => x.TotalConfirmed)\n return (covidData.toLocaleString());\n\n case \"NewRecovered\":\n covidData = SummaryData.filter(data => data.CountryCode === countryCode)\n .map(x => x.NewRecovered)\n return (covidData.toLocaleString());\n\n case \"TotalRecovered\":\n covidData = SummaryData.filter(data => data.CountryCode === countryCode)\n .map(x => x.TotalRecovered)\n return (covidData.toLocaleString());\n\n case \"NewDeaths\":\n covidData = SummaryData.filter(data => data.CountryCode === countryCode)\n .map(x => x.NewDeaths)\n return (covidData.toLocaleString());\n\n case \"TotalDeaths\":\n covidData = SummaryData.filter(data => data.CountryCode === countryCode)\n .map(x => x.TotalDeaths)\n return (covidData.toLocaleString());\n\n case \"LastUpdated\":\n covidData = SummaryData.filter(data => data.CountryCode === countryCode)\n .map(x => x.Date)\n return (new Date(covidData).toLocaleDateString());\n\n default:\n return \"N/A\"\n }\n}", "function getCountry(countryName) {\r\n\r\n /* Change the website title according to the country name */\r\n document.title = countryName;\r\n\r\n var theUrl = 'https://restcountries.eu/rest/v2/name/' + countryName;\r\n jQuery.ajax({\r\n url: theUrl,\r\n dataType: 'json',\r\n type: 'GET',\r\n cache: false,\r\n success: function (dataJSON) {\r\n displayCountry(dataJSON);\r\n }\r\n });\r\n}", "function searchCountry(name, bounds, delay=1) {\n // get the data for this country, *only* for updating the results panel\n // the map and table, continue to show all data\n var data = [];\n // search the data for matches to the country name\n DATA.tracker_data.forEach(function(feature) {\n // look for matching names in feature.properties.countries\n if (name == feature.country) data.push(feature);\n });\n\n // because we are not filtering the map, but only changing the bounds\n // results on the map can easily get out of sync due to a previous search filter\n // so first we need to explicity render() the map with all data, but not the table or results\n render({ name: name, map: true, results: false, table: false, fitbounds: false });\n // THEN update results panel for *this* country data only\n updateResultsPanel(data, name);\n // THEN the table, with all data, but not with this name\n // may seem superfluous, but important to keep the map/table in sync, and showing all data\n drawTable(DATA.tracker_data);\n\n // Last step: zoom the map to the selected country\n // some countries require special/custom bounds calcs, because they straddle the dateline or are otherwise non-standard\n switch (name) {\n case 'Russia':\n bounds = L.latLngBounds([38.35400, 24], [78.11962,178]);\n break;\n case 'United States':\n bounds = L.latLngBounds([18.3, -172.6], [71.7,-67.4]);\n break;\n case 'Canada':\n bounds = L.latLngBounds([41.6, -141.0], [81.7,-52.6]);\n break;\n default:\n break;\n }\n setTimeout(function() {\n CONFIG.map.fitBounds(bounds);\n }, delay)\n}", "function getCountryCoords(country) {\n\t$.ajax({\n\t\turl:\"https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=\" + encodeURIComponent(country),\n\t\ttype:\"GET\",\n\t\tsuccess:function(data) {\n\n\t\t\t//Call drawOverlay function from Gmaps.js to create an overlay for each country\n\n\t\t\tmap.drawOverlay({\n\t\t\t\tlat: data.results[0].geometry.location.lat,\n\t\t\t\tlng: data.results[0].geometry.location.lng,\n\t\t\t\tcontent: '<div class=\"overlay\">' + country + '<div class=\"overlay_arrow above\"></div></div>'\n\t\t\t});\n\t\t}\n\t});\n}", "function getCountry(name){\nreturn countryData[name.toUpperCase()]\n}", "function getAllCountry() {\r\n return get('/country/getall').then(function (res) {\r\n return res.data;\r\n }).catch(function (err) {\r\n return err.response.data;\r\n });\r\n}", "function index_es6_getCountries()\n{\n\treturn getCountries(metadata_min_json)\n}", "getCountryList() {\r\n this.sql_getCountryList = `SELECT id, country_name FROM country_tb ORDER BY id ASC`;\r\n return this.apdao.all(this.sql_getCountryList);\r\n }", "async function getCountry() {\n var data = await getData();\n var country = data.country;\n return country;\n }", "function getCountryInfo() {\n var e = document.getElementById(\"country\");\n var strCountry = e.options[e.selectedIndex].value;\n twlGeo.getGeoNames('countryInfo', { country: strCountry }, countryInfo)\n}", "async function getAllCountries(req, res) {\n // Constantes\n const PAG = req.query.pag || \"0\";\n const TAG = req.query.tag || \"idName\";\n const ORDER = req.query.order || \"ASC\";\n const NAME = req.query.name;\n try {\n flagApiCall = await apiAllRequest(flagApiCall);\n\n const countries = await dbPagRequest(PAG, TAG, ORDER, NAME);\n\n if (countries.count === 0) {\n return res.status(404).send(\"País no encontrado\");\n }\n const pages = Math.ceil(countries.count / 10);\n return res.status(200).send({ countries: countries.rows, pages });\n } catch (error) {\n console.log(\"caught\", error.message);\n }\n}", "async getCitiesByCountries(req, res, next) {\n try {\n const { country } = req.params;\n const cities = await models.Locations.findAll({\n attributes: ['city_name'],\n where: { country_name: country },\n returning: true\n });\n if (!cities.length) {\n return response.success(res, 200, 'No cities saved in the country');\n }\n return response.success(res, 200, cities);\n } catch (error) {\n return next({ message: error.message });\n }\n }", "function getCountries() {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", \"/countries\", false);\n xhr.onreadystatechange = function () {\n if (this.status === 200 && this.readyState === 4) {\n JSON.parse(this.responseText).countries.forEach(function (r) {\n countries[r.name] = r.id;\n });\n }\n }\n xhr.send();\n}", "function getDeaths(country) {\n // Initializing a flag\n let deathsFlag = false;\n let number = 0;\n let strDate = getDateString();\n \n let deaths = tsMap.find(el => el.deaths);\n \n deaths.deaths.forEach (record => {\n if (record[\"Country/Region\"].replace(/_/g, \" \") === country) {\n number = number + parseInt(record[strDate]);\n deathsFlag = true;\n }\n });\n if (deathsFlag) {\n return number;\n } else {\n return undefined;\n }\n }", "function printCountries(countries, region, search = false) {\n var summeryObj = {\n NewConfirmed: 0,\n TotalConfirmed: 0,\n NewDeaths: 0,\n TotalDeaths: 0,\n NewRecovered: 0,\n TotalRecovered: 0,\n };\n var template = loadTemplate(\"countryinfo.ejs\");\n $(\".capiCountryContainer\").html(\"\");\n\n $.each(countries, function (i, field) {\n if (\n countriesMapping[field.CountryCode].region == region ||\n region == \"global\" ||\n search == true\n ) {\n summeryObj[\"NewConfirmed\"] =\n summeryObj[\"NewConfirmed\"] + field.NewConfirmed;\n summeryObj[\"TotalConfirmed\"] =\n summeryObj[\"TotalConfirmed\"] + field.TotalConfirmed;\n summeryObj[\"NewDeaths\"] = summeryObj[\"NewDeaths\"] + field.NewDeaths;\n summeryObj[\"TotalDeaths\"] = summeryObj[\"TotalDeaths\"] + field.TotalDeaths;\n summeryObj[\"NewRecovered\"] =\n summeryObj[\"NewRecovered\"] + field.TotalDeaths;\n summeryObj[\"TotalRecovered\"] =\n summeryObj[\"TotalRecovered\"] + field.TotalRecovered;\n $(\".capiCountryContainer\").append(ejs.render(template, field));\n }\n });\n updatedCapiInformation(\n region,\n summeryObj.NewConfirmed,\n summeryObj.TotalConfirmed,\n summeryObj.NewDeaths,\n summeryObj.TotalDeaths,\n summeryObj.NewRecovered,\n summeryObj.TotalRecovered\n );\n}", "async function getCountries(){\n let response = await fetch(\"https://restcountries.com/v3.1/all\"); \n let countries = await response.json();\n \n let i = null;\n \n for(i=0;i<countries.length;i++){ \n let {name,capital,region,population,flags} = countries[i];\n \n let country = {\n \n name: name.common,\n capital: capital,\n region: region,\n population: population,\n flag: flags.svg\n }\n\n nations.push(country);\n }\n\n showCountries(nations);\n}", "function getCountries() {\n const url = 'https://restcountries.eu/rest/v2/';\n\n return new Promise((resolve, rejected) => {\n fetch(url)\n .then(response => response.json())\n .then(data => resolve(data)) // Prints result from `response.json()`\n .catch(err => rejected(err)); // Print the error\n })\n}", "function availableCountry() {\n let countries = [];\n Object.values(tdata).forEach(value => {\n let country = value.country.toUpperCase();\n if(countries.indexOf(country) !== -1) {\n\n }\n else {\n countries.push(country);\n }\n });\n return countries;\n}", "function randomCountry(){\r\n //A smaller list of many countries from around the world\r\n const randomList = [\r\n \"USA\",\r\n \"Canada\",\r\n \"Mexico\",\r\n \"Colombia\",\r\n \"Brazil\",\r\n \"Argentina\",\r\n \"Chile\",\r\n \"Peru\",\r\n \"Venezuela\",\r\n \"Cuba\",\r\n \"Ecuador\",\r\n \"Australia\",\r\n \"New Zealand\",\r\n \"China\",\r\n \"Japan\",\r\n \"Mongolia\",\r\n \"Madagascar\",\r\n \"Russia\",\r\n \"Poland\",\r\n \"Germany\",\r\n \"Netherlands\",\r\n \"Luxembourg\",\r\n \"Belgium\",\r\n \"France\",\r\n \"Italy\",\r\n \"Spain\",\r\n \"Austria\",\r\n \"United Kingdom\",\r\n \"Norway\",\r\n \"Sweden\",\r\n \"Finland\",\r\n \"Iceland\",\r\n \"Portugal\",\r\n \"Romania\",\r\n \"Switzerland\",\r\n \"Egypt\",\r\n \"Nigeria\",\r\n \"South Africa\",\r\n \"Algeria\",\r\n \"Morocco\",\r\n \"Ethiopia\",\r\n \"Ghana\",\r\n \"Kenya\",\r\n \"Tanzania\",\r\n \"Bhārat\"\r\n ];\r\n const REST_URL = \"https://restcountries.eu/rest/v2/name/\";\r\n\r\n let url = REST_URL;\r\n\r\n let rValue = Math.floor((Math.random() * 45));\r\n let country = randomList[rValue];\r\n countryShown = country;\r\n\r\n country = country.trim();\r\n\r\n country = encodeURIComponent(country);\r\n\r\n if(country.length < 1)return;\r\n\r\n url += country;\r\n document.querySelector(\"#status\").innerHTML = \"<b>Searching for '\" + countryShown + \"'</b>\";\r\n getData(url);\r\n}", "function getCountries() {\n var countryChoices = [\n {\n \"abbr\":\"\",\n \"name\":\"(not applicable)\"\n },\n {\n \"abbr\":\"AF\",\n \"name\":\"Afghanistan\"\n },\n {\n \"abbr\":\"AX\",\n \"name\":\"Akrotiri\"\n },\n {\n \"abbr\":\"AL\",\n \"name\":\"Albania\"\n },\n {\n \"abbr\":\"AG\",\n \"name\":\"Algeria\"\n },\n {\n \"abbr\":\"AQ\",\n \"name\":\"American Samoa\"\n },\n {\n \"abbr\":\"AN\",\n \"name\":\"Andorra\"\n },\n {\n \"abbr\":\"AO\",\n \"name\":\"Angola\"\n },\n {\n \"abbr\":\"AV\",\n \"name\":\"Anguilla\"\n },\n {\n \"abbr\":\"AY\",\n \"name\":\"Antarctica \"\n },\n {\n \"abbr\":\"AC\",\n \"name\":\"Antigua and Barbuda\"\n },\n {\n \"abbr\":\"AR\",\n \"name\":\"Argentina\"\n },\n {\n \"abbr\":\"AM\",\n \"name\":\"Armenia\"\n },\n {\n \"abbr\":\"AA\",\n \"name\":\"Aruba\"\n },\n {\n \"abbr\":\"AT\",\n \"name\":\"Ashmore and Cartier Islands\"\n },\n {\n \"abbr\":\"AS\",\n \"name\":\"Australia\"\n },\n {\n \"abbr\":\"AU\",\n \"name\":\"Austria\"\n },\n {\n \"abbr\":\"AJ\",\n \"name\":\"Azerbaijan\"\n },\n {\n \"abbr\":\"BF\",\n \"name\":\"Bahamas\"\n },\n {\n \"abbr\":\"BA\",\n \"name\":\"Bahrain\"\n },\n {\n \"abbr\":\"FQ\",\n \"name\":\"Baker Island \"\n },\n {\n \"abbr\":\"BG\",\n \"name\":\"Bangladesh\"\n },\n {\n \"abbr\":\"BB\",\n \"name\":\"Barbados \"\n },\n {\n \"abbr\":\"BO\",\n \"name\":\"Belarus\"\n },\n {\n \"abbr\":\"BE\",\n \"name\":\"Belgium\"\n },\n {\n \"abbr\":\"BH\",\n \"name\":\"Belize\"\n },\n {\n \"abbr\":\"BN\",\n \"name\":\"Benin\"\n },\n {\n \"abbr\":\"BD\",\n \"name\":\"Bermuda\"\n },\n {\n \"abbr\":\"BT\",\n \"name\":\"Bhutan\"\n },\n {\n \"abbr\":\"BL\",\n \"name\":\"Bolivia\"\n },\n {\n \"abbr\":\"BK\",\n \"name\":\"Bosnia-Herzegovina\"\n },\n {\n \"abbr\":\"BC\",\n \"name\":\"Botswana\"\n },\n {\n \"abbr\":\"BV\",\n \"name\":\"Bouvet Island\"\n },\n {\n \"abbr\":\"BR\",\n \"name\":\"Brazil\"\n },\n {\n \"abbr\":\"IO\",\n \"name\":\"British Indian Ocean Territory\"\n },\n {\n \"abbr\":\"VI\",\n \"name\":\"British Virgin Islands\"\n },\n {\n \"abbr\":\"BX\",\n \"name\":\"Brunei\"\n },\n {\n \"abbr\":\"BU\",\n \"name\":\"Bulgaria\"\n },\n {\n \"abbr\":\"UV\",\n \"name\":\"Burkina Faso\"\n },\n {\n \"abbr\":\"BM\",\n \"name\":\"Burma\"\n },\n {\n \"abbr\":\"BY\",\n \"name\":\"Burundi\"\n },\n {\n \"abbr\":\"CB\",\n \"name\":\"Cambodia\"\n },\n {\n \"abbr\":\"CM\",\n \"name\":\"Cameroon\"\n },\n {\n \"abbr\":\"CA\",\n \"name\":\"Canada \"\n },\n {\n \"abbr\":\"CV\",\n \"name\":\"Cape Verde\"\n },\n {\n \"abbr\":\"CJ\",\n \"name\":\"Cayman Islands\"\n },\n {\n \"abbr\":\"CT\",\n \"name\":\"Central African Republic\"\n },\n {\n \"abbr\":\"CD\",\n \"name\":\"Chad\"\n },\n {\n \"abbr\":\"CI\",\n \"name\":\"Chile\"\n },\n {\n \"abbr\":\"CH\",\n \"name\":\"China \"\n },\n {\n \"abbr\":\"KT\",\n \"name\":\"Christmas Island\"\n },\n {\n \"abbr\":\"IP\",\n \"name\":\"Clipperton Island\"\n },\n {\n \"abbr\":\"CK\",\n \"name\":\"Cocos (Keeling) Islands\"\n },\n {\n \"abbr\":\"CO\",\n \"name\":\"Colombia\"\n },\n {\n \"abbr\":\"CN\",\n \"name\":\"Comoros \"\n },\n {\n \"abbr\":\"CF\",\n \"name\":\"Congo (Brazzaville)\"\n },\n {\n \"abbr\":\"CG\",\n \"name\":\"Congo (Kinshasa)\"\n },\n {\n \"abbr\":\"CW\",\n \"name\":\"Cook Islands\"\n },\n {\n \"abbr\":\"CR\",\n \"name\":\"Coral Sea Islands\"\n },\n {\n \"abbr\":\"CS\",\n \"name\":\"Costa Rica\"\n },\n {\n \"abbr\":\"IV\",\n \"name\":\"Cote D'Ivoire (Ivory Coast)\"\n },\n {\n \"abbr\":\"HR\",\n \"name\":\"Croatia\"\n },\n {\n \"abbr\":\"CU\",\n \"name\":\"Cuba\"\n },\n {\n \"abbr\":\"UC\",\n \"name\":\"Curacao\"\n },\n {\n \"abbr\":\"CY\",\n \"name\":\"Cyprus\"\n },\n {\n \"abbr\":\"EZ\",\n \"name\":\"Czech Republic\"\n },\n {\n \"abbr\":\"DA\",\n \"name\":\"Denmark\"\n },\n {\n \"abbr\":\"DX\",\n \"name\":\"Dhekelia\"\n },\n {\n \"abbr\":\"DJ\",\n \"name\":\"Djibouti\"\n },\n {\n \"abbr\":\"DO\",\n \"name\":\"Dominica\"\n },\n {\n \"abbr\":\"DR\",\n \"name\":\"Dominican Republic\"\n },\n {\n \"abbr\":\"TT\",\n \"name\":\"East Timor \"\n },\n {\n \"abbr\":\"EC\",\n \"name\":\"Ecuador\"\n },\n {\n \"abbr\":\"EG\",\n \"name\":\"Egypt\"\n },\n {\n \"abbr\":\"ES\",\n \"name\":\"El Salvador\"\n },\n {\n \"abbr\":\"EK\",\n \"name\":\"Equatorial Guinea\"\n },\n {\n \"abbr\":\"ER\",\n \"name\":\"Eritrea\"\n },\n {\n \"abbr\":\"EN\",\n \"name\":\"Estonia\"\n },\n {\n \"abbr\":\"ET\",\n \"name\":\"Ethiopia\"\n },\n {\n \"abbr\":\"FK\",\n \"name\":\"Falkland Islands (Islas Malvinas)\"\n },\n {\n \"abbr\":\"FO\",\n \"name\":\"Faroe Islands\"\n },\n {\n \"abbr\":\"FM\",\n \"name\":\"Federated States of Micronesia\"\n },\n {\n \"abbr\":\"FJ\",\n \"name\":\"Fiji\"\n },\n {\n \"abbr\":\"FI\",\n \"name\":\"Finland\"\n },\n {\n \"abbr\":\"FR\",\n \"name\":\"France\"\n },\n {\n \"abbr\":\"FP\",\n \"name\":\"French Polynesia\"\n },\n {\n \"abbr\":\"FS\",\n \"name\":\"French Southern and Antarctic Lands\"\n },\n {\n \"abbr\":\"GB\",\n \"name\":\"Gabon\"\n },\n {\n \"abbr\":\"GA\",\n \"name\":\"The Gambia\"\n },\n {\n \"abbr\":\"GG\",\n \"name\":\"Georgia\"\n },\n {\n \"abbr\":\"GM\",\n \"name\":\"Germany\"\n },\n {\n \"abbr\":\"GH\",\n \"name\":\"Ghana\"\n },\n {\n \"abbr\":\"GI\",\n \"name\":\"Gibraltar\"\n },\n {\n \"abbr\":\"GR\",\n \"name\":\"Greece\"\n },\n {\n \"abbr\":\"GL\",\n \"name\":\"Greenland\"\n },\n {\n \"abbr\":\"GJ\",\n \"name\":\"Grenada\"\n },\n {\n \"abbr\":\"GQ\",\n \"name\":\"Guam\"\n },\n {\n \"abbr\":\"GT\",\n \"name\":\"Guatemala\"\n },\n {\n \"abbr\":\"GK\",\n \"name\":\"Guernsey\"\n },\n {\n \"abbr\":\"GV\",\n \"name\":\"Guinea\"\n },\n {\n \"abbr\":\"PU\",\n \"name\":\"Guinea-Bissau\"\n },\n {\n \"abbr\":\"GY\",\n \"name\":\"Guyana\"\n },\n {\n \"abbr\":\"HA\",\n \"name\":\"Haiti\"\n },\n {\n \"abbr\":\"HM\",\n \"name\":\"Heard Island and McDonald Islands\"\n },\n {\n \"abbr\":\"VT\",\n \"name\":\"Holy See\"\n },\n {\n \"abbr\":\"HO\",\n \"name\":\"Honduras\"\n },\n {\n \"abbr\":\"HK\",\n \"name\":\"Hong Kong\"\n },\n {\n \"abbr\":\"HQ\",\n \"name\":\"Howland Island \"\n },\n {\n \"abbr\":\"HU\",\n \"name\":\"Hungary\"\n },\n {\n \"abbr\":\"IC\",\n \"name\":\"Iceland\"\n },\n {\n \"abbr\":\"IN\",\n \"name\":\"India\"\n },\n {\n \"abbr\":\"ID\",\n \"name\":\"Indonesia\"\n },\n {\n \"abbr\":\"IR\",\n \"name\":\"Iran\"\n },\n {\n \"abbr\":\"IZ\",\n \"name\":\"Iraq\"\n },\n {\n \"abbr\":\"EI\",\n \"name\":\"Ireland\"\n },\n {\n \"abbr\":\"IS\",\n \"name\":\"Israel\"\n },\n {\n \"abbr\":\"IT\",\n \"name\":\"Italy\"\n },\n {\n \"abbr\":\"JM\",\n \"name\":\"Jamaica\"\n },\n {\n \"abbr\":\"JN\",\n \"name\":\"Jan Mayen\"\n },\n {\n \"abbr\":\"JA\",\n \"name\":\"Japan\"\n },\n {\n \"abbr\":\"DQ\",\n \"name\":\"Jarvis Island\"\n },\n {\n \"abbr\":\"JE\",\n \"name\":\"Jersey\"\n },\n {\n \"abbr\":\"JQ\",\n \"name\":\"Johnston Atoll\"\n },\n {\n \"abbr\":\"JO\",\n \"name\":\"Jordan\"\n },\n {\n \"abbr\":\"KZ\",\n \"name\":\"Kazakhstan\"\n },\n {\n \"abbr\":\"KE\",\n \"name\":\"Kenya\"\n },\n {\n \"abbr\":\"KQ\",\n \"name\":\"Kingman Reef\"\n },\n {\n \"abbr\":\"KR\",\n \"name\":\"Kiribati\"\n },\n {\n \"abbr\":\"KN\",\n \"name\":\"Korea, North\"\n },\n {\n \"abbr\":\"KS\",\n \"name\":\"Korea, South\"\n },\n {\n \"abbr\":\"KV\",\n \"name\":\"Kosovo\"\n },\n {\n \"abbr\":\"KU\",\n \"name\":\"Kuwait\"\n },\n {\n \"abbr\":\"KG\",\n \"name\":\"Kyrgyzstan\"\n },\n {\n \"abbr\":\"LA\",\n \"name\":\"Laos\"\n },\n {\n \"abbr\":\"LG\",\n \"name\":\"Latvia\"\n },\n {\n \"abbr\":\"LE\",\n \"name\":\"Lebanon\"\n },\n {\n \"abbr\":\"LT\",\n \"name\":\"Lesotho\"\n },\n {\n \"abbr\":\"LI\",\n \"name\":\"Liberia\"\n },\n {\n \"abbr\":\"LY\",\n \"name\":\"Libya\"\n },\n {\n \"abbr\":\"LS\",\n \"name\":\"Liechtenstein\"\n },\n {\n \"abbr\":\"LH\",\n \"name\":\"Lithuania\"\n },\n {\n \"abbr\":\"LU\",\n \"name\":\"Luxembourg \"\n },\n {\n \"abbr\":\"MC\",\n \"name\":\"Macau\"\n },\n {\n \"abbr\":\"MK\",\n \"name\":\"Macedonia\"\n },\n {\n \"abbr\":\"MA\",\n \"name\":\"Madagascar\"\n },\n {\n \"abbr\":\"MI\",\n \"name\":\"Malawi\"\n },\n {\n \"abbr\":\"MY\",\n \"name\":\"Malaysia\"\n },\n {\n \"abbr\":\"MV\",\n \"name\":\"Maldives\"\n },\n {\n \"abbr\":\"ML\",\n \"name\":\"Mali\"\n },\n {\n \"abbr\":\"MT\",\n \"name\":\"Malta\"\n },\n {\n \"abbr\":\"IM\",\n \"name\":\"Man, Isle of\"\n },\n {\n \"abbr\":\"RM\",\n \"name\":\"Marshall Islands\"\n },\n {\n \"abbr\":\"MR\",\n \"name\":\"Mauritania\"\n },\n {\n \"abbr\":\"MP\",\n \"name\":\"Mauritius\"\n },\n {\n \"abbr\":\"MX\",\n \"name\":\"Mexico\"\n },\n {\n \"abbr\":\"MQ\",\n \"name\":\"Midway Islands\"\n },\n {\n \"abbr\":\"MD\",\n \"name\":\"Moldova\"\n },\n {\n \"abbr\":\"MN\",\n \"name\":\"Monaco\"\n },\n {\n \"abbr\":\"MG\",\n \"name\":\"Mongolia \"\n },\n {\n \"abbr\":\"MJ\",\n \"name\":\"Montenegro\"\n },\n {\n \"abbr\":\"MH\",\n \"name\":\"Montserrat\"\n },\n {\n \"abbr\":\"MO\",\n \"name\":\"Morocco\"\n },\n {\n \"abbr\":\"MZ\",\n \"name\":\"Mozambique\"\n },\n {\n \"abbr\":\"WA\",\n \"name\":\"Namibia\"\n },\n {\n \"abbr\":\"NR\",\n \"name\":\"Nauru\"\n },\n {\n \"abbr\":\"BQ\",\n \"name\":\"Navassa Island\"\n },\n {\n \"abbr\":\"NP\",\n \"name\":\"Nepal\"\n },\n {\n \"abbr\":\"NL\",\n \"name\":\"Netherlands\"\n },\n {\n \"abbr\":\"NC\",\n \"name\":\"New Caledonia\"\n },\n {\n \"abbr\":\"NZ\",\n \"name\":\"New Zealand\"\n },\n {\n \"abbr\":\"NU\",\n \"name\":\"Nicaragua\"\n },\n {\n \"abbr\":\"NG\",\n \"name\":\"Niger\"\n },\n {\n \"abbr\":\"NI\",\n \"name\":\"Nigeria\"\n },\n {\n \"abbr\":\"NE\",\n \"name\":\"Niue \"\n },\n {\n \"abbr\":\"NF\",\n \"name\":\"Norfolk Island\"\n },\n {\n \"abbr\":\"CQ\",\n \"name\":\"Northern Mariana Islands\"\n },\n {\n \"abbr\":\"NO\",\n \"name\":\"Norway\"\n },\n {\n \"abbr\":\"MU\",\n \"name\":\"Oman\"\n },\n {\n \"abbr\":\"PK\",\n \"name\":\"Pakistan\"\n },\n {\n \"abbr\":\"PS\",\n \"name\":\"Palau\"\n },\n {\n \"abbr\":\"LQ\",\n \"name\":\"Palmyra Atoll\"\n },\n {\n \"abbr\":\"PM\",\n \"name\":\"Panama \"\n },\n {\n \"abbr\":\"PP\",\n \"name\":\"Papua-New Guinea\"\n },\n {\n \"abbr\":\"PF\",\n \"name\":\"Paracel Islands\"\n },\n {\n \"abbr\":\"PA\",\n \"name\":\"Paraguay\"\n },\n {\n \"abbr\":\"PE\",\n \"name\":\"Peru\"\n },\n {\n \"abbr\":\"RP\",\n \"name\":\"Philippines\"\n },\n {\n \"abbr\":\"PC\",\n \"name\":\"Pitcairn Islands\"\n },\n {\n \"abbr\":\"PL\",\n \"name\":\"Poland\"\n },\n {\n \"abbr\":\"PO\",\n \"name\":\"Portugal \"\n },\n {\n \"abbr\":\"RQ\",\n \"name\":\"Puerto Rico\"\n },\n {\n \"abbr\":\"QA\",\n \"name\":\"Qatar\"\n },\n {\n \"abbr\":\"RO\",\n \"name\":\"Romania\"\n },\n {\n \"abbr\":\"RS\",\n \"name\":\"Russia\"\n },\n {\n \"abbr\":\"RW\",\n \"name\":\"Rwanda\"\n },\n {\n \"abbr\":\"TB\",\n \"name\":\"Saint Barthelemy\"\n },\n {\n \"abbr\":\"RN\",\n \"name\":\"Saint Martin\"\n },\n {\n \"abbr\":\"WS\",\n \"name\":\"Samoa\"\n },\n {\n \"abbr\":\"SM\",\n \"name\":\"San Marino\"\n },\n {\n \"abbr\":\"TP\",\n \"name\":\"Sao Tome and Principe\"\n },\n {\n \"abbr\":\"SA\",\n \"name\":\"Saudi Arabia\"\n },\n {\n \"abbr\":\"SG\",\n \"name\":\"Senegal\"\n },\n {\n \"abbr\":\"RI\",\n \"name\":\"Serbia\"\n },\n {\n \"abbr\":\"SE\",\n \"name\":\"Seychelles \"\n },\n {\n \"abbr\":\"SL\",\n \"name\":\"Sierra Leone\"\n },\n {\n \"abbr\":\"SN\",\n \"name\":\"Singapore\"\n },\n {\n \"abbr\":\"NN\",\n \"name\":\"Sint Maarten\"\n },\n {\n \"abbr\":\"LO\",\n \"name\":\"Slovakia\"\n },\n {\n \"abbr\":\"SI\",\n \"name\":\"Slovenia\"\n },\n {\n \"abbr\":\"BP\",\n \"name\":\"Solomon Islands\"\n },\n {\n \"abbr\":\"SO\",\n \"name\":\"Somalia\"\n },\n {\n \"abbr\":\"SF\",\n \"name\":\"South Africa\"\n },\n {\n \"abbr\":\"SX\",\n \"name\":\"South Georgia and The S Sandwich Islands\"\n },\n {\n \"abbr\":\"OD\",\n \"name\":\"South Sudan\"\n },\n {\n \"abbr\":\"SP\",\n \"name\":\"Spain\"\n },\n {\n \"abbr\":\"PG\",\n \"name\":\"Spratly Islands \"\n },\n {\n \"abbr\":\"CE\",\n \"name\":\"Sri Lanka\"\n },\n {\n \"abbr\":\"SH\",\n \"name\":\"St. Helena\"\n },\n {\n \"abbr\":\"SC\",\n \"name\":\"St. Kitts and Nevis\"\n },\n {\n \"abbr\":\"ST\",\n \"name\":\"St. Lucia Island\"\n },\n {\n \"abbr\":\"SB\",\n \"name\":\"St. Pierre and Miquelon\"\n },\n {\n \"abbr\":\"VC\",\n \"name\":\"St. Vincent and Grenadines\"\n },\n {\n \"abbr\":\"SU\",\n \"name\":\"Sudan\"\n },\n {\n \"abbr\":\"NS\",\n \"name\":\"Suriname\"\n },\n {\n \"abbr\":\"SV\",\n \"name\":\"Svalbard\"\n },\n {\n \"abbr\":\"WZ\",\n \"name\":\"Swaziland\"\n },\n {\n \"abbr\":\"SW\",\n \"name\":\"Sweden \"\n },\n {\n \"abbr\":\"SZ\",\n \"name\":\"Switzerland\"\n },\n {\n \"abbr\":\"SY\",\n \"name\":\"Syria\"\n },\n {\n \"abbr\":\"TW\",\n \"name\":\"Taiwan\"\n },\n {\n \"abbr\":\"TI\",\n \"name\":\"Tajikistan\"\n },\n {\n \"abbr\":\"TZ\",\n \"name\":\"Tanzania\"\n },\n {\n \"abbr\":\"TH\",\n \"name\":\"Thailand\"\n },\n {\n \"abbr\":\"TO\",\n \"name\":\"Togo\"\n },\n {\n \"abbr\":\"TL\",\n \"name\":\"Tokelau \"\n },\n {\n \"abbr\":\"TN\",\n \"name\":\"Tonga\"\n },\n {\n \"abbr\":\"TD\",\n \"name\":\"Trinidad and Tobago\"\n },\n {\n \"abbr\":\"TS\",\n \"name\":\"Tunisia\"\n },\n {\n \"abbr\":\"TU\",\n \"name\":\"Turkey\"\n },\n {\n \"abbr\":\"TX\",\n \"name\":\"Turkmenistan\"\n },\n {\n \"abbr\":\"TK\",\n \"name\":\"Turks and Caicos Islands\"\n },\n {\n \"abbr\":\"TV\",\n \"name\":\"Tuvalu\"\n },\n {\n \"abbr\":\"UG\",\n \"name\":\"Uganda\"\n },\n {\n \"abbr\":\"UP\",\n \"name\":\"Ukraine\"\n },\n {\n \"abbr\":\"AE\",\n \"name\":\"United Arab Emirates\"\n },\n {\n \"abbr\":\"UK\",\n \"name\":\"United Kingdom\"\n },\n {\n \"abbr\":\"UY\",\n \"name\":\"Uruguay\"\n },\n {\n \"abbr\":\"UZ\",\n \"name\":\"Uzbekistan\"\n },\n {\n \"abbr\":\"NH\",\n \"name\":\"Vanuatu\"\n },\n {\n \"abbr\":\"VE\",\n \"name\":\"Venezuela\"\n },\n {\n \"abbr\":\"VM\",\n \"name\":\"Vietnam\"\n },\n {\n \"abbr\":\"VQ\",\n \"name\":\"Virgin Islands\"\n },\n {\n \"abbr\":\"WQ\",\n \"name\":\"Wake Island\"\n },\n {\n \"abbr\":\"WF\",\n \"name\":\"Wallis and Futuna\"\n },\n {\n \"abbr\":\"WI\",\n \"name\":\"Western Sahara\"\n },\n {\n \"abbr\":\"YM\",\n \"name\":\"Yemen (Aden)\"\n },\n {\n \"abbr\":\"ZA\",\n \"name\":\"Zambia\"\n },\n {\n \"abbr\":\"ZI\",\n \"name\":\"Zimbabwe\"\n },\n {\n \"abbr\":\"OC\",\n \"name\":\"Other Countries\"\n }\n ];\n return countryChoices;\n}", "async function getCountry() {\n let country = localStorage.getItem('alpha2Code')\n\n //Fetch the details\n await fetch(`https://restcountries.eu/rest/v2/alpha/${country}`)\n .then((res) => res.json())\n .then((count) => {\n let output = `\n <div class=\"card card-body bg-light m-2 p-3\">\n\n <div class=\"row name-div\">\n <div class=\"col-md-6 col-sm-12 name\">\n <img src=\"${\n count.flag\n }\" class=\"img-fluid img-thumbnail\" style= \"width: 70%;\"/>\n </div>\n <div class=\"col-md-6 col-sm-12 ml-5 name\">\n <h2 class=\"mt-5\"><strong><em>${count.name}</em></strong></h2>\n <p style=\"margin: 0;\"><i>Native Spelling</i></p>\n <h2 style=\"margin: 0;\"><em>${count.nativeName}</em></h2>\n </div>\n </div>\n <div class=\"\">\n <div id=\"info\">\n <div class=\"card card-body bg-secondary m-2\">\n <ul class=\"list-group\">\n <li class=\"list-group-item\"><strong>Capital:</strong> ${\n count.capital\n }</li>\n <li class=\"list-group-item\"><strong>Region:</strong> ${\n count.region\n }</li>\n\n <li class=\"list-group-item\"><strong>Subregion:</strong> ${\n count.subregion\n }</li>\n ${\n count.regionalBlocs[0]\n ? `<li class=\"list-group-item\"><strong>Regional Intergovernmental Organization:</strong/> (${count.regionalBlocs[0].acronym}) - <span>${count.regionalBlocs[0].name}</span></li>`\n : ``\n }\n \n \n <li class=\"list-group-item\"><strong>Population:</strong> ${\n count.population\n }</li>\n <li class=\"list-group-item\"><strong>Languages Spoken: <span>${\n count.languages.length\n } : </strong>\n ${count.languages.map((lang) => {\n return ` <span>${lang.name}</span>`\n })}\n </li>\n \n <li class=\"list-group-item\"><strong>Timezones: <span>${\n count.timezones.length\n } : </span></strong>\n ${count.timezones.map(\n (timezone) => ` <span>${timezone}</span>`\n )}\n \n </li>\n <li class=\"list-group-item\"><strong>Currencies:</strong>\n ${count.currencies.map(\n (currency) => ` <span>${currency.name}</span>`\n )}\n \n </li>\n </ul>\n </div>\n </div>\n </div>\n </div>\n \n `\n result.innerHTML = ''\n let doc = new DOMParser().parseFromString(output, 'text/html')\n result.appendChild(doc.body)\n })\n\n .catch((err) => err)\n}", "async getCountries() {\n try {\n const response = await fetch(this.apiUrl);\n const body = await response.json();\n const countries = body.map(country => ({\n code: country.alpha2Code.toLowerCase(),\n name: country.name,\n nativeName: country.nativeName,\n }));\n return countries;\n } catch (e) {\n throw new ErrorWrapped(this.errorMessage, e);\n }\n }", "function getResults(e) {\n e.preventDefault();\n url = baseURL + 'countries' + '?&api_key=' + key;\n console.log('URL', url);\n\n fetch(url)\n .then(res => res.json())\n .then(json => getCountry(json));\n\n}", "getPopulationByContinent() {\n\n\t}", "async function getAllTopCountries(request, h) {\n try {\n // Buscar todos los objetos\n const topCountries = await TopCountries.find();\n return h.response(topCountries).code(200);\n } catch (error) {\n return h.response(error).code(500);\n }\n}", "static renderTopCountriesChart(ids) {\n\t\tGen.query({\n\t\t\t'ids': ids,\n\t\t\t'dimensions': 'ga:country',\n\t\t\t'metrics': 'ga:sessions',\n\t\t\t'sort': '-ga:sessions',\n\t\t\t'max-results': 5\n\t\t})\n\t\t\t.then(function (response) {\n\n\t\t\t\tvar data = [];\n\t\t\t\tvar colors = ['#4D5360', '#949FB1', '#D4CCC5', '#E2EAE9', '#F7464A'];\n\n\t\t\t\tif(response.rows){\n\n\t\t\t\t\tresponse.rows.forEach(function (row, i) {\n\t\t\t\t\t\tdata.push({\n\t\t\t\t\t\t\tlabel: row[0],\n\t\t\t\t\t\t\tvalue: +row[1],\n\t\t\t\t\t\t\tcolor: colors[i]\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\n\t\t\t\t\tnew Chart(Gen.makeCanvas('chart-4-container')).Doughnut(data);\n\t\t\t\t\tGen.generateLegend('legend-4-container', data);\n\t\t\t\t}\n\t\t\t});\n\t}", "function getDataWithTopCountryNames(data, date) {\n var countries = {}\n var newArraySeries = [];\n data.forEach(\n function (e) {\n if (!countries[e[\"Country/Region\"]]) {\n countries[e[\"Country/Region\"]] = 0\n }\n countries[e[\"Country/Region\"]] += +e[date]\n }\n )\n for (var country in countries) {\n newArraySeries.push({country: country, data: countries[country]})\n }\n\n const sorted = newArraySeries.sort(function (a, b) {\n return b[\"data\"] - a[\"data\"];\n });\n\n\n const limitOf12 = newArraySeries[12][\"data\"];\n console.log(limitOf12)\n var result = []\n data.forEach(function (d, i) {\n var country;\n if (countries[d[\"Country/Region\"]] < limitOf12) {\n country = \"others\"\n } else {\n country = d[\"Country/Region\"]\n }\n let oneRow = d;\n oneRow[\"city\"] = d[\"Province/State\"];\n oneRow[\"country\"] = country;\n oneRow[\"population\"] = d[date];\n oneRow[\"latitude\"] = d.Lat;\n oneRow[\"longitude\"] = d.Long;\n\n result.push(oneRow)\n\n })\n\n return result\n }", "getCountry(req, res, next) {\n UsersService.prototype.getCountry().then(country => {\n res.status(200).send(country);\n }).catch((error) => next(error));\n }", "function apiCountryCall(currentCountry) {\n let num = 0;\n if (currentCountry.length == 14) {\n num = 13;\n }\n wiki().page(currentCountry[num]).then(page => page.summary()).then(response => {\n console.log(response)\n const country = new Country({\n countryName: currentCountry[0],\n capitalCity: currentCountry[1],\n population: currentCountry[2],\n urbanRent: currentCountry[3],\n urbanPE: currentCountry[4],\n ruralRent: currentCountry[5],\n ruralPE: currentCountry[6],\n interestRate: currentCountry[7],\n debtGDP: currentCountry[8],\n inflation: currentCountry[9],\n bondSymbol: currentCountry[10],\n urbanSymbol: currentCountry[11],\n ruralSymbol: currentCountry[12],\n countrySummary: response\n });\n\n Country.count({countryName: currentCountry[0]}, function (err, count) {\n if (count > 0){\n Country.findOneAndUpdate(\n {countryName: currentCountry[0]},\n {$set:{\n countryName: country['countryName'],\n capitalCity: country['capitalCity'],\n population: country['population'],\n urbanRent: country['urbanRent'],\n urbanPE: country['urbanPE'],\n ruralRent: country['ruralRent'],\n ruralPE: country['ruralPE'],\n interestRate: country['interestRate'],\n debtGDP: country['debtGDP'],\n inflation: country['inflation'],\n bondSymbol: country['bondSymbol'],\n urbanSymbol: country['urbanSymbol'],\n ruralSymbol: country['ruralSymbol'],\n countrySummary: country['countrySummary']\n }},{upsert:false},\n function (error, success) {\n if(error) {\n console.log(error);\n } else {\n console.log(currentCountry[0]);\n }\n }\n );\n } else {\n country.save();\n }\n })})\n }", "async function getCountryAW(name) {\n try {\n const result = await fetch(`https://restcountries.eu/rest/v2/name/${name}`);\n const data = await result.json();\n console.log(data);\n console.log(`Welcome to ${data[0].name}! This is one of the most popular countries in ${data[0].subregion}!`);\n return data;\n } catch(err) {\n console.log(err);\n alert(err);\n };\n}", "function searchFromFilter() {\r\n GetAjaxData(\"https://restcountries.eu/rest/v2/all?fields=name;topLevelDomain;capital;currencies;flag\", response => filterArrayOfCountries(response) , err => console.log(err))\r\n}", "async function CountrySearch(country_search, region) {\n let el = $('#countrieslist');\n el.html('');\n let apiURL = 'https://restcountries.eu/rest/v2/all';\n\n if(country_search == '') { // Show all countries\n apiURL = 'https://restcountries.eu/rest/v2/all';\n } else if(country_search != null && region == null) { // Show specific country - Search area\n apiURL = 'https://restcountries.eu/rest/v2/name/'+country_search+'';\n } else if (region != null) { // Show countries based on the region - Dropdown value\n apiURL = 'https://restcountries.eu/rest/v2/region/'+region+'';\n }\n\n // Function bellow prints all the cards\n const apiGet = await getByApi(apiURL);\n apiGet.forEach(function(country){ \n const elAppend = `\n <a id=\"click\" class=\"a\" onclick=\"countryInfo('${country.alpha2Code}')\" href=\"#\">\n <div id=\"card\" class=\"card\" style=\"width: 18rem;\">\n <img class=\"card-img-top\" src=\"${country.flag}\"alt=\"Card image cap\">\n <div class=\"card-body\"><h5 id=\"countryName\" class=\"card-text\">${country.name}</h5> \n <div id=\"card-description\" class=\"card-description\">\n <p class=\"info\"><span class=\"card-text\">Population: </span>${country.population.toLocaleString('en-US') }\n </p><p class=\"info\"><span class=\"card-text\">Region: </span>${country.region }\n </p><p class=\"info\"><span class=\"card-text\">Capital: </span>${country.capital }\n </p></div></div></a>` \n el.append(elAppend);\n }) \n}", "async function summaryByCountry() {\n let list = {};\n const url = 'https://api.covid19api.com/summary';\n const getSumInfoByCountry = async () => {\n try {\n const response = await axios({\n method: 'get',\n headers: {\n 'X-Access-Token': '5cf9dfd5-3449-485e-b5ae-70a60e997864'\n },\n url: `${url}`,\n });\n list = (response.data);\n } catch (e) {\n console.log(e);\n }\n };\n await getSumInfoByCountry();\n return list;\n}", "function getCountries(name) {\n\t\t\tvar request = {\n\t\t\t\tusername: 'markhamilton90',\n\t\t\t\tcallback: 'JSON_CALLBACK',\n\t\t\t\tcountry: name || ''\n\t\t\t}\n\t\t\treturn $http({\n\t\t\t\tcache: true,\n\t\t\t\tmethod: 'JSONP',\n\t\t\t\turl: 'http://api.geonames.org/countryInfoJSON?',\n\t\t\t\tparams: request\n\t\t\t})\n\t\t\t.then(function(response) {\n\t\t\t\t//console.log(response.data);\n\t\t\t\treturn response.data;\n\t\t\t},\n\t\t\tfunction() {\n\t\t\t\tconsole.log('Failure...');\n\t\t\t});\n\t\t}", "function renderTopCountriesChart(ids) {\n\t query({\n\t 'ids': ids,\n\t 'dimensions': 'ga:country',\n\t 'metrics': 'ga:sessions',\n\t 'sort': '-ga:sessions',\n\t 'max-results': 5\n\t })\n\t .then(function(response) {\n\n\t var data = [];\n\t var colors = ['#4D5360','#949FB1','#D4CCC5','#E2EAE9','#F7464A'];\n\n\t response.rows.forEach(function(row, i) {\n\t data.push({\n\t label: row[0],\n\t value: +row[1],\n\t color: colors[i]\n\t });\n\t });\n\n\t new Chart(makeCanvas('chart-4-container')).Doughnut(data);\n\t generateLegend('legend-4-container', data);\n\t });\n\t }", "function getCountryDetails($, fundTicker)\n{\n\tlet countryArr = []; \n\tlet getGeoId = $('#fund-geographical-breakdown').val();\n\t\n\tif(getGeoId!==undefined)\n\t{\n\t\tlet json = JSON.parse(getGeoId);\n\t\tlet jsonVals = json.attrArray;\n\t\tfor(let i=0; i<jsonVals.length; i++)\n\t\t{\n\t\t\tlet countries = [];\n\t\t\tlet countryname = jsonVals[i].name.value;\n\t\t\tlet countryweight = jsonVals[i].weight.value.split('%');\n\t\t\tlet geoKey = fundTicker+\",\"+countryname;\n\t\t\tlet date = new Date();\n\t\t\tcountries.push(geoKey);\n\t\t\tcountries.push(fundTicker);\n\t\t\tcountries.push(countryname);\n\t\t\tcountries.push(countryweight[0]);\n\t\t\tcountries.push(date);\n\t\t\tcountryArr.push(countries);\n\t\t}\n\n\t\tcountryArr.sort((a,b) => b[2] - a[2]);\n\t\tlet top10Countries = countryArr.slice(0,10);\n\t\n\t\treturn top10Countries;\n\t}\n}", "function findCountry(country) {\r\n if (country.name == \"India\") {\r\n return country;\r\n }\r\n }", "async function searchForCountry(){\n let response = await fetch(`https://restcountries.com/v3.1/name/${searchBar.value}`);\n \n\n let filtered = await response.json();\n \n let i = null;\n filteredNations = [];\n \n for(i=0;i<filtered.length;i++){ \n let {name,capital,region,population,flags} = filtered[i];\n \n let country = {\n \n name: name.common,\n capital: capital,\n region: region,\n population: population,\n flag: flags.svg\n }\n \n filteredNations.push(country);\n }\n\n showCountries(filteredNations);\n console.log(filteredNations);\n console.log(filterCountries.value);\n}", "CountryList() {\n this.service.getCountryMobileCode().subscribe(res => {\n if (res['status'] == '1') {\n console.log(\"api response\", res);\n this.country_Obj = res['data'];\n }\n });\n }", "function ordersByCountryDetails(responseData) {\n var aggregateData = _(responseData[3].orders).groupBy('Countries.ID').map(function(item, itemId) {\n var obj = [];\n var countryName = _(responseData[0].countries).filter({ID: parseInt(itemId)}).value()[0].Title;\n _.forEach(item, function(element) {\n element['Countries'] = _(responseData[0].countries).filter({ID: parseInt(itemId)}).value();\n element['Tomato'] = _(responseData[1].tomatoes).filter({ID: parseInt(element.Tomato.ID)}).value();\n element['Status'] = _(responseData[2].statuses).filter({ID: parseInt(element.Status.ID)}).value();\n });\n obj.push(countryName, item);\n return obj;\n }).fromPairs().value();\n return aggregateData;\n }", "async function filterByRegion(){\n \n \n let response = await fetch(`https://restcountries.com/v3.1/region/${filterCountries.value}`);\n \n\n let filtered = await response.json();\n \n let i = null;\n filteredNations = [];\n\n for(i=0;i<filtered.length;i++){ \n let {name,capital,region,population,flags} = filtered[i];\n \n let country = {\n \n name: name.common,\n capital: capital,\n region: region,\n population: population,\n flag: flags.svg\n }\n\n filteredNations.push(country);\n }\n showCountries(filteredNations);\n console.log(filteredNations);\n console.log(filterCountries.value);\n}", "async function getCountries (req, res) {\n try {\n\n const [ countries ] = await database.pool.query('SELECT * FROM countries ORDER BY country ASC');\n res.send(countries);\n\n }catch (err) {\n\n res.status(500);\n res.send({ error: err.message})\n }\n}", "function queryCovid19dataset(tableName, country) {\n if (!['confirmed_cases', 'deaths', 'recovered_cases'].includes(tableName)) {\n return Promise.reject(new Error('Invalid table name ' + tableName));\n }\n // We convert some of the countries names to match those in the dataset.\n // Those countries are recognized by DialogFlow NLU but have different\n // naming conventions that are specific to the tables inside\n // bigquery-public-data.covid19_jhu_csse dataset.\n const countryNameCorrection = {\n 'United States of America': 'US',\n 'United States': 'US',\n 'Cape Verde': 'Cabo Verde',\n 'Democratic Republic of the Congo': 'Congo (Kinshasa)',\n 'Republic of the Congo': 'Congo (Brazzaville)',\n 'Côte d\\'Ivoire': 'Cote d\\'Ivoire',\n 'Vatikan': 'Holy See',\n 'South Korea': 'Korea, South',\n 'Taiwan': 'Taiwan*',\n };\n if (Object.keys(countryNameCorrection).includes(country)) {\n country = countryNameCorrection[country];\n }\n var totalQuery = `SELECT *\n FROM bigquery-public-data.covid19_jhu_csse.` +\n tableName + `\n `;\n // If the country is specified, we will limit results to that country.\n if (country) {\n totalQuery += `\n WHERE country_region = @country\n `;\n }\n\n // Run the query.\n const bigqueryClient = new BigQuery();\n return bigqueryClient\n .query({\n query: totalQuery,\n // Include parameters that we specified in the query (@country).\n params: {country},\n location: 'US',\n timeout: 5000 // milliseconds\n })\n .then(resp => {\n const [rows] = resp;\n if (!rows || !rows.length) {\n return null;\n }\n // Sum all the values in the last column - the one with the latest data.\n return rows.map(r => r[Object.keys(r)[Object.keys(r).length - 1]])\n .reduce((a, b) => a + b, 0);\n });\n}", "function showCountryDetail(){\n var country = document.querySelectorAll(\".countries > div > div\");\n country.forEach(function(c){\n c.addEventListener(\"click\", function(){\n toggleDisplay(filterForm, \"none\"); // SET DISPLAY TO NONE\n toggleDisplay(country, \"none\"); // SET DISPLAY TO NONE;\n var keyString = \"name/\" + this.querySelector(\"h1\").getAttribute(\"data-name\") + \"?fullText=true\";\n var borderString = \"\";\n getXmlData(keyString, function(data){\n HTMLCountryDetails(data);\n });\n });\n });\n}", "function get_country_profile_data(country_name)\n{\n data = get_country_data(world_2011_data, country_name);\n ret_data = {};\n\n emissions_productivity = data.gdp /(data.total_emissions);//Multiply by 1000 to convert from kT to T\n\n hierarchical_data = [\n {name: \"gdp_per_capita\", text: \"GDP Per Capita\", unit: \"US$/Capita\", value: data.gdp_per_capita, maximum : 101000},\n {name: \"co2_per_capita\", text: \"CO2 Per Capita\", unit: \"Tons/Capita\", value: data.co2_per_capita, maximum : 44},\n {name: \"emissions_productivity\", text: \"Emissions Productivity\", unit: \"US$/T of CO2\", value: emissions_productivity, maximum : 8000000},\n {name: \"total_emissions\", text: \"Total Emissions\", unit: \"kT of CO2 Eq.\", value: data.total_emissions, maximum : 12064260},\n\n ]\n\n return hierarchical_data;\n}", "function fetchCountries(){\n console.log('IMonData: [Countries] Fetching data..');\n var store = new Store();\n var futures = [];\n var baseUrl = 'https://thenetmonitor.org/v2/countries';\n\n var fut = HTTP.get.future()(baseUrl, { timeout: Settings.timeout*3 });\n futures.push(fut);\n var results = fut.wait();\n store.sync(results.data);\n _.each(results.data.data, function(d){\n store.sync(d.relationships.data_points);\n });\n\n console.log('IMonData: [Countries] Data fetched.');\n Future.wait(futures);\n\n var insert = function(){\n console.log('IMonData: [Countries] Inserting...');\n _.each(store.findAll('countries'), insertCountryData);\n console.log('IMonData: [Countries] Inserted.');\n };\n\n Future.task(insert);\n\n}", "function search(data, countryFromList) {\n let obj = data.find((o) => o.Country === countryFromList);\n printResults(obj);\n}", "function _getAllCountries(req, res, next) {\n\tvar query = {};\n\tCOUNTRIES_COLLECTION.find(query, function (countrieserror, countries) {\n\t\tif (countrieserror || !countries) {\n\t\t\tjson.status = '0';\n\t\t\tjson.result = { 'message': 'Countries not found!' };\n\t\t\tres.send(json);\n\t\t} else {\n\t\t\tjson.status = '1';\n\t\t\tjson.result = { 'message': 'countries found successfully.', 'countries': countries };\n\t\t\tres.send(json);\n\t\t}\n\t});\n}", "function viewCountry() {\n\tvar id = this.id;\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onload = loadCountry;\n\txhttp.open(\"GET\", \"countries/\" + id + \".xml\", true);\n\txhttp.send();\n\t}", "function searching(){\r\n const REST_URL = \"https://restcountries.eu/rest/v2/name/\";\r\n\r\n let url = REST_URL;\r\n\r\n let country = document.querySelector(\"#searchterm\").value;\r\n countryShown = country;\r\n\r\n country = country.trim();\r\n\r\n country = encodeURIComponent(country);\r\n\r\n if(country.length < 1)return;\r\n\r\n url += country;\r\n\r\n document.querySelector(\"#status\").innerHTML = \"<b>Searching for '\" + countryShown + \"'</b>\";\r\n getData(url);\r\n}", "async function query(city, country) {\n let query = `?country=${country}&city=${city}`;\n let res = await axios.get(`${BASE_API}${query}`);\n return res.data;\n}", "function filterResult(region) {\n const result = []\n if (region == \"All\") {\n renderResult(data)\n\n }\n else {\n for (let country of data) {\n if (country['region'] == region) {\n result.push(country)\n }\n }\n renderResult(result)\n }\n\n}", "function countryDetails(country, countries15) {\n\n main.innerHTML = '';\n main.append(...Countries([country])) ;\n \n\n if(main.childElementCount == 1) {\n main.classList.add('isolated');\n }\n\n main.firstElementChild.id = 'focused';\n \n let allLanguages = '';\n country.languages.forEach(language => {\n\n if(allLanguages == '') {\n allLanguages += language.name;\n }else {\n allLanguages += ', ' + language.name;\n }\n });\n\n let allTimezones = '';\n country.timezones.forEach(timezone => {\n\n if(allTimezones == '') {\n allTimezones += timezone;\n }else {\n allTimezones += ', ' + timezone;\n }\n });\n\n main.firstElementChild.lastElementChild.innerHTML += `<br> All lngs: ${allLanguages} <br> Timezone(s): ${allTimezones} <br> Population: ${country.population}`; \n \n headerUI(country.name, countries15);\n}", "function getCountryData() {\n let selectedCountry = this.value;\n let url = 'https://covid-api.mmediagroup.fr/v1/cases?country=' + selectedCountry;\n fetch(url, {\n method: 'GET',\n mode: 'cors',\n headers: {\n Accept: 'application/json',\n }\n }).then(function(response) {\n return response.json();\n }).then(function(data) {\n console.log(data);\n var countryCases = data.All.confirmed;\n var countryDeaths = data.All.deaths;\n var countryRecovered;\n var countryActives;\n if(data.All.recovered > 0) {\n countryRecovered = data.All.recovered;\n countryActives = ((countryCases - countryRecovered) - countryDeaths);\n countryRecovered = countryRecovered.toLocaleString();\n countryActives = countryActives.toLocaleString();\n } else {\n countryRecovered = 'No Data';\n countryActives = 'No Data';\n }\n \n\n countryCasesText.textContent = countryCases.toLocaleString();\n countryDeathsText.textContent = countryDeaths.toLocaleString();\n countryActivesText.textContent = countryActives;\n countryRecoveriesText.textContent = countryRecovered;\n\n countryName.textContent = selectedCountry;\n countryContainer.classList.remove('invisible');\n }).catch(function(err) {\n console.log(err)\n });\n}", "function getCountries() {\n weatherService.getCountryList().then(resolver, rejector);\n //if success\n function resolver(response) {\n vm.countries = response.data;\n geteCountryForecast();\n }\n\n //if reject\n function rejector(response) {\n console.log(response);\n }\n }", "function getCountries() {\n var countryCode = $http.post(\n $global.API_URL + 'api/crm/country/');\n return countryCode;\n }", "function getCountries() {\n var countryCode = $http.post(\n $global.API_URL + 'api/crm/country/');\n return countryCode;\n }", "function getCountries() {\n var countryCode = $http.post(\n $global.API_URL + 'api/crm/country/');\n return countryCode;\n }", "function getCountries() {\n var countryCode = $http.post(\n $global.API_URL + 'api/crm/country/');\n return countryCode;\n }", "function loadCountries(){\n RegService.GetCountries()\n .then(function (response) {\n\n vm.countries = response.data;\n\n },function(response){\n });\n }", "async function fetchData() {\n var countryCode = document.getElementById(\"country\").value;\n const indicatorCode = \"SP.POP.TOTL\";\n const baseUrl = \"https://api.worldbank.org/v2/country/\";\n const url =\n baseUrl + countryCode + \"/indicator/\" + indicatorCode + \"?format=json\";\n console.log(\"Fetching data from URL: \" + url);\n // Fetch is a built-in tool for sending HTTP requests\n var response = await fetch(url);\n\n if (response.status == 200) {\n var fetchedData = await response.json();\n console.log(fetchedData);\n\n var data = getValues(fetchedData);\n var labels = getLabels(fetchedData);\n var countryName = getCountryName(fetchedData);\n renderChart(data, labels, countryName);\n }\n}", "function getCountryData(e) {\n let countryId = e.target.id;\n\n if (lastId !== \"\" && lastId !== countryId) {\n if (lastId === \"RU\") {\n lastId = \"ru-main\";\n }\n document.getElementById(lastId).style.fill = \"rgb(192, 192, 192)\";\n }\n\n document.getElementById(countryId).style.fill = \"red\";\n\n if (countryId === \"ru-main\") {\n countryId = \"RU\";\n }\n\n fetch(URL + countryId)\n .then(res => res.json())\n .then(countryArray => {\n let country = countryArray[0];\n document.getElementById(\"countryInfo\").innerHTML = \n `Country: ${country.name}<br>\n Population: ${country.population}<br>\n Area: ${country.area}<br>\n Region: ${country.region}<br>\n Borders: ${country.borders}<br>\n `;\n })\n lastId = countryId;\n}", "function addCountryFilter(country) {\n var uppercase = country.toUpperCase();\n if(uppercase === \"ALL\") {\n activeSheet.applyFilterAsync(\n \"Country / Region\",\n \"\",\n tableau.FilterUpdateType.ALL);\n } else {\n var match = matchVoiceToDataCase(data, columnIndex, country);\n activeSheet.applyFilterAsync(\n \"Country / Region\",\n match,\n tableau.FilterUpdateType.ADD);\n }\n }", "async getSources(category, country, language) {\n let url = '/sources?';\n\n if (!_.isNil(country)) {\n url = `${url}country=${country}&`;\n }\n\n if (!_.isNil(category)) {\n url = `${url}category=${category}&`;\n }\n\n if (!_.isNil(language)) {\n url = `${url}language=${language}&`;\n }\n\n try {\n const result = await NewsApiClient.getInstance().get(url);\n if (!result || !result.sources || result.status.toLowerCase() !== 'ok') {\n Logger.error(`Response from ${url} is invalid`, result);\n return this.getErrorResponse('unexpectedError');\n }\n\n delete result.status;\n return this.getSuccessResponse(result.sources);\n } catch (error) {\n Logger.error(`Response from ${url} is invalid`, error);\n const errorMessage = handleErrorMessage(error);\n return this.getErrorResponse(errorMessage);\n }\n }", "function findCountry(countryName) {\n //checks if the data already are in the sessionStorage\n \n if (sessionStorage.length) {\n data = JSON.parse(sessionStorage.getItem(\"countries\"));\n // calls the function that mounts the card of the country with the object that contains\n // the informations about the country\n assembleCardDetail(\n data.find((current) => {\n return current.name === countryName;\n })\n );\n } else {\n fetch(`https://restcountries.eu/rest/v2/all`)\n .then((response) => response.json())\n .then((jsondata) => {\n // fetch the data, put it in the sessionStorage and in the data variable\n // the data variable exists to be manipulated by the routines of the script\n // sessionStorage is used so you don't have to apply fetch everytime\n data = jsondata\n sessionStorage.setItem(\"countries\",JSON.stringify(jsondata))\n let country = jsondata.find((current)=> current.name === countryName)\n assembleCardDetail(country);\n });\n }\n}", "function getUniqueNationalities()\n{\n\t$.get(publicPort + 'GetUniqueNationalities',function(data,status){\n\t\tvar countryBox = document.getElementById('countryCmbBox');\n\n\t\tfor(var i=0; i<data.length; i++)\n\t\t{\n\t\t\tvar option = document.createElement(\"option\");\n \t\t\toption.text = data[i];\n \t\t\tcountryBox.add(option);\n\t\t}\n\t\tgetNationalityAverages();\n\t});\n\n\n}" ]
[ "0.71858144", "0.6749322", "0.6736854", "0.67075634", "0.6704463", "0.6632638", "0.6436481", "0.631527", "0.62870216", "0.6184942", "0.6183807", "0.6175802", "0.61719215", "0.616218", "0.6148462", "0.61320513", "0.6096406", "0.60891145", "0.6066463", "0.60660785", "0.6059716", "0.6054981", "0.60479873", "0.60347134", "0.6033128", "0.60320723", "0.6017682", "0.6014732", "0.600921", "0.6005148", "0.5947136", "0.5940916", "0.5931948", "0.59292746", "0.5926385", "0.5918135", "0.59169096", "0.5907528", "0.5904214", "0.589323", "0.5877147", "0.58699405", "0.58657736", "0.5839629", "0.58137375", "0.5798099", "0.5797614", "0.57974946", "0.57922035", "0.5791756", "0.57907885", "0.5773921", "0.5767247", "0.57557917", "0.57372123", "0.5731589", "0.57262284", "0.57230884", "0.5710025", "0.5705769", "0.5693393", "0.5690236", "0.56856596", "0.5682341", "0.5667228", "0.5666543", "0.5665796", "0.5664206", "0.56635016", "0.56624347", "0.5642512", "0.5641808", "0.56285083", "0.56269395", "0.5625928", "0.5611731", "0.56111157", "0.5602808", "0.56000286", "0.5596363", "0.55916995", "0.5587975", "0.5578054", "0.5576238", "0.55704254", "0.5570047", "0.55520016", "0.55508375", "0.55469173", "0.55441415", "0.5534784", "0.5534784", "0.5534784", "0.5534784", "0.5533567", "0.5532268", "0.55272776", "0.5513738", "0.55075777", "0.55062693", "0.54942733" ]
0.0
-1
Get the data ready to visualize
function prepData(local, region) { countyData = setupNumbers(_.clone(local[0], true)); regionData = setupNumbers(_.clone(region[0], true)); yearNames = []; var years = _.pluck(regionData, YEAR_KEY); var maxYear = _.max(years); var minYear = _.min(years); yearNames = _.uniq(years); // Once we have the data, set up the visualizations setup(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getTheData() {\n if(expensesR) {\n\tmod3L.remove();\n\tmod3R.remove();\n }\n // get the data\n expensesP = d3.select('#expensesP')\n .property('value');\n expensesR = d3.select('#expensesR')\n .property('value');\n // use the function to show the painting\n show(parseInt(expensesP),parseInt(expensesR));\n}", "function getTheData() {\n if(totalSale) {\n\tmod1.remove();\n }\n //get the data\n totalSale = d3.select(\"#totalRealSales\")\n .property(\"value\");\n totalTarget = d3.select(\"#totalTargetSales\")\n .property(\"value\");\n //use the function to show the painting\n show(parseInt(totalSale),parseInt(totalTarget));\n}", "function get_data() {\n $.getJSON(\"data\", function (data) {\n console.log(\"data obtained!\");\n // reset the plot_data object\n var plot_data = {};\n $.each(data, function (k, v) {\n plot_data[k] = v;\n })\n // plot the data\n Plotly.react(plotDiv, [plot_data], {margin: {t: 0}})\n })\n}", "function getdata() {\n\n var url = `/data`;\n\n d3.json(url).then(function(xx) {\n\n data = []\n // xx.slice(s, e)\n globaldata = xx;\n unfiltered = xx;\n actual = [], minute = []\n \n makedata();\n})\n}", "async function makeVisualization(){\n {\n console.log(\"loading local data\");\n data = await getData('dataSelection.json');\n }\n console.log({ data });\n \n setupScales();\n setupAxes(group);\n drawBars(group);\n setupInput();\n }", "function getData() {\n\n\t\td3.select(\"#loading\").html(\"Carregando a nuvem de termos...\");\n\n\t\td3.json(\"/cloud/\", function(error, json) {\n\n\n\n\t\t\td3.select(\"#loading\").html(\"\");\n\n\t\t\tif (error) {\n\t\t\t\treturn console.warn(error);\n\t\t\t}\n\n\n\t\t\tfor (key in json){\n\t\t\t\twords_array.push({text: key, size: json[key]})\n\t\t\t}\n\n\t\t\tcalculateCloud(words_array);\n\t\t});\n\t}", "function getData() {\n d3.json(\"samples.json\").then(data => {\n\n // retrieve data\n let samples = data.samples.map(samples => { return samples })\n let metaData = data.metadata.map(metadata => { return metadata })\n\n // filter data\n let filteredData = samples.filter(idFilter)\n let filteredMetaData = metaData.filter(idFilter)\n\n // update charts and demo info panel\n updateCharts(filteredData, filteredMetaData[0].wfreq)\n updateDemoInfo(filteredMetaData[0])\n })\n}", "function getData(){\n Plotly.d3.json('/country/scores', function (error, happydatabar) { //happydatabar is the main array string for all our array data from country/scores route\n if (error) return console.warn(error);\n buildbarcharts(happydatabar); // call buildbardcharts function where the bar charts will be plotted\n }); \n }", "function displayDataPrep(){\n var arrDatasets=[],color = Please.make_color({colors_returned: Object.size(getY)}),i=0;\n for (var key in getY){\n console.log(key);\n dsData={label: key,\n fillColor : \"rgba(220,220,220,0)\",\n strokeColor : color[i],\n pointColor : color[i],\n pointStrokeColor : \"#fff\",\n pointHighlightFill : \"#fff\",\n pointHighlightStroke : color[i],\n data:getY[key]\n };\n arrDatasets.push(dsData);\n i++;\n }\n return {labels : xDisplay, datasets: arrDatasets};\n}", "function getData()\n{\n\treturn [{\n\n\t type: 'scatter3d',\n\n\t // Set the X, Y and Z values to the selected columns\n\t x: colSelectionX,\n\t y: colSelectionY,\n\t z: colSelectionZ,\n\t text: textSelection,\n\n\t mode: 'markers',\n\t\tmarker: getMarker(markerSize, colours),\n\t}];\n}", "function getData() {\n var url = baseUrl + '.dods?';\n var selected = $('#variables :checkbox').filter(':checked');\n selected.each(function(i) {\n if (this.id == 'location.time_series.time') timeIndex = i;\n url += this.id + ',';\n });\n if (selected.length <= 1) return;\n\n // Get buoy id.\n for (var i=0; i<buoys.markers.length; i++) {\n var marker = buoys.markers[i];\n if (marker.icon.imageDiv.firstChild.getAttribute('src') == 'js/OpenLayers/img/marker.png') {\n var id = marker.metadata.id;\n break;\n }\n }\n\n url = url.replace(/,$/, '');\n //url += '&location.time>1.1e12'; // get only a couple of points for this demo.\n url += '&location._id=' + id;\n\n jsdap.loadData(url, plotData, '/proxy/');\n}", "function initData(){\n container.prepend(progressInfo);\n jQuery.get(getPageURL(0, resource)).done(function(data) {\n records = processData(data, true);\n initView(new recline.Model.Dataset({records:records}));\n numReq = getRequestNumber(data.result.total, pageSize);\n for (var i = 1; i <= numReq; i++) {\n requestData(getPageURL(i, resource));\n };\n });\n }", "function drawData() {\n\t var calcdata = gd.calcdata,\n\t i;\n\t\n\t // in case of traces that were heatmaps or contour maps\n\t // previously, remove them and their colorbars explicitly\n\t for(i = 0; i < calcdata.length; i++) {\n\t var trace = calcdata[i][0].trace,\n\t isVisible = (trace.visible === true),\n\t uid = trace.uid;\n\t\n\t if(!isVisible || !Plots.traceIs(trace, '2dMap')) {\n\t fullLayout._paper.selectAll(\n\t '.hm' + uid +\n\t ',.contour' + uid +\n\t ',#clip' + uid\n\t ).remove();\n\t }\n\t\n\t if(!isVisible || !trace._module.colorbar) {\n\t fullLayout._infolayer.selectAll('.cb' + uid).remove();\n\t }\n\t }\n\t\n\t // loop over the base plot modules present on graph\n\t var basePlotModules = fullLayout._basePlotModules;\n\t for(i = 0; i < basePlotModules.length; i++) {\n\t basePlotModules[i].plot(gd);\n\t }\n\t\n\t // styling separate from drawing\n\t Plots.style(gd);\n\t\n\t // show annotations and shapes\n\t Shapes.drawAll(gd);\n\t Plotly.Annotations.drawAll(gd);\n\t\n\t // source links\n\t Plots.addLinks(gd);\n\t\n\t // Mark the first render as complete\n\t gd._replotting = false;\n\t\n\t return Plots.previousPromises(gd);\n\t }", "function readData() {\n d3.json(url).then(function (data) {\n samples_data = data;\n initializeIDPulldown();\n buildBarChart(0);\n buildBubbleChart(0);\n buildDemographics(0);\n buildGaugeChart(0);\n // log out the entire dataset\n console.log(samples_data);\n })\n}", "function drawData() {\n\t var calcdata = gd.calcdata,\n\t i;\n\t\n\t // in case of traces that were heatmaps or contour maps\n\t // previously, remove them and their colorbars explicitly\n\t for(i = 0; i < calcdata.length; i++) {\n\t var trace = calcdata[i][0].trace,\n\t isVisible = (trace.visible === true),\n\t uid = trace.uid;\n\t\n\t if(!isVisible || !Registry.traceIs(trace, '2dMap')) {\n\t var query = (\n\t '.hm' + uid +\n\t ',.contour' + uid +\n\t ',#clip' + uid\n\t );\n\t\n\t fullLayout._paper\n\t .selectAll(query)\n\t .remove();\n\t\n\t fullLayout._infolayer.selectAll('g.rangeslider-container')\n\t .selectAll(query)\n\t .remove();\n\t }\n\t\n\t if(!isVisible || !trace._module.colorbar) {\n\t fullLayout._infolayer.selectAll('.cb' + uid).remove();\n\t }\n\t }\n\t\n\t // loop over the base plot modules present on graph\n\t var basePlotModules = fullLayout._basePlotModules;\n\t for(i = 0; i < basePlotModules.length; i++) {\n\t basePlotModules[i].plot(gd);\n\t }\n\t\n\t // keep reference to shape layers in subplots\n\t var layerSubplot = fullLayout._paper.selectAll('.layer-subplot');\n\t fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer');\n\t\n\t // styling separate from drawing\n\t Plots.style(gd);\n\t\n\t // show annotations and shapes\n\t Registry.getComponentMethod('shapes', 'draw')(gd);\n\t Registry.getComponentMethod('annotations', 'draw')(gd);\n\t\n\t // source links\n\t Plots.addLinks(gd);\n\t\n\t // Mark the first render as complete\n\t fullLayout._replotting = false;\n\t\n\t return Plots.previousPromises(gd);\n\t }", "function getData(){\n\t\t//load the data\n\t\t$.getJSON(\"data/canada-strikes.geojson\", function(response){\n\t\t\t\t//call relevant functions\n\t\t\t\tprocessData(response);\n\t\t\t\tcreatePropSymbols(response, map, attributes);\n\t\t\t\tcreateSequenceControls();\n\t\t});\n}", "function drawData() {\n var calcdata = gd.calcdata,\n i,\n rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container');\n\n // in case of traces that were heatmaps or contour maps\n // previously, remove them and their colorbars explicitly\n for(i = 0; i < calcdata.length; i++) {\n var trace = calcdata[i][0].trace,\n isVisible = (trace.visible === true),\n uid = trace.uid;\n\n if(!isVisible || !Registry.traceIs(trace, '2dMap')) {\n var query = (\n '.hm' + uid +\n ',.contour' + uid +\n ',#clip' + uid\n );\n\n fullLayout._paper\n .selectAll(query)\n .remove();\n\n rangesliderContainers\n .selectAll(query)\n .remove();\n }\n\n if(!isVisible || !trace._module.colorbar) {\n fullLayout._infolayer.selectAll('.cb' + uid).remove();\n }\n }\n\n // loop over the base plot modules present on graph\n var basePlotModules = fullLayout._basePlotModules;\n for(i = 0; i < basePlotModules.length; i++) {\n basePlotModules[i].plot(gd);\n }\n\n // keep reference to shape layers in subplots\n var layerSubplot = fullLayout._paper.selectAll('.layer-subplot');\n fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer');\n\n // styling separate from drawing\n Plots.style(gd);\n\n // show annotations and shapes\n Registry.getComponentMethod('shapes', 'draw')(gd);\n Registry.getComponentMethod('annotations', 'draw')(gd);\n\n // source links\n Plots.addLinks(gd);\n\n // Mark the first render as complete\n fullLayout._replotting = false;\n\n return Plots.previousPromises(gd);\n }", "function drawData() {\n var calcdata = gd.calcdata,\n i,\n rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container');\n\n // in case of traces that were heatmaps or contour maps\n // previously, remove them and their colorbars explicitly\n for(i = 0; i < calcdata.length; i++) {\n var trace = calcdata[i][0].trace,\n isVisible = (trace.visible === true),\n uid = trace.uid;\n\n if(!isVisible || !Registry.traceIs(trace, '2dMap')) {\n var query = (\n '.hm' + uid +\n ',.contour' + uid +\n ',#clip' + uid\n );\n\n fullLayout._paper\n .selectAll(query)\n .remove();\n\n rangesliderContainers\n .selectAll(query)\n .remove();\n }\n\n if(!isVisible || !trace._module.colorbar) {\n fullLayout._infolayer.selectAll('.cb' + uid).remove();\n }\n }\n\n // loop over the base plot modules present on graph\n var basePlotModules = fullLayout._basePlotModules;\n for(i = 0; i < basePlotModules.length; i++) {\n basePlotModules[i].plot(gd);\n }\n\n // keep reference to shape layers in subplots\n var layerSubplot = fullLayout._paper.selectAll('.layer-subplot');\n fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer');\n\n // styling separate from drawing\n Plots.style(gd);\n\n // show annotations and shapes\n Registry.getComponentMethod('shapes', 'draw')(gd);\n Registry.getComponentMethod('annotations', 'draw')(gd);\n\n // source links\n Plots.addLinks(gd);\n\n // Mark the first render as complete\n fullLayout._replotting = false;\n\n return Plots.previousPromises(gd);\n }", "async function getData() {\n //load the all scores\n let questionScores = await d3.csv(\"/javascripts/data/questionScores.csv\");\n \n //load the question framework\n let framework = await d3.csv(\"/javascripts/data/framework.csv\");\n\n //load the scoring metric\n let scoringMetric = await d3.csv(\"/javascripts/data/scoringMetric.csv\");\n\n //load the indicator scores\n // let indicatorScores = await d3.csv(\"/javascripts/data/indicatorScores.csv\");\n\n //get country names\n let countryData = await d3.csv(\"/javascripts/data/countryData.csv\");\n\n //get ee scores\n let eeScores = await d3.csv(\"/javascripts/data/eeScores.csv\");\n \n //draw the charts using all the data\n return draw(questionScores, framework, scoringMetric, countryData, eeScores)// something using both resultA and resultB\n}", "function get_data() {}", "get Charting() {}", "function myPlottingData(){\n\tthis['ResQTL'] = \"\", \n\tthis['ResRel'] = \"\",\n\tthis['ResRelbetweenC'] = \"\",\n\tthis['ResgMean'] = \"\",\n\tthis['Summary'] = \"\",\n\tthis['RespMean'] = \"\",\n\tthis['ResAccBVE'] = \"\",\n\tthis['confidence'] = false,\n\tthis['legend'] = true\n}", "function getdata() {\n\n var url = `/sunburst`;\n d3.json(url).then(function(sunnyb) {\n\n ids = sunnyb.ids\n lbl = sunnyb.labels\n par = sunnyb.parents\n val = (sunnyb.values).map(Number)\n weat = sunnyb.weather\n\n draw();\n})\n}", "function getData(){\r\n\r\n// Loading and mapping data\r\nd3.json(\"cellphones.json\", function(error, data) {\r\n\r\n // If error, show in console\r\n if (error) return console.warn(error);\r\n\r\n // Create global variable for the dataset\r\n makeMap(data);\r\n\r\n})}", "function gotData(data) {\n // console.log(data);\n subData_ = data;\n timeline.unshift(new sR(subData_));\n island = [];\n //remap values for subredditSubscribers to 2, 1500\n //it will draw a minimum of 2 voronoi cells and a max of 1500 v. cells\n subMapped = map(timeline[0].subredditSubscribers, 1, maxSub, 36, 1500, true);\n //remap subredditSubscribers values to determinate the distance of the v. cell\n //more subredditSubscribers less distance, less subredditSubscribers more distance\n subMappedDist = map(timeline[0].subredditSubscribers, 1, maxSub, 50, 10, true);\n for (var i = 0; i < cellColors.length; i++){\n if (cellColors[i][3] == 'land'){\n island.push(cells[sites[i].voronoiId]);\n }\n }\n if (timeline.length == 1 || timeline[0].subredditSubscribers != timeline[1].subredditSubscribers){\n b = true;\n nameGenerator()\n }\n if (timeline.length > 1){\n b = false;\n }\n if (timeline.length > 2) {\n timeline.pop();\n }\n}", "function getData() {\n\t$.getJSON(\"js/polls.json\", function(data) {\n\t\t//When we have the data, pass it to the `drawMarkers()` function\n\t\tdrawMarkers(data);\n\t});\n}", "function getData() {\n console.log(data)\n }", "function get_data() {\n\t\tnodes = bubble_nodes[selected_type]\n\t\t// filter nodes\n\t\tnodes = nodes.filter(x => x.count > 1)\n\n\t\tvar maxSize = d3v5.max(nodes, d => +d.count)\n\t\tvar minSize = d3v5.min(nodes, d => +d.count)\n\t\t\n\t\t// size bubbles based on area\n\t\tvar radiusScale = d3v5.scaleSqrt()\n\t\t\t.domain([minSize, maxSize])\n\t\t\t.range([10, 50])\n\t\t\n\t\t// format nodes info\n\t\tnodes = nodes.map(d => ({\n\t\t\t...d,\n\t\t\tradius: radiusScale(+d.count),\n\t\t\tsize: +d.count,\n\t\t\tx: Math.random() * -200,\n\t\t\ty: Math.random() * 100\n\t\t}))\n\n\t\t// console.log('bubble nodes', nodes)\n\t\treturn nodes\n\t}", "function data(){\n return values;\n }", "function generateData() {\n for (var i = 0; i < numProducts; i++) {\n labels[i] = productObjectList[i].name;\n clickData[i] = productObjectList[i].clicks;\n percentData[i] = calcPercentage(productObjectList[i]);\n colorData[i] = productObjectList[i].color;\n }\n}", "run() {\n\n let end = this.settings.show + this.settings.offset;\n\n let start = this.settings.offset;\n\n let nextDataSetIndex = end;\n let previousDataSetIndex = start - 1;\n\n let currentEntryEnd = start + this.settings.show;\n\n if (this.data) {\n const filteredData = this\n .data\n .slice(start, end);\n\n //set default has more to true\n this.hasNext = true;\n this.hasPrevious = true;\n\n //if start is less than 0 set it to 0\n if (start < 0) {\n start = 0;\n }\n\n if (end < 2) {\n end = 1;\n }\n\n //tell if we have more data\n if (!this.data[nextDataSetIndex]) {\n this.hasNext = false;\n }\n\n //tell if we have previous data\n if (!this.data[previousDataSetIndex]) {\n this.hasPrevious = false;\n }\n\n if (currentEntryEnd > this.data.length) {\n currentEntryEnd = this.data.length\n }\n\n this.currentEntry = start + 1;\n this.currentEntryEnd = currentEntryEnd;\n this.dataCount = this.data.length;\n\n this.dataToShow = filteredData\n\n return {data: filteredData}\n } else {\n this.dataToShow = [{}]\n return {data: ''}\n }\n\n }", "function receiveData(data) {\n console.log('data was received succefuly');\n\n\n //formatting the data\n data[0].forEach(function (d) {\n d.datum = parseTime(d.datum);\n d.DATA = convertCommaFloats(d.werte.Tavg_temp);\n d.werte.Qualitaetsgrenze = convertCommaFloats(d.werte.Qualitaetsgrenze);\n d.werte.Tavg_temp = convertCommaFloats(d.werte.Tavg_temp);\n });\n visualiseData(data[0]);\n}", "function grabTableData() {\n var cache1 = CacheService.getDocumentCache();\n var dataForChart = (cache1.get('mtData'));\n Logger.log('return:' + JSON.parse(dataForChart));\n return dataForChart;\n}", "function data() {\n\treturn {\n\t\tsize: 224,\n\t\tN: undefined,\n\t\tpos: undefined,\n\t\tylabels: undefined,\n\t\tdatasource: undefined\n\t};\n}", "function GetData(error, response) {\n if (error) throw error;\n\n //parsing data to JSON\n var display = JSON.parse(response[0].responseText);\n console.log(display);\n\n //creating lists, to store information for each variable\n list_countries = []\n list_variables_axes = []\n Life_Quality_mark = []\n Employement_Rate = []\n Voter_turnout = []\n\n // obtaining variables for the axes (total of three)\n variables_axes = display.dataSets[0].observations\n for (var i = 0; i < 10; i++)\n {\n for (var j = 0; j < 3; j++)\n {\n observation = i + \":\" + j + \":0:0\"\n list_variables_axes.push(variables_axes[observation][0])\n }\n }\n\n // storing ax variable 'Life_Quality_mark' in own list\n for (var i = 2; i < 30; i+=3){\n Life_Quality_mark.push(list_variables_axes[i])\n }\n\n // storing ax variable 'Voter_turnout' in own list\n for (var i = 0; i < 30; i+=3){\n\n Voter_turnout.push(list_variables_axes[i])\n }\n\n // storing ax variable 'Employement_Rate' in own list\n for (var i = 1; i < 30; i+=3){\n\n Employement_Rate.push(list_variables_axes[i])\n }\n\n // obtaining countries of DOM, and storing in a list\n countries = display.structure.dimensions.observation[0].values\n for (i = 0; i <10; i++){\n\n list_countries.push(countries[i]['name'])\n }\n\n // creating list (array in array), for all the variables\n dataset=[]\n\n // pushing all the variables to the list of the dataset\n for (i =0; i < 10; i++){\n dataset.push([list_countries[i],Life_Quality_mark[i],Voter_turnout[i],Employement_Rate[i]])\n }\n\n // creating list for dict\n dict = []\n\n // writing the data to a dictenory, called dict\n for(var data = 0; data < dataset.length; data++)\n {\n dict.push({\n \"Country\" : dataset[data][0],\n \"Life_Quality_mark\" : dataset[data][1],\n \"Voter_turnout\" : dataset[data][2],\n \"Employement_Rate\" : dataset[data][3],\n })\n }\n\n // calling the build function which gets the parameter dict\n build (dict);\n}", "getData () {\n if (this._graphData) {\n return this._graphData;\n }\n }", "function getData(data) {\n console.log(\"data is loaded\");\n console.log(data);\n\n // refresh the time and date\n setDateAndTime();\n\n // send data to components\n showQueue(data.queue);\n showStockStatus(data.storage);\n showOrders(data.queue, data.serving);\n\n // set which bartender is serving each order\n setBartender(data.bartenders);\n\n // set the icon for each bartender\n setBartenderIcon();\n}", "function data() {\n const div = document.createElement( 'div' );\n const title = document.createElement( 'title' );\n const content = document.createElement( 'content' );\n const p = document.createElement( 'p' );\n\n my.data.entries.map( entry => {\n const title_clone = title.cloneNode( true );\n const content_clone = content.cloneNode( true );\n const p_clone = p.cloneNode( true );\n title_clone.innerHTML = entry.title;\n $.setContent( p_clone, $.html( entry.content ) );\n content_clone.appendChild( p_clone );\n div.appendChild( title_clone );\n div.appendChild( content_clone );\n } );\n\n return div;\n }", "function getDataFromSelection() {\n Office.context.document.getSelectedDataAsync(Office.CoercionType.Matrix,\n function (result) {\n var dataSet = MakeData(result);\n $('#container').highcharts({\n chart: {\n type: 'heatmap',\n marginTop: 40,\n marginBottom: 80,\n plotBorderWidth: 1\n },\n\n\n title: {\n text: 'Schedulings Per Day Per Hour'\n },\n\n xAxis: {\n categories: dataSet.xAxis,\n title:\"Date\"\n },\n\n yAxis: {\n categories: dataSet.yAxis,\n title: \"Time\"\n },\n\n colorAxis: {\n min: 0,\n minColor: '#FFFFFF',\n maxColor: Highcharts.getOptions().colors[0]\n },\n\n legend: {\n align: 'right',\n layout: 'vertical',\n margin: 0,\n verticalAlign: 'top',\n y: 25,\n symbolHeight: 280\n },\n\n tooltip: {\n formatter: function () {\n return '<b>' + this.point.value + \" Installs Occuring On <br/>\" + moment(this.series.xAxis.categories[this.point.x]).add(this.series.yAxis.categories[this.point.y], 'hours').format(\"LLLL\")+ \"</b>\";\n }\n },\n\n series: [{\n name: 'Sales per employee',\n borderWidth: 1,\n data: dataSet.Data,\n dataLabels: {\n enabled: true,\n color: '#000000'\n }\n }]\n\n });\n });\n }", "function displayData() {\n var url = \"api/inputData\"\n d3.json(url).then(function (response) {\n\n d3.select(\"#totalCount\").text(response.length);\n updateArticle(response, 0);\n\n });\n}", "getPlotlyData(){\n\t\t// check here if 'show' is true or not (if not, return null immediately)\n\t\tvar data = this.getData();\n\t\tif(!this.valueOf('show')){return null;}\n\t\treturn {\n\t\t\tx: data[0],\n\t\t\ty: data[1],\n\t\t\tname: this.valueOf('label'),\n\t\t\tshowlegend: !(this.valueOf('label') == ''), // only show in legend if field isn't blank\n\t\t\tline: {\n\t\t\t\tcolor: this.getColor(), // color and opacity (convert to rgba)\n\t\t\t\twidth: this.valueOf('line_width'), // line width in pixels\n\t\t\t}\n\t\t}\n\t}", "function getData() {\n\t\t// Set data values\n\t\t$(\"label\").html(\"Auto Refresh <span class='subtle'>- every \" + REFRESH_RATE/1000 + \" seconds</span>\");\n\t\treturn $.getJSON(SEPTA_URL, dataOptions, displayData);\n\t}", "function getDataSetTitles(dataChoice) {\n document.getElementById(\"title\").innerHTML = dataset[dataChoice].title;\n document.getElementById(\"description\").innerHTML = dataset[dataChoice].description;\n renderTreemap(dataset[dataChoice].url); //send json url to renderTreemap\n }", "function getData(){\r\n\r\n \r\n //url of the site where the info comes from\r\n const Launches_URL = \"https://api.spacexdata.com/v2/launches/all\";\r\n \r\n let url = Launches_URL;\r\n\r\n \r\n \r\n \r\n //calling the method that will look through the retrieved info\r\n $.ajax({\r\n dataType: \"json\",\r\n url: url,\r\n data: null,\r\n success: jsonLoaded\r\n });\r\n\t}", "function getData() {\n $http.get(ctrl.mapVisUrl).\n success(function(data, status, headers, config) {\n processData(data); //Process the result.\n ctrl.isLoading = false; //Tell the loadingGif to turn off, we're done.\n\n }).\n error(function(data, status, headers, config) {\n ctrl.isLoading = false;\n });\n }", "function getDashboardData(){\n var _serviceURI = '';\n $.each(DATA_METRICS_ARR, function(_index, _dataset){\n if((DATA_METRICS_ARR[_index] !== 'NA')){\n objloadedArr.push(DATA_METRICS_ARR[_index]);\n _serviceURI = DATA_SERVICE_URI + \"?dataset=\" + _dataset + \"&session_id=\" + session_id + \"&from=\" + from_date + \"&to=\" + to_date + \"&aggreg_type=\" + aggreg_typ;\n $engine.makeAJAXRequest(\n _serviceURI,\n 'get',\n {},\n '',\n 'json',\n {itemIndex: _index, dataSet: _dataset},\n true,\n graphDataSuccessHandler,\n dataErrorHandler\n );\n }\n });\n }", "function getData() {\n $.ajax({\n type: 'post',\n url: '../lib/stats.php',\n success: function(response) {\n if (JSON.stringify(object.orders) != JSON.stringify(JSON.parse(response).orders)) {\n object = JSON.parse(response);\n ordersData = object.orders;\n cakesData = object.cakes;\n fillingsData = object.fillings;\n decorationsData = object.decorations;\n drawCharts();\n }\n clear = true;\n }\n });\n}", "function getData() {\n var dropdownMenu = d3.select(\"#selDataset\");\n // Assign the value of the dropdown menu option to a variable\n var dataset = dropdownMenu.property(\"value\");\n // Initialize an empty array for the country's data\n // Call function to update the chart\n updatePlotly(data);\n}", "function getData() {\n return {\n ergReps: ergReps,\n bikeReps: bikeReps,\n repRate: repRate,\n totTime: totTime,\n Distance: Distance\n }\n }", "function dataViaAjax()\n\t {\n\t\t jsonData = $.ajax({\n type: \"GET\",\n\t\turl: \"index_db.php\",\n\t\tdata: \"start=\" + startNumber + \"&speed=\" + speed + \"&throttle=\" + throttle + \"&battery=\" + battery + \"&batteryTemp=\" + batteryTemp + \"&airTemp=\" + airTemp + \"&coolentTemp=\" + coolentTemp,\n\t\tdataType:\"json\",\n async: false,\n\t\tsuccess: function(data){\n\t\t \n },\n\t\t\terror: function(e){\n console.log(e.message);\n }\n\t\t}).responseText;\n\t//Converts the JSON object into useful graph data\n data = new google.visualization.DataTable(jsonData);\n\t \n\t }", "function getData() {\r\n\tvar apiURL = HAM.config.apiBaseURL + \r\n\t\t\t\"/object?apikey=\" + HAM.config.apiKey + \r\n\t\t\t\"&s=random&color=any&size=1&q=dimensions:*&fields=title,people,culture,dated,dimensions,colors,imagepermissionlevel,primaryimageurl\";\r\n\r\n\tvar xmlrequest = new XMLHttpRequest();\r\n\r\n\txmlrequest.onreadystatechange = function() {\r\n\t\tif (this.readyState == 4) {\r\n\t\t\tif (this.status == 200) {\r\n\t\t\t\tcurrent = JSON.parse(this.responseText);\r\n\t\t\t\tprocessData(current);\r\n\t\t\t} else {\r\n\t\t\t\tdone = true;\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\t\t\t\r\n\txmlrequest.open(\"GET\", apiURL, true);\r\n\txmlrequest.send();\r\n\r\n\txmlrequest = null;\r\n\tapiURL = null;\r\n}", "function getData()\n\t\t{\n\t\t\tvar newData = { hello : \"world! it's \" + new Date().toLocaleTimeString() }; // Just putting some sample data in for fun.\n\n\t\t\t/* Get my data from somewhere and populate newData with it... Probably a JSON API or something. */\n\t\t\t/* ... */\n\n\t\t\t// I'm calling updateCallback to tell it I've got new data for it to munch on.\n\t\t\tupdateCallback(newData);\n\t\t}", "function init(){\n getData();\n}", "function getData()\n\t\t{\n\t\t\tvar newData = { hello : \"world! it's \" + new Date().toLocaleTimeString() }; // Just putting some sample data in for fun.\n\n\t\t\t/* Get my data from somewhere and populate newData with it... Probably a JSON API or something. */\n\t\t\t/* ... */\n\t\t\tupdateCallback(newData);\n\t\t}", "async function dataGen() {\n if (clicked && !data[0]) {\n try {\n const sensorData = await api.get('/sensor/show/one', {\n params: {\n dono: localStorage.getItem('urbanVG-user'),\n nome: clicked\n }\n })\n\n if (sensorData.data) {\n setColor(sensorData.data.cor)\n\n if (sensorData.data.feed[0]) {\n if (sensorData.data.feed.length > 5) {\n for (let i = 0; i < 5; i++) {\n let feedAux = sensorData.data.feed[(sensorData.data.feed.length - 6) + i];\n setData(prev => [\n ...prev,\n {\n name: `${(new Date(feedAux.data).getDate()) > 9 ? (new Date(feedAux.data).getDate()) : \"0\" + (new Date(feedAux.data).getDay())}/${(new Date(feedAux.data).getMonth() + 1) > 9 ? (new Date(feedAux.data).getMonth()) : \"0\" + (new Date(feedAux.data).getMonth() + 1)}`,\n valor: feedAux.valor\n }\n ])\n }\n } else {\n sensorData.data.feed.map(element => {\n setData(prev => [\n ...prev,\n {\n name: `${(new Date(element.data).getDate()) > 9 ? (new Date(element.data).getDate()) : \"0\" + (new Date(element.data).getDay())}/${(new Date(element.data).getMonth() + 1) > 9 ? (new Date(element.data).getMonth()) : \"0\" + (new Date(element.data).getMonth() + 1)}`,\n valor: element.valor\n }\n ])\n })\n }\n }\n }\n } catch (error) {\n alerts.showAlert('Problema na conexão com o servidor!', 'Error', 'singup-alert')\n }\n }\n }", "function getData() {\n // data downloaded from the USGS at http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/ on 4/4/16\n // month.geojson represents recorded earthquakes between 03/04/2016 and 04/04/2016\n // week.geojson represents recorded earthquakes betwen 03/28/2016 and 04/04/2016\n var url = \"data/week.geojson\";\n return esriRequest(url, {\n responseType: \"json\"\n });\n }", "function graphData(data) {\n console.log(\"render graphs\");\n _.take(data,10).forEach(function (o) {\n //data.forEach(function (o) {\n var dataRecord = {\n \"c\": o.test,\n \"v\": o.april,\n };\n\n\n // console.log(dataRecord);\n transformedDataFiltered.push(dataRecord);\n });\n}", "chart() {\r\n var formattedData = [];\r\n if (this.data[0]) {\r\n formattedData.push(Object.keys(this.data[0].dataValues));\r\n for (var line in this.data) {\r\n formattedData.push(Object.values(this.data[line].dataValues));\r\n }\r\n }\r\n return formattedData;\r\n }", "function loadData()\n\t{\n\t\tloadMaterials(false);\n\t\tloadLabors(false);\n\t}", "async function getData() {\n const api_url = \"json/scenes.json\";\n const response = await fetch(api_url);\n const data = await response.json();\n showSceneThree(data);\n loadSceneThreeSVG();\n console.log(data);\n}", "function getdata() {\n var returnarray = [];\n var data1 = vartable[scatterplot_varname1].data;\n var data2 = vartable[scatterplot_varname2].data;\n var length = data_length();\n for(i=0;i<length;i++) {\n // The data is rounded to 3 digits for printing, becouse otherwise the labels might be very long\n returnarray.push([Number(data1[i].toFixed(3)),Number(data2[i].toFixed(3))]);\n }\n return returnarray;\n }", "function loadData(){\n\t\tloadParetoData();\n\t\tloadConstraints();\n\t\t\n\t}", "function showData(m) {\n try {\n let html = 'accel';\n html += '<table><tr><td>' + m.accel.x.toFixed(3) + '</td><td>' + m.accel.y.toFixed(3) + '</td><td>' + m.accel.z.toFixed(3) + '</tr></table>';\n html += '</table>';\n\n html += 'rot';\n html += '<table><tr><td>' + m.rot.alpha.toFixed(3) + '</td><td>' + m.rot.beta.toFixed(3) + '</td><td>' + m.rot.gamma.toFixed(3) + '</tr></table>';\n\n html += 'rotMotion';\n html += '<table><tr><td>' + m.rotMotion.alpha.toFixed(3) + '</td><td>' + m.rotMotion.beta.toFixed(3) + '</td><td>' + m.rotMotion.gamma.toFixed(3) + '</tr></table>';\n\n html += 'accelGrav';\n html += '<table><tr><td>' + m.accelGrav.x.toFixed(3) + '</td><td>' + m.accelGrav.y.toFixed(3) + '</td><td>' + m.accelGrav.z.toFixed(3) + '</tr></table>';\n html += '</table>';\n document.getElementById('last').innerHTML = html;\n } catch (err) {\n logError(err);\n }\n}", "function selectFullData(){\n\n // bar chart\n var rates = getCheckedRadioValue('malware');\n listdatacollector(minTime,maxTime,rates);\n updatelist_data();\n //behavoiur graph\n bartobehavior(rates);\n // theread graph\n var temp = getDataForTimeFrame(minTemp,maxTemp);\n generateThreadGraph([temp],minTemp,maxTemp);\n\n}", "loadingData() {}", "loadingData() {}", "function getData() \n{\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.onreadystatechange = function ()\n {\n if (this.readyState == 4 && this.status == 200)\n {\n // creates a new Data() object from picalc.js\n window.data = new Data(JSON.parse (this.responseText));\n\n // this is essentially the view logic; it builds the HTML\n setup();\n }\n };\n\n xmlhttp.open(\"GET\", \"https://tspi.io/factory-planet/planetary_commodities.json\", true);\n xmlhttp.send();\n}", "function drawViz(){\n\n let currentYearData = incomingData.filter(filterYear);\n console.log(\"---\\nthe currentYearData array now carries the data for year\", currentYear);\n\n\n // Below here is where your coding should take place! learn from lab 6:\n // https://github.com/leoneckert/critical-data-and-visualization-spring-2020/tree/master/labs/lab-6\n // the three steps in the comments below help you to know what to aim for here\n\n // bind currentYearData to elements\n\n\n\n // take care of entering elements\n\n\n\n // take care of updating elements\n\n\n\n\n\n\n\n\n\n\n }", "function getAllResult(){\r\n\t\r\n\tif (processDone) {\r\n for(var key in Obj_Fetch)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\tvar temp_var={};\r\n\t\t\t\t\t\ttemp_var.cancertype=key;\r\n\t\t\t\t\t\ttemp_var.male=Obj_Fetch[key].MALE;\r\n\t\t\t\t\t\ttemp_var.female=Obj_Fetch[key].FEMALE;\r\n\t\t\t\t\t\tfetch_data_array.push(temp_var);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\taddAllScatterPlot(fetch_data_array);\r\n\t\t\t\t\t\t\r\n } else {\r\n setTimeout(getResult, 250);\r\n }\r\n }", "function visualize(theData){\r\n\t// Part 1: Essential Local Variables and Functions\r\n\t// ===============================================\r\n\t// curX and curY will determine what data get's represented in each axis\r\n\r\n}", "function get_data(){\n\n var x = new XMLHttpRequest();\n\n x.onreadystatechange = function(){\n if(x.status === 200 && x.readyState === 4) {\n var jsonResp = JSON.parse(x.responseText);\n var nodes_strings = jsonResp['strings'];\n var nodes_length = jsonResp['nodes_length'];\n data.map = jsonResp['map_data'];\n for(var j = 0; j < nodes_length; j++){\n data.nodes['node_'+j] = jsonResp['node_'+j];\n for(var i = 0; i < data_format.node.length - 2; i++){\n data.nodes['node_'+j][data_format.node[i]] = data.nodes['node_'+j][data_format.node[i]].toFixed(3)\n }\n if(j==$(dom_elements.nodeselection_name).val()){\n for(var i = 0; i < data_format.node.length; i++){\n element_id = '#'+data_format.node[i];\n $(element_id).text(data.nodes['node_'+j][data_format.node[i]] + data_format.units[data_format.node[i]]);\n }\n }\n }\n if(dom_elements.map_series_selection=='Map'){\n heatmap.renderColor(dom_elements, data);\n }\n else if(dom_elements.map_series_selection=='Serie'){\n timeserie.drawChart(jsonResp['time_data'], data_format);\n }\n }\n }\n x.open('GET', '/data_query?' + 'interp=' + dom_elements.selected_map\n + '&map=' + dom_elements.map_series_selection\n + '&node_n=' + $(dom_elements.nodeselection_name).val()\n + '&init_date=' + date.from.getDate() + '/' + (date.from.getMonth()+1) + '/' + date.from.getFullYear()\n + '&finish_date=' + date.to.getDate() + '/' + (date.to.getMonth()+1) + '/' + date.to.getFullYear(), true);\n x.send();\n }", "async function getDataVisual() {\n // Get input from the user\n let input = document.getElementById(\"site-search\").value;\n // array with objects for each category of art\n // array contains url for the GET request to the museums's API\n // the reponse is stored in json\n // the prepared data will be stored in data\n const artDataArray = [\n {\n type: \"Paintings\",\n background: \"rgba(100, 149, 237, 0.5)\",\n border: \"rgba(100, 149, 237, 1)\",\n url: serverURL + `munch/malerier/${input}`,\n json: {},\n data: [],\n },\n {\n type: \"Graphics\",\n background: \"rgba(255, 209, 26, 0.5)\",\n border: \"rgba(255, 209, 26, 1)\",\n url: serverURL + `munch/grafikk/${input}`,\n json: {},\n data: [],\n },\n {\n type: \"Drawings\",\n background: \"rgba(255, 194, 180, 0.5)\",\n border: \"rgba(255, 194, 180, 1)\",\n url: serverURL + `munch/tegninger/${input}`,\n json: {},\n data: [],\n },\n {\n type: \"Sculptures\",\n background: \"rgba(179, 255, 179, 0.5)\",\n border: \"rgba(179, 255, 179, 1)\",\n url: serverURL + `munch/skulpturer/${input}`,\n json: {},\n data: [],\n },\n {\n type: \"Photopraphies\",\n background: \"rgba(0, 196, 154, 0.5)\",\n border: \"rgba(0, 196, 154, 1)\",\n url: serverURL + `munch/fotografi/${input}`,\n json: {},\n data: [],\n },\n {\n type: \"Documentary Photopraphies\",\n background: \"rgba(255, 102 , 0, 0.5)\",\n border: \"rgba(255, 102 , 0, 1)\",\n url: serverURL + `munch/dokumentarfoto/${input}`,\n json: {},\n data: [],\n },\n ];\n\n // if there is no input, return an empty data array\n if (input.length === 0) {\n return artDataArray;\n }\n\n // obtaining the data from the API\n // for loop iterating over the artDataArray\n // for each index position, (each category of art) a fetch request is issued with the respective url\n for (i in artDataArray) {\n console.log(\"Getting data from: \" + artDataArray[i].url);\n let json = await fetch(artDataArray[i].url)\n .then((response) => {\n return response.json();\n })\n .catch((error) => {\n console.log(error);\n });\n // the JSON from the response is stored in the json object of each art collection\n // console.log(\"hits: \" + json.data.length);\n console.log(json);\n artDataArray[i].json = json;\n }\n // Preparing the data requierd for making the Timeline Chart\n // iterating over all elemets in the artDataArray and each work of art inside the data array\n for (i in artDataArray) {\n let xArtworks = [];\n let xtitle = [];\n\n // For each hit\n for (artwork of artDataArray[i].json.data) {\n // Check if artwork has \"metadata\" property\n if (artwork.hasOwnProperty(\"metadata\")) {\n //Get title from data\n let { metadata } = artwork;\n let value = \"NoTitle\";\n // Check for \"105\" property\n if (metadata.hasOwnProperty(\"105\")) {\n value = metadata[105].value;\n // if not, check \"5\"\n } else if (metadata.hasOwnProperty(\"5\")) {\n value = metadata[5].value;\n }\n // Check if value exists\n if (value != null) {\n let titleString = value.toString();\n if (titleString != null) {\n xtitle.push(titleString);\n } else {\n xtitle.push(\"\");\n }\n } else {\n xtitle.push(\"\");\n }\n }\n // Get year number from data\n // check if more than one year number is offered e.g. 1890-92\n // pick the first 4 digits as year, push them to array\n if (artwork.metadata[203].value.length > 4) {\n let str = artwork.metadata[203].value.toString();\n let re = /^\\d{4}/;\n let found = str.match(re);\n if (found != null) {\n xArtworks.push(parseInt(found[0]));\n } else {\n xArtworks.push(null);\n }\n // also push the 4 digit years to the array\n } else if (artwork.metadata[203].value.length == 4) {\n xArtworks.push(parseInt(artwork.metadata[203].value));\n } else {\n xArtworks.push(null);\n }\n // -----------------------------------------------------------------------------------------------------\n // ---------------------------------------- LIST -------------------------------------------------------\n // for each artwork create an element in list element\n // displaying a mini image, the title, and the year number\n const root = document.createElement(\"div\");\n // added box here :)\n const box = document.createElement(\"div\");\n // added class box to the element\n box.setAttribute(\"class\", \"box\");\n const titletitle = document.createElement(\"div\");\n const datedate = document.createElement(\"div\");\n const kunstner = document.createElement(\"div\");\n const photographer = document.createElement(\"div\");\n const imageimage = document.createElement(\"img\");\n\n if (artwork.hasOwnProperty(\"metadata\")) {\n let { metadata } = artwork;\n // retrieve title\n if (metadata.hasOwnProperty(\"105\")) {\n titletitle.textContent = `Title: ${metadata[105].value.toString()}`;\n } else {\n titletitle.textContent = `Title: `;\n }\n // retrieve date\n if (metadata.hasOwnProperty(\"203\")) {\n datedate.textContent = `Date : ${metadata[203].value.toString()}`;\n } else {\n datedate.textContent = `Date : `;\n }\n // retrieve artist\n if (metadata.hasOwnProperty(\"110\")) {\n kunstner.textContent = `Artist : ${metadata[110].value.toString()}`;\n } else {\n kunstner.textContent = `Artist : `;\n }\n // for credit: retrieve photographer\n if (metadata.hasOwnProperty(\"80\")) {\n photographer.textContent = `Photographer : ${artwork.metadata[80].value[0].toString()}`;\n } else {\n photographer.textContent = `Photographer : `;\n }\n }\n // image for the miniature preview\n if (artwork.hasOwnProperty(\"previews\")) {\n imageimage.src = `https://foto.munchmuseet.no${artwork.previews[0].href}`;\n }\n\n // Add all the elements to the box element and then add box to root\n box.appendChild(titletitle);\n box.appendChild(datedate);\n box.appendChild(kunstner);\n box.appendChild(photographer);\n box.appendChild(imageimage);\n root.appendChild(box);\n // append root to the list elememt in index.html\n document.getElementById(\"list\").appendChild(root);\n }\n // --------------------------------------------------------------------------------------------------\n // ---------------------- Create Y Part of data -----------------------------------------------------\n // ---------------------- Creating an array with all titles -----------------------------------------\n // creating an array with the year numbers that occured\n let uniqueYears = Array.from(new Set(xArtworks)).sort();\n\n let data = [];\n let title = [];\n // if the arrays have the same lentgh, each title should end up in the same index position\n // as the corresponding work of art\n if (xtitle.length != xArtworks.length) {\n throw \"Error, xtitle is not of same length as xArtWorks\";\n }\n // creating the y values, that are counted up\n // iterating over the unique years and the years in the xArtworks array\n // the first time a uniqueYear is found in the xArtworks array y=1\n // every time the uniqueYear occurs again the y value counts up by 1\n // the title is pushed as well\n for (let x of uniqueYears) {\n // start at 1\n let y = 1;\n for (let i in xArtworks) {\n if (x === xArtworks[i]) {\n // the object conatining e.g. {1900, 4}\n data.push({ x, y });\n title.push(xtitle[i]);\n y++;\n }\n }\n }\n // For the Pie Chart: determining the number of works of art for a query term\n // length array = how many were found\n let numberArtworks = data.length;\n // the object stored in the data array containing an array of objects and two additional arrays\n artDataArray[i].data = { data, title, numberArtworks };\n }\n\n return artDataArray;\n}", "function loaded(){\n graph([]);\n pieChart([],[],[],[]);\n}", "function getData() {\n\n\n $.ajax({\n url: \"http://157.230.17.132:4001/sales\",\n method: \"GET\",\n success: function (data) {\n console.log(data);\n\n\n //ordino i dati per le chart\n var salesByEmployee = getSalesByEmployee(data);\n var salesByMonth = getSalesByMonth(data);\n var employeeArray = getEmployees(data);\n var quarterlySales = getQuarterlySales(salesByMonth);\n\n\n fillEmployeeOptions(employeeArray);\n\n //disegno le chart\n drawLineChart(salesByMonth);\n drawPieChart(salesByEmployee);\n drawBarChart(quarterlySales);\n },\n error: function () {\n console.log(\"error\");\n }\n })\n\n}", "function fetch_data() {\n var dataset = $('#dataset').val(),\n url = '../../data/' + $('#dataset option:selected').attr('url');\n $.ajax(url, {\n success: function (resp) {\n var wasPlaying = animationState.mode === 'play';\n animation_pause();\n animationState = {};\n var rows;\n switch (dataset) {\n case 'adderall':\n rows = resp.split(/\\r\\n|\\n|\\r/);\n rows.splice(0, 1);\n rows = rows.map(function (r) {\n var fields = r.split(',');\n return [fields[12], fields[24], fields[25]].map(parseFloat);\n });\n break;\n case 'cities':\n rows = resp.split(/\\r\\n|\\n|\\r/);\n rows.splice(rows.length - 1, 1);\n rows = rows.map(function (r) {\n var fields = r.split('\",\"');\n return ['' + fields[0].replace(/(^\\s+|\\s+$|^\"|\"$)/g, '').length, fields[2].replace(/(^\\s+|\\s+$|^\"|\"$)/g, ''), fields[3].replace(/(^\\s+|\\s+$|^\"|\"$)/g, '')].map(parseFloat);\n });\n break;\n case 'earthquakes':\n animationState.orderedData = true;\n rows = resp;\n break;\n }\n datapoints = rows;\n var text = 'Loaded: ' + datapoints.length;\n $('#points-loaded').text(text).attr('title', text);\n show_points(datapoints);\n reset_styles();\n if (wasPlaying) {\n animation_play();\n }\n }\n });\n }", "async function fetchData() {\n\n // get the datasets.json data\n const url = withPrefix('/data/datasets.json')\n const resp = await fetch(url)\n const datasets = await resp.json()\n\n // sort the datasets by added date, descending\n datasets.sort((a, b) => new Date(b.added) - new Date(a.added))\n\n // update the display with latest data\n setDatasets(datasets)\n setFiltered(datasets.map(d => d.slug))\n setSubjects(getSubjects(datasets))\n setStart(getEarliestDate(datasets))\n }", "function data_ready() {\n // latest two weeks of data... subtract 13 instead of 14 because dtaes\n // are inclusive and -14 gives fencepost error\n var edate = telemetry.midnight(telemetry.maxDate);\n var sdate = telemetry.midnight(add_days(edate, -13));\n draw_dashboard(sdate, edate);\n}", "function getValues() {\n\t$.get(\"/load_charts/get-charts/\", function (data){ drawChart(data, threshold); });\n}", "function setup() {\n // http://datamx.io/dataset/salario-minimo-historico-1877-2019\n loadTable('../../data/mx_salariominimo_1877-2019.csv', 'csv', 'header', gotData);\n createCanvas(windowWidth, windowHeight);\n}", "function drawVisualization(){\n $(document).ready(function(){\n var request=$.ajax({\n url:\"https://restcountries.eu/rest/v1/\"\n })\n request.done(function(data, status){\n var datos = [[\"Country\",\"Population\"]];\n for(i=0;i<data.length;i++){\n graf=data[i];\n var grafForWidget=[graf.name, Number(graf.population)];\n datos.push(grafForWidget);\n \n }\n var datosRecogidos = google.visualization.arrayToDataTable(datos);\n var options = {\n title: 'Consume external api of total population in differents countries',\n pieHole: 0.4,\n };\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(datosRecogidos, options);\n\n })\n })\n}", "function getResult(){\r\n\t\r\n\td3.select(\"svg\").remove();\r\n\tif (processDone) {\r\n //return some variables\r\n\t\t \r\n\t\t for(var key in Obj_Fetch)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\tvar temp_var={};\r\n\t\t\t\t\t\ttemp_var.cancertype=key;\r\n\t\t\t\t\t\ttemp_var.male=Obj_Fetch[key].MALE;\r\n\t\t\t\t\t\ttemp_var.female=Obj_Fetch[key].FEMALE;\r\n\t\t\t\t\t\tfetch_data_array.push(temp_var);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\taddScatterPlot(fetch_data_array);\r\n\t\t\t\t\t\tconsole.log(fetch_data_array);\r\n\r\n } else {\r\n setTimeout(getResult, 250);\r\n }\r\n }", "getMultipleGraphDatas(state, getters) {\n const res = [\n {\n yAxisText: 'SOC',\n xAxisEnabled: false,\n labelsFormatterText: null,\n data: getters.getGraphDataSoc\n },\n {\n yAxisText: 'Intensity',\n xAxisEnabled: false,\n labelsFormatterText: 'I',\n data: getters.getGraphDataIntensity\n },\n {\n yAxisText: 'Temperature',\n xAxisEnabled: false,\n labelsFormatterText: '°',\n data: getters.getGraphDataTemperature\n },\n {\n yAxisText: 'Voltage',\n xAxisEnabled: true,\n labelsFormatterText: 'V',\n data: getters.getGraphDataVoltage\n },\n ];\n return res;\n }", "all() {\n return Util_1.default.toDataset(this.data);\n }", "function fetchParsedJson() {\n\treturn JSON.parse(datasetToDisplay);\n}", "function fetchData() {\n let targetEl = this,\n url = `/svgdata/${this.dataset.target}`;\n\n fetch(url)\n .then(res => res.json())\n .then(data => {\n console.log(data);\n\n //populate the popover\n buildPopover(data, targetEl);\n })\n\n .catch((err) => console.log(err));\n }", "function loadData() {\n return d3.json(dataFileName)\n}", "function getPieData(){\r\n\t \t\t var jsonUnit = \"\";\r\n\t \t\t var color =\"\";\r\n\t \t\t var highlight=\"\";\r\n\t \t\t\r\n\t \t\t for(var i=0; i<mediaValues.length;i++){\r\n\t \t\t\t switch(i%5) {\r\n\t \t\t\t case 0:\r\n\t \t\t\t color = \"#4EC3E4\";\r\n\t \t\t\t highlight = \"#4EC3E4\";\r\n\t \t\t\t break;\r\n\t \t\t\t case 1:\r\n\t \t\t\t \tcolor = \"#65D99A\";\r\n\t \t\t\t \thighlight = \"#65D99A\";\r\n\t \t\t\t break;\r\n\t \t\t\t case 2:\r\n\t \t\t\t \tcolor = \"#FFCE56\";\r\n\t \t\t\t \thighlight = \"#FFCE56\";\r\n\t \t\t\t break;\r\n\t \t\t\t case 3:\r\n\t \t\t\t \tcolor = \"#F7464A\";\r\n\t \t\t\t \thighlight = \"#F7464A\";\r\n\t \t\t\t break;\r\n\t \t\t\t default:\r\n\t \t\t\t color = \"#4D5360\";\r\n\t \t\t\t}\r\n\t \t\t\t if(mediaValues.length==1){\r\n\t \t\t\t\t jsonUnit = \"[\"+jsonUnit + JSON.stringify({\"value\":mediaValues[i],\"label\":mediaLabels[i],\"color\":color,\"highlight\":highlight}) + \"]\";\r\n\t \t\t\t\t break;\r\n\t \t\t\t }\r\n\t \t\t\t if(i==0){\r\n\t \t\t\t\t jsonUnit = \"[\"+jsonUnit + JSON.stringify({\"value\":mediaValues[i],\"label\":mediaLabels[i],\"color\":color,\"highlight\":highlight});\r\n\t \t\t\t }\r\n\t \t\t\t if(i>0 && i<mediaValues.length-1){\r\n\t \t\t\t\t jsonUnit = jsonUnit+\",\" + JSON.stringify({\"value\":mediaValues[i],\"label\":mediaLabels[i],\"color\":color,\"highlight\":highlight});\r\n\t \t\t\t }\r\n\t \t\t\t if(i==mediaValues.length-1){\r\n\t \t\t\t\t jsonUnit = jsonUnit +\",\" + JSON.stringify({\"value\":mediaValues[i],\"label\":mediaLabels[i],\"color\":color,\"highlight\":highlight})+\"]\";\r\n\t \t\t\t }\r\n\t \t\t }\r\n\t \t\t return JSON.parse(jsonUnit);\r\n\t \t }", "function getCurrentDataAsDict() {\n\tfunction naArray(len) {\n\t\tvar ret = [];\n\t\tfor(var i in len) { ret.push(\"N/A\"); }\n\t\treturn ret;\n\t}\n\n\tvar tbl = {}\n\tvar names = [];\n\tif(viewerVars.plotType == viewerVars.plotTypeEnum.SCATTER_2D) {\n\t\tfor(i in myDiv.data) {\n\t\t\tvar data = myDiv.data[i];\n\t\t\tvar dlen = data.x.length;\n\t\t\tnames.push(data.name);\n\t\t\tfor(j = 0; j < dlen; j++) {\n\t\t\t\tvar t = new Date(data.x[j]).toISOString();\n\t\t\t\tif(!(t in tbl)) { tbl[t] = naArray(myDiv.data); }\n\t\t\t\ttbl[t][i] = data.y[j];\n\t\t\t}\n\t\t}\n\t\treturn [names, tbl];\n\t} else {\n\t\tnames.push(viewerVars.pvs[0]); // We only support one waveform for now...\n\t\tvar maxColumnNum = 0;\n\t\tvar numSamples = viewerVars.pvData[pvName].secs.length;\n\t\tfor(var j = 0; j < numSamples; j++) {\n\t\t\tvar t = new Date(viewerVars.pvData[pvName].secs[j]).toISOString();\n\t\t\tvar val = viewerVars.pvData[pvName].vals[j];\n\t\t\tif(val.length > maxColumnNum) { maxColumnNum = val.length; }\n\t\t\tif(!(t in tbl)) { tbl[t] = naArray(val.length); }\n\t\t\tfor(var k = 0; k < val.length; k++) {\n\t\t\t\ttbl[t][k] = val[k];\n\t\t\t}\n\t\t}\n\t\tfor(var n = 1; n < maxColumnNum; n++) { names.push(n); }\n\t\treturn [names, tbl];\n\t}\n}", "getData(){}", "fetchData() {\n this.initLoading();\n let qs = this.setAndGetQuerySetFromSandBox(this.view, this.qs_url);\n this.data.instance = qs.cache = qs.model.getInstance({}, qs);\n this.setLoadingSuccessful();\n this.getParentInstancesForPath();\n }", "fetchData() {\n this.initLoading();\n let qs = this.setAndGetQuerySetFromSandBox(this.view, this.qs_url);\n this.data.instance = qs.cache = qs.model.getInstance({}, qs);\n this.setLoadingSuccessful();\n this.getParentInstancesForPath();\n }", "function displayData(data,viewtype){\n // Check if init function exists in data from call\n if (data.initFunc != \"\"){ \n var init = window[data.initFunc];\n if(typeof init === 'function') {\n // Draw the graph or display \"not enough info\" tabpane\n if(!init(data)) {\n displayNei();\n }\n }\n }\n hideLoadingIcon(viewtype);\n \n }", "function getNewData() {\n\t\tdash.flashTime();\n\t\tModel.SensorManager.getCurrentDataValues(function(syncTime, isNew) {\n\t\t\tif(isNew) {\n\t\t\t\tdash.refresh();\n\t\t\t\tVC.Graphs.replot();\n\t\t\t\tcount += syncTime;\n\t\t\t}\n\t\t\t//Make UI changes when the data dies or resurrects\n\t\t\tdash.setStatus();\n\n\t\t\tdash.flashTime();\n\t\t});\n\t}", "function getData() {\n return [\n {\n name: 'Apple',\n scoreToday: 62,\n scoreLastYear: 25\n },\n {\n name: 'Banana',\n scoreToday: 90,\n scoreLastYear: 71\n },\n {\n name: 'Peach',\n scoreToday: 43,\n scoreLastYear: 59\n },\n {\n name: 'Orange',\n scoreToday: 65,\n scoreLastYear: 43\n },\n {\n name: 'Lime',\n scoreToday: 88,\n scoreLastYear: 63\n }\n ];\n }", "function gotData(data) {\r\n let idx = 0;\r\n listings = [];\r\n data.forEach((element) => {\r\n let list = new Listing();\r\n list.loadFB(element.val(), idx);\r\n listings.push({'val': list, 'ref': element.ref, 'visible': true, 'simpleView': true,});\r\n idx++;\r\n });\r\n applyFilters();\r\n}", "function loadData(){\n\n\tvar dataCall = $.ajax({\n\t type: 'GET',\n\t url: config.datafile,\n\t dataType: 'text',\n\t});\n\n\tvar geomCall = $.ajax({\n\t type: 'GET',\n\t url: config.geomfile,\n\t dataType: 'json',\n\t});\n\n\t$.when(dataCall,geomCall).then(function(dataArgs,geomArgs){\n\t\tinitDash(d3.csv.parse(dataArgs[0]),geomArgs[0]);\n\t});\n\n}", "async function getData(){\r\n\r\n const xs = [];\r\n const ys = [];\r\n const ns = [];\r\n const ss = []\r\n const response = await fetch(\"ZonAnn.Ts+dSST.csv\");\r\n const data = await response.text();\r\n console.log(data);\r\n\r\n var table = data.split(\"\\n\").slice(1); //removing the headers from the data set. (not important right now.)\r\n table .forEach((element) => {\r\n var columns = element.split(\",\");\r\n var year = columns[0];\r\n xs.push(year); //we're pushing each year into the array of xlabels and then plotting it on the x-axis.\r\n var temperature = columns[1];\r\n ys.push(Number(temperature) + 14); //here the 14 deg Celsius s the global mean from 1951 to 1980ish. \r\n //we're pushing each year into the array of xlabels and then plotting it on the x-axis.\r\n var nHemp = columns[2];\r\n ns.push(Number(nHemp) + 14);\r\n var sHemp = columns[3];\r\n ss.push(Number(sHemp) + 14);\r\n console.log(year + \"\\t\" + temperature + \" \" + nHemp + \" \" + sHemp);\r\n });\r\n return {xs, ys, ns, ss};\r\n}", "function gotAllData(err) {\n console.log(\"gotAllData()\");\n // report an error, you’d want to do something better than this in production\n if (err) {\n console.log(\"error loading data\");\n console.error(err);\n return;\n }\n // call function to show the data\n showData();\n}", "function initial() {\n // select dropdown menu \n var dropdown = d3.select(\"#selDataset\");\n\n // read the data \n d3.json(\"samples.json\").then((data)=> {\n console.log(data)\n\n // get the id data to the dropdwown menu\n data.names.forEach(function(name) {\n dropdown.append(\"option\").text(name).property(\"value\");\n })\n \n\n // call the functions to display the data and the plots to the page\n doplot(data.names[0]);\n getInfo(data.names[0]);\n });\n}", "function getResultDetailed(){\r\n\t\r\n\tif (processDone) {\r\n \r\n\t\t for(var key in Obj_Fetch)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\tvar temp_var={};\r\n\t\t\t\t\t\ttemp_var.cancertypedetailed=key;\r\n\t\t\t\t\t\ttemp_var.male=Obj_Fetch[key].MALE;\r\n\t\t\t\t\t\ttemp_var.female=Obj_Fetch[key].FEMALE;\r\n\t\t\t\t\t\tfetch_data_array.push(temp_var);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\taddScatterPlotDetailed(fetch_data_array);\r\n\t\t\t\t\t\tconsole.log(fetch_data_array);\r\n\r\n } else {\r\n setTimeout(getResult, 250);\r\n }\r\n }", "function demographicData(selection) {\n // view data again\n d3.json('samples.json').then((data) => {\n // console.log(data)\n // all metadata\n var metaData = data.metadata\n // console.log(metaData);\n // selection metadata\n var selectionMD = metaData.filter(meta => meta.id.toString() === selection)[0];\n // console.log(selectionMD)\n // select demographic info from HTML-line31\n var demographicInfo = d3.select(\"#sample-metadata\")\n // clear out info for new id\n demographicInfo.html(\"\");\n // add to html\n Object.entries(selectionMD).forEach((key) => {\n demographicInfo.append(\"h5\").text(key[0].toUpperCase() + \": \" + key[1] + \"\\n\");\n });\n });\n\n}" ]
[ "0.6935823", "0.6932973", "0.68572956", "0.68111944", "0.6731942", "0.6709401", "0.6687431", "0.6643146", "0.6612664", "0.66000646", "0.6579407", "0.65738785", "0.65654385", "0.6513586", "0.6486394", "0.6431203", "0.6425973", "0.6425973", "0.6392435", "0.6371812", "0.6354434", "0.6306185", "0.6277704", "0.6256344", "0.6221993", "0.6217336", "0.62169904", "0.62101835", "0.6204212", "0.61991", "0.61913407", "0.6160876", "0.6160785", "0.6150915", "0.61478895", "0.61340183", "0.61240613", "0.6103488", "0.6102616", "0.6098992", "0.6084598", "0.608225", "0.6077432", "0.60760933", "0.60692996", "0.60692924", "0.60607046", "0.60593945", "0.60499597", "0.603987", "0.602332", "0.60221446", "0.6015564", "0.60133857", "0.5999378", "0.5997415", "0.59865075", "0.5985306", "0.5976667", "0.5973491", "0.5970683", "0.59679973", "0.5967399", "0.5952128", "0.5946692", "0.5946692", "0.5942972", "0.59413856", "0.59396404", "0.5936677", "0.59364194", "0.593521", "0.59242666", "0.5921896", "0.59195304", "0.5914116", "0.59098154", "0.5908598", "0.59049606", "0.58934027", "0.5893166", "0.58916324", "0.58812463", "0.58800644", "0.5879801", "0.5879708", "0.5872959", "0.5871987", "0.5868623", "0.5861119", "0.5861119", "0.5859737", "0.585263", "0.58509773", "0.58504575", "0.5838887", "0.58359337", "0.5835203", "0.5832878", "0.5831355", "0.5831321" ]
0.0
-1
eu and ru have different entity_iditem_id mappings so we need to get these mappings when region changes
async function getItemManifest(region) { if (region == 'eu') { const euResponse = await axios.get(euManifest); return euResponse.data; } else if (region == 'ru') { const ruResponse = await axios.get(ruManifest); return ruResponse.data; } else { const response = await axios.get(ruManifest); return response.data; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function valCountriesAndRegions() { \n var rcrdsObj = entityObj.curRcrds;\n var countries = buildCountryRefObj(); \n \n for (var locDesc in rcrdsObj) { checkCntryAndRegion(rcrdsObj[locDesc]); }\n\n function checkCntryAndRegion(rcrdsAry) { //console.log(\"checkCntryAndRegion called. rcrdsAry = %O\", rcrdsAry)\n rcrdsAry.forEach(function(rcrd){\n if (rcrd.country === null) { return; }\n if (rcrd.country in countries) { //console.log(\"----country key found\")\n checkRegion(rcrd)\n } else if (countryCanBeDetermined(rcrd.country, rcrd)) { //console.log(\"--------country can be determined\") \n checkRegion(rcrd)\n } else { console.log(\"unable to determine country = %s, rcrd = %O \", rcrd.country, rcrd) }\n });\n\n function countryCanBeDetermined(cntryStr, rcrd) {\n if (cntryStrInCntryKey(cntryStr, rcrd) || cntryHasNameVariant(cntryStr, rcrd)) {\n return true;\n } else { return false; }\n } \n function cntryStrInCntryKey(cntryStr, rcrd) {\n var capsCntry = cntryStr.toUpperCase();\n\n for (var cntryKey in countries) {\n var capsCntryKey = cntryKey.toUpperCase(); \n if (capsCntryKey.search(capsCntry) !== -1) { //console.log(\"cntryStrInCntryKey found. org = %s, new = %s\", cntryStr, cntryKey)\n rcrd.country = cntryKey;\n return true; \n }\n }\n }\n function cntryHasNameVariant(cntryStr, rcrd) {\n var nameVariations = { \n \"USA\": \"United States\",\n \"US Virgin Islands\": \"Virgin Islands, U.S.\",\n \"Niue Island\": \"Niue\",\n \"Java\": \"Indonesia\",\n };\n if (cntryStr in nameVariations) { //console.log(\"cntryHasNameVariant. org = %s, new = %s\", cntryStr, nameVariations[cntryStr])\n rcrd.country = nameVariations[cntryStr];\n return true; \n }\n }\n function checkRegion(rcrd) { \n var cntryRegion = countries[rcrd.country];// console.log(\"cntryRegion = \", cntryRegion);\n if (rcrd.region === null) { rcrd.region = cntryRegion; //console.log(\"------------region null.\") \n } else if (rcrd.region === cntryRegion) { //console.log(\"------------regions equal\") \n } else if ( regionCanBeDetermined() ) {// console.log(\"--------regions can be determined\") \n } else { console.log(\"unable to determine region. rcrd = %O\", rcrd) }\n \n function regionCanBeDetermined() { //console.log(\"regionCanBeDetermined?? region = %s, rcrd = %O\", rcrd.region, rcrd) \n var nameVariations = {\n \"Caribbean\": \"Caribbean Islands\",\n \"West Africa\": \"Sub-Saharan Africa\",\n }\n if (rcrd.region in nameVariations) { //console.log(\"regionCanBeDetermined. org = %s, new = %s, rcrd = %O\", rcrd.region, nameVariations[rcrd.region], rcrd)\n rcrd.region = nameVariations[rcrd.region];\n return true; \n } else if (rcrd.country === \"Mexico\" && rcrd.region === \"North America\") {\n rcrd.region = \"Central America\";\n return true; \n } else { return false; }\n }\n } /* End checkRegion */\n } /* End checkCntryAndRegion */\n }", "function loadAdditionalIso2Mappings () {\n const variants = {\n 'Kuna Yala': 'Guna Yala',\n 'Comarca Guna Yala': 'Guna Yala',\n 'Darien': 'Darién',\n 'Emberá': 'Embera Wounaan',\n 'Ngäbe-Buglé': 'Ngöbe-Buglé',\n 'Comarca Ngäbe Buglé': 'Ngöbe-Buglé'\n }\n Object.keys(variants).forEach(k => {\n provinceIso2[k] = provinceIso2[variants[k]]\n })\n Object.keys(provinceIso2).forEach(k => {\n provinceIso2[k.toUpperCase()] = provinceIso2[k]\n })\n}", "function loadAllRegions() {\n var allRegions = 'ACAC Member, AFCAC Member, LACAC, European Civil Aviation Commission';\n return allRegions.split(/, +/g).map(function (region) {\n var index = 1;\n return {\n value: region.toLowerCase(),\n //value: index++,\n display: region\n };\n });\n }", "function setRegion(id){\n regionId = id;\n}", "getEntities() {\n let _entitiesItems = JSON.parse(JSON.stringify(this._config.entities))\n if (!_entitiesItems || _entitiesItems.length === 0) return\n _entitiesItems.forEach((item) => {\n if (item.entity) {\n const t = item.entity.split(\".\")\n item.id = `${t[0]}.${t[1]}`\n } else {\n item.id = \"OD-\" + Math.floor(Math.random() * 1000)\n }\n })\n return _entitiesItems\n }", "getEntities() {\n let _entitiesItems = JSON.parse(JSON.stringify(this._config.entities))\n if (!_entitiesItems || _entitiesItems.length === 0) return\n _entitiesItems.forEach((item) => {\n if (item.entity) {\n const t = item.entity.split(\".\")\n item.id = `${t[0]}.${t[1]}`\n } else {\n item.id = \"OD-\" + Math.floor(Math.random() * 1000)\n }\n })\n return _entitiesItems\n }", "function SelectedLookupOrganization(item) {\n if (item.data) {\n RateHeaderGeneralCtrl.ePage.Entities.Header.Data.ORG_FK = item.data.entity.PK;\n RateHeaderGeneralCtrl.ePage.Entities.Header.Data.ORG_Code = item.data.entity.Code;\n RateHeaderGeneralCtrl.ePage.Masters.Organization = item.data.entity.Code;\n\n }\n else {\n RateHeaderGeneralCtrl.ePage.Entities.Header.Data.ORG_FK = item.PK;\n RateHeaderGeneralCtrl.ePage.Entities.Header.Data.ORG_Code = item.Code;\n RateHeaderGeneralCtrl.ePage.Masters.Organization = item.Code;\n }\n }", "function isEuCountryCode(twoCharCountryCode) {\n var twoCharCountryCode = twoCharCountryCode || Drupal.settings.tesla.country;\n twoCharCountryCode = twoCharCountryCode.toUpperCase();\n\n var regions_by_country = {\n \"AD\": \"OT\",\n \"AE\": \"OT\",\n \"AF\": \"OT\",\n \"AG\": \"OT\",\n \"AI\": \"OT\",\n \"AL\": \"OT\",\n \"AM\": \"OT\",\n \"AN\": \"OT\",\n \"AO\": \"OT\",\n \"AQ\": \"OT\",\n \"AR\": \"OT\",\n \"AS\": \"OT\",\n \"AT\": \"EU\",\n \"AU\": \"AU\",\n \"AW\": \"OT\",\n \"AZ\": \"OT\",\n \"BA\": \"OT\",\n \"BB\": \"OT\",\n \"BD\": \"OT\",\n \"BE\": \"EU\",\n \"BF\": \"OT\",\n \"BG\": \"EU\",\n \"BH\": \"OT\",\n \"BI\": \"OT\",\n \"BJ\": \"OT\",\n \"BM\": \"OT\",\n \"BN\": \"OT\",\n \"BO\": \"OT\",\n \"BR\": \"OT\",\n \"BS\": \"OT\",\n \"BT\": \"OT\",\n \"BV\": \"OT\",\n \"BW\": \"OT\",\n \"BY\": \"OT\",\n \"BZ\": \"OT\",\n \"CA\": \"CA\",\n \"CC\": \"OT\",\n \"CD\": \"OT\",\n \"CF\": \"OT\",\n \"CG\": \"OT\",\n \"CH\": \"EU\",\n \"CI\": \"OT\",\n \"CK\": \"OT\",\n \"CL\": \"OT\",\n \"CM\": \"OT\",\n \"CN\": \"OT\",\n \"CO\": \"OT\",\n \"CR\": \"OT\",\n \"CU\": \"OT\",\n \"CV\": \"OT\",\n \"CX\": \"OT\",\n \"CY\": \"EU\",\n \"CZ\": \"EU\",\n \"DE\": \"EU\",\n \"DJ\": \"OT\",\n \"DK\": \"EU\",\n \"DM\": \"OT\",\n \"DO\": \"OT\",\n \"DZ\": \"OT\",\n \"EC\": \"OT\",\n \"EE\": \"OT\",\n \"EG\": \"OT\",\n \"EH\": \"OT\",\n \"ER\": \"OT\",\n \"ES\": \"EU\",\n \"EU\": \"EU\",\n \"ET\": \"OT\",\n \"FI\": \"EU\",\n \"FJ\": \"OT\",\n \"FK\": \"OT\",\n \"FM\": \"OT\",\n \"FO\": \"OT\",\n \"FR\": \"EU\",\n \"GA\": \"OT\",\n \"GB\": \"GB\",\n \"GD\": \"OT\",\n \"GE\": \"OT\",\n \"GF\": \"OT\",\n \"GH\": \"OT\",\n \"GI\": \"OT\",\n \"GL\": \"OT\",\n \"GM\": \"OT\",\n \"GN\": \"OT\",\n \"GP\": \"OT\",\n \"GQ\": \"OT\",\n \"GR\": \"EU\",\n \"GS\": \"OT\",\n \"GT\": \"OT\",\n \"GU\": \"OT\",\n \"GW\": \"OT\",\n \"GY\": \"OT\",\n \"HK\": \"HK\",\n \"HM\": \"OT\",\n \"HN\": \"OT\",\n \"HR\": \"EU\",\n \"HT\": \"OT\",\n \"HU\": \"EU\",\n \"ID\": \"OT\",\n \"IE\": \"EU\",\n \"IL\": \"OT\",\n \"IN\": \"OT\",\n \"IO\": \"OT\",\n \"IQ\": \"OT\",\n \"IR\": \"OT\",\n \"IS\": \"EU\",\n \"IT\": \"EU\",\n \"JM\": \"OT\",\n \"JO\": \"OT\",\n \"JP\": \"JP\",\n \"KE\": \"OT\",\n \"KG\": \"OT\",\n \"KH\": \"OT\",\n \"KI\": \"OT\",\n \"KM\": \"OT\",\n \"KN\": \"OT\",\n \"KP\": \"OT\",\n \"KR\": \"OT\",\n \"KW\": \"OT\",\n \"KY\": \"OT\",\n \"KZ\": \"OT\",\n \"LA\": \"OT\",\n \"LB\": \"OT\",\n \"LC\": \"OT\",\n \"LI\": \"EU\",\n \"LK\": \"OT\",\n \"LR\": \"OT\",\n \"LS\": \"OT\",\n \"LT\": \"OT\",\n \"LU\": \"EU\",\n \"LV\": \"OT\",\n \"LY\": \"OT\",\n \"MA\": \"OT\",\n \"MC\": \"EU\",\n \"MD\": \"OT\",\n \"ME\": \"OT\",\n \"MG\": \"OT\",\n \"MH\": \"OT\",\n \"MK\": \"OT\",\n \"ML\": \"OT\",\n \"MM\": \"OT\",\n \"MN\": \"OT\",\n \"MO\": \"MO\",\n \"MP\": \"OT\",\n \"MQ\": \"OT\",\n \"MR\": \"OT\",\n \"MS\": \"OT\",\n \"MT\": \"EU\",\n \"MU\": \"OT\",\n \"MV\": \"OT\",\n \"MW\": \"OT\",\n \"MX\": \"OT\",\n \"MY\": \"OT\",\n \"MZ\": \"OT\",\n \"NA\": \"OT\",\n \"NC\": \"OT\",\n \"NE\": \"OT\",\n \"NF\": \"OT\",\n \"NG\": \"OT\",\n \"NI\": \"OT\",\n \"NL\": \"EU\",\n \"NO\": \"EU\",\n \"NP\": \"OT\",\n \"NR\": \"OT\",\n \"NU\": \"OT\",\n \"NZ\": \"OT\",\n \"OM\": \"OT\",\n \"PA\": \"OT\",\n \"PE\": \"OT\",\n \"PF\": \"OT\",\n \"PG\": \"OT\",\n \"PH\": \"OT\",\n \"PK\": \"OT\",\n \"PL\": \"OT\",\n \"PM\": \"OT\",\n \"PN\": \"OT\",\n \"PR\": \"OT\",\n \"PS\": \"OT\",\n \"PT\": \"OT\",\n \"PW\": \"OT\",\n \"PY\": \"OT\",\n \"QA\": \"OT\",\n \"RE\": \"OT\",\n \"RO\": \"OT\",\n \"RS\": \"OT\",\n \"RU\": \"OT\",\n \"RW\": \"OT\",\n \"SA\": \"OT\",\n \"SB\": \"OT\",\n \"SC\": \"OT\",\n \"SD\": \"OT\",\n \"SE\": \"EU\",\n \"SG\": \"OT\",\n \"SH\": \"OT\",\n \"SI\": \"OT\",\n \"SJ\": \"OT\",\n \"SK\": \"OT\",\n \"SL\": \"OT\",\n \"SM\": \"OT\",\n \"SN\": \"OT\",\n \"SO\": \"OT\",\n \"SR\": \"OT\",\n \"ST\": \"OT\",\n \"SV\": \"OT\",\n \"SY\": \"OT\",\n \"SZ\": \"OT\",\n \"TC\": \"OT\",\n \"TD\": \"OT\",\n \"TF\": \"OT\",\n \"TG\": \"OT\",\n \"TH\": \"OT\",\n \"TJ\": \"OT\",\n \"TK\": \"OT\",\n \"TL\": \"OT\",\n \"TM\": \"OT\",\n \"TN\": \"OT\",\n \"TO\": \"OT\",\n \"TR\": \"OT\",\n \"TT\": \"OT\",\n \"TV\": \"OT\",\n \"TW\": \"OT\",\n \"TZ\": \"OT\",\n \"UA\": \"OT\",\n \"UG\": \"OT\",\n \"UM\": \"OT\",\n \"US\": \"US\",\n \"UY\": \"OT\",\n \"UZ\": \"OT\",\n \"VA\": \"OT\",\n \"VC\": \"OT\",\n \"VE\": \"OT\",\n \"VG\": \"OT\",\n \"VI\": \"OT\",\n \"VN\": \"OT\",\n \"VU\": \"OT\",\n \"WF\": \"OT\",\n \"WS\": \"OT\",\n \"YE\": \"OT\",\n \"YT\": \"OT\",\n \"ZA\": \"OT\",\n \"ZM\": \"OT\",\n \"ZW\": \"OT\"\n };\n\n return regions_by_country[twoCharCountryCode] === \"EU\";\n}", "async getRegionItems(name) {\n const values = await this.cockpit.regionData(name);\n const template = await this.cockpit.regionGet(name);\n return { data: {values, template}, name };\n }", "function getItemIds(items,taxcode){\n \t\t\ttry{\n \t\t\t\tvar columns = ['internalid','name','displayname','internalid'];\n\t \t\t\tvar newItems = [];\n\t \t\t\tfor(var i = 0;i < items.length;i++){\n\t \t\t\t\tvar itemSearch = search.create({\n\t\t \t\t\t\ttype:search.Type.ITEM,\n\t\t \t\t\t\ttitle:'Find item id',\n\t\t \t\t\t\tcolumns:columns,\n\t\t \t\t\t\tfilters:[['name','is',items[i].item]]\n\t\t \t\t\t});\n\n\t\t \t\t\tvar results = itemSearch.run().getRange({start: 0, end: 1000});\n\t\t \t\t\tlog.debug ({\n\t\t title: 'Finding items',\n\t\t details: results.length\n\t\t });\n\n\t\t var internalid = searchResults(results,columns,items[i].item,'name');\n\t\t log.debug ({\n\t\t title: 'item id',\n\t\t details: internalid\n\t\t });\n\t\t newItems.push({\n\t\t \titem:internalid,\n\t\t \tquantity:items[i].quantity,\n\t\t \ttaxcode:taxcode,\n\t\t \tprice:items[i].price,\n\t\t \trate:items[i].rate\n\t\t })\n\t \t\t\t}\n\n\t return newItems;\n \t\t\t}\n \t\t\tcatch(err){\n \t\t\t\tlog.error({\n\t\t\t\t\ttitle:err.name + ' error getting item ids',\n\t\t\t\t\tdetails:err\n\t\t\t\t});\n \t\t\t}\n \t\t\t\n \t\t}", "keyFromId(aItemId) {\n return this._itemIdKeyMap.get(aItemId);\n }", "function findRegion(country) {\n\tvar region = autoRegionMap[country];\n\tif (region) {\n\t\t$(\"#selRegion\").val(region);\n\t\t$(\"#selRegionEdit\").val(region);\n\t}\n}", "function get_map(){\n var filter = get_filter_params();\n fetch_map_values(filter);\n\n //si une region (ville ou pays) est selectionnee on raffraichit aussi la liste correspondante\n if(selected_region.type){\n //on ajoute le parametre country_id\n var country_or_city_json = $.parseJSON('{\"'+selected_region.type+'\":\"'+selected_region.id+'\"}');\n //on join les trois tableaux de parametres\n $.extend(filter,country_or_city_json);\n new_search('get_experiences_map',filter);\n }\n}", "static async _injectRegions(event) {\n try {\n let regions = await EventsAPI.getRegions(event.eventID);\n regions = regions.map(EventsAPI._reformatIncomingRegion);\n return {\n ...event,\n regions: _.keyBy(regions, \"regionID\")\n };\n } catch (err) {\n console.error(\n `Failed to fetch regions for ${event.name} (eventID: ${\n event.eventID\n }). Check the EventsAPI._injectRegions function in 'api/index.js'`,\n err\n );\n return {\n ...event,\n regions: {}\n };\n }\n }", "function getRegionFromCountry(cc) {\n var region;\n for (var regionKey in LoLRegions) {\n var countries = LoLRegions[regionKey].countries;\n _.forOwn(countries, function(key, countryIndex) {\n if (cc == countries[countryIndex]) {\n region = LoLRegions[regionKey];\n return LoLRegions[regionKey];\n }\n });\n }\n\n //if no region, set name to noserver\n if (!region) {\n region = {name: 'noserver'};\n }\n return region;\n }", "getEntityIds() {\n return Object.keys(this.items)\n }", "function parseRegion(post, type, assetsById) {\n return (post[type] || []).map((region, index) => {\n const id = `${post.id}-${index}`\n const assetId = deepGet(region, ['links', 'assets'])\n const asset = assetsById[assetId]\n let data = null\n if (typeof region.data === 'object') {\n data = camelizeKeys(region.data)\n } else {\n data = region.data\n }\n if (region.kind === 'image' && typeof assetId === 'string' && asset) {\n return { ...region, data, id, asset }\n }\n return { ...region, data, id }\n })\n}", "get regions() {\n return this.getNodeByVariableCollectionId('regions').variableCollection;\n }", "function common_getProvinceCityMap(){\n var common_provinceCityMap = {\n \"1\": [\n {\n \"id\": 72,\n \"name\": \"朝阳区\"\n },\n {\n \"id\": 2800,\n \"name\": \"海淀区\"\n },\n {\n \"id\": 2801,\n \"name\": \"西城区\"\n },\n {\n \"id\": 2802,\n \"name\": \"东城区\"\n },\n {\n \"id\": 2803,\n \"name\": \"崇文区\"\n },\n {\n \"id\": 2804,\n \"name\": \"宣武区\"\n },\n {\n \"id\": 2805,\n \"name\": \"丰台区\"\n },\n {\n \"id\": 2806,\n \"name\": \"石景山区\"\n },\n {\n \"id\": 2807,\n \"name\": \"门头沟\"\n },\n {\n \"id\": 2808,\n \"name\": \"房山区\"\n },\n {\n \"id\": 2809,\n \"name\": \"通州区\"\n },\n {\n \"id\": 2810,\n \"name\": \"大兴区\"\n },\n {\n \"id\": 2812,\n \"name\": \"顺义区\"\n },\n {\n \"id\": 2814,\n \"name\": \"怀柔区\"\n },\n {\n \"id\": 2816,\n \"name\": \"密云区\"\n },\n {\n \"id\": 2901,\n \"name\": \"昌平区\"\n },\n {\n \"id\": 2953,\n \"name\": \"平谷区\"\n },\n {\n \"id\": 3065,\n \"name\": \"延庆县\"\n }],\n \"2\": [\n {\n \"id\": 2813,\n \"name\": \"徐汇区\"\n },\n {\n \"id\": 2815,\n \"name\": \"长宁区\"\n },\n {\n \"id\": 2817,\n \"name\": \"静安区\"\n },\n {\n \"id\": 2820,\n \"name\": \"闸北区\"\n },\n {\n \"id\": 2822,\n \"name\": \"虹口区\"\n },\n {\n \"id\": 2823,\n \"name\": \"杨浦区\"\n },\n {\n \"id\": 2824,\n \"name\": \"宝山区\"\n },\n {\n \"id\": 2825,\n \"name\": \"闵行区\"\n },\n {\n \"id\": 2826,\n \"name\": \"嘉定区\"\n },\n {\n \"id\": 2830,\n \"name\": \"浦东新区\"\n },\n {\n \"id\": 2833,\n \"name\": \"青浦区\"\n },\n {\n \"id\": 2834,\n \"name\": \"松江区\"\n },\n {\n \"id\": 2835,\n \"name\": \"金山区\"\n },\n {\n \"id\": 2837,\n \"name\": \"奉贤区\"\n },\n {\n \"id\": 2841,\n \"name\": \"普陀区\"\n },\n {\n \"id\": 2919,\n \"name\": \"崇明县\"\n },\n {\n \"id\": 78,\n \"name\": \"黄浦区\"\n }],\n \"3\": [\n {\n \"id\": 51035,\n \"name\": \"东丽区\"\n },\n {\n \"id\": 51036,\n \"name\": \"和平区\"\n },\n {\n \"id\": 51037,\n \"name\": \"河北区\"\n },\n {\n \"id\": 51038,\n \"name\": \"河东区\"\n },\n {\n \"id\": 51039,\n \"name\": \"河西区\"\n },\n {\n \"id\": 51040,\n \"name\": \"红桥区\"\n },\n {\n \"id\": 51041,\n \"name\": \"蓟县\"\n },\n {\n \"id\": 51042,\n \"name\": \"静海县\"\n },\n {\n \"id\": 51043,\n \"name\": \"南开区\"\n },\n {\n \"id\": 51044,\n \"name\": \"塘沽区\"\n },\n {\n \"id\": 51045,\n \"name\": \"西青区\"\n },\n {\n \"id\": 51046,\n \"name\": \"武清区\"\n },\n {\n \"id\": 51047,\n \"name\": \"津南区\"\n },\n {\n \"id\": 51048,\n \"name\": \"汉沽区\"\n },\n {\n \"id\": 51049,\n \"name\": \"大港区\"\n },\n {\n \"id\": 51050,\n \"name\": \"北辰区\"\n },\n {\n \"id\": 51051,\n \"name\": \"宝坻区\"\n },\n {\n \"id\": 51052,\n \"name\": \"宁河县\"\n }],\n \"4\": [\n {\n \"id\": 113,\n \"name\": \"万州区\"\n },\n {\n \"id\": 114,\n \"name\": \"涪陵区\"\n },\n {\n \"id\": 115,\n \"name\": \"梁平县\"\n },\n {\n \"id\": 119,\n \"name\": \"南川区\"\n },\n {\n \"id\": 123,\n \"name\": \"潼南县\"\n },\n {\n \"id\": 126,\n \"name\": \"大足区\"\n },\n {\n \"id\": 128,\n \"name\": \"黔江区\"\n },\n {\n \"id\": 129,\n \"name\": \"武隆县\"\n },\n {\n \"id\": 130,\n \"name\": \"丰都县\"\n },\n {\n \"id\": 131,\n \"name\": \"奉节县\"\n },\n {\n \"id\": 132,\n \"name\": \"开县\"\n },\n {\n \"id\": 133,\n \"name\": \"云阳县\"\n },\n {\n \"id\": 134,\n \"name\": \"忠县\"\n },\n {\n \"id\": 135,\n \"name\": \"巫溪县\"\n },\n {\n \"id\": 136,\n \"name\": \"巫山县\"\n },\n {\n \"id\": 137,\n \"name\": \"石柱县\"\n },\n {\n \"id\": 138,\n \"name\": \"彭水县\"\n },\n {\n \"id\": 139,\n \"name\": \"垫江县\"\n },\n {\n \"id\": 140,\n \"name\": \"酉阳县\"\n },\n {\n \"id\": 141,\n \"name\": \"秀山县\"\n },\n {\n \"id\": 48131,\n \"name\": \"璧山县\"\n },\n {\n \"id\": 48132,\n \"name\": \"荣昌县\"\n },\n {\n \"id\": 48133,\n \"name\": \"铜梁县\"\n },\n {\n \"id\": 48201,\n \"name\": \"合川区\"\n },\n {\n \"id\": 48202,\n \"name\": \"巴南区\"\n },\n {\n \"id\": 48203,\n \"name\": \"北碚区\"\n },\n {\n \"id\": 48204,\n \"name\": \"江津区\"\n },\n {\n \"id\": 48205,\n \"name\": \"渝北区\"\n },\n {\n \"id\": 48206,\n \"name\": \"长寿区\"\n },\n {\n \"id\": 48207,\n \"name\": \"永川区\"\n },\n {\n \"id\": 50950,\n \"name\": \"江北区\"\n },\n {\n \"id\": 50951,\n \"name\": \"南岸区\"\n },\n {\n \"id\": 50952,\n \"name\": \"九龙坡区\"\n },\n {\n \"id\": 50953,\n \"name\": \"沙坪坝区\"\n },\n {\n \"id\": 50954,\n \"name\": \"大渡口区\"\n },\n {\n \"id\": 50995,\n \"name\": \"綦江区\"\n },\n {\n \"id\": 51026,\n \"name\": \"渝中区\"\n },\n {\n \"id\": 51027,\n \"name\": \"高新区\"\n },\n {\n \"id\": 51028,\n \"name\": \"北部新区\"\n },\n {\n \"id\": 4164,\n \"name\": \"城口县\"\n }],\n \"5\": [\n {\n \"id\": 142,\n \"name\": \"石家庄市\"\n },\n {\n \"id\": 148,\n \"name\": \"邯郸市\"\n },\n {\n \"id\": 164,\n \"name\": \"邢台市\"\n },\n {\n \"id\": 199,\n \"name\": \"保定市\"\n },\n {\n \"id\": 224,\n \"name\": \"张家口市\"\n },\n {\n \"id\": 239,\n \"name\": \"承德市\"\n },\n {\n \"id\": 248,\n \"name\": \"秦皇岛市\"\n },\n {\n \"id\": 258,\n \"name\": \"唐山市\"\n },\n {\n \"id\": 264,\n \"name\": \"沧州市\"\n },\n {\n \"id\": 274,\n \"name\": \"廊坊市\"\n },\n {\n \"id\": 275,\n \"name\": \"衡水市\"\n }],\n \"6\": [\n {\n \"id\": 303,\n \"name\": \"太原市\"\n },\n {\n \"id\": 309,\n \"name\": \"大同市\"\n },\n {\n \"id\": 318,\n \"name\": \"阳泉市\"\n },\n {\n \"id\": 325,\n \"name\": \"晋城市\"\n },\n {\n \"id\": 330,\n \"name\": \"朔州市\"\n },\n {\n \"id\": 336,\n \"name\": \"晋中市\"\n },\n {\n \"id\": 350,\n \"name\": \"忻州市\"\n },\n {\n \"id\": 368,\n \"name\": \"吕梁市\"\n },\n {\n \"id\": 379,\n \"name\": \"临汾市\"\n },\n {\n \"id\": 398,\n \"name\": \"运城市\"\n },\n {\n \"id\": 3074,\n \"name\": \"长治市\"\n }],\n \"7\": [\n {\n \"id\": 412,\n \"name\": \"郑州市\"\n },\n {\n \"id\": 420,\n \"name\": \"开封市\"\n },\n {\n \"id\": 427,\n \"name\": \"洛阳市\"\n },\n {\n \"id\": 438,\n \"name\": \"平顶山市\"\n },\n {\n \"id\": 446,\n \"name\": \"焦作市\"\n },\n {\n \"id\": 454,\n \"name\": \"鹤壁市\"\n },\n {\n \"id\": 458,\n \"name\": \"新乡市\"\n },\n {\n \"id\": 468,\n \"name\": \"安阳市\"\n },\n {\n \"id\": 475,\n \"name\": \"濮阳市\"\n },\n {\n \"id\": 482,\n \"name\": \"许昌市\"\n },\n {\n \"id\": 489,\n \"name\": \"漯河市\"\n },\n {\n \"id\": 495,\n \"name\": \"三门峡市\"\n },\n {\n \"id\": 502,\n \"name\": \"南阳市\"\n },\n {\n \"id\": 517,\n \"name\": \"商丘市\"\n },\n {\n \"id\": 527,\n \"name\": \"周口市\"\n },\n {\n \"id\": 538,\n \"name\": \"驻马店市\"\n },\n {\n \"id\": 549,\n \"name\": \"信阳市\"\n },\n {\n \"id\": 2780,\n \"name\": \"济源市\"\n }],\n \"8\": [\n {\n \"id\": 560,\n \"name\": \"沈阳市\"\n },\n {\n \"id\": 573,\n \"name\": \"大连市\"\n },\n {\n \"id\": 579,\n \"name\": \"鞍山市\"\n },\n {\n \"id\": 584,\n \"name\": \"抚顺市\"\n },\n {\n \"id\": 589,\n \"name\": \"本溪市\"\n },\n {\n \"id\": 593,\n \"name\": \"丹东市\"\n },\n {\n \"id\": 598,\n \"name\": \"锦州市\"\n },\n {\n \"id\": 604,\n \"name\": \"葫芦岛市\"\n },\n {\n \"id\": 609,\n \"name\": \"营口市\"\n },\n {\n \"id\": 613,\n \"name\": \"盘锦市\"\n },\n {\n \"id\": 617,\n \"name\": \"阜新市\"\n },\n {\n \"id\": 621,\n \"name\": \"辽阳市\"\n },\n {\n \"id\": 632,\n \"name\": \"朝阳市\"\n },\n {\n \"id\": 6858,\n \"name\": \"铁岭市\"\n }],\n \"9\": [\n {\n \"id\": 639,\n \"name\": \"长春市\"\n },\n {\n \"id\": 644,\n \"name\": \"吉林市\"\n },\n {\n \"id\": 651,\n \"name\": \"四平市\"\n },\n {\n \"id\": 2992,\n \"name\": \"辽源市\"\n },\n {\n \"id\": 657,\n \"name\": \"通化市\"\n },\n {\n \"id\": 664,\n \"name\": \"白山市\"\n },\n {\n \"id\": 674,\n \"name\": \"松原市\"\n },\n {\n \"id\": 681,\n \"name\": \"白城市\"\n },\n {\n \"id\": 687,\n \"name\": \"延边州\"\n }],\n \"10\": [\n {\n \"id\": 727,\n \"name\": \"鹤岗市\"\n },\n {\n \"id\": 731,\n \"name\": \"双鸭山市\"\n },\n {\n \"id\": 737,\n \"name\": \"鸡西市\"\n },\n {\n \"id\": 742,\n \"name\": \"大庆市\"\n },\n {\n \"id\": 753,\n \"name\": \"伊春市\"\n },\n {\n \"id\": 757,\n \"name\": \"牡丹江市\"\n },\n {\n \"id\": 765,\n \"name\": \"佳木斯市\"\n },\n {\n \"id\": 773,\n \"name\": \"七台河市\"\n },\n {\n \"id\": 776,\n \"name\": \"黑河市\"\n },\n {\n \"id\": 782,\n \"name\": \"绥化市\"\n },\n {\n \"id\": 793,\n \"name\": \"大兴安岭地区\"\n },\n {\n \"id\": 698,\n \"name\": \"哈尔滨市\"\n },\n {\n \"id\": 712,\n \"name\": \"齐齐哈尔市\"\n }],\n \"11\": [\n {\n \"id\": 799,\n \"name\": \"呼和浩特市\"\n },\n {\n \"id\": 805,\n \"name\": \"包头市\"\n },\n {\n \"id\": 810,\n \"name\": \"乌海市\"\n },\n {\n \"id\": 812,\n \"name\": \"赤峰市\"\n },\n {\n \"id\": 823,\n \"name\": \"乌兰察布市\"\n },\n {\n \"id\": 835,\n \"name\": \"锡林郭勒盟\"\n },\n {\n \"id\": 848,\n \"name\": \"呼伦贝尔市\"\n },\n {\n \"id\": 870,\n \"name\": \"鄂尔多斯市\"\n },\n {\n \"id\": 880,\n \"name\": \"巴彦淖尔市\"\n },\n {\n \"id\": 891,\n \"name\": \"阿拉善盟\"\n },\n {\n \"id\": 895,\n \"name\": \"兴安盟\"\n },\n {\n \"id\": 902,\n \"name\": \"通辽市\"\n }],\n \"12\": [\n {\n \"id\": 904,\n \"name\": \"南京市\"\n },\n {\n \"id\": 911,\n \"name\": \"徐州市\"\n },\n {\n \"id\": 919,\n \"name\": \"连云港市\"\n },\n {\n \"id\": 925,\n \"name\": \"淮安市\"\n },\n {\n \"id\": 933,\n \"name\": \"宿迁市\"\n },\n {\n \"id\": 939,\n \"name\": \"盐城市\"\n },\n {\n \"id\": 951,\n \"name\": \"扬州市\"\n },\n {\n \"id\": 959,\n \"name\": \"泰州市\"\n },\n {\n \"id\": 965,\n \"name\": \"南通市\"\n },\n {\n \"id\": 972,\n \"name\": \"镇江市\"\n },\n {\n \"id\": 978,\n \"name\": \"常州市\"\n },\n {\n \"id\": 984,\n \"name\": \"无锡市\"\n },\n {\n \"id\": 988,\n \"name\": \"苏州市\"\n }],\n \"13\": [\n {\n \"id\": 2900,\n \"name\": \"济宁市\"\n },\n {\n \"id\": 1000,\n \"name\": \"济南市\"\n },\n {\n \"id\": 1007,\n \"name\": \"青岛市\"\n },\n {\n \"id\": 1016,\n \"name\": \"淄博市\"\n },\n {\n \"id\": 1022,\n \"name\": \"枣庄市\"\n },\n {\n \"id\": 1025,\n \"name\": \"东营市\"\n },\n {\n \"id\": 1032,\n \"name\": \"潍坊市\"\n },\n {\n \"id\": 1042,\n \"name\": \"烟台市\"\n },\n {\n \"id\": 1053,\n \"name\": \"威海市\"\n },\n {\n \"id\": 1058,\n \"name\": \"莱芜市\"\n },\n {\n \"id\": 1060,\n \"name\": \"德州市\"\n },\n {\n \"id\": 1072,\n \"name\": \"临沂市\"\n },\n {\n \"id\": 1081,\n \"name\": \"聊城市\"\n },\n {\n \"id\": 1090,\n \"name\": \"滨州市\"\n },\n {\n \"id\": 1099,\n \"name\": \"菏泽市\"\n },\n {\n \"id\": 1108,\n \"name\": \"日照市\"\n },\n {\n \"id\": 1112,\n \"name\": \"泰安市\"\n }],\n \"14\": [\n {\n \"id\": 1151,\n \"name\": \"黄山市\"\n },\n {\n \"id\": 1159,\n \"name\": \"滁州市\"\n },\n {\n \"id\": 1167,\n \"name\": \"阜阳市\"\n },\n {\n \"id\": 1174,\n \"name\": \"亳州市\"\n },\n {\n \"id\": 1180,\n \"name\": \"宿州市\"\n },\n {\n \"id\": 1201,\n \"name\": \"池州市\"\n },\n {\n \"id\": 1206,\n \"name\": \"六安市\"\n },\n {\n \"id\": 2971,\n \"name\": \"宣城市\"\n },\n {\n \"id\": 1114,\n \"name\": \"铜陵市\"\n },\n {\n \"id\": 1116,\n \"name\": \"合肥市\"\n },\n {\n \"id\": 1121,\n \"name\": \"淮南市\"\n },\n {\n \"id\": 1124,\n \"name\": \"淮北市\"\n },\n {\n \"id\": 1127,\n \"name\": \"芜湖市\"\n },\n {\n \"id\": 1132,\n \"name\": \"蚌埠市\"\n },\n {\n \"id\": 1137,\n \"name\": \"马鞍山市\"\n },\n {\n \"id\": 1140,\n \"name\": \"安庆市\"\n }],\n \"15\": [\n {\n \"id\": 1158,\n \"name\": \"宁波市\"\n },\n {\n \"id\": 1273,\n \"name\": \"衢州市\"\n },\n {\n \"id\": 1280,\n \"name\": \"丽水市\"\n },\n {\n \"id\": 1290,\n \"name\": \"台州市\"\n },\n {\n \"id\": 1298,\n \"name\": \"舟山市\"\n },\n {\n \"id\": 1213,\n \"name\": \"杭州市\"\n },\n {\n \"id\": 1233,\n \"name\": \"温州市\"\n },\n {\n \"id\": 1243,\n \"name\": \"嘉兴市\"\n },\n {\n \"id\": 1250,\n \"name\": \"湖州市\"\n },\n {\n \"id\": 1255,\n \"name\": \"绍兴市\"\n },\n {\n \"id\": 1262,\n \"name\": \"金华市\"\n }],\n \"16\": [\n {\n \"id\": 1303,\n \"name\": \"福州市\"\n },\n {\n \"id\": 1315,\n \"name\": \"厦门市\"\n },\n {\n \"id\": 1317,\n \"name\": \"三明市\"\n },\n {\n \"id\": 1329,\n \"name\": \"莆田市\"\n },\n {\n \"id\": 1332,\n \"name\": \"泉州市\"\n },\n {\n \"id\": 1341,\n \"name\": \"漳州市\"\n },\n {\n \"id\": 1352,\n \"name\": \"南平市\"\n },\n {\n \"id\": 1362,\n \"name\": \"龙岩市\"\n },\n {\n \"id\": 1370,\n \"name\": \"宁德市\"\n }],\n \"17\": [\n {\n \"id\": 1432,\n \"name\": \"孝感市\"\n },\n {\n \"id\": 1441,\n \"name\": \"黄冈市\"\n },\n {\n \"id\": 1458,\n \"name\": \"咸宁市\"\n },\n {\n \"id\": 1466,\n \"name\": \"恩施州\"\n },\n {\n \"id\": 1475,\n \"name\": \"鄂州市\"\n },\n {\n \"id\": 1477,\n \"name\": \"荆门市\"\n },\n {\n \"id\": 1479,\n \"name\": \"随州市\"\n },\n {\n \"id\": 3154,\n \"name\": \"神农架林区\"\n },\n {\n \"id\": 1381,\n \"name\": \"武汉市\"\n },\n {\n \"id\": 1387,\n \"name\": \"黄石市\"\n },\n {\n \"id\": 1396,\n \"name\": \"襄阳市\"\n },\n {\n \"id\": 1405,\n \"name\": \"十堰市\"\n },\n {\n \"id\": 1413,\n \"name\": \"荆州市\"\n },\n {\n \"id\": 1421,\n \"name\": \"宜昌市\"\n },\n {\n \"id\": 2922,\n \"name\": \"潜江市\"\n },\n {\n \"id\": 2980,\n \"name\": \"天门市\"\n },\n {\n \"id\": 2983,\n \"name\": \"仙桃市\"\n }],\n \"18\": [\n {\n \"id\": 1482,\n \"name\": \"长沙市\"\n },\n {\n \"id\": 1488,\n \"name\": \"株洲市\"\n },\n {\n \"id\": 1495,\n \"name\": \"湘潭市\"\n },\n {\n \"id\": 1501,\n \"name\": \"衡阳市\"\n },\n {\n \"id\": 1511,\n \"name\": \"邵阳市\"\n },\n {\n \"id\": 1522,\n \"name\": \"岳阳市\"\n },\n {\n \"id\": 1530,\n \"name\": \"常德市\"\n },\n {\n \"id\": 1540,\n \"name\": \"张家界市\"\n },\n {\n \"id\": 1544,\n \"name\": \"郴州市\"\n },\n {\n \"id\": 1555,\n \"name\": \"益阳市\"\n },\n {\n \"id\": 1560,\n \"name\": \"永州市\"\n },\n {\n \"id\": 1574,\n \"name\": \"怀化市\"\n },\n {\n \"id\": 1586,\n \"name\": \"娄底市\"\n },\n {\n \"id\": 1592,\n \"name\": \"湘西州\"\n }],\n \"19\": [\n {\n \"id\": 1601,\n \"name\": \"广州市\"\n },\n {\n \"id\": 1607,\n \"name\": \"深圳市\"\n },\n {\n \"id\": 1609,\n \"name\": \"珠海市\"\n },\n {\n \"id\": 1611,\n \"name\": \"汕头市\"\n },\n {\n \"id\": 1617,\n \"name\": \"韶关市\"\n },\n {\n \"id\": 1627,\n \"name\": \"河源市\"\n },\n {\n \"id\": 1634,\n \"name\": \"梅州市\"\n },\n {\n \"id\": 1709,\n \"name\": \"揭阳市\"\n },\n {\n \"id\": 1643,\n \"name\": \"惠州市\"\n },\n {\n \"id\": 1650,\n \"name\": \"汕尾市\"\n },\n {\n \"id\": 1655,\n \"name\": \"东莞市\"\n },\n {\n \"id\": 1657,\n \"name\": \"中山市\"\n },\n {\n \"id\": 1659,\n \"name\": \"江门市\"\n },\n {\n \"id\": 1666,\n \"name\": \"佛山市\"\n },\n {\n \"id\": 1672,\n \"name\": \"阳江市\"\n },\n {\n \"id\": 1677,\n \"name\": \"湛江市\"\n },\n {\n \"id\": 1684,\n \"name\": \"茂名市\"\n },\n {\n \"id\": 1690,\n \"name\": \"肇庆市\"\n },\n {\n \"id\": 1698,\n \"name\": \"云浮市\"\n },\n {\n \"id\": 1704,\n \"name\": \"清远市\"\n },\n {\n \"id\": 1705,\n \"name\": \"潮州市\"\n }],\n \"20\": [\n {\n \"id\": 3168,\n \"name\": \"崇左市\"\n },\n {\n \"id\": 1715,\n \"name\": \"南宁市\"\n },\n {\n \"id\": 1720,\n \"name\": \"柳州市\"\n },\n {\n \"id\": 1726,\n \"name\": \"桂林市\"\n },\n {\n \"id\": 1740,\n \"name\": \"梧州市\"\n },\n {\n \"id\": 1746,\n \"name\": \"北海市\"\n },\n {\n \"id\": 1749,\n \"name\": \"防城港市\"\n },\n {\n \"id\": 1753,\n \"name\": \"钦州市\"\n },\n {\n \"id\": 1757,\n \"name\": \"贵港市\"\n },\n {\n \"id\": 1761,\n \"name\": \"玉林市\"\n },\n {\n \"id\": 1792,\n \"name\": \"贺州市\"\n },\n {\n \"id\": 1806,\n \"name\": \"百色市\"\n },\n {\n \"id\": 1818,\n \"name\": \"河池市\"\n },\n {\n \"id\": 3044,\n \"name\": \"来宾市\"\n }],\n \"21\": [\n {\n \"id\": 1827,\n \"name\": \"南昌市\"\n },\n {\n \"id\": 1832,\n \"name\": \"景德镇市\"\n },\n {\n \"id\": 1836,\n \"name\": \"萍乡市\"\n },\n {\n \"id\": 1842,\n \"name\": \"新余市\"\n },\n {\n \"id\": 1845,\n \"name\": \"九江市\"\n },\n {\n \"id\": 1857,\n \"name\": \"鹰潭市\"\n },\n {\n \"id\": 1861,\n \"name\": \"上饶市\"\n },\n {\n \"id\": 1874,\n \"name\": \"宜春市\"\n },\n {\n \"id\": 1885,\n \"name\": \"抚州市\"\n },\n {\n \"id\": 1898,\n \"name\": \"吉安市\"\n },\n {\n \"id\": 1911,\n \"name\": \"赣州市\"\n }],\n \"22\": [\n {\n \"id\": 2103,\n \"name\": \"凉山州\"\n },\n {\n \"id\": 1930,\n \"name\": \"成都市\"\n },\n {\n \"id\": 1946,\n \"name\": \"自贡市\"\n },\n {\n \"id\": 1950,\n \"name\": \"攀枝花市\"\n },\n {\n \"id\": 1954,\n \"name\": \"泸州市\"\n },\n {\n \"id\": 1960,\n \"name\": \"绵阳市\"\n },\n {\n \"id\": 1962,\n \"name\": \"德阳市\"\n },\n {\n \"id\": 1977,\n \"name\": \"广元市\"\n },\n {\n \"id\": 1983,\n \"name\": \"遂宁市\"\n },\n {\n \"id\": 1988,\n \"name\": \"内江市\"\n },\n {\n \"id\": 1993,\n \"name\": \"乐山市\"\n },\n {\n \"id\": 2005,\n \"name\": \"宜宾市\"\n },\n {\n \"id\": 2016,\n \"name\": \"广安市\"\n },\n {\n \"id\": 2022,\n \"name\": \"南充市\"\n },\n {\n \"id\": 2033,\n \"name\": \"达州市\"\n },\n {\n \"id\": 2042,\n \"name\": \"巴中市\"\n },\n {\n \"id\": 2047,\n \"name\": \"雅安市\"\n },\n {\n \"id\": 2058,\n \"name\": \"眉山市\"\n },\n {\n \"id\": 2065,\n \"name\": \"资阳市\"\n },\n {\n \"id\": 2070,\n \"name\": \"阿坝州\"\n },\n {\n \"id\": 2084,\n \"name\": \"甘孜州\"\n }],\n \"23\": [\n {\n \"id\": 3690,\n \"name\": \"三亚市\"\n },\n {\n \"id\": 3698,\n \"name\": \"文昌市\"\n },\n {\n \"id\": 3699,\n \"name\": \"五指山市\"\n },\n {\n \"id\": 3701,\n \"name\": \"临高县\"\n },\n {\n \"id\": 3702,\n \"name\": \"澄迈县\"\n },\n {\n \"id\": 3703,\n \"name\": \"定安县\"\n },\n {\n \"id\": 3704,\n \"name\": \"屯昌县\"\n },\n {\n \"id\": 3705,\n \"name\": \"昌江县\"\n },\n {\n \"id\": 3706,\n \"name\": \"白沙县\"\n },\n {\n \"id\": 3707,\n \"name\": \"琼中县\"\n },\n {\n \"id\": 3708,\n \"name\": \"陵水县\"\n },\n {\n \"id\": 3709,\n \"name\": \"保亭县\"\n },\n {\n \"id\": 3710,\n \"name\": \"乐东县\"\n },\n {\n \"id\": 3711,\n \"name\": \"三沙市\"\n },\n {\n \"id\": 2121,\n \"name\": \"海口市\"\n },\n {\n \"id\": 3115,\n \"name\": \"琼海市\"\n },\n {\n \"id\": 3137,\n \"name\": \"万宁市\"\n },\n {\n \"id\": 3173,\n \"name\": \"东方市\"\n },\n {\n \"id\": 3034,\n \"name\": \"儋州市\"\n }],\n \"24\": [\n {\n \"id\": 2144,\n \"name\": \"贵阳市\"\n },\n {\n \"id\": 2150,\n \"name\": \"六盘水市\"\n },\n {\n \"id\": 2155,\n \"name\": \"遵义市\"\n },\n {\n \"id\": 2169,\n \"name\": \"铜仁市\"\n },\n {\n \"id\": 2180,\n \"name\": \"毕节市\"\n },\n {\n \"id\": 2189,\n \"name\": \"安顺市\"\n },\n {\n \"id\": 2196,\n \"name\": \"黔西南州\"\n },\n {\n \"id\": 2205,\n \"name\": \"黔东南州\"\n },\n {\n \"id\": 2222,\n \"name\": \"黔南州\"\n }],\n \"25\": [\n {\n \"id\": 4108,\n \"name\": \"迪庆州\"\n },\n {\n \"id\": 2235,\n \"name\": \"昆明市\"\n },\n {\n \"id\": 2247,\n \"name\": \"曲靖市\"\n },\n {\n \"id\": 2258,\n \"name\": \"玉溪市\"\n },\n {\n \"id\": 2270,\n \"name\": \"昭通市\"\n },\n {\n \"id\": 2281,\n \"name\": \"普洱市\"\n },\n {\n \"id\": 2291,\n \"name\": \"临沧市\"\n },\n {\n \"id\": 2298,\n \"name\": \"保山市\"\n },\n {\n \"id\": 2304,\n \"name\": \"丽江市\"\n },\n {\n \"id\": 2309,\n \"name\": \"文山州\"\n },\n {\n \"id\": 2318,\n \"name\": \"红河州\"\n },\n {\n \"id\": 2332,\n \"name\": \"西双版纳州\"\n },\n {\n \"id\": 2336,\n \"name\": \"楚雄州\"\n },\n {\n \"id\": 2347,\n \"name\": \"大理州\"\n },\n {\n \"id\": 2360,\n \"name\": \"德宏州\"\n },\n {\n \"id\": 2366,\n \"name\": \"怒江州\"\n }],\n \"26\": [\n {\n \"id\": 3970,\n \"name\": \"阿里地区\"\n },\n {\n \"id\": 3971,\n \"name\": \"林芝地区\"\n },\n {\n \"id\": 2951,\n \"name\": \"拉萨市\"\n },\n {\n \"id\": 3107,\n \"name\": \"那曲地区\"\n },\n {\n \"id\": 3129,\n \"name\": \"山南地区\"\n },\n {\n \"id\": 3138,\n \"name\": \"昌都地区\"\n },\n {\n \"id\": 3144,\n \"name\": \"日喀则地区\"\n }],\n \"27\": [\n {\n \"id\": 2428,\n \"name\": \"延安市\"\n },\n {\n \"id\": 2442,\n \"name\": \"汉中市\"\n },\n {\n \"id\": 2454,\n \"name\": \"榆林市\"\n },\n {\n \"id\": 2468,\n \"name\": \"商洛市\"\n },\n {\n \"id\": 2476,\n \"name\": \"安康市\"\n },\n {\n \"id\": 2376,\n \"name\": \"西安市\"\n },\n {\n \"id\": 2386,\n \"name\": \"铜川市\"\n },\n {\n \"id\": 2390,\n \"name\": \"宝鸡市\"\n },\n {\n \"id\": 2402,\n \"name\": \"咸阳市\"\n },\n {\n \"id\": 2416,\n \"name\": \"渭南市\"\n }],\n \"28\": [\n {\n \"id\": 2525,\n \"name\": \"庆阳市\"\n },\n {\n \"id\": 2534,\n \"name\": \"陇南市\"\n },\n {\n \"id\": 2544,\n \"name\": \"武威市\"\n },\n {\n \"id\": 2549,\n \"name\": \"张掖市\"\n },\n {\n \"id\": 2556,\n \"name\": \"酒泉市\"\n },\n {\n \"id\": 2564,\n \"name\": \"甘南州\"\n },\n {\n \"id\": 2573,\n \"name\": \"临夏州\"\n },\n {\n \"id\": 3080,\n \"name\": \"定西市\"\n },\n {\n \"id\": 2487,\n \"name\": \"兰州市\"\n },\n {\n \"id\": 2492,\n \"name\": \"金昌市\"\n },\n {\n \"id\": 2495,\n \"name\": \"白银市\"\n },\n {\n \"id\": 2501,\n \"name\": \"天水市\"\n },\n {\n \"id\": 2509,\n \"name\": \"嘉峪关市\"\n },\n {\n \"id\": 2518,\n \"name\": \"平凉市\"\n }],\n \"29\": [\n {\n \"id\": 2580,\n \"name\": \"西宁市\"\n },\n {\n \"id\": 2585,\n \"name\": \"海东地区\"\n },\n {\n \"id\": 2592,\n \"name\": \"海北州\"\n },\n {\n \"id\": 2597,\n \"name\": \"黄南州\"\n },\n {\n \"id\": 2603,\n \"name\": \"海南州\"\n },\n {\n \"id\": 2605,\n \"name\": \"果洛州\"\n },\n {\n \"id\": 2612,\n \"name\": \"玉树州\"\n },\n {\n \"id\": 2620,\n \"name\": \"海西州\"\n }],\n \"30\": [\n {\n \"id\": 2628,\n \"name\": \"银川市\"\n },\n {\n \"id\": 2632,\n \"name\": \"石嘴山市\"\n },\n {\n \"id\": 2637,\n \"name\": \"吴忠市\"\n },\n {\n \"id\": 2644,\n \"name\": \"固原市\"\n },\n {\n \"id\": 3071,\n \"name\": \"中卫市\"\n }],\n \"31\": [\n {\n \"id\": 4110,\n \"name\": \"五家渠市\"\n },\n {\n \"id\": 4163,\n \"name\": \"博尔塔拉蒙古自治州阿拉山口口岸\"\n },\n {\n \"id\": 15945,\n \"name\": \"阿拉尔市\"\n },\n {\n \"id\": 15946,\n \"name\": \"图木舒克市\"\n },\n {\n \"id\": 2652,\n \"name\": \"乌鲁木齐市\"\n },\n {\n \"id\": 2654,\n \"name\": \"克拉玛依市\"\n },\n {\n \"id\": 2656,\n \"name\": \"石河子市\"\n },\n {\n \"id\": 2658,\n \"name\": \"吐鲁番地区\"\n },\n {\n \"id\": 2662,\n \"name\": \"哈密地区\"\n },\n {\n \"id\": 2666,\n \"name\": \"和田地区\"\n },\n {\n \"id\": 2675,\n \"name\": \"阿克苏地区\"\n },\n {\n \"id\": 2686,\n \"name\": \"喀什地区\"\n },\n {\n \"id\": 2699,\n \"name\": \"克孜勒苏州\"\n },\n {\n \"id\": 2704,\n \"name\": \"巴音郭楞州\"\n },\n {\n \"id\": 2714,\n \"name\": \"昌吉州\"\n },\n {\n \"id\": 2723,\n \"name\": \"博尔塔拉州\"\n },\n {\n \"id\": 2727,\n \"name\": \"伊犁州\"\n },\n {\n \"id\": 2736,\n \"name\": \"塔城地区\"\n },\n {\n \"id\": 2744,\n \"name\": \"阿勒泰地区\"\n }],\n \"32\": [\n {\n \"id\": 2768,\n \"name\": \"台湾市\"\n }],\n \"42\": [\n {\n \"id\": 2754,\n \"name\": \"香港特别行政区\"\n }],\n \"43\": [\n {\n \"id\": 2770,\n \"name\": \"澳门市\"\n }],\n \"84\": [\n {\n \"id\": 1310,\n \"name\": \"钓鱼岛\"\n }],\n '53283':\n {\n 'A': [\n {\n id: 53285,\n name: '阿尔巴尼亚'\n },\n {\n id: 53296,\n name: '阿尔及利亚'\n },\n {\n id: 53284,\n name: '阿富汗'\n },\n {\n id: 53297,\n name: '阿根廷'\n },\n {\n id: 53300,\n name: '阿联酋'\n },\n {\n id: 53302,\n name: '阿鲁巴'\n },\n {\n id: 53495,\n name: '阿曼'\n },\n {\n id: 53315,\n name: '阿塞拜疆'\n },\n {\n id: 53320,\n name: '埃及'\n },\n {\n id: 53336,\n name: '埃塞俄比亚'\n },\n {\n id: 53337,\n name: '爱尔兰'\n },\n {\n id: 53338,\n name: '爱沙尼亚'\n },\n {\n id: 53339,\n name: '安道尔'\n },\n {\n id: 53341,\n name: '安哥拉'\n },\n {\n id: 53343,\n name: '安圭拉'\n },\n {\n id: 53346,\n name: '奥地利'\n },\n {\n id: 53347,\n name: '澳大利亚'\n },\n {\n id: 53344,\n name: '安提瓜和巴布达'\n }],\n 'B': [\n {\n id: 53349,\n name: '巴巴多斯'\n },\n {\n id: 53352,\n name: '巴哈马'\n },\n {\n id: 53353,\n name: '巴基斯坦'\n },\n {\n id: 53354,\n name: '巴拉圭'\n },\n {\n id: 53355,\n name: '巴林'\n },\n {\n id: 53356,\n name: '巴拿马'\n },\n {\n id: 53357,\n name: '巴西'\n },\n {\n id: 53359,\n name: '白俄罗斯'\n },\n {\n id: 53361,\n name: '百慕大三角'\n },\n {\n id: 53362,\n name: '保加利亚'\n },\n {\n id: 53365,\n name: '贝宁'\n },\n {\n id: 53367,\n name: '比利时'\n },\n {\n id: 53368,\n name: '冰岛'\n },\n {\n id: 53370,\n name: '波多黎各'\n },\n {\n id: 53372,\n name: '波兰'\n },\n {\n id: 53375,\n name: '玻利维亚'\n },\n {\n id: 53377,\n name: '伯利兹'\n },\n {\n id: 53379,\n name: '博茨瓦纳'\n },\n {\n id: 53380,\n name: '不丹'\n },\n {\n id: 53384,\n name: '布隆迪'\n },\n {\n id: 53382,\n name: '布基纳法索'\n },\n {\n id: 53350,\n name: '巴布亚新几内亚'\n },\n {\n id: 53374,\n name: '波斯尼亚和黑塞哥维那'\n }],\n 'CDEF': [\n {\n id: 53387,\n name: '丹麦'\n },\n {\n id: 53389,\n name: '德国'\n },\n {\n id: 53391,\n name: '东帝汶'\n },\n {\n id: 53392,\n name: '多哥'\n },\n {\n id: 53395,\n name: '俄罗斯'\n },\n {\n id: 53396,\n name: '厄瓜多尔'\n },\n {\n id: 53398,\n name: '法国'\n },\n {\n id: 53399,\n name: '法罗群岛'\n },\n {\n id: 53401,\n name: '菲律宾'\n },\n {\n id: 53403,\n name: '斐济群岛'\n },\n {\n id: 53405,\n name: '芬兰'\n },\n {\n id: 53406,\n name: '佛得角'\n },\n {\n id: 53400,\n name: '法属圭亚那'\n },\n {\n id: 53397,\n name: '厄立特里亚'\n },\n {\n id: 53386,\n name: '赤道几内亚'\n },\n {\n id: 53394,\n name: '多米尼加共和国'\n }],\n 'GH': [\n {\n id: 53407,\n name: '冈比亚'\n },\n {\n id: 53408,\n name: '刚果'\n },\n {\n id: 53409,\n name: '哥伦比亚'\n },\n {\n id: 53410,\n name: '哥斯达黎加'\n },\n {\n id: 53411,\n name: '格林纳达'\n },\n {\n id: 53412,\n name: '格陵兰'\n },\n {\n id: 53413,\n name: '格鲁吉亚'\n },\n {\n id: 53414,\n name: '古巴'\n },\n {\n id: 53415,\n name: '瓜德罗普'\n },\n {\n id: 53417,\n name: '关岛'\n },\n {\n id: 53419,\n name: '圭亚那'\n },\n {\n id: 53420,\n name: '哈萨克斯坦'\n },\n {\n id: 53421,\n name: '海地'\n },\n {\n id: 53422,\n name: '韩国'\n },\n {\n id: 53423,\n name: '荷兰'\n },\n {\n id: 53425,\n name: '黑山'\n },\n {\n id: 53426,\n name: '洪都拉斯'\n }],\n 'JK': [\n {\n id: 53430,\n name: '吉布提'\n },\n {\n id: 53434,\n name: '几内亚'\n },\n {\n id: 53436,\n name: '几内亚比绍'\n },\n {\n id: 53440,\n name: '加拿大'\n },\n {\n id: 53442,\n name: '加纳'\n },\n {\n id: 53444,\n name: '加蓬'\n },\n {\n id: 53445,\n name: '柬埔寨'\n },\n {\n id: 53447,\n name: '捷克'\n },\n {\n id: 53449,\n name: '津巴布韦'\n },\n {\n id: 53451,\n name: '喀麦隆'\n },\n {\n id: 53453,\n name: '卡塔尔'\n },\n {\n id: 53455,\n name: '开曼群岛'\n },\n {\n id: 53457,\n name: '科摩罗'\n },\n {\n id: 53458,\n name: '科特迪瓦'\n },\n {\n id: 53460,\n name: '科威特'\n },\n {\n id: 53461,\n name: '克罗地亚'\n },\n {\n id: 53463,\n name: '肯尼亚'\n },\n {\n id: 53464,\n name: '库克群岛'\n },\n {\n id: 53432,\n name: '吉尔吉斯斯坦'\n }],\n 'L': [\n {\n id: 53466,\n name: '拉脱维亚'\n },\n {\n id: 53467,\n name: '莱索托'\n },\n {\n id: 53476,\n name: '老挝'\n },\n {\n id: 53479,\n name: '黎巴嫩'\n },\n {\n id: 53481,\n name: '立陶宛'\n },\n {\n id: 53482,\n name: '利比里亚'\n },\n {\n id: 53484,\n name: '利比亚'\n },\n {\n id: 53486,\n name: '列支敦士登'\n },\n {\n id: 53491,\n name: '卢森堡'\n },\n {\n id: 53493,\n name: '卢旺达'\n },\n {\n id: 53494,\n name: '罗马尼亚'\n }],\n 'M': [\n {\n id: 53298,\n name: '马尔代夫'\n },\n {\n id: 53299,\n name: '马耳他'\n },\n {\n id: 53301,\n name: '马拉维'\n },\n {\n id: 53303,\n name: '马来西亚'\n },\n {\n id: 53304,\n name: '马里'\n },\n {\n id: 53305,\n name: '马其顿'\n },\n {\n id: 53306,\n name: '马提尼克'\n },\n {\n id: 53307,\n name: '毛里求斯'\n },\n {\n id: 53308,\n name: '毛里塔尼亚'\n },\n {\n id: 53309,\n name: '美国'\n },\n {\n id: 53286,\n name: '美属萨摩亚'\n },\n {\n id: 53311,\n name: '蒙古'\n },\n {\n id: 53312,\n name: '蒙特塞拉特'\n },\n {\n id: 53313,\n name: '孟加拉'\n },\n {\n id: 53314,\n name: '秘鲁'\n },\n {\n id: 53317,\n name: '摩尔多瓦'\n },\n {\n id: 53318,\n name: '摩洛哥'\n },\n {\n id: 53319,\n name: '摩纳哥'\n },\n {\n id: 53321,\n name: '莫桑比克'\n },\n {\n id: 53322,\n name: '墨西哥'\n },\n {\n id: 53316,\n name: '密克罗尼西亚'\n },\n {\n id: 53310,\n name: '美属维尔京群岛'\n },\n {\n id: 53496,\n name: '马达加斯加'\n }],\n 'NPR': [\n {\n id: 53323,\n name: '纳米比亚'\n },\n {\n id: 53324,\n name: '南非'\n },\n {\n id: 53325,\n name: '南苏丹'\n },\n {\n id: 53326,\n name: '尼泊尔'\n },\n {\n id: 53327,\n name: '尼加拉瓜'\n },\n {\n id: 53328,\n name: '尼日尔'\n },\n {\n id: 53329,\n name: '尼日利亚'\n },\n {\n id: 53330,\n name: '挪威'\n },\n {\n id: 53331,\n name: '帕劳'\n },\n {\n id: 53332,\n name: '葡萄牙'\n },\n {\n id: 53333,\n name: '日本'\n },\n {\n id: 53334,\n name: '瑞典'\n },\n {\n id: 53335,\n name: '瑞士'\n }],\n 'S': [\n {\n id: 53340,\n name: '萨尔瓦多'\n },\n {\n id: 53342,\n name: '萨摩亚'\n },\n {\n id: 53345,\n name: '塞尔维亚'\n },\n {\n id: 53348,\n name: '塞拉利昂'\n },\n {\n id: 53351,\n name: '塞内加尔'\n },\n {\n id: 53358,\n name: '塞浦路斯'\n },\n {\n id: 53360,\n name: '塞舌尔'\n },\n {\n id: 53363,\n name: '沙特阿拉伯'\n },\n {\n id: 53369,\n name: '圣卢西亚'\n },\n {\n id: 53371,\n name: '圣马力诺'\n },\n {\n id: 53376,\n name: '斯里兰卡'\n },\n {\n id: 53378,\n name: '斯洛伐克'\n },\n {\n id: 53381,\n name: '斯洛文尼亚'\n },\n {\n id: 53383,\n name: '斯威士兰'\n },\n {\n id: 53385,\n name: '苏丹'\n },\n {\n id: 53388,\n name: '苏里南'\n },\n {\n id: 53393,\n name: '索马里'\n },\n {\n id: 53390,\n name: '所罗门群岛'\n },\n {\n id: 53366,\n name: '圣基茨和尼维斯'\n },\n {\n id: 53364,\n name: '圣多美和普林西比'\n },\n {\n id: 53373,\n name: '圣文森特和格林纳丁斯'\n }],\n 'TW': [\n {\n id: 53402,\n name: '塔吉克斯坦'\n },\n {\n id: 53404,\n name: '泰国'\n },\n {\n id: 53418,\n name: '坦桑尼亚'\n },\n {\n id: 53424,\n name: '汤加'\n },\n {\n id: 53431,\n name: '突尼斯'\n },\n {\n id: 53433,\n name: '图瓦卢'\n },\n {\n id: 53435,\n name: '土耳其'\n },\n {\n id: 53437,\n name: '瓦努阿图'\n },\n {\n id: 53438,\n name: '危地马拉'\n },\n {\n id: 53439,\n name: '委内瑞拉'\n },\n {\n id: 53441,\n name: '文莱'\n },\n {\n id: 53443,\n name: '乌干达'\n },\n {\n id: 53446,\n name: '乌克兰'\n },\n {\n id: 53448,\n name: '乌拉圭'\n },\n {\n id: 53450,\n name: '乌兹别克斯坦'\n },\n {\n id: 53429,\n name: '特立尼达和多巴哥'\n },\n {\n id: 53427,\n name: '特克斯和凯科斯群岛'\n }],\n 'XYZ': [\n {\n id: 53452,\n name: '西班牙'\n },\n {\n id: 53454,\n name: '希腊'\n },\n {\n id: 53456,\n name: '新加坡'\n },\n {\n id: 53462,\n name: '新西兰'\n },\n {\n id: 53465,\n name: '匈牙利'\n },\n {\n id: 53468,\n name: '叙利亚'\n },\n {\n id: 53469,\n name: '牙买加'\n },\n {\n id: 53470,\n name: '亚美尼亚'\n },\n {\n id: 53471,\n name: '也门'\n },\n {\n id: 53472,\n name: '伊拉克'\n },\n {\n id: 53473,\n name: '伊朗'\n },\n {\n id: 53474,\n name: '以色列'\n },\n {\n id: 53475,\n name: '意大利'\n },\n {\n id: 53477,\n name: '印度'\n },\n {\n id: 53478,\n name: '印度尼西亚'\n },\n {\n id: 53480,\n name: '英国'\n },\n {\n id: 53485,\n name: '约旦'\n },\n {\n id: 53487,\n name: '越南'\n },\n {\n id: 53488,\n name: '赞比亚'\n },\n {\n id: 53489,\n name: '乍得'\n },\n {\n id: 53490,\n name: '智利'\n },\n {\n id: 53492,\n name: '中非'\n },\n {\n id: 53459,\n name: '新喀里多尼亚'\n },\n {\n id: 53483,\n name: '英属维尔京群岛'\n }]\n }\n };;\n return common_provinceCityMap;\n}", "static getAllRegionsById(region_id) {\n const url = `${API_URL}/region/${region_id}`\n return axios.get(url)\n }", "function updateEntityIds (elem) {\n if (elem && elem.__data__) {\n var data = elem.__data__;\n var idFields = ['startId', 'endId', 'originId'];\n idFields.forEach(function(field){\n if (data.hasOwnProperty(field)) {\n data[field] = guid();\n }\n });\n\n // 'id' field is obligatory\n data.id = guid();\n }\n\n return elem;\n }", "function buildEntitiesLookup(items, radix) {\n\t\tvar i, chr, entity, lookup = {};\n\n\t\tif (items) {\n\t\t\titems = items.split(',');\n\t\t\tradix = radix || 10;\n\n\t\t\t// Build entities lookup table\n\t\t\tfor (i = 0; i < items.length; i += 2) {\n\t\t\t\tchr = String.fromCharCode(parseInt(items[i], radix));\n\n\t\t\t\t// Only add non base entities\n\t\t\t\tif (!baseEntities[chr]) {\n\t\t\t\t\tentity = '&' + items[i + 1] + ';';\n\t\t\t\t\tlookup[chr] = entity;\n\t\t\t\t\tlookup[entity] = chr;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn lookup;\n\t\t}\n\t}", "function buildEntitiesLookup(items, radix) {\n\t\tvar i, chr, entity, lookup = {};\n\n\t\tif (items) {\n\t\t\titems = items.split(',');\n\t\t\tradix = radix || 10;\n\n\t\t\t// Build entities lookup table\n\t\t\tfor (i = 0; i < items.length; i += 2) {\n\t\t\t\tchr = String.fromCharCode(parseInt(items[i], radix));\n\n\t\t\t\t// Only add non base entities\n\t\t\t\tif (!baseEntities[chr]) {\n\t\t\t\t\tentity = '&' + items[i + 1] + ';';\n\t\t\t\t\tlookup[chr] = entity;\n\t\t\t\t\tlookup[entity] = chr;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn lookup;\n\t\t}\n\t}", "function buildEntitiesLookup(items, radix) {\n\t\tvar i, chr, entity, lookup = {};\n\n\t\tif (items) {\n\t\t\titems = items.split(',');\n\t\t\tradix = radix || 10;\n\n\t\t\t// Build entities lookup table\n\t\t\tfor (i = 0; i < items.length; i += 2) {\n\t\t\t\tchr = String.fromCharCode(parseInt(items[i], radix));\n\n\t\t\t\t// Only add non base entities\n\t\t\t\tif (!baseEntities[chr]) {\n\t\t\t\t\tentity = '&' + items[i + 1] + ';';\n\t\t\t\t\tlookup[chr] = entity;\n\t\t\t\t\tlookup[entity] = chr;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn lookup;\n\t\t}\n\t}", "function FindMetaDataForRegion(region) {\n // Check in the region cache first. This will find all entries we have\n // already resolved (parsed from a string encoding).\n var md = regionCache[region];\n if (md)\n return md;\n for (var countryCode in dataBase) {\n var entry = dataBase[countryCode];\n // Each entry is a string encoded object of the form '[\"US..', or\n // an array of strings. We don't want to parse the string here\n // to save memory, so we just substring the region identifier\n // and compare it. For arrays, we compare against all region\n // identifiers with that country code. We skip entries that are\n // of type object, because they were already resolved (parsed into\n // an object), and their country code should have been in the cache.\n if (Array.isArray(entry)) {\n for (var n = 0; n < entry.length; n++) {\n if (typeof entry[n] == \"string\" && entry[n].substr(2,2) == region) {\n if (n > 0) {\n // Only the first entry has the formats field set.\n // Parse the main country if we haven't already and use\n // the formats field from the main country.\n if (typeof entry[0] == \"string\")\n entry[0] = ParseMetaData(countryCode, entry[0]);\n var formats = entry[0].formats;\n var current = ParseMetaData(countryCode, entry[n]);\n current.formats = formats;\n return entry[n] = current;\n }\n\n entry[n] = ParseMetaData(countryCode, entry[n]);\n return entry[n];\n }\n }\n continue;\n }\n if (typeof entry == \"string\" && entry.substr(2,2) == region)\n return dataBase[countryCode] = ParseMetaData(countryCode, entry);\n }\n }", "_uniqueEntities(callback) {\n const uniqueIds = Object.create(null);\n return id => {\n if (!(id in uniqueIds)) {\n uniqueIds[id] = true;\n callback((0, _N3DataFactory.termFromId)(this._entities[id], this._factory));\n }\n };\n }", "function stateAbbrToName(item) {\n var states = {\n \"AA\": \"Armed Forces Americas\",\n \"AB\": \"Alberta\",\n \"AE\": \"Armed Forces Africa/Canada/Europe/Middle East\",\n \"AK\": \"Alaska\",\n \"AL\": \"Alabama\",\n \"AP\": \"Armed Forces Pacific\",\n \"AR\": \"Arkansas\",\n \"AS\": \"American Samoa\",\n \"AZ\": \"Arizona\",\n \"BC\": \"British Columbia\",\n \"CA\": \"California\",\n \"CO\": \"Colorado\",\n \"CT\": \"Connecticut\",\n \"DC\": \"District Of Columbia\",\n \"DE\": \"Delaware\",\n \"FL\": \"Florida\",\n \"FM\": \"Federated States Of Micronesia\",\n \"GA\": \"Georgia\",\n \"GU\": \"Guam\",\n \"HI\": \"Hawaii\",\n \"IA\": \"Iowa\",\n \"ID\": \"Idaho\",\n \"IL\": \"Illinois\",\n \"IN\": \"Indiana\",\n \"KS\": \"Kansas\",\n \"KY\": \"Kentucky\",\n \"LA\": \"Louisiana\",\n \"MA\": \"Massachusetts\",\n \"MB\": \"Manitoba\",\n \"MD\": \"Maryland\",\n \"ME\": \"Maine\",\n \"MH\": \"Marshall Islands\",\n \"MI\": \"Michigan\",\n \"MN\": \"Minnesota\",\n \"MO\": \"Missouri\",\n \"MP\": \"Northern Mariana Islands\",\n \"MS\": \"Mississippi\",\n \"MT\": \"Montana\",\n \"NB\": \"New Brunswick\",\n \"NC\": \"North Carolina\",\n \"ND\": \"North Dakota\",\n \"NE\": \"Nebraska\",\n \"NF\": \"Newfoundland and Labrador\",\n \"NH\": \"New Hampshire\",\n \"NJ\": \"New Jersey\",\n \"NL\": \"Newfoundland and Labrador\",\n \"NM\": \"New Mexico\",\n \"NS\": \"Nova Scotia\",\n \"NT\": \"Northwest Territories\",\n \"NU\": \"Nunavut\",\n \"NV\": \"Nevada\",\n \"NY\": \"New York\",\n \"OH\": \"Ohio\",\n \"OK\": \"Oklahoma\",\n \"ON\": \"Ontario\",\n \"OR\": \"Oregon\",\n \"PA\": \"Pennsylvania\",\n \"PE\": \"Prince Edward Island\",\n \"PR\": \"Puerto Rico\",\n \"PW\": \"Palau\",\n \"QC\": \"Québec\",\n \"RI\": \"Rhode Island\",\n \"SC\": \"South Carolina\",\n \"SD\": \"South Dakota\",\n \"SK\": \"Saskatchewan\",\n \"TN\": \"Tennessee\",\n \"TX\": \"Texas\",\n \"UT\": \"Utah\",\n \"VA\": \"Virginia\",\n \"VI\": \"Virgin Islands\",\n \"VT\": \"Vermont\",\n \"WA\": \"Washington\",\n \"WI\": \"Wisconsin\",\n \"WV\": \"West Virginia\",\n \"WY\": \"Wyoming\",\n \"YT\": \"Yukon\"\n };\n\n item.name = states[item.name];\n item.highlighted = item.name;\n \n return item;\n}", "loadEntity(itemId) {\n\n }", "function getRangesForDraftEntity(block,key){var ranges=[];block.findEntityRanges(function(c){return c.getEntity()===key;},function(start,end){ranges.push({start:start,end:end});});!!!ranges.length?true?invariant(false,'Entity key not found in this range.'):invariant(false):void 0;return ranges;}", "function cityToRegion(PatientObj, city){\n let placeholder = 0;\n for(index in regionCities){\n if(placeholder < regionCities[index].length)\n placeholder = regionCities[index].length;\n }\n for (index in regionCities){\n for(i = 0; i < placeholder; i++){\n if (city == regionCities[index][i])\n PatientObj.region = index;\n }\n }\n return PatientObj;\n}", "getEntityIdsAsString() {\n const d = Object.keys(this.items)\n .filter((item) => this.items[item].datasource == undefined && this.items[item].stateOnly == false)\n .map((item) => this.items[item].id)\n return [...new Set(d)].join(\",\")\n }", "function getCountriesInRegion(cc) {\n var region = { countries: '' };\n for (var regionKey in LoLRegions) {\n var countries = LoLRegions[regionKey].countries;\n _.forOwn(countries, function(key, countryIndex) {\n if (cc == countries[countryIndex]) {\n region = LoLRegions[regionKey];\n return LoLRegions[regionKey];\n }\n });\n }\n return region;\n }", "function getRegionFromCurrData(id) {\n\t// If the id is less than 1,000 then it's a state code. Convert to 5-digit FIPS\n\tid = (currData.resolution === \"state\") ? id * 1000: id;\n\treturn currData.regions[currData.regions_idx[id]];\n}", "function regionLookup(client, regionName, cache, cb) {\n if (cache[regionName]) cb(null, cache[regionName]);\n else regionRequester(client, regionName, function(err, result) {\n if (err) cb(err);\n else {\n for(var i = 0; i < result.length; i++) {\n if (result[i].regionName == regionName) {\n cache[regionName] = result[i];\n cb(null, result[i]);\n return;\n }\n }\n cb(new Error((\"Region not found: \" + regionName)));\n }\n });\n }", "getEntitieslist() {\n const d = this.items\n return Object.keys(d).map(function (field) {\n return d[field]\n })\n }", "function parseRegionActual (seasonData, regionId) {\n let regionSubset = seasonData[regionId]\n\n let epiweeks = fct.utils.epiweek.seasonEpiweeks(SEASON_ID)\n return epiweeks.map(ew => {\n let ewData = regionSubset.find(({ epiweek }) => epiweek === ew)\n // Rename keys to match the expectations of flusight\n // and extend by filling in missing epiweeks\n if (ewData) {\n return {\n week: ewData.epiweek,\n actual: ewData.wili,\n lagData: ewData.lagData.map(({ lag, wili }) => { return { lag, value: wili } })\n }\n } else {\n return {\n week: ew,\n actual: null,\n lagData: []\n }\n }\n })\n}", "function normalizeItem(item) {\n item = fillInMissingLocales(item);\n\n\n return item;\n }", "function encodeEntityRanges(block,storageMap){var encoded=[];block.findEntityRanges(function(character){return!!character.getEntity();},function(/*number*/start,/*number*/end){var text=block.getText();var key=block.getEntityAt(start);encoded.push({offset:strlen(text.slice(0,start)),length:strlen(text.slice(start,end)),// Encode the key as a number for range storage.\r\n\tkey:Number(storageMap[DraftStringKey.stringify(key)])});});return encoded;}", "initItem() {\n let item = {}\n\n Object.keys(this.setNewItemFields()).map((Key) => {\n if (Key === 'translatables') {\n this.setNewItemFields()[Key].map((key) => {\n // generate translatable items\n item[key] = Object.fromEntries(this.getLocalesList().map(locale => [locale, '']))\n }, this)\n } else {\n this.setNewItemFields()[Key].map((key) => {\n // generate items\n // if array means you don`t want default value from type\n if (Array.isArray(key)) {\n item[key[0]] = key[1]\n } else {\n item[key] = window[`${Key.charAt(0).toUpperCase() + Key.slice(1)}`]()\n }\n }, Key)\n }\n }, this)\n\n return item\n }", "static loadMapFromId(id) {\n\t\tswitch(id) {\n\t\t\tcase \"USA_current_house\":\n\t\t\t\tMapLoader.loadPresetMap(id, {enableCongress: true});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_current_senate\":\n\t\t\tcase \"USA_2024_projection\":\n\t\t\tcase \"USA_2020_cook\":\n\t\t\tcase \"USA_2020_inside\":\n\t\t\tcase \"USA_2020_sabatos\":\n\t\t\tcase \"USA_2020_house_cook\":\n\t\t\tcase \"USA_2016_presidential\":\n\t\t\tcase \"USA_2012_presidential\":\n\t\t\tcase \"USA_2008_presidential\":\n\t\t\tcase \"USA_2004_presidential\":\n\t\t\tcase \"USA_2000_presidential\":\n\t\t\tcase \"USA_1996_presidential\":\n\t\t\tcase \"USA_1992_presidential\":\n\t\t\tcase \"USA_1988_presidential\":\n\t\t\tcase \"USA_1984_presidential\":\n\t\t\tcase \"USA_1980_presidential\":\n\t\t\tcase \"USA_1976_presidential\":\n\t\t\tcase \"USA_1972_presidential\":\n\t\t\tcase \"USA_1968_presidential\":\n\t\t\tcase \"USA_1964_presidential\":\n\t\t\tcase \"USA_1960_presidential\":\n\t\t\tcase \"USA_1956_presidential\":\n\t\t\tcase \"USA_1952_presidential\":\n\t\t\tcase \"USA_1948_presidential\":\n\t\t\tcase \"USA_1944_presidential\":\n\t\t\tcase \"USA_1940_presidential\":\n\t\t\tcase \"USA_1936_presidential\":\n\t\t\tcase \"USA_1932_presidential\":\n\t\t\tcase \"USA_1928_presidential\":\n\t\t\tcase \"USA_1924_presidential\":\n\t\t\tcase \"USA_1920_presidential\":\n\t\t\tcase \"USA_1916_presidential\":\n\t\t\tcase \"USA_1912_presidential\":\n\t\t\tcase \"USA_1908_presidential\":\n\t\t\tcase \"USA_1904_presidential\":\n\t\t\tcase \"USA_1900_presidential\":\n\t\t\tcase \"USA_1896_presidential\":\n\t\t\tcase \"USA_1892_presidential\":\n\t\t\tcase \"USA_1888_presidential\":\n\t\t\tcase \"USA_1884_presidential\":\n\t\t\tcase \"USA_1880_presidential\":\n\t\t\tcase \"USA_1876_presidential\":\n\t\t\tcase \"USA_1876_presidential\":\n\t\t\tcase \"USA_1872_presidential\":\n\t\t\tcase \"USA_1868_presidential\":\n\t\t\tcase \"USA_1864_presidential\":\n\t\t\tcase \"USA_2016_presidential_county\":\n\t\t\tcase \"UnitedKingdom_current_parliament\":\n\t\t\t\tMapLoader.loadPresetMap(id);\n\t\t\t\tbreak;\n\t\t\tcase \"Canada_2019_house_of_commons\":\n\t\t\t\tMapLoader.loadPresetMap('can/' + id);\n\t\t\t\tbreak;\n\t\t\tcase \"USA_Canada\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_canada.svg\", 16, 0.01, \"congressional\", \"presidential\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_2020_presidential\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_presidential.svg\", 16, 1, \"usa_ec\", \"presidential\", \"open\", {updateText: true, voters: 'usa_voting_pop', enablePopularVote: true});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_split_maine\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_1972_presidential.svg\", 16, 1, \"usa_1972_ec\", \"presidential\", \"open\", {updateText: true});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_2020_senatorial\":\n\t\t\tcase \"USA_2020_senate\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_senate.svg\", 16, 1, \"usa_senate\", \"senatorial\", \"2020\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_2020_gubernatorial\":\n\t\t\tcase \"USA_2020_governors\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_gubernatorial.svg\", 16, 1, \"usa_gubernatorial\", \"gubernatorial\", \"2020\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_2020_democratic_primary\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_dem_primary.svg\", 16, 1, \"dem_primary\", \"primary\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('democratic primary');\n\t\t\t\tbreak;\n\t\t\tcase \"USA_2020_republican_primary\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_rep_primary.svg\", 16, 1, \"rep_primary\", \"primary\", \"open\",{updateText: false});\n\t\t\t\tPresetLoader.loadPreset('republican primary');\n\t\t\t\tbreak;\n\t\t\tcase \"USA_county\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_county.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_congressional\":\n\t\t\tcase \"USA_2020_house\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_congressional_2018.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: false, enableCongress: true});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_congressional_2008\":\n\t\t\tcase \"USA_2008_house\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_congressional_2008.svg\", 16, 0.005, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_gubernatorial\":\n\t\t\tcase \"USA_governors\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_gubernatorial.svg\", 16, 1.5, \"usa_gubernatorial\", \"gubernatorial\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_senatorial\":\n\t\t\tcase \"USA_senate\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_senate.svg\", 16, 1.5, \"usa_senate\", \"senatorial\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_takeall\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_no_districts.svg\", 16, 1, \"usa_no_districts_ec\", \"presidential\", \"open\", {updateText: true});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_proportional\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_no_districts.svg\", 16, 1, \"usa_no_districts_ec\", \"proportional\", \"open\", {updateText: true});\n\t\t\t\tbreak;\n\t\t\tcase \"USA_pre_civilwar\":\n\t\t\t\tMapLoader.loadMap(\"./res/usa_pre_civilwar.svg\", 16, 1, \"usa_pre_civilwar_ec\", \"presidential\", \"open\", {updateText: true});\n\t\t\t\tbreak;\n\t\t\tcase \"Germany_states\":\n\t\t\t\tMapLoader.loadMap(\"./res/germany.svg\", 16, 1, \"congressional\", \"presidential\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('germany')\n\t\t\t\tbreak;\n\t\t\tcase \"Germany_constituencies\":\n\t\t\tcase \"Germany_bundestag\":\n\t\t\t\tMapLoader.loadMap(\"./res/germany_constituencies.svg\", 16, 0.25, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('germany')\n\t\t\t\tbreak;\n\t\t\tcase \"France_constituencies\":\n\t\t\tcase \"France_national_assembly\":\n\t\t\t\tMapLoader.loadMap(\"./res/france_constituencies.svg\", 16, 0.25, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('france')\n\t\t\t\tbreak;\n\t\t\tcase \"Netherlands_provinces\":\n\t\t\t\tMapLoader.loadMap(\"./res/netherlands_provinces.svg\", 16, 0.15, \"netherlands_provinces\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('netherlands');\n\t\t\t\tbreak;\n\t\t\tcase \"Netherlands_gemeenten\":\n\t\t\t\tMapLoader.loadMap(\"./res/netherlands_gemeenten.svg\", 16, 0.15, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('netherlands');\n\t\t\t\tbreak;\n\t\t\tcase \"Italy_states\":\n\t\t\t\tMapLoader.loadMap(\"./res/italy.svg\", 16, 1, \"congressional\", \"presidential\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('italy')\n\t\t\t\tbreak;\n\t\t\tcase \"Portugal_assembly_of_the_republic\":\n\t\t\t\tMapLoader.loadMap(\"./res/portugal_constituencies.svg\", 16, 0.25, \"portugal_constituencies\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('portugal');\n\t\t\t\tbreak;\n\t\t\tcase \"Spain_constituencies\":\n\t\t\tcase \"Spain_congress_of_deputies\":\n\t\t\t\tMapLoader.loadMap(\"./res/spain_constituencies.svg\", 16, 0.25, \"spain_constituencies\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('spain');\n\t\t\t\tbreak;\n\t\t\tcase \"Turkey_national_assembly\":\n\t\t\t\tMapLoader.loadMap(\"./res/turkey_provinces.svg\", 16, 0.5, \"turkey_national_assembly\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('turkey');\n\t\t\t\tbreak;\n\t\t\tcase \"India_lok_sabha\":\n\t\t\t\tMapLoader.loadMap(\"./res/india_constituencies.svg\", 16, 0.1, \"congressional\", \"presidential\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('india');\n\t\t\t\tbreak;\n\t\t\tcase \"UnitedKingdom_constituencies\":\n\t\t\tcase \"UnitedKingdom_house_of_commons\":\n\t\t\t\tMapLoader.loadMap(\"./res/unitedkingdom.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('uk')\n\t\t\t\tbreak;\n\t\t\tcase \"Ireland_constituencies\":\n\t\t\tcase \"Ireland_dail_eireann\":\n\t\t\t\tMapLoader.loadMap(\"./res/ireland_constituencies.svg\", 16, 0.075, \"ireland_constituencies\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('ireland')\n\t\t\t\tbreak;\n\t\t\tcase \"Canada_provinces\":\n\t\t\t\tMapLoader.loadMap(\"./res/canada_states.svg\", 38, 2, \"congressional\", \"presidential\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('canada')\n\t\t\t\tbreak;\n\t\t\tcase \"Canada_constituencies\":\n\t\t\tcase \"Canada_house_of_commons\":\n\t\t\t\tMapLoader.loadMap(\"./res/canada_constituencies.svg\", 16, 0.1, \"congressional\", \"congressional\", \"open\", {updateText: true});\n\t\t\t\tPresetLoader.loadPreset('canada')\n\t\t\t\tbreak;\n\t\t\tcase \"Australia_constituencies\":\n\t\t\tcase 'Australia_house_of_representatives':\n\t\t\t\tMapLoader.loadMap(\"./res/australia_constituencies.svg\", 16, 0.5, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('australia')\n\t\t\t\tbreak;\n\t\t\tcase \"Australia_states\":\n\t\t\t\tMapLoader.loadMap(\"./res/australia.svg\", 16, 0.075, \"congressional\", \"presidential\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('australia')\n\t\t\t\tbreak;\n\t\t\tcase \"Brazil_deputies\":\n\t\t\tcase 'Brazil_chamber_of_deputies':\n\t\t\t\tMapLoader.loadMap(\"./res/brazil_states.svg\", 16, 50, \"brazil_deputies\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('brazil');\n\t\t\t\tbreak;\n\t\t\tcase 'Brazil_federal_senate':\n\t\t\t\tMapLoader.loadMap('./res/brazil_states.svg', 16, 50, \"brazil_senate\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('brazil');\n\t\t\t\tbreak;\n\t\t\tcase 'Russia_federal_council':\n\t\t\t\tMapLoader.loadMap('./res/russia_federal_subjects.svg', 16, 0.25, 'russia_federal_council', 'proportional', 'open', {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('russia');\n\t\t\t\tbreak;\n\t\t\tcase 'Russia_duma':\n\t\t\t\tMapLoader.loadMap('./res/russia_constituencies.svg', 16, 0.15, 'duma', 'congressional', 'open', {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('russia');\n\t\t\t\tbreak;\n\t\t\tcase \"Trinidad_Tobago_house_of_representatives\":\n\t\t\t\tMapLoader.loadMap(\"./res/trinidad_tobago_house_of_representatives.svg\", 16, 0.25, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('trinidad_tobago');\n\t\t\t\tbreak;\n\t\t\tcase \"Switzerland_national_council\":\n\t\t\t\tMapLoader.loadMap(\"./res/che/switzerland_cantons.svg\", 16, 0.25, \"switzerland_national_council\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('switzerland');\n\t\t\t\tbreak;\n\t\t\tcase \"Switzerland_council_of_states\":\n\t\t\t\tMapLoader.loadMap(\"./res/che/switzerland_cantons.svg\", 16, 0.25, \"switzerland_council_of_states\", \"proportional\", \"open\", {updateText: false});\n\t\t\t\tPresetLoader.loadPreset('switzerland');\n\t\t\t\tbreak;\n\t\t\tcase \"EuropeanUnion\":\n\t\t\t\tMapLoader.loadMap(\"./res/eu.svg\", 16, 0.25, \"eu_parliament\", \"primary\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"World\":\n\t\t\t\tMapLoader.loadMap(\"./res/world.svg\", 38, 0.25, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"LTE_presidential\":\n\t\t\t\tMapLoader.loadMap(\"./res/lte_president.svg\", 30, 1, \"lte_ec\", \"presidential\", \"open\", {updateText: true});\n\t\t\t\tbreak;\n\t\t\tcase \"LTE_senatorial\":\n\t\t\t\tMapLoader.loadMap(\"./res/lte_senate.svg\", 35, 1, \"ltesenate\", \"senatorial\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tcase \"LTE_congressional\":\n\t\t\t\tMapLoader.loadMap(\"./res/lte_house.svg\", 35, 1, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tMapLoader.loadMap(\"./res/usa_presidential.svg\", 16, 1, \"usa_ec\", \"presidential\", \"open\", {updateText: true, voters: 'usa_voting_pop', enablePopularVote: true});\n\t\t\t\tbreak;\n\t\t}\n\t}", "function test_service_catalog_orchestration_global_region() {}", "function getIdFromMapAndEntity(map, entity)\n {\n for (var i in map.fields) {\n if (map.fields[i].id) {\n var fieldName = '_' + map.fields[i].name;\n\n if (fieldName in entity) {\n return Util.Promise.buildResolved(entity[fieldName]);\n } else {\n return Util.Promise.buildRejected(\n 'persister.mapper.unrecognizedFieldOnSource',\n map,\n entity\n );\n }\n }\n }\n\n return Util.Promise.buildRejected(\n 'persister.mapper.idFieldNotFound',\n map,\n entity\n );\n }", "onRegionUpdate(updated_region) {\n this.viewing_region = updated_region;\n this.fetch_regions();\n }", "getELLMap() {\n return {};\n }", "function wpsc_change_regions_when_country_changes() {\n\twpsc_copy_meta_value_to_similiar( jQuery( this ) );\n\twpsc_update_regions_list_to_match_country( jQuery( this ) );\n\treturn true;\n}", "function EntityColorMapping(entity)\n{\n\tswitch(entity.type)\n\t{\n\t\tcase 'character':\n\t\t{\n\t\t\tif(parent.party_list.includes(entity.id))\n\t\t\t{\n\t\t\t\treturn 0x1BD545;\n\t\t\t}\n\t\t\telse if(entity.npc == null)\n\t\t\t{\n\t\t\t\treturn 0xDCE20F;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 0x2341DB;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'monster':\n\t\t{\n\t\t\treturn 0xEE190E;\n\t\t\tbreak;\n\t\t}\n\t\t\t\n\t}\n}", "getEntityIndex(id, type) {\n let idPropertyName = type === 'resourcePerson' ? 'rp' : type;\n return this.state[EntityTypes[type]].findIndex(entity => entity[idPropertyName + '_id'] === parseInt(id));\n }", "function getLocation(lat, lng) {\n\tvar region = false;\n\tvar regionID;\n\tvar regions = [\n\t\t['Monschau', 'Schleiden', 'Bad Münstereifel', 'Rheinland-Pfalz', 'Rheinland-Pfalz', 'Rheinland-Pfalz', 'Hessen', 'Hessen', 'Hessen', 'Hessen'],\n\t\t['Aachen', 'Zülpich', 'Euskirchen', 'Bonn', 'Rheinland-Pfalz', 'Rheinland-Pfalz', 'Hessen', 'Hessen', 'Hessen', 'Hessen'],\n\t\t['Geilenkirchen', 'Düren', 'Köln', 'Köln-Mülheim', 'Waldbröl', 'Freudenberg', 'Siegen', 'Hessen', 'Hessen', 'Hessen'],\n\t\t['Heinsberg', 'Mönchengladbach', 'Neuss', 'Solingen', 'Gummersbach', 'Olpe', 'Schmallenberg', 'Bad Berleburg', 'Hessen', 'Hessen'],\n\t\t['Nettetal', 'Krefeld', 'Düsseldorf', 'Wuppertal', 'Hagen', 'Iserlohn', 'Arnsberg', 'Brilon', 'Hessen', 'Hessen'],\n\t\t['Geldern', 'Moers', 'Duisburg', 'Essen', 'Dortmund', 'Unna', 'Soest', 'Büren', 'Marsberg', 'Warburg'],\n\t\t['Kleve', 'Wesel', 'Dorsten', 'Recklinghausen', 'Lünen', 'Hamm/Westfalen', 'Beckum', 'Lippstadt', 'Paderborn', 'Bad Driburg'],\n\t\t['Emmerich am Rhein', 'Bocholt', 'Borken', 'Coesfeld', 'Münster', 'Warendorf', 'Rheda-Wiedenbrück', 'Gütersloh', 'Detmold', 'Bad Pyrmont'],\n\t\t['The Netherlands', 'The Netherlands', 'Vreden', 'Ahaus', 'Steinfurt', 'Lengerich', 'Bad Ilburg', 'Bielefeld', 'Herford', 'Niedersachsen'],\n\t\t['The Netherlands', 'The Netherlands', 'The Netherlands', 'Niedersachsen', 'Rheine', 'Ibbenbüren', 'Niedersachsen', 'Lübbecke', 'Minden', 'Niedersachsen']\n\t];\n\tif ( lat >= 50.4 && lat < 52.4 && lng >= 6.0 && lng < 9.333333 ) {\n\t\tvar latIndex = Math.floor((lat-50.4)*5); // 5 tiles per degree\n\t\tvar lngIndex = Math.floor((lng-6.0)*3); // 3 tiles per degree\n\t\tregion = regions[latIndex][lngIndex];\n\t};\n if ( region != 'The Netherlands' ) {\n regionID = 5500-latIndex*200+lngIndex*2+2;\n\t};\n\tif ( lat >= 50.9 && lat < 51.1 && lng >= 5.666666 && lng < 6.0 ) {\n\t\tregion = 'Selfkant';\n\t\tregionID = 5000;\n\t};\n return [ region, regionID ];\n}", "function getEntityIDMap(scene, entityIds) {\n const map = {};\n let entityId;\n let entity;\n for (let i = 0, len = entityIds.length; i < len; i++) {\n entityId = entityIds[i];\n entity = scene.component[entityId];\n if (!entity) {\n scene.warn(\"pick(): Component not found: \" + entityId);\n continue;\n }\n if (!entity.isEntity) {\n scene.warn(\"pick(): Component is not an Entity: \" + entityId);\n continue;\n }\n map[entityId] = true;\n }\n return map;\n}", "convertCoords(regionId, x, y) {\n let xcoord = mapArray[regionId - 3].center[1] - (w / 2) + (w * x);\n let ycoord = mapArray[regionId - 3].center[0] + (k / 2) - (k * y);\n return { xcoord, ycoord };\n }", "function getRegion($region_ville){\n $('input.autocomplete-region').autocomplete({\n data: $region_ville,\n limit: 20, // The max amount of results that can be shown at once. Default: Infinity.\n onAutocomplete: function(val) {\n // Callback function when value is autcompleted.\n $.ajax({\n url: '/booking/city_or_region/'+val,\n type: 'GET',\n cache: false,\n contentType: false,\n processData: false,\n beforeSend: function(){},\n success: function(data_json){\n data = $.parseJSON(data_json);\n if (data.status==\"ok\") {\n if (data.page==\"search\") {\n $('#autocompelet-center').empty();\n $('#autocompelet-center').html(data.html);\n $('select').material_select();\n }\n }\n },\n error: function() {\n alert(\"Une erreur est survenue\");\n }\n\n });\n },\n minLength: 1, // The minimum length of the input for the autocomplete to start. Default: 1.\n });\n }", "function wpsc_update_regions_list_to_match_country( country_select ) {\n\tvar country_meta_key = wpsc_get_element_meta_key( country_select );\n\tvar region_meta_key;\n\n\tif ( country_meta_key.indexOf( \"shipping\" ) === 0 ) {\n\t\tregion_meta_key = 'shippingregion';\n\t} else {\n\t\tregion_meta_key = 'billingregion';\n\t}\n\n\tvar region_select = wpsc_country_region_element( country_select );\n\tvar all_region_selects = wpsc_get_wpsc_meta_elements( region_meta_key ).filter( 'select' );\n\tvar country_code = wpsc_get_value_from_wpsc_meta_element( country_select );\n\tvar region = wpsc_get_value_from_wpsc_meta_element( region_meta_key );\n\n\tif ( wpsc_country_has_regions( country_code ) ) {\n\t\tvar select_a_region_message = wpsc_no_region_selected_message( country_code );\n\t\tvar regions = wpsc_country_regions( country_code );\n\t\tall_region_selects.empty();\n\t\tall_region_selects.append( wpsc_create_option( select_a_region_message ) );\n\t\tfor ( var region_code in regions ) {\n\t\t if ( regions.hasOwnProperty( region_code ) ) {\n\t\t\t var region_name = regions[region_code];\n\t\t\t all_region_selects.append( wpsc_create_option( region_name, region_code ) );\n\t\t }\n\t\t}\n\n\t\tif ( region ) {\n\t\t\tall_region_selects.val( region );\n\t\t}\n\n\t\tregion_select.show();\n\t} else {\n\t\tregion_select.hide();\n\t\tregion_select.empty();\n\t}\n\n\twpsc_update_location_labels( country_select );\n\twpsc_update_location_elements_visibility();\n\twpsc_copy_meta_value_to_similiar( country_select );\n}", "function getItemAccountInternalID()\r\n{\r\n\ttry\r\n\t{\r\n\t\t//getting revenue account id of the particular item in the line\r\n\t\tItemRevenueAccountIntID = nlapiLookupField('item', SOItemIntId, 'incomeaccount');\r\n\r\n\t}\t\r\n\tcatch(e)\r\n\t{\r\n\t\terrorHandler('getItemAccountsInternalIDs', e);\r\n\r\n\t}\r\n}", "function extractRegion(locale) {\n\treturn locale.split('.')[0]\n\t\t\t\t\t\t\t .split('_')[1];\n}", "async getCockpitRegions() {\n const regions = await this.getRegionNames();\n return Promise.all(regions.map(name => {\n var i = this.getRegionItems(name);\n return i;\n }));\n }", "function setEnumerationUnits(italyRegions, map, path, colorScale) {\n var wineRegions = map.selectAll(\".regions\")\n .data(italyRegions)\n .enter()\n .append(\"path\")\n .attr(\"class\", function(d){\n return \"regions \" + d.properties.adm1_code;\n })\n .attr(\"d\", path)\n .style(\"fill\", function(d){\n return choropleth(d.properties, colorScale);\n })\n .on(\"mouseover\", function(d){\n highlight(d.properties);\n })\n .on(\"mouseout\", function(d){\n dehighlight(d.properties);\n })\n .on(\"mousemove\", moveLabel);\n\n var desc = wineRegions.append(\"desc\")\n .text('{\"stroke\": \"#000\" , \"stroke-width\": \"1.5px\"}');\n }", "function getNodeRegion( node, defaultTo ) {\n var region = node.getAttribute( \"region\" );\n\n if ( region !== null ) {\n return region;\n } else {\n return defaultTo || \"\";\n }\n }", "function get_sequence_source_mappings(epvRefseqResultMap) {\n\n\tvar resultList = glue.tableToObjects(glue.command([\"list\",\"sequence\",\"sequenceID\",\"source.name\"]));\t\n\t\t\n\t_.each(resultList,function(resultObj){\n\n\t\t//glue.log(\"INFO\", \"This result is:\", resultObj);\n\t\tvar sequenceID = resultObj[\"sequenceID\"];\n\t\tvar sourceName = resultObj[\"source.name\"];\n\t\t//var sourceName = [\"ncbi-refseqs\"];\n\t\tepvRefseqResultMap[sequenceID] = sourceName;\n\n\t});\n\t\n}", "static get iso3166() {}", "function setRegionLevels(id){\n regionLevel = id;\n}", "function wpsc_country_region_element( country ) {\n\n\t// if the meta key was was given as the arument we can find the element easy enough\n\tif ( typeof country == \"string\" ) {\n\t\tcountry = wpsc_get_wpsc_meta_element( country );\n\t}\n\n\tvar country_id = country.attr('id');\n\tvar region_id = country_id + \"_region\";\n\tvar region_select = jQuery( \"#\" + region_id );\n\n\treturn region_select;\n}", "getRegion() {\n return super.getAsNullableString(\"region\");\n }", "function getIdType(chunks,options,resArray) {\n chunks = chunks.toString('utf-8');\n // console.log(`BODY: ${chunks}`);\n \n var entities = JSON.parse(chunks).entities;\n \n // console.log(`entities : ${JSON.stringify(entities)}`);\n \n var entity = entities[0];\n \n if(entities.length > 0 && entity.hasOwnProperty('AA')) {\n var resIndex = (options.resIndex >> 1);\n // console.log(`resIndex : ${resIndex}`);\n resArray[resIndex] = entities;\n resArray[resIndex]['isAu'] = (1 === (options.resIndex & 1));\n\t\tglobalTypeQueryCount++;\n }\n}", "static getAllRegions() {\n const url = `${API_URL}/region/`\n return axios.get(url)\n }", "function getStateID(abbrev)\n{\n\tif(abbrev == \"AL\"){ return 0;}\n\tif(abbrev == \"AK\"){ return 1;}\n if(abbrev == \"AZ\"){ return 2;}\n if(abbrev == \"AR\"){ return 3;}\n if(abbrev == \"CA\"){ return 4;}\n if(abbrev == \"CO\"){ return 5;}\n if(abbrev == \"CT\"){ return 6;}\n if(abbrev == \"DE\"){ return 7;}\n if(abbrev == \"DC\"){ return 8;}\n if(abbrev == \"FL\"){ return 9;}\n\tif(abbrev == \"GA\"){ return 10;}\n\tif(abbrev == \"HI\"){ return 11;}\n\tif(abbrev == \"ID\"){ return 12;}\n\tif(abbrev == \"IL\"){ return 13;}\n\tif(abbrev == \"IN\"){ return 14;}\n\tif(abbrev == \"IA\"){ return 15;}\n\tif(abbrev == \"KS\"){ return 16;}\n\tif(abbrev == \"KY\"){ return 17;}\n\tif(abbrev == \"LA\"){ return 18;}\n if(abbrev == \"ME\"){ return 19;}\n if(abbrev == \"MD\"){ return 20;}\n\tif(abbrev == \"MA\"){ return 21;}\t\n\tif(abbrev == \"MI\"){ return 22;}\t\t\n\tif(abbrev == \"MN\"){ return 23;}\t\t\n\tif(abbrev == \"MS\"){ return 24;}\t\n\tif(abbrev == \"MT\"){ return 25;}\n\tif(abbrev == \"MO\"){ return 26;}\n\tif(abbrev == \"NE\"){ return 27;}\n if(abbrev == \"NV\"){ return 28;}\n if(abbrev == \"NH\"){ return 29;}\n if(abbrev == \"NJ\"){ return 30;}\n if(abbrev == \"NM\"){ return 31;}\n if(abbrev == \"NY\"){ return 32;}\n if(abbrev == \"NC\"){ return 33;}\n if(abbrev == \"ND\"){ return 34;}\n\tif(abbrev == \"OH\"){ return 35;}\n\tif(abbrev == \"OK\"){ return 36;}\n\tif(abbrev == \"OR\"){ return 37;}\n\tif(abbrev == \"PM\"){ return 38;}\n\tif(abbrev == \"PA\"){ return 39;}\n if(abbrev == \"RI\"){ return 40;}\n if(abbrev == \"SC\"){ return 41;}\n if(abbrev == \"SD\"){ return 42;}\n if(abbrev == \"TN\"){ return 43;}\n if(abbrev == \"TX\"){ return 44;}\n if(abbrev == \"UT\"){ return 45;}\n if(abbrev == \"VT\"){ return 46;}\n\tif(abbrev == \"VA\"){ return 47;}\n\tif(abbrev == \"WA\"){ return 48;}\n\tif(abbrev == \"WV\"){ return 49;}\n\tif(abbrev == \"WI\"){ return 50;}\n\tif(abbrev == \"WY\"){ return 51;}\n}", "get region() {\n return this.getStringAttribute('region');\n }", "function mapEntities() {\n\n var entity = {\n positions:{},\n years:{} ,\n entity: this.Entity\n };\n\n // determine kind of entity\n var key = undefined;\n\n if( !(this.productId === undefined)) {\n // have product id\n key = this.productId;\n entity.kind = \"product\";\n } else if(!(this.accountId === undefined)) {\n key = this.accountId;\n entity.kind = \"account\";\n } else {\n // myst be top level\n key = this.Entity;\n entity.kind = \"top\"\n }\n\n // position is designated by title\n var position = {\n // expectation data rows keyed by source\n expectations:{},\n // actial results keyed by year\n results:{}\n };\n\n if (this.qualifier == \"Ergebnis\") {\n // this is real value\n position.results[this.year] = this.value\n } else {\n // compose expectation value\n // and described by qualifier. it also provides\n // map of years. data series will be created in finalisation step\n var source = { };\n source[this.year] = this.value;\n position.expectations[this.source] = source;\n }\n\n // store position and year in the entity\n entity.positions[this.title] = position;\n entity.years[this.year] = null;\n\n emit(key, entity);\n}", "function set_entityusecode() {\n var STATES = get_states_map(); //use state map to get state abbreviations based on states internal ids\n var USECODES = create_usecodes_map();\n var length_of_address_list = nlapiGetLineItemCount('addressbook'); //find length of address book so we can sort through it\n var tax_exempt_states = nlapiGetFieldValues('custentity_tax_exempt_states'); //grab array of internal ids where the customer is tax exempt\n if (tax_exempt_states) {\n for (var i = 1; i <= length_of_address_list; i++) { //loop through each address line\n nlapiSelectLineItem('addressbook', i);\n var state = nlapiGetCurrentLineItemValue('addressbook', 'state'); //grab state on the line\n nlapiLogExecution('DEBUG', 'state', state);\n if(STATES[state]){\n var state_id = STATES[state].toString(); //need to compare to string for comparison\n if (tax_exempt_states.indexOf(state_id) !== -1) { //if state on address is in tax exempt states\n nlapiSetCurrentLineItemValue('addressbook', 'custpage_ava_entityusecode', USECODES.G); //set entity use code to 2\n } else {\n nlapiSetCurrentLineItemValue('addressbook', 'custpage_ava_entityusecode', USECODES.TAXABLE); // else set it to 1\n }\n nlapiCommitLineItem('addressbook');\n }\n }\n }\n window.entityusecode_needs_to_be_set = false; //this is a global used to tell if this function should be called. Set to true on click of adding or editing an address\n\n function create_usecodes_map() {\n return {\n Z: '2'\n , G: '3'\n , TAXABLE: '1'\n };\n }\n function get_states_map() {\n return {\n AL: 1,\n AK: 2,\n AZ: 3,\n AR: 4,\n CA: 5,\n CO: 6,\n CT: 7,\n DE: 8,\n FL: 9,\n GA: 10,\n HI: 11,\n ID: 12,\n IL: 13,\n IN: 14,\n IA: 15,\n KS: 16,\n KY: 17,\n LA: 18,\n ME: 19,\n MD: 20,\n MA: 21,\n MI: 22,\n MN: 23,\n MS: 24,\n MO: 25,\n MT: 26,\n NE: 27,\n NV: 28,\n NH: 29,\n NJ: 30,\n NM: 31,\n NY: 32,\n NC: 33,\n ND: 34,\n OH: 35,\n OK: 36,\n OR: 37,\n PA: 38,\n RI: 39,\n SC: 40,\n SD: 41,\n TN: 42,\n TX: 43,\n UT: 44,\n VT: 45,\n VA: 46,\n WA: 47,\n WV: 48,\n WI: 49,\n WY: 50\n };\n }\n}", "function setReg(d) {\n d.region = region.get(d.id) || 0;\n return d.region;\n}", "function getIdOfItem(item){\n return item.id;\n}", "function getRegions (req, res, next) {\n return db.Countries\n .findAll({\n attributes: ['region'],\n group: 'region'\n })\n .map(data => data.region)\n .then(data => {\n req.resJson = { data }\n return next()\n })\n .catch(error => next(error))\n}", "function fillInIds() {\n entityObj.curRcrds = attachTempIds(entityObj.curRcrds); //console.log(\"entityObj.curRcrds = %O\", entityObj.curRcrds)\n }", "translate(itemName){\n\t\titemName = this.idCorrection(itemName);\n\t\tvar res=\"\";\n\t\tlet index = this.globalTables.search(\"translate\");\n\t\tif (index!=-1){\n\t\t\tthis.globalTables[index].array.forEach(function(item){\n\t\t\t\tif (itemName===item.itemName)\n\t\t\t\t\tres = item.itemTranslate;\n\t\t\t});\n\t\t}\n\t\telse{\n\t\t\tconsole.error(`Global table ${itemName} isnt found`);\n\t\t}\n\t\treturn res;\n\t}", "function addMarkerRegionToMI() {\n\t\t\tconsole.log(\"addMarkerRegionToMI()\");\n\n\t\t\tif (\n vm.markerRegionSearch == null\n || vm.markerRegionSearch.refsKey == null\n || vm.markerRegionSearch.refsKey == \"\"\n ) {\n alert(\"Add To Mutation Involves Required Fields:\\n\\nAllele\\nChr\\nStart Coordinate\\nEnd Coordinate\\nRelationship Type\\nJ#\");\n\t\t\t\tdocument.getElementById(\"startCoordinate\").focus();\n\t\t\t\treturn;\n\t\t\t}\n\n if (vm.markerRegion.length == 0) {\n alert(\"Add To Mutation Involves: 0 Markers found\");\n\t\t\t\tdocument.getElementById(\"startCoordinate\").focus();\n\t\t\t\treturn;\n }\n\n var newMI = vm.apiDomain.mutationInvolves.length;\n\n for(var i=0;i<vm.apiDomain.mutationInvolves.length; i++) { \n if (vm.apiDomain.mutationInvolves[i].processStatus == \"c\") {\n newMI = i;\n break;\n }\n }\n\n for(var i=0;i<vm.markerRegion.length; i++) { \n\t\t\t vm.apiDomain.mutationInvolves[newMI] = {\n\t\t\t\t \"processStatus\": \"c\",\n\t\t\t\t \"relationshipKey\": \"\",\n\t\t\t \t \"alleleKey\": vm.apiDomain.alleleKey,\n \"alleleSymbol\": \"\",\n\t\t\t \t \"markerKey\": vm.markerRegion[i].markerKey,\n \"markerSymbol\": vm.markerRegion[i].symbol,\n \"markerAccID\": vm.markerRegion[i].accID,\n \"organismKey\": \"1\",\n \"organism\": \"mouse, laboratory\",\n\t\t\t \t \"categoryKey\": \"1003\",\n\t\t\t \t \"categoryTerm\": \"\",\n\t\t\t \t \"relationshipTermKey\": vm.markerRegionSearch.relationshipTermKey,\n\t\t\t \t \"relationshipTerm\": \"\",\n\t\t\t \t \"qualifierKey\": \"11391898\",\n\t\t\t \t \"qualifierTerm\": \"\",\n\t\t\t \t \"evidenceKey\": \"11391900\",\n\t\t\t \t \"evidenceTerm\": \"IGC\",\n\t\t\t\t \"refsKey\": vm.markerRegionSearch.refsKey,\n\t\t\t \t \"jnumid\": vm.markerRegionSearch.jnumid,\n\t\t\t\t \"short_citation\": vm.markerRegionSearch.short_citation,\n\t\t\t\t \"createdBy\": \"\",\n\t\t\t\t \"creation_date\": \"\",\n\t\t\t\t \"modifiedBy\": \"\",\n\t\t\t\t \"modification_date\": \"\"\n\t\t\t }\n\n addMINoteRow(i);\n newMI = newMI + 1;\n }\n }", "function common_getCityMap(){\n var common_cityMap = {\n '朝阳区': '1|72',\n '海淀区': '1|2800',\n '西城区': '1|2801',\n '东城区': '1|2802',\n '崇文区': '1|2803',\n '宣武区': '1|2804',\n '丰台区': '1|2805',\n '石景山区': '1|2806',\n '门头沟': '1|2807',\n '房山区': '1|2808',\n '通州区': '1|2809',\n '大兴区': '1|2810',\n '顺义区': '1|2812',\n '怀柔区': '1|2814',\n '密云区': '1|2816',\n '昌平区': '1|2901',\n '平谷区': '1|2953',\n '延庆县': '1|3065',\n '徐汇区': '2|2813',\n '长宁区': '2|2815',\n '静安区': '2|2817',\n '闸北区': '2|2820',\n '虹口区': '2|2822',\n '杨浦区': '2|2823',\n '宝山区': '2|2824',\n '闵行区': '2|2825',\n '嘉定区': '2|2826',\n '浦东新区': '2|2830',\n '青浦区': '2|2833',\n '松江区': '2|2834',\n '金山区': '2|2835',\n '奉贤区': '2|2837',\n '普陀区': '2|2841',\n '崇明县': '2|2919',\n '黄浦区': '2|78',\n '东丽区': '3|51035',\n '和平区': '3|51036',\n '河北区': '3|51037',\n '河东区': '3|51038',\n '河西区': '3|51039',\n '红桥区': '3|51040',\n '蓟县': '3|51041',\n '静海县': '3|51042',\n '南开区': '3|51043',\n '塘沽区': '3|51044',\n '西青区': '3|51045',\n '武清区': '3|51046',\n '津南区': '3|51047',\n '汉沽区': '3|51048',\n '大港区': '3|51049',\n '北辰区': '3|51050',\n '宝坻区': '3|51051',\n '宁河县': '3|51052',\n '万州区': '4|113',\n '涪陵区': '4|114',\n '梁平区': '4|115',\n '南川区': '4|119',\n '潼南区': '4|123',\n '大足区': '4|126',\n '黔江区': '4|128',\n '武隆区': '4|129',\n '丰都县': '4|130',\n '奉节县': '4|131',\n '开州区': '4|132',\n '云阳县': '4|133',\n '忠县': '4|134',\n '巫溪县': '4|135',\n '巫山县': '4|136',\n '石柱县': '4|137',\n '彭水县': '4|138',\n '垫江县': '4|139',\n '酉阳县': '4|140',\n '秀山县': '4|141',\n '璧山区': '4|48131',\n '荣昌区': '4|48132',\n '铜梁区': '4|48133',\n '合川区': '4|48201',\n '巴南区': '4|48202',\n '北碚区': '4|48203',\n '江津区': '4|48204',\n '渝北区': '4|48205',\n '长寿区': '4|48206',\n '永川区': '4|48207',\n '江北区': '4|50950',\n '南岸区': '4|50951',\n '九龙坡区': '4|50952',\n '沙坪坝区': '4|50953',\n '大渡口区': '4|50954',\n '綦江区': '4|50995',\n '渝中区': '4|51026',\n '高新区': '4|51027',\n '北部新区': '4|51028',\n '城口县': '4|4164',\n '石家庄市': '5|142',\n '邯郸市': '5|148',\n '邢台市': '5|164',\n '保定市': '5|199',\n '张家口市': '5|224',\n '承德市': '5|239',\n '秦皇岛市': '5|248',\n '唐山市': '5|258',\n '沧州市': '5|264',\n '廊坊市': '5|274',\n '衡水市': '5|275',\n '太原市': '6|303',\n '大同市': '6|309',\n '阳泉市': '6|318',\n '晋城市': '6|325',\n '朔州市': '6|330',\n '晋中市': '6|336',\n '忻州市': '6|350',\n '吕梁市': '6|368',\n '临汾市': '6|379',\n '运城市': '6|398',\n '长治市': '6|3074',\n '郑州市': '7|412',\n '开封市': '7|420',\n '洛阳市': '7|427',\n '平顶山市': '7|438',\n '焦作市': '7|446',\n '鹤壁市': '7|454',\n '新乡市': '7|458',\n '安阳市': '7|468',\n '濮阳市': '7|475',\n '许昌市': '7|482',\n '漯河市': '7|489',\n '三门峡市': '7|495',\n '南阳市': '7|502',\n '商丘市': '7|517',\n '周口市': '7|527',\n '驻马店市': '7|538',\n '信阳市': '7|549',\n '济源市': '7|2780',\n '沈阳市': '8|560',\n '大连市': '8|573',\n '鞍山市': '8|579',\n '抚顺市': '8|584',\n '本溪市': '8|589',\n '丹东市': '8|593',\n '锦州市': '8|598',\n '葫芦岛市': '8|604',\n '营口市': '8|609',\n '盘锦市': '8|613',\n '阜新市': '8|617',\n '辽阳市': '8|621',\n '朝阳市': '8|632',\n '铁岭市': '8|6858',\n '长春市': '9|639',\n '吉林市': '9|644',\n '四平市': '9|651',\n '辽源市': '9|2992',\n '通化市': '9|657',\n '白山市': '9|664',\n '松原市': '9|674',\n '白城市': '9|681',\n '延边州': '9|687',\n '鹤岗市': '10|727',\n '双鸭山市': '10|731',\n '鸡西市': '10|737',\n '大庆市': '10|742',\n '伊春市': '10|753',\n '牡丹江市': '10|757',\n '佳木斯市': '10|765',\n '七台河市': '10|773',\n '黑河市': '10|776',\n '绥化市': '10|782',\n '大兴安岭地区': '10|793',\n '哈尔滨市': '10|698',\n '齐齐哈尔市': '10|712',\n '呼和浩特市': '11|799',\n '包头市': '11|805',\n '乌海市': '11|810',\n '赤峰市': '11|812',\n '乌兰察布市': '11|823',\n '锡林郭勒盟': '11|835',\n '呼伦贝尔市': '11|848',\n '鄂尔多斯市': '11|870',\n '巴彦淖尔市': '11|880',\n '阿拉善盟': '11|891',\n '兴安盟': '11|895',\n '通辽市': '11|902',\n '南京市': '12|904',\n '徐州市': '12|911',\n '连云港市': '12|919',\n '淮安市': '12|925',\n '宿迁市': '12|933',\n '盐城市': '12|939',\n '扬州市': '12|951',\n '泰州市': '12|959',\n '南通市': '12|965',\n '镇江市': '12|972',\n '常州市': '12|978',\n '无锡市': '12|984',\n '苏州市': '12|988',\n '济宁市': '13|2900',\n '济南市': '13|1000',\n '青岛市': '13|1007',\n '淄博市': '13|1016',\n '枣庄市': '13|1022',\n '东营市': '13|1025',\n '潍坊市': '13|1032',\n '烟台市': '13|1042',\n '威海市': '13|1053',\n '莱芜市': '13|1058',\n '德州市': '13|1060',\n '临沂市': '13|1072',\n '聊城市': '13|1081',\n '滨州市': '13|1090',\n '菏泽市': '13|1099',\n '日照市': '13|1108',\n '泰安市': '13|1112',\n '黄山市': '14|1151',\n '滁州市': '14|1159',\n '阜阳市': '14|1167',\n '亳州市': '14|1174',\n '宿州市': '14|1180',\n '池州市': '14|1201',\n '六安市': '14|1206',\n '宣城市': '14|2971',\n '铜陵市': '14|1114',\n '合肥市': '14|1116',\n '淮南市': '14|1121',\n '淮北市': '14|1124',\n '芜湖市': '14|1127',\n '蚌埠市': '14|1132',\n '马鞍山市': '14|1137',\n '安庆市': '14|1140',\n '宁波市': '15|1158',\n '衢州市': '15|1273',\n '丽水市': '15|1280',\n '台州市': '15|1290',\n '舟山市': '15|1298',\n '杭州市': '15|1213',\n '温州市': '15|1233',\n '嘉兴市': '15|1243',\n '湖州市': '15|1250',\n '绍兴市': '15|1255',\n '金华市': '15|1262',\n '福州市': '16|1303',\n '厦门市': '16|1315',\n '三明市': '16|1317',\n '莆田市': '16|1329',\n '泉州市': '16|1332',\n '漳州市': '16|1341',\n '南平市': '16|1352',\n '龙岩市': '16|1362',\n '宁德市': '16|1370',\n '孝感市': '17|1432',\n '黄冈市': '17|1441',\n '咸宁市': '17|1458',\n '恩施州': '17|1466',\n '鄂州市': '17|1475',\n '荆门市': '17|1477',\n '随州市': '17|1479',\n '神农架林区': '17|3154',\n '武汉市': '17|1381',\n '黄石市': '17|1387',\n '襄阳市': '17|1396',\n '十堰市': '17|1405',\n '荆州市': '17|1413',\n '宜昌市': '17|1421',\n '潜江市': '17|2922',\n '天门市': '17|2980',\n '仙桃市': '17|2983',\n '长沙市': '18|1482',\n '株洲市': '18|1488',\n '湘潭市': '18|1495',\n '衡阳市': '18|1501',\n '邵阳市': '18|1511',\n '岳阳市': '18|1522',\n '常德市': '18|1530',\n '张家界市': '18|1540',\n '郴州市': '18|1544',\n '益阳市': '18|1555',\n '永州市': '18|1560',\n '怀化市': '18|1574',\n '娄底市': '18|1586',\n '湘西州': '18|1592',\n '广州市': '19|1601',\n '深圳市': '19|1607',\n '珠海市': '19|1609',\n '汕头市': '19|1611',\n '韶关市': '19|1617',\n '河源市': '19|1627',\n '梅州市': '19|1634',\n '揭阳市': '19|1709',\n '惠州市': '19|1643',\n '汕尾市': '19|1650',\n '东莞市': '19|1655',\n '中山市': '19|1657',\n '江门市': '19|1659',\n '佛山市': '19|1666',\n '阳江市': '19|1672',\n '湛江市': '19|1677',\n '茂名市': '19|1684',\n '肇庆市': '19|1690',\n '云浮市': '19|1698',\n '清远市': '19|1704',\n '潮州市': '19|1705',\n '崇左市': '20|3168',\n '南宁市': '20|1715',\n '柳州市': '20|1720',\n '桂林市': '20|1726',\n '梧州市': '20|1740',\n '北海市': '20|1746',\n '防城港市': '20|1749',\n '钦州市': '20|1753',\n '贵港市': '20|1757',\n '玉林市': '20|1761',\n '贺州市': '20|1792',\n '百色市': '20|1806',\n '河池市': '20|1818',\n '来宾市': '20|3044',\n '南昌市': '21|1827',\n '景德镇市': '21|1832',\n '萍乡市': '21|1836',\n '新余市': '21|1842',\n '九江市': '21|1845',\n '鹰潭市': '21|1857',\n '上饶市': '21|1861',\n '宜春市': '21|1874',\n '抚州市': '21|1885',\n '吉安市': '21|1898',\n '赣州市': '21|1911',\n '凉山州': '22|2103',\n '成都市': '22|1930',\n '自贡市': '22|1946',\n '攀枝花市': '22|1950',\n '泸州市': '22|1954',\n '绵阳市': '22|1960',\n '德阳市': '22|1962',\n '广元市': '22|1977',\n '遂宁市': '22|1983',\n '内江市': '22|1988',\n '乐山市': '22|1993',\n '宜宾市': '22|2005',\n '广安市': '22|2016',\n '南充市': '22|2022',\n '达州市': '22|2033',\n '巴中市': '22|2042',\n '雅安市': '22|2047',\n '眉山市': '22|2058',\n '资阳市': '22|2065',\n '阿坝州': '22|2070',\n '甘孜州': '22|2084',\n '三亚市': '23|3690',\n '文昌市': '23|3698',\n '五指山市': '23|3699',\n '临高县': '23|3701',\n '澄迈县': '23|3702',\n '定安县': '23|3703',\n '屯昌县': '23|3704',\n '昌江县': '23|3705',\n '白沙县': '23|3706',\n '琼中县': '23|3707',\n '陵水县': '23|3708',\n '保亭县': '23|3709',\n '乐东县': '23|3710',\n '三沙市': '23|3711',\n '海口市': '23|2121',\n '琼海市': '23|3115',\n '万宁市': '23|3137',\n '东方市': '23|3173',\n '儋州市': '23|3034',\n '贵阳市': '24|2144',\n '六盘水市': '24|2150',\n '遵义市': '24|2155',\n '铜仁市': '24|2169',\n '毕节市': '24|2180',\n '安顺市': '24|2189',\n '黔西南州': '24|2196',\n '黔东南州': '24|2205',\n '黔南州': '24|2222',\n '迪庆州': '25|4108',\n '昆明市': '25|2235',\n '曲靖市': '25|2247',\n '玉溪市': '25|2258',\n '昭通市': '25|2270',\n '普洱市': '25|2281',\n '临沧市': '25|2291',\n '保山市': '25|2298',\n '丽江市': '25|2304',\n '文山州': '25|2309',\n '红河州': '25|2318',\n '西双版纳州': '25|2332',\n '楚雄州': '25|2336',\n '大理州': '25|2347',\n '德宏州': '25|2360',\n '怒江州': '25|2366',\n '阿里地区': '26|3970',\n '林芝市': '26|3971',\n '拉萨市': '26|2951',\n '那曲地区': '26|3107',\n '山南地区': '26|3129',\n '昌都地区': '26|3138',\n '日喀则地区': '26|3144',\n '延安市': '27|2428',\n '汉中市': '27|2442',\n '榆林市': '27|2454',\n '商洛市': '27|2468',\n '安康市': '27|2476',\n '西安市': '27|2376',\n '铜川市': '27|2386',\n '宝鸡市': '27|2390',\n '咸阳市': '27|2402',\n '渭南市': '27|2416',\n '庆阳市': '28|2525',\n '陇南市': '28|2534',\n '武威市': '28|2544',\n '张掖市': '28|2549',\n '酒泉市': '28|2556',\n '甘南州': '28|2564',\n '临夏州': '28|2573',\n '定西市': '28|3080',\n '兰州市': '28|2487',\n '金昌市': '28|2492',\n '白银市': '28|2495',\n '天水市': '28|2501',\n '嘉峪关市': '28|2509',\n '平凉市': '28|2518',\n '西宁市': '29|2580',\n '海东地区': '29|2585',\n '海北州': '29|2592',\n '黄南州': '29|2597',\n '海南州': '29|2603',\n '果洛州': '29|2605',\n '玉树州': '29|2612',\n '海西州': '29|2620',\n '银川市': '30|2628',\n '石嘴山市': '30|2632',\n '吴忠市': '30|2637',\n '固原市': '30|2644',\n '中卫市': '30|3071',\n '五家渠市': '31|4110',\n '博尔塔拉蒙古自治州阿拉山口口岸': '31|4163',\n '阿拉尔市': '31|15945',\n '图木舒克市': '31|15946',\n '乌鲁木齐市': '31|2652',\n '克拉玛依市': '31|2654',\n '石河子市': '31|2656',\n '吐鲁番地区': '31|2658',\n '哈密地区': '31|2662',\n '和田地区': '31|2666',\n '阿克苏地区': '31|2675',\n '喀什地区': '31|2686',\n '克孜勒苏州': '31|2699',\n '巴音郭楞州': '31|2704',\n '昌吉州': '31|2714',\n '博尔塔拉州': '31|2723',\n '伊犁州': '31|2727',\n '塔城地区': '31|2736',\n '阿勒泰地区': '31|2744',\n '台湾市': '32|2768',\n '钓鱼岛': '84|1310',\n '香港特别行政区': '52993|52994',\n '澳门特别行政区': '52993|52995'\n };\n return common_cityMap;\n}", "function fromDatastore(item){\n item.id = item[Datastore.KEY].id;\n return item;\n}", "function mapFromTxLangCode(str) {\n return str.replace(\"_\", \"-\").replace(\"@\", \"-\").replace(\"latin\", \"latn\");\n }", "getCountryNameById (countryId) {\n var i = 0\n var res = ''\n Object.keys(map).forEach(key => {\n var continentName = map[key]\n for (var countries in continentName) {\n if (i == countryId) {\n res = countries\n }\n i++\n }\n })\n // console.log('returned value = ' + res)\n return res\n }", "async loadRegions () {\n const saved = await fetch('/regions.json');\n this.input.region.items = await saved.json();\n }", "static updateItemMap(type, itemMap, itemIdx, r, c, height, width) {\n const gridWidth = StorageGrid.getData(type).width;\n for (let r1 = r; r1 < r + height; r1 += 1) {\n for (let c1 = c; c1 < c + width; c1 += 1) {\n const mapObj = {};\n if (r1 === r && c1 === c) {\n mapObj.status = TOP;\n mapObj.idx = itemIdx;\n } else {\n mapObj.status = OCCUIPED;\n }\n\n itemMap.set(r1 * gridWidth + c1, mapObj);\n }\n }\n }", "function regions(request, response) {\n\n console.log(\"get all regions\");\n\n db.find({\"agency.region\": new RegExp('.')}, function (err, docs) {\n\n var map = new HashMap();\n var result = [];\n\n for(var i = 0; i < docs.length; i++) {\n\n var agency = docs[i].agency;\n var key = agency.region;\n\n if(!map.has(key)) {\n map.set(key, key);\n result.push(\n {\n region: agency.region,\n lat: agency.lat,\n lon: agency.lon,\n geohash: agency.geohash\n })\n console.log('regions:key:' + key + ' = ' + JSON.stringify(agency));\n }\n }\n\n result.sort(function(regionA, regionB) {\n if(regionA.region < regionB.region )\n return -1;\n else if (regionA.region > regionB.region)\n return 1;\n else\n return 0;\n });\n\n response.send(JSON.stringify(result))\n\n });\n\n}", "function encodeEntityRanges(block, storageMap) {\n\t var encoded = [];\n\t block.findEntityRanges(function (character) {\n\t return !!character.getEntity();\n\t }, function ( /*number*/start, /*number*/end) {\n\t var text = block.getText();\n\t var key = block.getEntityAt(start);\n\t encoded.push({\n\t offset: strlen(text.slice(0, start)),\n\t length: strlen(text.slice(start, end)),\n\t // Encode the key as a number for range storage.\n\t key: Number(storageMap[DraftStringKey.stringify(key)])\n\t });\n\t });\n\t return encoded;\n\t}", "getCountryIdByName (countryName) {\n var i = 0\n var res = -1\n Object.keys(map).forEach(key => {\n var continentName = map[key]\n for (var countries in continentName) {\n if (countries === countryName) {\n res = i\n }\n i++\n }\n })\n // console.log('returned value = ' + res)\n return res\n }", "handleChangeRegion(e, index, region) {\n let flightData = this.state.flightData;\n flightData.region = region;\n\n this.setState({ flightData: flightData });\n\n //Get cities data by region\n this.getCities(region);\n this.setState({ disableCity: false });\n }", "getRegions(stage) {\n return this.meta.getRegions(stage);\n }", "function extractPlaceholderToIds(messageBundle) {\n var messageMap = messageBundle.getMessageMap();\n var placeholderToIds = {};\n Object.keys(messageMap).forEach(function (msgId) {\n placeholderToIds[msgId] = messageMap[msgId].placeholderToMsgIds;\n });\n return placeholderToIds;\n}", "function getRegionalStates(){\n var regionalCode = $.request.parameters.get('regionalCode');\n \tvar output = {\n\t\tresults: []\n\t};\n\toutput.results.push({});\n\tvar connection = $.db.getConnection();\n\tvar pstmtState = '';\n\tvar queryState = '';\n\ttry {\n\t\tqueryState = 'select ST.STATE_CODE,ST.STATE_NAME from \"MDB_DEV\".\"TRN_REGIONAL\" as TR inner join \"MDB_DEV\".\"STATESDATA\" as ST on TR.STATE_CODE = ST.STATE_CODE where TR.REGIONAL_CODE = ?';\n\t\t//'SELECT REGIONAL_CODE,REGIONAL_NAME FROM \"MDB_DEV\".\"MST_REGIONAL\" ';\n\t\tpstmtState = connection.prepareStatement(queryState);\n\t\tpstmtState.setString(1,regionalCode);\n\t\tvar rsState = pstmtState.executeQuery();\n\t\twhile (rsState.next()) {\n\t\t\tvar record = {};\n\t\t\trecord.StateCode = rsState.getString(1);\n\t\t\trecord.StateName = rsState.getString(2);\n\t\t\toutput.results.push(record);\n\t\t}\n\n\t\tconnection.close();\n\t} catch (e) {\n\n\t\t$.response.status = $.net.http.INTERNAL_SERVER_ERROR;\n\t\t$.response.setBody(e.message);\n\t\treturn;\n\t}\n\n\tvar body = JSON.stringify(output);\n\t$.response.contentType = 'application/json';\n\t$.response.setBody(body);\n\t$.response.status = $.net.http.OK;\n}", "setRegion(value) {\n super.put(\"region\", value);\n }", "function loadMapFromId(id) {\n\tswitch(id) {\n\t\tcase \"2018_congress\":\n\t\t\tloadCurrentCongress();\n\t\t\tbreak;\n\t\tcase \"2020_cook\":\n\t\tcase \"2020_inside\":\n\t\tcase \"2020_sabatos\":\n\t\tcase \"2016_presidential\":\n\t\tcase \"2012_presidential\":\n\t\tcase \"2008_presidential\":\n\t\tcase \"2004_presidential\":\n\t\tcase \"2000_presidential\":\n\t\tcase \"1996_presidential\":\n\t\tcase \"1992_presidential\":\n\t\tcase \"1988_presidential\":\n\t\tcase \"1984_presidential\":\n\t\tcase \"1980_presidential\":\n\t\tcase \"1976_presidential\":\n\t\tcase \"1972_presidential\":\n\t\tcase \"1968_presidential\":\n\t\tcase \"1964_presidential\":\n\t\tcase \"1960_presidential\":\n\t\tcase \"1956_presidential\":\n\t\tcase \"1952_presidential\":\n\t\tcase \"1948_presidential\":\n\t\tcase \"1944_presidential\":\n\t\tcase \"1940_presidential\":\n\t\tcase \"1936_presidential\":\n\t\tcase \"1932_presidential\":\n\t\tcase \"1928_presidential\":\n\t\tcase \"1924_presidential\":\n\t\tcase \"1920_presidential\":\n\t\tcase \"1916_presidential\":\n\t\tcase \"1912_presidential\":\n\t\tcase \"1908_presidential\":\n\t\tcase \"1904_presidential\":\n\t\tcase \"1900_presidential\":\n\t\tcase \"1896_presidential\":\n\t\tcase \"1892_presidential\":\n\t\tcase \"1888_presidential\":\n\t\tcase \"1884_presidential\":\n\t\tcase \"1880_presidential\":\n\t\tcase \"1876_presidential\":\n\t\tcase \"1876_presidential\":\n\t\tcase \"1872_presidential\":\n\t\tcase \"1868_presidential\":\n\t\tcase \"1864_presidential\":\n\t\tcase \"2016_presidential_county\":\n\t\t\tloadPresetMap(id);\n\t\t\tbreak;\n\t\t\tbreak;\n\t\tcase \"2020_presidential\":\n\t\t\tloadMap(\"./res/usa_presidential.svg\", 16, 1, \"usa_ec\", \"presidential\", \"open\", {updateText: true, voters: 'usa_voting_pop', enablePopularVote: true});\n\t\t\tbreak;\n\t\tcase \"1972_presidential\":\n\t\t\tloadMap(\"./res/usa_1972_presidential.svg\", 16, 1, \"usa_1972_ec\", \"presidential\", \"open\", {updateText: true});\n\t\t\tbreak;\n\t\tcase \"2020_senatorial\":\n\t\t\tloadMap(\"./res/usa_senate.svg\", 16, 1, \"usa_senate\", \"senatorial\", \"2020\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"2020_gubernatorial\":\n\t\t\tloadMap(\"./res/usa_gubernatorial.svg\", 16, 1, \"usa_gubernatorial\", \"gubernatorial\", \"2020\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"2020_democratic_primary\":\n\t\t\tloadMap(\"./res/usa_dem_primary.svg\", 16, 1, \"dem_primary\", \"primary\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"2020_republican_primary\":\n\t\t\tloadMap(\"./res/usa_rep_primary.svg\", 16, 1, \"rep_primary\", \"primary\", \"open\",{updateText: false});\n\t\t\tbreak;\n\t\tcase \"USA_county\":\n\t\t\tloadMap(\"./res/usa_county.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"USA_congressional\":\n\t\t\tloadMap(\"./res/usa_congressional_2018.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"USA_congressional_2008\":\n\t\t\tloadMap(\"./res/usa_congressional_2008.svg\", 16, 0.005, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"USA_gubernatorial\":\n\t\t\tloadMap(\"./res/usa_gubernatorial.svg\", 16, 1.5, \"usa_gubernatorial\", \"gubernatorial\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"USA_senatorial\":\n\t\t\tloadMap(\"./res/usa_senate.svg\", 16, 1.5, \"usa_senate\", \"senatorial\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"USA_takeall\":\n\t\t\tloadMap(\"./res/usa_no_districts.svg\", 16, 1, \"usa_no_districts_ec\", \"presidential\", \"open\", {updateText: true});\n\t\t\tbreak;\n\t\tcase \"USA_proportional\":\n\t\t\tloadMap(\"./res/usa_no_districts.svg\", 16, 1, \"usa_no_districts_ec\", \"proportional\", \"open\", {updateText: true});\n\t\t\tbreak;\n\t\tcase \"USA_pre_civilwar\":\n\t\t\tloadMap(\"./res/usa_pre_civilwar.svg\", 16, 1, \"usa_pre_civilwar_ec\", \"presidential\", \"open\", {updateText: true});\n\t\t\tbreak;\n\t\tcase \"Germany_states\":\n\t\t\tloadMap(\"./res/germany.svg\", 16, 1, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tloadPreset('germany')\n\t\t\tbreak;\n\t\tcase \"Germany_constituencies\":\n\t\t\tloadMap(\"./res/germany_constituencies.svg\", 16, 1, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tloadPreset('germany')\n\t\t\tbreak;\n\t\tcase \"France_constituencies\":\n\t\t\tloadMap(\"./res/france_constituencies.svg\", 16, 0.25, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tloadPreset('france')\n\t\t\tbreak;\n\t\tcase \"Italy_states\":\n\t\t\tloadMap(\"./res/italy.svg\", 16, 1, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tloadPreset('italy')\n\t\t\tbreak;\n\t\tcase \"Spain_constituencies\":\n\t\t\tloadmap(\"./res/spain_constituencies.svg\", 16, 1, \"spain_constituencies\", \"proportional\", \"open\", {updateText: true});\n\t\t\tbreak;\n\t\tcase \"UnitedKingdom_constituencies\":\n\t\t\tloadMap(\"./res/unitedkingdom.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tloadPreset('uk')\n\t\t\tbreak;\n\t\tcase \"Canada_provinces\":\n\t\t\tloadMap(\"./res/canada_states.svg\", 38, 2, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tloadPreset('canada')\n\t\t\tbreak;\n\t\tcase \"Canada_constituencies\":\n\t\t\tloadMap(\"./res/canada_constituencies.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: true});\n\t\t\tloadPreset('canada')\n\t\t\tbreak;\n\t\tcase \"Australia_constituencies\":\n\t\t\tloadMap(\"./res/australia_constituencies.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tloadPreset('australia')\n\t\t\tbreak;\n\t\tcase \"Australia_states\":\n\t\t\tloadMap(\"./res/australia.svg\", 16, 0.075, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tloadPreset('australia')\n\t\t\tbreak;\n\t\tcase \"EuropeanUnion\":\n\t\t\tloadMap(\"./res/eu.svg\", 16, 0.25, \"eu_parliament\", \"primary\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"World\":\n\t\t\tloadMap(\"./res/world.svg\", 38, 0.5, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"LTE_presidential\":\n\t\t\tloadMap(\"./res/lte_president.svg\", 30, 1, \"lte_ec\", \"presidential\", \"open\", {updateText: true});\n\t\t\tbreak;\n\t\tcase \"LTE_senatorial\":\n\t\t\tloadMap(\"./res/lte_senate.svg\", 35, 1, \"ltesenate\", \"senatorial\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tcase \"LTE_congressional\":\n\t\t\tloadMap(\"./res/lte_house.svg\", 35, 1, \"congressional\", \"congressional\", \"open\", {updateText: false});\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tloadMap(\"./res/usa_presidential.svg\", 16, 1, \"usa_ec\", \"presidential\", \"open\", {updateText: true, voters: 'usa_voting_pop', enablePopularVote: true});\n\t\t\tbreak;\n\t}\n}", "async getRegionByID(req, res) {\n res.status(200).json({\n region: req.region,\n status: 200,\n ok: true,\n title: 'Successful request',\n message: 'Region Found',\n });\n }", "getAllItemsFromSiteId(db, site_id) {\n return db.from(\"inventory\").where({\n site_id: site_id,\n });\n }", "function initializeTranslateTable() {\n return {\n\t\"BB10-WebWorks-Samples\": \"BB10-Web<em>...</em>Samples\",\n\t\"Cascades-Community-Samples\": \"Cascades-Comm<em>...</em>\",\n\t\"jQuery-Mobile-Samples\": \"jQuery-Mobile<em>...</em>\",\n\t\"OpenGLES2-ProgrammingGuide\": \"OpenGLES<em>...</em>Guide\",\n\t\"PushSampleApp(AIR-BB10)\": \"PushSample<em>...</em>AIR-BB10\",\n\t\"Qt2Cascades-Samples\": \"Qt2Cascades<em>...</em>\",\n\t\"Qt2Cascades.IPC\": \"Qt2<em>...</em>.IPC\",\n\t\"Qt2Cascades.Network\": \"Qt2<em>...</em>.Network\",\n\t\"Qt2Cascades.Threads\": \"Qt2<em>...</em>.Threads\",\n\t\"Qt2Cascades.QtConcurrency\": \"Qt2<em>...</em>.QtConcurrency\",\n\t\"Qt2Cascades.Script\": \"Qt2<em>...</em>.Script\",\n\t\"Qt2Cascades.StateMachine\": \"Qt2<em>...</em>.StateMachine\",\n\t\"Qt2Cascades.SQL\": \"Qt2<em>...</em>.SQL\",\n\t\"Qt2Cascades.Tools\": \"Qt2<em>...</em>.Tools\",\n\t\"Qt2Cascades.XML\": \"Qt2<em>...</em>.XML\",\n\t\"SampleBPSANE(AIR)\": \"SampleBPSANE<em>...</em>AIR\",\n\t\"SampleApplication(AIR)\": \"SampleApp<em>...</em>AIR\",\n\t\"SampleLibrary(AIR)\": \"SampleLib<em>...</em>AIR\",\n\t\"ScoreloopIntegrationSample\": \"Scoreloop<em>...</em>\",\n\t\"ScoreloopIntegrationSample(Cascades)\": \"Scoreloop<em>...</em>(Cascades)\",\n\t\"StarshipSettings(AIR-BB10)\": \"Starship<em>...</em>AIR-BB10\",\n\t\"WeatherGuesser(AIR-BB10)\": \"Weather<em>...</em>AIR-BB10\",\n\t\"WebWorks-Community-APIs\": \"WebWorks-<em>...</em>APIs\"\n };\n}", "_uniqueEntities(callback) {\n var uniqueIds = Object.create(null),\n entities = this._entities;\n return function (id) {\n if (!(id in uniqueIds)) {\n uniqueIds[id] = true;\n callback(fromId(entities[id]));\n }\n };\n }", "async onRegionSubscription(store, snapshot) {\n\n /**\n * TODO:\n * - deal with deleted region (check if region is curently selected)\n * - deal with updating issues (list does not update)\n */\n // console.log('snapshot', snapshot)\n const user = await userService.getUser()\n const { items } = snapshot\n const updated = items.filter(\n (item) => item.dateLastUpdated > LAST_REGION_UPDATE && item.userLastUpdated !== user.name,\n )\n\n updated.forEach((item) => {\n item = new models.RegionModel(item)\n // record the new `lastUpdate`\n if (item.dateLastUpdated > LAST_REGION_UPDATE) {\n actions.setLastRegionUpdate(item.dateLastUpdated)\n }\n // update the region locally if need be\n const existing = store.getters.regionById(item.id)\n // don't overwrite indexes with `undefined` values\n delete item.index\n delete item.displayIndex\n\n if (existing) {\n if (item.dateLastUpdated > existing.dateLastUpdated) {\n store.dispatch('commitRegionUpdate', {\n update: item,\n region: existing\n })\n\n // only dispatch if the regionId matches the current selected region\n const selectedRegion = store.getters.selectedRegion\n if (selectedRegion && existing.id === selectedRegion.id) {\n // trigger update event for the RTE\n EventBus.$emit('realtime-region-update', item)\n }\n }\n } else {\n store.dispatch('commitRegionAdd', item)\n }\n })\n }", "function updateRegionCountryNames(region) {\n let currentRegionCountries = []\n regionInfo[region].forEach(el => {\n el && currentRegionCountries.push(el)\n })\n\n document.querySelector('.countries-of-region').innerHTML = ''; // removing prior countries\n for (let country of currentRegionCountries) {\n document.querySelector('.countries-of-region').insertAdjacentHTML('beforeend', `<p class='${country}'>${country}</p><br><br>`);\n }\n}", "function getLocaleId() {\n return LOCALE_ID;\n}", "function getLocaleId() {\n return LOCALE_ID;\n}", "function getLocaleId() {\n return LOCALE_ID;\n}", "function getLocaleId() {\n return LOCALE_ID;\n}", "function getLocaleId() {\n return LOCALE_ID;\n}", "function getLocaleId() {\n return LOCALE_ID;\n}" ]
[ "0.5673479", "0.54454905", "0.5367876", "0.5277067", "0.52213895", "0.52213895", "0.519641", "0.5184962", "0.5180875", "0.517186", "0.51667744", "0.5149466", "0.51056194", "0.50919724", "0.50568193", "0.50346017", "0.5029587", "0.5024988", "0.5006605", "0.5001268", "0.500123", "0.4986275", "0.4986275", "0.4986275", "0.49770054", "0.4955224", "0.49479604", "0.49422625", "0.4940443", "0.49209636", "0.4905669", "0.48821917", "0.4879368", "0.48704278", "0.4853305", "0.48339123", "0.4828327", "0.48233724", "0.48185748", "0.4814042", "0.48054904", "0.4794985", "0.47891152", "0.47881702", "0.47793898", "0.47779703", "0.47754416", "0.47635266", "0.47618848", "0.47464517", "0.4737902", "0.47340694", "0.47319046", "0.47289196", "0.47281417", "0.47276992", "0.4726834", "0.47223952", "0.47222853", "0.4720334", "0.47169712", "0.47004408", "0.46893263", "0.46865904", "0.4683113", "0.46830592", "0.46630123", "0.4662565", "0.46611866", "0.4645377", "0.46414617", "0.46406934", "0.46394777", "0.46378723", "0.46371445", "0.4628138", "0.46166378", "0.46092105", "0.46006486", "0.45982876", "0.45934665", "0.45927897", "0.4592221", "0.4590546", "0.4589811", "0.45896333", "0.45836467", "0.45825118", "0.45762882", "0.45636445", "0.45626384", "0.45583627", "0.45576635", "0.4551916", "0.45446515", "0.4538896", "0.4538896", "0.4538896", "0.4538896", "0.4538896", "0.4538896" ]
0.0
-1
search bar is mounted for the first time
componentDidMount() { console.log('search bar mounted'); getItemManifest(this.props.entity.region).then((data) => { this.setState( { entity: {...this.props.entity}, EntityList: data, }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function onSearch() {\n var wasActive = !!activeSearch\n activeSearch = searchBox.value\n if (!wasActive) {\n viewer.addFilter(searchFilter)\n }\n clearOption.style.visibility = \"visible\"\n onSearchBlur()\n viewer.filter()\n refreshFilterPane()\n }", "initSearch() {\n this.search.init();\n\n if (this.visible) {\n this.closeSearch();\n } else {\n this.openSearch();\n }\n }", "startSearch() {\n if (!this._isEnabled) {\n return;\n }\n this.showLoading();\n }", "function _renderSearch() {\n _$navbar.setMod(_B_BAR, _M_SEARCH, false);\n setTimeout(function() {\n _$navbar.setMod(_B_BAR, _M_SEARCH, _searchIsActive);\n }, CFG.TIME.ANIMATION);\n }", "handleSearchBar()\n {\n this._page = 1;\n this._searchBar = $(\"#searchBar\").val();\n this.getBooks();\n }", "function initSearch() {\n var searchInput=$(\"#search-input\");\n var magnifier=$(\"#magnifier\");\n var filmWrapper=$(\".film-wrapper\");\n var seriesWrapper=$(\".series-wrapper\");\n var myQuery;\n\n searchInput.on('keydown',function(e) {\n if (e.which == 13) {\n myQuery=searchInput.val();\n searchApi(myQuery);\n searchInput.val(\"\");\n }\n });\n\n magnifier.click(function() {\n myQuery=searchInput.val();\n searchApi(myQuery);\n searchInput.val(\"\");\n });\n}", "componentDidMount() {\n $(\"#searchBar\").keyup(function(e){\n if(e.which == 13 || $(\"#searchBar\").val().length === 0){\n Actions.searchVenues($(\"#searchBar\").val())\n Actions.updateList();\n\n } // if\n\n });\n }", "search() {\n this.trigger('search', {\n element: this.searchBar,\n query: this.searchBar.value\n });\n }", "_deferredInvocUpdateSearch() {\n QuickFilterBarMuxer.updateSearch();\n }", "function _focusSearch() {\n setTimeout(function() {\n _$search.focus();\n }, CFG.TIME.DELAY);\n }", "function focusSearchBoxListener(){ $('#query').val('').focus() }", "componentDidMount() {\r\n this.searchRef.focus();\r\n }", "function updateForSearchVisible() {\n /* Prevent accidental scrolling of the body, prevent page layout jumps */\n let scrolledBodyWidth = document.body.offsetWidth;\n document.body.style.overflow = 'hidden';\n document.body.style.paddingRight = (document.body.offsetWidth - scrolledBodyWidth) + 'px';\n\n document.getElementById('search-input').value = '';\n document.getElementById('search-input').focus();\n document.getElementById('search-results').style.display = 'none';\n document.getElementById('search-notfound').style.display = 'none';\n document.getElementById('search-help').style.display = 'block';\n}", "function initSearchBar() {\n var category = $('select#search-category').val();\n var placeholder = CONFIG.search_placeholder[category];\n var search = $('input#mapsearch');\n var width = $(window).width();\n if (width < 768) {\n if (search.hasClass('collapsed')) return;\n search.addClass('collapsed');\n setTimeout(function() { search.attr('placeholder','') }, 300);\n search.siblings().find('span.glyphicon-search').on('click', function() {\n search.toggleClass('collapsed');\n if (search.hasClass('collapsed')) {\n setTimeout(function() {\n search.attr('placeholder','');\n search.val('');\n }, 300);\n } else {\n search.attr('placeholder',placeholder);\n // search.off('click');\n }\n });\n } else {\n search.removeClass('collapsed');\n search.attr('placeholder',placeholder);\n }\n}", "handleFilterFormInitSearchEvent() {\n\t\tthis.listingElement.classList.add('registry-component-list--loading');\n\t\tthis.listingElement.setAttribute('aria-busy', 'true');\n\t}", "onSearch() {\n try {\n const searchText = this.getSearchHash();\n if (searchText === this.priorSearchText)\n return;\n this.engine.search(searchText);\n this.priorSearchText = searchText;\n }\n catch (ex) {\n this.publish(\"error\", ex.message);\n }\n }", "function initUI () {\n // Clear query when clear icon is clicked\n $('#searchBoxIcon').click(function () {\n $('#searchBoxInput').val('')\n $('#searchBoxInput').trigger('keyup')\n })\n\n // Event when chenging query\n $('#searchBoxInput').keyup(function () {\n var $searchResults = $('#searchResults')\n var query = $(this).val().trim()\n\n // Icon switching\n if (query.length) {\n $('#searchBoxIcon').attr('src', '/img/clear.png')\n $('#searchBoxIcon').css('cursor', 'pointer')\n } else {\n $('#searchBoxIcon').attr('src', '/img/search.png')\n $('#searchBoxIcon').css('cursor', 'default')\n }\n\n // Only trigger a search when 2 chars. at least have been provided\n if (query.length < 2) {\n $searchResults.hide()\n return\n }\n\n // Display search results\n renderResults(fuse.search(query))\n $searchResults.show()\n })\n\n // Emit keyup event for when the query is already setted with browser back etc.\n $('#searchBoxInput').trigger('keyup')\n}", "focusSearchBar() {\n const searchInputEl = this.searchBarContainer && \n this.searchBarContainer.querySelector('.js-yext-query');\n searchInputEl && searchInputEl.focus();\n }", "function initSearch() {\r\n\tconsole.log(\"searchReady\");\r\n}", "prev(){\n // if is something in search input use search items array\n if (this.searchInput.select) {\n this.page.curSearch--\n this.searchItems()\n // else use discover items array\n } else {\n this.page.cur--\n this.discoverItems()\n }\n // scroll to top\n this.scrollToTop(300)\n }", "function handleSearchV2() {\n $(\".blog-topbar .search-btn\").on(\"click\", function() {\n if (jQuery(\".topbar-search-block\").hasClass(\"topbar-search-visible\")) {\n jQuery(\".topbar-search-block\").slideUp();\n jQuery(\".topbar-search-block\").removeClass(\"topbar-search-visible\");\n } else {\n jQuery(\".topbar-search-block\").slideDown();\n jQuery(\".topbar-search-block\").addClass(\"topbar-search-visible\");\n }\n });\n $(\".blog-topbar .search-close\").on(\"click\", function() {\n jQuery(\".topbar-search-block\").slideUp();\n jQuery(\".topbar-search-block\").removeClass(\"topbar-search-visible\");\n });\n jQuery(window).scroll(function() {\n jQuery(\".topbar-search-block\").slideUp();\n jQuery(\".topbar-search-block\").removeClass(\"topbar-search-visible\");\n });\n }", "_setInputVisible(){\r\n this.filterString = this.currentText;\r\n this.inputIsVisible = true;\r\n this.$nextTick(() => {\r\n this.getRef('input').focus();\r\n })\r\n }", "function search() {\r\n let searchTerm = id(\"search-term\").value.trim();\r\n if (searchTerm !== \"\") {\r\n id(\"home\").disabled = false;\r\n loadBooks(\"&search=\" + searchTerm);\r\n }\r\n }", "function searchActivated() {\n $('.search-text').toggle();\n $('#floatingBarsG').toggle();\n getDataFromYelp();\n}", "function triggerUpdate () {\n if (SearchTextInput.value.length > 0) { // Refresh only if a search is active\n\t// Clear input timeout if there was one active, to replace it by new (maybe faster) one\n\t// This allows to integrate together multiple events without intermediate displays,\n\t// like remove of a folder and its subtree\n\tif (inputTimeout != null) {\n\t clearTimeout(inputTimeout);\n\t}\n\t// Schedule a new one\n\tinputTimeout = setTimeout(updateSearch, UpdateSearchDelay);\n }\n}", "componentDidMount(){\n this.search.focus();\n }", "clickSearch() {\n this.set('loading', true);\n this.elasticSearch.setFilterString(\"\");\n this.elasticSearch.clearUserSearch();\n this.elasticSearch.queryUsers();\n }", "function initializePage() {\n\tconsole.log(\"Javascript connected!\");\n /*$(\"#searchbar\").hide();\n $(\"#searchBtn\").click(function(){\n $(\"#searchbar\").show();\n $(\"#searchbar\").css(\"width\",\"50%\");\n console.log(\"????????????//\");\n\n });*/\n \n}", "function init() {\n updateResults();\n bind.typeaheadKeys();\n bind.searchFocus();\n bind.searchChange();\n bind.searchSubmit();\n bind.historyState();\n}", "function active(){\n\tvar searchBar = document.getElementById(\"searchBar\");\n\n\tif(searchBar.value == \"Search...\"){\n\t\tsearchBar.value = \"\";\n\t\tsearchBar.placeholder = \"Search...\"\n\t}\n}", "locationSearch() {\n if (this.$locationInput.val()) {\n $('.spinner-zone').show();\n IndexSearchObj.searchYelp();\n this.focusBlur();\n }\n }", "initAutoComplete() {\n if ($(\"#banner-search-bar\").length) {\n this.initAutoCompleteOn($('#banner-search-bar'));\n }\n this.initAutoCompleteOn($('#header-search-bar'));\n }", "function searchWine(){\n setSearchFor();\n whatToSearch();\n watchSubmit();\n}", "onUpdateContent() {\n this.checkAutocomplete();\n\n if (!this.search) {\n this.emmitEvent('');\n }\n }", "searchClicked(_) {\n flikrSearch(this.state.term).fork(this.showError,this.updateResults)\n }", "function searchthis(e){\n $.search.value = \"keyword to search\";\n $.search.blur();\n focused = false;\n needclear = true;\n}", "_addSearchBarEvents() {\n const searchBarForm = document.getElementById(\"search-bar-form\");\n const searchBarInput = document.getElementById(\"search-bar-input\");\n\n searchBarForm.onclick = (e) => e.stopPropagation();\n\n searchBarInput.onfocus = () => {\n this._closeAllFiltersExceptClicked();\n };\n\n searchBarInput.oninput = (e) => {\n let recipesListToDisplay;\n\n if (searchBarInput.value.length >= 3) {\n recipesListToDisplay = this.getRecipesListToDisplay();\n\n this._displaySearchResultMessage(recipesListToDisplay);\n } else if (this._badgesList.length > 0) {\n recipesListToDisplay = this._recipesList.search(\n {\n userInput: \"\",\n joinedBadges: this._userRequest.joinedBadges,\n },\n this._hashTableForSearchingRecipes\n );\n\n this._displaySearchResultMessage(recipesListToDisplay);\n } else {\n recipesListToDisplay = this._recipesList;\n\n const messageAside = document.getElementById(\"message\");\n\n messageAside.classList.remove(\"opened\");\n }\n\n this._renderFiltersOptions(\n this.getItemsListsToDisplay(recipesListToDisplay)\n );\n this._renderCards(recipesListToDisplay);\n };\n\n searchBarForm.onsubmit = (e) => {\n e.preventDefault();\n searchBarInput.blur();\n };\n }", "function initUI() {\n // Clear query when clear icon is clicked\n $('#searchBoxIcon').click(function () {\n $('#searchBoxInput').val('')\n $('#searchBoxInput').trigger('keyup')\n })\n\n // Event when chenging query\n $('#searchBoxInput').keyup(function () {\n var $searchResults = $('#searchResults')\n var query = $(this).val()\n\n // Icon switching\n if (query.length) {\n $('#searchBoxIcon').attr('src', '/img/clear.png')\n $('#searchBoxIcon').css('cursor', 'pointer')\n } else {\n $('#searchBoxIcon').attr('src', '/img/search.png')\n $('#searchBoxIcon').css('cursor', 'default')\n }\n\n // Only trigger a search when 2 chars. at least have been provided\n if (query.length < 2) {\n $searchResults.hide()\n return\n }\n\n // Display search results\n renderResults(search(query))\n $searchResults.show()\n })\n\n // Emit keyup event for when the query is already setted with browser back etc.\n $('#searchBoxInput').trigger('keyup')\n}", "componentDidMount() {\n this.refs.searchBar.focus();\n }", "constructor() {\n this.addSearchHTML(); //Js is synchronous, so must call this function first\n this.resultsDiv = $(\"#search-overlay__results\");\n this.openButton = $(\".js-search-trigger\");\n this.closeButton = $(\".search-overlay__close\");\n this.searchOverlay = $(\".search-overlay\"); \n this.searchField = $(\"#search-term\");\n this.isOverlayOpen = false;\n this.isSpinnerVisible = false;\n this.typingTimer; //call to reset timer\n this.previousValue;\n this.events();\n }", "function topNavSearch() {\n\n\t\tvar topNavSearch = $('.top-nav-search-wrap'),\n\t\t\ttopnavSearchX = topNavSearch.children('div').find('i');\n\n\t\tif ( topNavSearch.length > 0 ) {\n\n\t\t\ttopNavSearch.children('div').width( sidebarTop.children('div').outerWidth() );\n\t\t\ttopnavSearchX.attr( 'class', 'fa fa-times search-icon' );\n\n\t\t\ttopNavSearch.children('a').on('click', function(event) {\n\t\t\t\tevent.preventDefault();\n\t\t\t\ttopNavSearch.children('div').fadeIn();\n\t\t\t});\n\n\t\t\ttopnavSearchX.on('click', function() {\n\t\t\t\ttopNavSearch.children('div').fadeOut();\n\t\t\t});\n\n\t\t}\n\n\t}", "function showForm () {\n if (typeof _links !== 'object' || !Array.isArray(_links) || !_links) { return init(); }\n if (!_root.getAttribute('data-searchinit')) {\n _root.setAttribute('data-searchinit','true');\n win.setTimeout(function () {\n _search.querySelector('input').focus();\n }, 220);\n } else {\n _root.removeAttribute('data-searchinit');\n }\n }", "function search() {\n $.var.currentSupplier = $.var.search;\n $.var.currentID = 0;\n $.var.search.query = $(\"#searchable\").val();\n if ($.var.search.query.trim().length === 0) { // if either no string, or string of only spaces\n $.var.search.query = \" \"; // set query to standard query used on loadpage\n }\n $.var.search.updateWebgroupRoot();\n}", "openSearch() {\n this.element_main.style.visibility = \"visible\"; // show search box\n this.element_input.focus(); // put focus in input box so you can just start typing\n this.visible = true; // search visible\n }", "function init() {\n\n loadLatestSearch();\n\n displayLatestSearches();\n\n searchHandler();\n\n $('#submitBtn').on(\"click\", () => {\n saveSearchTerm($('#search').val().toUpperCase()); \n searchHandler($('#search').val());\n })\n}", "constructor() {\n this.addSearchHTML();\n this.resultsDiv = document.querySelector(\"#search-overlay__results\");\n this.openButton = document.querySelectorAll(\".js-search-trigger\");\n this.closeButton = document.querySelector(\".search-overlay__close\");\n this.searchOverlay = document.querySelector(\".search-overlay\");\n this.searchField = document.querySelector(\"#search-term\");\n this.isOverlayOpen = false;\n this.isSpinnerVisible = false;\n this.previousValue;\n this.typingTimer;\n this.events();\n }", "function searchEventListener() {\n\t$(\"#searchbtn\").click(function() {\n\t\tif ($(\"#searchbox\").val() != '') {\n\t\t\tsearchNewspapers($(\"#searchbox\").val());\n\t\t}\n\t});\n}", "searchinputCallback(event) {\n const inputVal = this.locationInput;\n if (inputVal) {\n this.getListQuery(inputVal);\n }\n else {\n this.queryItems = [];\n if (this.userSelectedOption) {\n this.userQuerySubmit('false');\n }\n this.userSelectedOption = '';\n if (this.settings.showRecentSearch) {\n this.showRecentSearch();\n }\n else {\n this.dropdownOpen = false;\n }\n }\n }", "search(e){\n \n\t e.preventDefault();\n\t let input = document.querySelector('#photo-search');\n\t let term = input.value;\n\t \n\t if(term.length > 2){\t\t \n\t\t input.classList.add('searching');\n\t\t this.container.classList.add('loading');\n\t\t this.search_term = term;\n\t\t this.is_search = true;\n\t\t this.doSearch(this.search_term);\t\t \n\t } else {\t\t \n\t\t input.focus();\t\t \n\t }\n\t \n }", "constructor () {\n this._csrf = document.querySelector('[name=\"_csrf\"]').value\n\n this.injectHTML()\n this.headerSearchIcon = document.querySelector(\".header-search-icon\")\n this.overlay = document.querySelector(\".search-overlay\")\n this.closeIcon = document.querySelector(\".close-live-search\")\n this.inputField = document.querySelector(\"#live-search-field\")\n this.resultsArea = document.querySelector(\".live-search-results\")\n this.loaderIcon = document.querySelector(\".circle-loader\") //As soon as someone is typing in this field of search (see the div class of live-search-results)\n\n this.typingWaitTimer \n //waiting for 500ms to 700ms after it stopped typing new characters. Wait a tiny bit after they(users) stopped typing, and then send off a request.\n\n\n this.previousValue\n //Only if value in the field has changed, then we show a loading icon here.\n\n this.events()\n }", "function initSearchBox(options) {\n // Invoke auto complete for search box\n var searchOptions = {\n data: options,\n list: {\n maxNumberOfElments: 0,\n match: {enabled: true},\n onChooseEvent: function () {\n searchChooseItem();\n }\n }\n };\n searchInput.easyAutocomplete(searchOptions);\n\n // Start searching when typing in search box\n searchInput.on(\"input\", function (e) {\n e.preventDefault();\n searchChooseItem();\n });\n }", "searchPrev(){\n this.searchIndex--;\n this.searchMovie();\n this.$nextTick(function(){\n scrollRight(\"search_display\");\n });\n }", "constructor() {\n this.addSearchHTML();\n\n this.openButton = $('.js-search-trigger');\n this.closeButton = $('.search-overlay__close');\n this.searchOverlay = $('.search-overlay');\n this.searchField = $('#search-term');\n this.isOpen = false;\n this.typingTimer;\n this.resultsDiv = $('#search-overlay__result');\n this.previousValue;\n this.isSpinVisible = false;\n \n this.events();\n }", "function setQuery() {\n getSearch(search.value);\n}", "function searchUpdated(term) {\n setsearch(term);\n }", "function webSearchCallback() {\n // This needs to be in a timeout so that we don't end up refocused\n // in the url bar\n setTimeout(BrowserSearch.webSearch, 0);\n }", "_onSearchModalShown() {\n document.getElementById(this.settings.searchInputId).focus();\n }", "function displayNewSearchResults(event) {\n let searchTerm = event.target.value;\n let currentSearch = giphy[\"query\"][\"q\"];\n if (searchTerm !== currentSearch && searchTerm !== \"\") {\n giphy[\"query\"][\"q\"] = searchTerm;\n updateOffset(true);\n update();\n }\n}", "onConfirmSearchBar() {\n //this.search(this.state.search)\n }", "function searchCocktail() {\n //set searchTerm to what a user typed in\n console.log(searchValue.current.value);\n setSearchTerm(searchValue.current.value);\n }", "function onSearchFocus() {\n if (activeSearch) {\n searchButton.className = \"pivot_searchbtn\"\n // pop up the suggestions as if we had pressed a key\n onSearchKeyPress({})\n } else {\n searchForm.className = \"\"\n searchBox.value = \"\"\n }\n /* note that this must be on mousedown, not onclick!\n mousedown on this element happens before blur on the text box,\n but before click on this element. we change the text box's contents\n on blur, so using mousedown is the easiest solution. */\n searchButton.onmousedown = onSearch\n }", "function do_search() {\n var query = input_box.val().toLowerCase();\n\n if(query && query.length) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= settings.minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, settings.searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }", "function do_search() {\n var query = input_box.val().toLowerCase();\n\n if(query && query.length) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= settings.minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, settings.searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }", "search(){\n // Condition checks if nothing has been input when first entering website and clicking the button or when something is typed and then deleted\n // returns out of method if this is the case as there will be no results\n if(this.state === null || this.state.term === ''){\n return;\n }\n\n // Calls the passed down event handler search function from App.js\n this.props.onSearch(this.state.term);\n }", "function searchBook() {\n setSearchTerm(searchValue.current.value)\n }", "function setupSearchBar(){\n\t//set up search bar button\n\t//search is declared within utilities.js\n\t\n\t//document.getElementById('search_button').onclick=search;\n\t//document.getElementById('clear_search_button').onclick=clearSearch;\n\t\n\n\t//document.getElementById('search_text_bar').placeholder = search_placeholder_string;\n\tdocument.getElementById('myInput').placeholder = search_placeholder_string;\n\n\t//make it so when you hit the enter button after typing text, it will act as a click\n\tdocument.getElementById(\"myInput\").addEventListener(\"keyup\", function(event) {\n\t\t//console.log(\"typing!\");\n\t\tif(document.getElementById(\"closeSearch\").style.display == \"none\"){\n\t\t\tdocument.getElementById(\"closeSearch\").style.display = \"block\";\n\t\t}\n\n\t//document.getElementById(\"search_text_bar\").addEventListener(\"keyup\", function(event) {\n\t\t// Cancel the default action, if needed\n\t\tevent.preventDefault();\n\t\t// Number 13 is the \"Enter\" key on the keyboard\n\t\tif (event.keyCode === 13) {\n\t\t\t// Trigger the button element with a click\n\t\t\t//document.getElementById(\"search_button\").click();\n\t\t\tsearch();\n\t\t}\n\t});\n}", "componentDidMount() {\n this.useSearchEngine();\n \n }", "function searchBar() {\n\t$(\".page-header\").append(\"<div class=\\\"searchBar\\\"><input type=\\\"text\\\" id=\\\"myInput\\\" placeholder=\\\"Search for names..\\\"></div>\");\n\t$(\"#myInput\").keyup(function () {\n\t let filter = $(this).val();\n\t\t $(\".student-item\").each(function () {\n\t\t if ($(this).text().search(new RegExp(filter, \"i\")) < 0 && $(this).attr(\"id\") !== \"page\") {\n\t\t $(this).hide();\n\t\t } else {\n\t\t \t$(\".null\").remove();\n\t\t $(this).show()\n\t\t }\n\t\t });\n\t\t \tif($('.student-item').children(':visible').length < 1 && $('.null').length === 0)\t {\t\n\t\t \t\t\t$(\".student-list\").prepend(\"<h1 class=\\\"null\\\">no matches</h1>\");\n\t\t\t\t} \n\n\t\t\t\t//if input box has no input, recreate first page with 10 elements\n\t\t\t\trestorePage(filter);\n\t});\n\n}", "onSearchTermChange() {\n this.search();\n Metrics.getInstance().updateMetric(Filters.SEARCH, 1);\n }", "function initSearchButton(){\n\n\tif($j('.search_slides_from_window_top').length){\n\t\t$j('.search_slides_from_window_top').click(function(e){\n\t\t\te.preventDefault();\n\n\t\t\tif($j('html').hasClass('touch')){\n\t\t\t\tif ($j('.qode_search_form').height() == \"0\") {\n\t\t\t\t\t$j('.qode_search_form input[type=\"text\"]').onfocus = function () {\n\t\t\t\t\t\twindow.scrollTo(0, 0);\n\t\t\t\t\t\tdocument.body.scrollTop = 0;\n\t\t\t\t\t};\n\t\t\t\t\t$j('.qode_search_form input[type=\"text\"]').onclick = function () {\n\t\t\t\t\t\twindow.scrollTo(0, 0);\n\t\t\t\t\t\tdocument.body.scrollTop = 0;\n\t\t\t\t\t};\n\t\t\t\t\t$j('.header_top_bottom_holder').css('top','50px');\n\t\t\t\t\t$j('.qode_search_form').css('height','50px');\n\t\t\t\t\t$j('.content_inner').css('margin-top','50px');\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').css('top','0'); }\n\t\t\t\t} else {\n\t\t\t\t\t$j('.qode_search_form').css('height','0');\n\t\t\t\t\t$j('.header_top_bottom_holder').css('top','0');\n\t\t\t\t\t$j('.content_inner').css('margin-top','0');\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').css('top',-$scroll);}\n\t\t\t\t}\n\n\t\t\t\t$j(window).scroll(function() {\n\t\t\t\t\tif ($j('.qode_search_form').height() != \"0\" && $scroll > 50) {\n\t\t\t\t\t\t$j('.qode_search_form').css('height','0');\n\t\t\t\t\t\t$j('.header_top_bottom_holder').css('top','0');\n\t\t\t\t\t\t$j('.content_inner').css('margin-top','0');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t$j('.qode_search_close').click(function(e){\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\t$j('.qode_search_form').css('height','0');\n\t\t\t\t\t$j('.header_top_bottom_holder').css('top','0');\n\t\t\t\t\t$j('.content_inner').css('margin-top','0');\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').css('top',-$scroll);}\n\t\t\t\t});\n\n\t\t\t} else {\n\t\t\t\tif($j('.title').hasClass('has_fixed_background')){\n\t\t\t\t\tvar yPos = parseInt($j('.title.has_fixed_background').css('backgroundPosition').split(\" \")[1]);\n\t\t\t\t}else { \n\t\t\t\t\tvar yPos = 0;\n\t\t\t\t}\n\t\t\t\tif ($j('.qode_search_form').height() == \"0\") {\n\t\t\t\t\t$j('.qode_search_form input[type=\"text\"]').focus();\n\t\t\t\t\t$j('.header_top_bottom_holder').stop().animate({top:\"50px\"},150);\n\t\t\t\t\t$j('.qode_search_form').stop().animate({height:\"50px\"},150);\n\t\t\t\t\t$j('.content_inner').stop().animate({marginTop:\"50px\"},150);\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').stop().animate({top:0},150); }\n\t\t\t\t\t$j('.title.has_fixed_background').animate({\n\t\t\t\t\t\t'background-position-y': (yPos + 50)+'px'\n\t\t\t\t\t}, 150);\n\t\t\t\t} else {\n\t\t\t\t\t$j('.qode_search_form').stop().animate({height:\"0\"},150);\n\t\t\t\t\t$j('.header_top_bottom_holder').stop().animate({top:\"0px\"},150);\n\t\t\t\t\t$j('.content_inner').stop().animate({marginTop:\"0\"},150);\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').stop().animate({top:-$scroll},150);}\n\t\t\t\t\t$j('.title.has_fixed_background').animate({\n\t\t\t\t\t\t'background-position-y': (yPos - 50)+'px'\n\t\t\t\t\t}, 150);\n\t\t\t\t}\n\n\t\t\t\t$j(window).scroll(function() {\n\t\t\t\t\tif ($j('.qode_search_form').height() != \"0\" && $scroll > 50) {\n\t\t\t\t\t\t$j('.qode_search_form').stop().animate({height:\"0\"},150);\n\t\t\t\t\t\t$j('.header_top_bottom_holder').stop().animate({top:\"0px\"},150);\n\t\t\t\t\t\t$j('.content_inner').stop().animate({marginTop:\"0\"},150);\n\t\t\t\t\t\t$j('.title.has_fixed_background').css('backgroundPosition', 'center '+(yPos)+'px');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t$j('.qode_search_close').click(function(e){\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\t$j('.qode_search_form').stop().animate({height:\"0\"},150);\n\t\t\t\t\t$j('.content_inner').stop().animate({marginTop:\"0\"},150);\n\t\t\t\t\t$j('.header_top_bottom_holder').stop().animate({top:\"0px\"},150);\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').stop().animate({top:-$scroll},150);}\n\t\t\t\t\t$j('.title.has_fixed_background').animate({\n\t\t\t\t\t\t'background-position-y': (yPos)+'px'\n\t\t\t\t\t}, 150);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\t\n\t//search type - search_slides_from_header_bottom\n if($j('.search_slides_from_header_bottom').length){\n\n $j('.search_slides_from_header_bottom').click(function(e){\n\n e.preventDefault();\n\n if($j('.qode_search_form_2').hasClass('animated')) {\n $j('.qode_search_form_2').removeClass('animated');\n $j('.qode_search_form_2').css('bottom','0');\n } else {\n $j('.qode_search_form input[type=\"text\"]').focus();\n $j('.qode_search_form_2').addClass('animated');\n var search_form_height = $j('.qode_search_form_2').height();\n $j('.qode_search_form_2').css('bottom',-search_form_height);\n\n }\n\n $j('.qode_search_form_2').addClass('disabled');\n $j('.qode_search_form_2 input[type=\"submit\"]').attr('disabled','disabled');\n if(($j('.qode_search_form_2 .qode_search_field').val() !== '') && ($j('.qode_search_form_2 .qode_search_field').val() !== ' ')) {\n $j('.qode_search_form_2 input[type=\"submit\"]').removeAttr('disabled');\n $j('.qode_search_form_2').removeClass('disabled');\n }\n else {\n $j('.qode_search_form_2').addClass('disabled');\n $j('.qode_search_form_2 input[type=\"submit\"]').attr('disabled','disabled');\n }\n\n $j('.qode_search_form_2 .qode_search_field').keyup(function() {\n if(($j(this).val() !== '') && ($j(this).val() != ' ')) {\n $j('.qode_search_form_2 input[type=\"submit\"]').removeAttr('disabled');\n $j('.qode_search_form_2').removeClass('disabled');\n }\n else {\n $j('.qode_search_form_2 input[type=\"submit\"]').attr('disabled','disabled');\n $j('.qode_search_form_2').addClass('disabled');\n }\n });\n\n\n $j('.content, footer').click(function(e){\n e.preventDefault();\n $j('.qode_search_form_2').removeClass('animated');\n $j('.qode_search_form_2').css('bottom','0');\n });\n\n });\n }\n\n //search type - search covers header\n if($j('.search_covers_header').length){\n\n $j('.search_covers_header').click(function(e){\n\n e.preventDefault();\n if($j(\".search_covers_only_bottom\").length){\n var headerHeight = $j('.header_bottom').height();\n }\n else{\n if($j(\".fixed_top_header\").length){\n var headerHeight = $j('.top_header').height();\n }else{\n var headerHeight = $j('.header_top_bottom_holder').height();\n }\n }\n\n\t\t\t$j('.qode_search_form_3 .form_holder_outer').height(headerHeight);\n\n if($j(\".search_covers_only_bottom\").length){\n $j('.qode_search_form_3').css('bottom',0);\n $j('.qode_search_form_3').css('top','auto');\n }\n\t\t\t$j('.qode_search_form_3').stop(true).fadeIn(600,'easeOutExpo');\n\t\t\t$j('.qode_search_form_3 input[type=\"text\"]').focus();\n\n\n\t\t\t$j(window).scroll(function() {\n if($j(\".search_covers_only_bottom\").length){\n var headerHeight = $j('.header_bottom').height();\n }\n else{\n if($j(\".fixed_top_header\").length){\n var headerHeight = $j('.top_header').height();\n }else{\n var headerHeight = $j('.header_top_bottom_holder').height();\n }\n }\n\t\t\t\t$j('.qode_search_form_3 .form_holder_outer').height(headerHeight);\n\t\t\t});\n\n\t\t\t$j('.qode_search_close, .content, footer').click(function(e){\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\t$j('.qode_search_form_3').stop(true).fadeOut(450,'easeOutExpo');\n\t\t\t});\n\n\t\t\t$j('.qode_search_form_3').blur(function(e){\n\t\t\t\t\t$j('.qode_search_form_3').stop(true).fadeOut(450,'easeOutExpo');\n\t\t\t});\n });\n }\n\t\t\n//search type - fullscreen search\n if($j('.fullscreen_search').length){\n\t\t//search type Circle Appear\n\t\tif($j(\".fullscreen_search_holder.from_circle\").length){\n\t\t\t$j('.fullscreen_search').on('click',function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\tif($j('.fullscreen_search_overlay').hasClass('animate')){\n\t\t\t\t\t$j('.fullscreen_search_overlay').removeClass('animate');\n\t\t\t\t\t$j('.fullscreen_search_holder').css('opacity','0');\n\t\t\t\t\t$j('.fullscreen_search_close').css('opacity','0');\n\t\t\t\t\t$j('.fullscreen_search_close').css('visibility','hidden');\n\t\t\t\t\t$j('.fullscreen_search').css('opacity','1');\n\t\t\t\t\t$j('.fullscreen_search_holder').css('display','none');\n\t\t\t\t} else {\n\t\t\t\t\t$j('.fullscreen_search_overlay').addClass('animate');\n\t\t\t\t\t$j('.fullscreen_search_holder').css('display','block');\n\t\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t\t$j('.fullscreen_search_holder').css('opacity','1');\n\t\t\t\t\t\t$j('.fullscreen_search_close').css('opacity','1');\n\t\t\t\t\t\t$j('.fullscreen_search_close').css('visibility','visible');\n\t\t\t\t\t\t$j('.fullscreen_search').css('opacity','0');\n\t\t\t\t\t},200);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t});\n\t\t\t$j('.fullscreen_search_close').on('click',function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\t$j('.fullscreen_search_overlay').removeClass('animate');\n\t\t\t\t$j('.fullscreen_search_holder').css('opacity','0');\n\t\t\t\t$j('.fullscreen_search_close').css('opacity','0');\n\t\t\t\t$j('.fullscreen_search_close').css('visibility','hidden');\n\t\t\t\t$j('.fullscreen_search').css('opacity','1');\n\t\t\t\t$j('.fullscreen_search_holder').css('display','none');\n\t\t\t\t\n\t\t\t});\n\t\t}\n\t\t//search type Fade Appear\n\t\tif($j(\".fullscreen_search_holder.fade\").length){\n\t\t\t$j('.fullscreen_search').on('click',function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\tif($j('.fullscreen_search_holder').hasClass('animate')) {\n\t\t\t\t\t$j('body').removeClass('fullscreen_search_opened');\n\t\t\t\t\t$j('.fullscreen_search_holder').removeClass('animate');\n\t\t\t\t\t$j('body').removeClass('search_fade_out');\n\t\t\t\t\t$j('body').removeClass('search_fade_in');\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\t$j('body').addClass('fullscreen_search_opened');\n\t\t\t\t\t$j('body').removeClass('search_fade_out');\n\t\t\t\t\t$j('body').addClass('search_fade_in');\n\t\t\t\t\t$j('.fullscreen_search_holder').addClass('animate');\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t});\n\t\t\t$j('.fullscreen_search_close').on('click',function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\t$j('body').removeClass('fullscreen_search_opened');\n\t\t\t\t$j('.fullscreen_search_holder').removeClass('animate');\n\t\t\t\t$j('body').removeClass('search_fade_in');\n\t\t\t\t$j('body').addClass('search_fade_out');\n\t\t\t\t\n\t\t\t});\n\t\t}\n\t\t\n\t\t//Text input focus change\n\t\t$j('.fullscreen_search_holder .search_field').focus(function(){\n\t\t\t$j('.fullscreen_search_holder .field_holder .line').css(\"width\",\"100%\");\n\t\t});\n\t\t\n\t\t$j('.fullscreen_search_holder .search_field').blur(function(){\n\t\t\t$j('.fullscreen_search_holder .field_holder .line').css(\"width\",\"0\");\n\t\t});\n\t\t\n\t\t//search close button - setting its position vertically\n\t\t$j(window).scroll(function() {\n\t\t\tvar bottom_height = $j(\".page_header .header_bottom\").height();\n\t\t\tif($j(\".page_header\").hasClass(\"sticky\")){\n\t\t\t\t$j(\".fullscreen_search_holder .side_menu_button\").css(\"height\",bottom_height);\n\t\t\t\t$j(\".fullscreen_search_holder .close_container\").css(\"top\",\"0\");\n\t\t\t} else if($j(\".page_header\").hasClass(\"fixed\")){ \n\t\t\t\t$j(\".fullscreen_search_holder .side_menu_button\").css(\"height\",bottom_height);\n\t\t\t} else {\n\t\t\t\t$j(\".fullscreen_search_holder .side_menu_button\").css(\"height\",\"\");\n\t\t\t\t$j(\".fullscreen_search_holder .close_container\").css(\"top\",\"\");\n\t\t\t}\n\t\t});\n }\n\n if($j('.qode_search_submit').length) {\n $j('.qode_search_submit').click(function(e) {\n e.preventDefault();\n e.stopPropagation();\n\n var searchForm = $j(this).parents('form').first();\n\n searchForm.submit();\n });\n }\n\t\n}", "loaded() {\n this.searchField.waitForVisible();\n return true;\n }", "function initHeaderSearch()\n\t{\n\t\tif($('.search_button').length)\n\t\t{\n\t\t\t$('.search_button').on('click', function()\n\t\t\t{\n\t\t\t\tif($('.header_search_container').length)\n\t\t\t\t{\n\t\t\t\t\t$('.header_search_container').toggleClass('active');\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}", "function start() {\n var mc = autocomplete(document.getElementById('search'))\n .keys(keys)\n .dataField(\"State\")\n .placeHolder(\"Search States - Start typing here\")\n .width(960)\n .height(500)\n .onSelected(onSelect)\n .render();\n}", "showSearchContainer(e) {\n e.preventDefault();\n this.setState({\n showingSearch: !this.state.showingSearch,\n searchTerm: '',\n searchResults: {items: [], total: 0}\n });\n }", "function setupSearch() {\n $(\".search-btn\").click(submitSearch);\n $(\".date-search-bar\").keypress(submitSearch);\n $(\".search-bar\").keypress(submitSearch);\n\n var filter = getURLParameter(\"filter\");\n\n var searchTip;\n\n if (filter !== null) {\n searchTip = sprintf(\"Search with the %s filter\", filter);\n } else if (endsWith(window.location.pathname, \"visualizations\")) {\n searchTip = sprintf(\"Filter %s's visualizations\", profileUsername);\n } else {\n searchTip = sprintf(\"Search %s's history\", profileUsername);\n }\n\n makeTip(\".search-bar\", searchTip, \"right\", \"hover\");\n makeTip(\".date-search-bar\", \"Limit search by date.\", \"bottom\", \"hover\");\n}", "componentDidMount() {\n this.makeFullSearch();\n }", "function updateSearch () {\n // Triggered by timeout (or Enter key), so now clear the id\n inputTimeout = null;\n\n // Get search string\n let value = SearchTextInput.value;\n\n // Do not trigger any search if the input box is empty\n // Can happen in rare cases where we would hit the cancel button, and updateSearch() is dispatched\n // before the event dispatch to manageSearchTextHandler() and so before it could clear the timeout.\n if (value.length > 0) { // Launch search only if there is something to search for\n\t// Activate search mode and Cancel search button if not already\n\tif (sboxState != SBoxExecuted) {\n\t enableCancelSearch();\n\t}\n\t// Update search history list\n\tupdateSearchList(value);\n\n\t// Discard previous results table if there is one\n\tif (resultsTable != null) {\n\t SearchResult.removeChild(resultsTable);\n\t resultsTable = null;\n\t curResultRowList = {};\n//\t resultsFragment = null;\n\n\t // If a row cell was highlighted, do not highlight it anymore\n//\t clearCellHighlight(rcursor, rlastSelOp, rselection.selectIds);\n\t cancelCursorSelection(rcursor, rselection);\n\t}\n\n\t// Display waiting for results icon\n\tWaitingSearch.hidden = false;\n\n\t// Look for bookmarks matching the search text in their contents (title, url .. etc ..)\n\tlet searching;\n\tif (!options.noffapisearch\n\t\t&& (options.searchField == \"both\") && (options.searchScope == \"all\") && (options.searchMatch == \"words\")) {\n//console.log(\"Using FF Search API\");\n\t // It seems that parameters can make the search API fail and return 0 results sometimes, so strip them out,\n\t // there will be too much result maybe, but at least some results !\n\t let simpleUrl;\n\t let paramsPos = value.indexOf(\"?\");\n\t if (paramsPos >= 0) {\n\t\tsimpleUrl = value.slice(0, paramsPos);\n\t }\n\t else {\n\t\tsimpleUrl = value;\n\t }\n\t searching = browser.bookmarks.search(decodeURI(simpleUrl));\n\t}\n\telse {\n//console.log(\"Using BSP2 internal search algorithm\");\n\t searching = new Promise ( // Do it asynchronously as that can take time ...\n\t\t(resolve) => {\n\t\t let a_matchStr;\n\t\t let matchRegExp;\n\t\t let isRegExp, isTitleSearch, isUrlSearch;\n\t\t let a_BN;\n\n\t\t if (options.searchField == \"both\") {\n\t\t\tisTitleSearch = isUrlSearch = true;\n\t\t }\n\t\t else if (options.searchField == \"title\") {\n\t\t\tisTitleSearch = true;\n\t\t\tisUrlSearch = false;\n\t\t }\n\t\t else {\n\t\t\tisTitleSearch = false; \n\t\t\tisUrlSearch = true;\n\t\t }\n\n\t\t if (options.searchMatch == \"words\") { // Build array of words to match\n\t\t\tisRegExp = false;\n\t\t\ta_matchStr = strLowerNormalize(value).split(\" \"); // Ignore case and diacritics\n\t\t }\n\t\t else {\n\t\t\tisRegExp = true;\n\t\t\ttry {\n\t\t\t matchRegExp = new RegExp (strNormalize(value), \"i\"); // Ignore case and diacritics\n\t\t\t}\n\t\t\tcatch (e) { // If malformed regexp, do not continue, match nothing\n\t\t\t a_BN = [];\n\t\t\t}\n\t\t }\n\n\t\t if (a_BN == undefined) { // No error detected, execute search\n\t\t\tif (options.searchScope == \"all\") { // Use the List form\n\t\t\t a_BN = searchCurBNList(a_matchStr, matchRegExp, isRegExp, isTitleSearch, isUrlSearch);\n\t\t\t}\n\t\t\telse { // Use the recursive form\n\t\t\t let BN;\n\t\t\t if (cursor.cell == null) { // Start from Root\n\t\t\t\tBN = rootBN;\n\t\t\t }\n\t\t\t else { // Retrieve BN of cell in cursor\n\t\t\t\tBN = curBNList[cursor.bnId];\n\t\t\t\t// Protection\n\t\t\t\tif (BN == undefined) {\n\t\t\t\t BN = rootBN;\n\t\t\t\t}\n\t\t\t }\n\t\t\t a_BN = searchBNRecur(BN, a_matchStr, matchRegExp, isRegExp, isTitleSearch, isUrlSearch,\n\t\t\t\t\t\t\t\t (options.searchScope == \"subfolder\") // Go down to subfolders, or only current folder ?\n\t\t\t\t\t\t\t\t );\n\t\t\t}\n\t\t }\n\n\t\t resolve(a_BN);\n\t\t}\n\t );\n\t}\n\tsearching.then(\n\t function (a_BTN) { // An array of BookmarkTreeNode or of BookmarkNode (a poor man's kind of \"polymorphism\" in Javascript ..)\n\t\t// Create the search results table only if a search is still active.\n\t\t// Can happen when browser.bookmarks.search() is very long, like higher than InputKeyDelay,\n\t\t// and we have cleared the input box / cancelled the search in between.\n\t\tif (SearchTextInput.value.length > 0) { // Display results only if there is something to search for\n\t\t displayResults(a_BTN);\n\t\t}\n\t }\n\t);\n }\n}", "function handleSearch(e) {\n setSearchRes([]);\t \n const idx = lunr(function() {\nthis.ref('id');\nthis.field('text');\nthis.metadataWhitelist = ['position'];\n//console.log('hook: ',mdPaths)\nmdRaws.forEach(function(raw) {\nthis.add(raw);\n}, this);\t\n});\nlet results = e.target.value !== \"\" ? idx.search(e.target.value) : [];\n//console.log(idx.search(e.target.value));\n//console.log('search result: ', searchResult);\n// let resultRaw = document.querySelector('.result-raw');\n//\t\tresultRaw.remove();\t\t\n\nsetBar(true);\nsetSearchRes(results);\t \n\nlet expanded = document.querySelector('.search-bar-expanded');\nlet dropdown = document.querySelector('.dropdown');\nlet navSearch = document.querySelector('.navbar__search');\n if (expanded !== null) {\ndropdown.style.display = 'block';\nnavSearch.style.position = 'relative';\t \n\t \n//\t console.log(mdRaws);\n }\n//console.log(expanded);\t\ndropdown.style.display = 'hide';\n}", "function search() {\n if (_.isEmpty($scope.user.name)) {\n return;\n }\n\n $scope.step1lock = true;\n $scope.loadingText = 'Searching for Summoner...';\n\n $('.step-1').fadeOut(1000,function(){\n $('.loader').fadeIn(1000, function() {\n $('.loader').fadeOut(1000, function() {\n $('.step-2').fadeIn(1000, function() {\n $(window).resize();\n $('#highchart').highcharts().reflow();\n });\n });\n });\n });\n }", "focusSearchBar() {\n setTimeout(() => this.searchBar.focus(), 200);\n }", "function initSearch(event) {\n var searchPageDoc = event.target;\n var searchField = searchPageDoc.getElementByTagName(\"searchField\");\n if (!searchField) { return; }\n \n var keyboard = searchField.getFeature(\"Keyboard\");\n keyboard.onTextChange = function () {\n doSearch(keyboard.text, searchPageDoc);\n }\n}", "onSearchInput(evt) {\n this.setState({ searchTerm: evt.target.value, didAtLeastOneSearch: true });\n\n clearTimeout(this.searchDebounce);\n this.searchDebounce = setTimeout(async () => {\n const rez = await this.search();\n this.setState({ searchOffset: 0, searchResults: rez });\n }, 100);\n }", "onActionClickSearchBar() {\n this.search(this.state.search)\n }", "startSearching() {\n // Initializing the pre search data so that the data can be recovered when search is finished\n this._preSearchData = this.crudStore.getData();\n }", "function focus () {\n hasFocus = true;\n //-- if searchText is null, let's force it to be a string\n if (!angular.isString($scope.searchText)) $scope.searchText = '';\n ctrl.hidden = shouldHide();\n if (!ctrl.hidden) handleQuery();\n }", "function focus () {\n hasFocus = true;\n //-- if searchText is null, let's force it to be a string\n if (!angular.isString($scope.searchText)) $scope.searchText = '';\n ctrl.hidden = shouldHide();\n if (!ctrl.hidden) handleQuery();\n }", "componentDidMount() {\n DeviceEventEmitter.addListener('event.ready', this.app_ready);\n DeviceEventEmitter.addListener(\n 'event.is_search_empty',\n this.is_search_empty,\n );\n }", "focus() {\n this.$refs.searchInput.focus();\n }", "componentDidMount() {\n this.search();\n }", "registerCollapseFiltersOnSearchbarSearch() {\n let pendingQueryUpdate = false;\n\n ANSWERS.core.globalStorage.on('update', 'query', () => {\n pendingQueryUpdate = true;\n });\n\n ANSWERS.core.globalStorage.on('update', 'vertical-results', verticalResults => {\n if (verticalResults.searchState !== 'search-complete' || !pendingQueryUpdate) {\n return;\n }\n this.collapseFilters();\n pendingQueryUpdate = false;\n });\n }", "function HB_Element_SearchBox() {\n\n\t \t$( '.hb-search .open.show-full-screen' ).on( 'click', function() {\n\n\t \t\tvar _this = $( this );\n\t \t\tvar parent = _this.parents( '.hb-search' );\n\n\t\t\t/*******************************************************************\n\t\t\t * Render HTML for effect *\n\t\t\t ******************************************************************/\n\t\t\t var sidebar_content = parent.find( '.hb-search-fs' )[ 0 ].outerHTML;\n\t\t\t $( 'body' ).append( sidebar_content );\n\n\t\t\t var background_style = $( this ).attr( 'data-background-style' );\n\t\t\t var layout = $( this ).attr( 'data-layout' );\n\t\t\t var search_form = $( 'body > .hb-search-fs' );\n\n\t\t\t if ( layout == 'topbar' && $( this ).hasClass( 'active-topbar' ) ) {\n\t\t\t \tsearch_close();\n\t\t\t } else {\n\n\t\t\t \tswitch ( layout ) {\n\t\t\t \t\tcase 'full-screen':\n\t\t\t \t\tsearch_form.fadeIn( 300 );\n\t\t\t \t\t$( 'html' ).addClass( 'no-scroll' );\n\t\t\t \t\tbreak;\n\t\t\t \t\tcase 'topbar':\n\n\t\t\t \t\tvar admin_bar = $( '#wpadminbar' );\n\t\t\t \t\tvar margin_top = admin_bar.length ? admin_bar.height() : '0';\n\n\t\t\t \t\t$( this ).addClass( 'active-topbar' );\n\n\t\t\t \t\tsearch_form.css( {\n\t\t\t \t\t\t'display': 'block',\n\t\t\t \t\t\t'top': ( margin_top - 80 ) + 'px'\n\t\t\t \t\t} ).animate( {\n\t\t\t \t\t\t'top': margin_top + 'px'\n\t\t\t \t\t} );\n\t\t\t \t\t$( 'body > .wrapper-outer' ).css( {\n\t\t\t \t\t\t'position': 'relative',\n\t\t\t \t\t\t'top': '0px'\n\t\t\t \t\t} ).animate( {\n\t\t\t \t\t\t'top': '80px'\n\t\t\t \t\t} );\n\n\t\t\t \t\tbreak;\n\t\t\t \t}\n\n\t\t\t \tsearch_form.addClass( background_style + ' ' + layout );\n\t\t\t \tsearch_form.find( '.close' ).attr( 'data-layout', layout );\n\t\t\t \tsearch_form.find( 'form input' ).focus();\n\t\t\t }\n\n\t\t\t} );\n\n\t \tfunction search_close() {\n\t \t\tvar _this = $( 'body > .hb-search-fs .close' );\n\t \t\tvar layout = _this.attr( 'data-layout' );\n\n\t \t\tswitch ( layout ) {\n\t \t\t\tcase 'full-screen':\n\t \t\t\t$( 'body > .hb-search-fs' ).fadeOut( 300, function() {\n\t \t\t\t\t$( 'html' ).removeClass( 'no-scroll' );\n\t \t\t\t\t$( 'body > .hb-search-fs' ).remove();\n\t \t\t\t\t$( 'body > .wrapper-outer' ).removeAttr( 'style' );\n\t \t\t\t} );\n\t \t\t\tbreak;\n\t \t\t\tcase 'topbar':\n\t \t\t\tvar admin_bar = $( '#wpadminbar' );\n\t \t\t\tvar margin_top = admin_bar.length ? admin_bar.height() : '0';\n\n\t \t\t\t$( 'body > .hb-search-fs' ).animate( {\n\t \t\t\t\t'top': ( margin_top - 80 ) + 'px'\n\t \t\t\t}, function() {\n\t \t\t\t\t$( this ).remove();\n\t \t\t\t} );\n\n\t \t\t\t$( 'body > .wrapper-outer' ).animate( {\n\t \t\t\t\t'top': '0px'\n\t \t\t\t}, function() {\n\t \t\t\t\t$( this ).removeAttr( 'style' );\n\t \t\t\t} );\n\n\t \t\t\tbreak;\n\t \t\t}\n\n\t \t\t$( '.header .hb-search' ).find( '.open.active-topbar' ).removeClass( 'active-topbar' );\n\t \t}\n\n\t \t$( 'body' ).on( 'click', '.hb-search-fs .close', function() {\n\t \t\tsearch_close();\n\t \t} );\n\n\t \t$( '.header .hb-search.dropdown .open' ).click( function() {\n\t \t\tvar _this = $( this );\n\t \t\tvar parents = _this.closest( '.hb-search' );\n\t \t\tvar search_form = parents.find( '.search-form:first' );\n\t \t\tvar index_current = $( '.header .hb-search.dropdown' ).index( parents );\n\t \t\tvar parents_info = parents[ 0 ].getBoundingClientRect();\n\t \t\tvar border_top_width = parseInt( parents.css( 'borderTopWidth' ) );\n\t \t\tvar border_bottom_width = parseInt( parents.css( 'borderBottomWidth' ) );\n\n\t\t\t// Remove active element item more\n\t\t\t$( '.header .hb-search.dropdown:not(:eq(' + index_current + '))' ).removeClass( 'active-dropdown' );\n\n\t\t\tif ( parents.hasClass( 'active-dropdown' ) ) {\n\t\t\t\tparents.removeClass( 'active-dropdown' );\n\t\t\t\tsearch_form.removeClass( 'set-width' );\n\t\t\t} else {\n\t\t\t\tWR_Click_Outside( _this, '.hb-search', function( e ) {\n\t\t\t\t\tparents.removeClass( 'active-dropdown' );\n\t\t\t\t\tsearch_form.removeClass( 'set-width' );\n\t\t\t\t} );\n\n\t\t\t\t// Reset style\n\t\t\t\tsearch_form.removeAttr( 'style' );\n\n\t\t\t\tvar width_content_broswer = $( window ).width();\n\n\t\t\t\tif ( search_form.width() > ( width_content_broswer - 10 ) ) {\n\t\t\t\t\tsearch_form.css( 'width', ( width_content_broswer - 10 ) );\n\t\t\t\t\tsearch_form.addClass( 'set-width' );\n\t\t\t\t}\n\n\t\t\t\tvar width_content_broswer = $( window ).width();\n\t\t\t\tvar search_form_info = search_form[ 0 ].getBoundingClientRect();\n\t\t\t\tvar current_info = _this[ 0 ].getBoundingClientRect();\n\n\t\t\t\t// Get offset\n\t\t\t\tvar offset_option = ( width_content_broswer > 1024 ) ? parseInt( WR_Data_Js[ 'offset' ] ) : 0;\n\n\t\t\t\t// Set left search form if hide broswer because small\n\t\t\t\tif ( width_content_broswer < ( search_form_info.right + 5 ) ) {\n\t\t\t\t\tvar left_search_form = ( search_form_info.right + 5 + offset_option ) - width_content_broswer;\n\t\t\t\t\tsearch_form.css( 'left', -left_search_form + 'px' );\n\t\t\t\t} else if ( search_form_info.left < ( 5 + offset_option ) ) {\n\t\t\t\t\tsearch_form.css( 'left', '5px' );\n\t\t\t\t}\n\n\t\t\t\tvar margin_top = ( parents.attr( 'data-margin-top' ) == 'empty' ) ? parents.attr( 'data-margin-top' ) : parseInt( parents.attr( 'data-margin-top' ) );\n\n\t\t\t\t// Remove margin top when stick\n\t\t\t\tif ( _this.closest( '.sticky-row-scroll' ).length || margin_top == 'empty' ) {\n\t\t\t\t\tvar parent_sticky_info = _this.closest( ( _this.closest( '.sticky-row-scroll' ).length ? '.sticky-row' : '.hb-section-outer' ) )[ 0 ].getBoundingClientRect();\n\t\t\t\t\tvar offset_top = parseInt( ( parent_sticky_info.bottom - parents_info.bottom ) + ( parents_info.height - border_top_width ) );\n\n\t\t\t\t\tsearch_form.css( 'top', offset_top );\n\t\t\t\t} else if ( margin_top > 0 ) {\n\t\t\t\t\tsearch_form.css( 'top', ( margin_top + ( parents_info.height - ( border_top_width + border_bottom_width ) ) ) );\n\t\t\t\t}\n\n\t\t\t\tparents.addClass( 'active-dropdown' );\n\n\t\t\t\t// Set width input if overflow\n\t\t\t\tvar ls_form = parents.find( '.wrls-form' );\n\n\t\t\t\tif( ls_form.length ) {\n\t\t\t\t\tvar width_cate = parents.find( '.cate-search-outer' ).width();\n\t\t\t\t}\n\n\t\t\t\tsetTimeout( function() {\n\t\t\t\t\tparents.find( '.txt-search' ).focus();\n\t\t\t\t}, 300 );\n\t\t\t}\n\t\t} );\n\n\t \t/* Action for expand width */\n\t \t$( '.header .hb-search.expand-width .open' ).on( 'click', function( event ) {\n\t \t\tvar _this = $( this );\n\t \t\tvar parents = _this.closest( '.hb-search' );\n\t \t\tvar form_search = parents.find( '.search-form form' )\n\t \t\tvar info_form = form_search[ 0 ].getBoundingClientRect();\n\t \t\tvar width_form = info_form.width;\n\t \t\tvar header = _this.closest( '.header' );\n\t \t\tvar is_vertical = header.hasClass( 'vertical-layout' );\n\t \t\tvar is_expand_right = true;\n\n\t \t\tif ( parents.hasClass( 'expan-width-active' ) ) {\n\t \t\t\tform_search.stop( true, true ).css( {\n\t \t\t\t\toverflow: 'hidden'\n\t \t\t\t} ).animate( {\n\t \t\t\t\twidth: '0px'\n\t \t\t\t}, 200, function() {\n\t \t\t\t\tparents.removeClass( 'expan-width-active' );\n\t \t\t\t\tform_search.removeAttr( 'style' );\n\n\t \t\t\t\t/*** Show elements element current ***/\n\t \t\t\t\tvar parents_container = _this.closest( '.container' ).find( '.hide-expand-search' );\n\n\t \t\t\t\tparents_container.css( 'visibility', '' ).animate( {\n\t \t\t\t\t\topacity: 1\n\t \t\t\t\t}, 200, function() {\n\t \t\t\t\t\tparents_container.removeClass( 'hide-expand-search' );\n\t \t\t\t\t\t$( this ).css( 'opacity', '' );\n\t \t\t\t\t} );\n\t \t\t\t} );\n\t \t\t} else {\n\t \t\t\tWR_Click_Outside( _this, '.hb-search', function( e ) {\n\t \t\t\t\tform_search.stop( true, true ).css( {\n\t \t\t\t\t\toverflow: 'hidden'\n\t \t\t\t\t} ).animate( {\n\t \t\t\t\t\twidth: '0px'\n\t \t\t\t\t}, 200, function() {\n\t \t\t\t\t\tparents.removeClass( 'expan-width-active' );\n\t \t\t\t\t\tform_search.removeAttr( 'style' );\n\n\t \t\t\t\t\t/*** Show elements element current ***/\n\t \t\t\t\t\tvar parents_container = _this.closest( '.container' ).find( '.hide-expand-search' );\n\n\t \t\t\t\t\tparents_container.css( 'visibility', '' ).animate( {\n\t \t\t\t\t\t\topacity: 1\n\t \t\t\t\t\t}, 200, function() {\n\t \t\t\t\t\t\tparents_container.removeClass( 'hide-expand-search' );\n\t \t\t\t\t\t\t$( this ).css( 'opacity', '' );\n\t \t\t\t\t\t} );\n\t \t\t\t\t} );\n\t \t\t\t} );\n\n\t \t\t\tvar info_search_current = _this[ 0 ].getBoundingClientRect();\n\t \t\t\tvar width_ofset_left = info_search_current.left + info_search_current.width / 2;\n\t \t\t\tvar width_broswer = document.body.offsetWidth;\n\t \t\t\tvar width_open = parents.outerWidth();\n\n\t \t\t\tif ( is_vertical ) {\n\n\t \t\t\t\tvar info_parents = parents[ 0 ].getBoundingClientRect();\n\t \t\t\t\tvar info_header = header[ 0 ].getBoundingClientRect();\n\n\t\t\t\t\t// Left position\n\t\t\t\t\tif ( header.hasClass( 'left-position-vertical' ) ) {\n\t\t\t\t\t\tis_expand_right = ( info_parents.left - info_header.left - 10 ) >= info_form.width ? false : true;\n\n\t\t\t\t\t\t// Right position\n\t\t\t\t\t} else {\n\t\t\t\t\t\tis_expand_right = ( info_header.right - info_parents.right - 10 ) >= info_form.width ? true : false\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tis_expand_right = width_ofset_left * 2 < width_broswer;\n\t\t\t\t}\n\n\t\t\t\t// Expand right\n\t\t\t\tif ( is_expand_right ) {\n\n\t\t\t\t\t/** * Hide elements right element current ** */\n\t\t\t\t\tvar list_next_all = parents.nextUntil();\n\n\t\t\t\t\tif ( list_next_all.length ) { console.log( 'fasdf' );\n\t\t\t\t\tvar width_next = 0;\n\n\t\t\t\t\tvar handle_animate = function() {\n\t\t\t\t\t\tform_search.stop( true, true ).css( {\n\t\t\t\t\t\t\tleft: width_open + 5,\n\t\t\t\t\t\t\twidth: 0,\n\t\t\t\t\t\t\toverflow: 'hidden',\n\t\t\t\t\t\t\tvisibility: 'initial'\n\t\t\t\t\t\t} ).animate( {\n\t\t\t\t\t\t\twidth: width_form\n\t\t\t\t\t\t}, 200, function() {\n\t\t\t\t\t\t\t$( this ).css( 'overflow', '' );\n\t\t\t\t\t\t} );\n\t\t\t\t\t};\n\n\t\t\t\t\tif ( !is_vertical ) {\n\t\t\t\t\t\tlist_next_all.each( function( key, val ) {\n\t\t\t\t\t\t\tif ( width_next < width_form ) {\n\t\t\t\t\t\t\t\t$( val ).animate( {\n\t\t\t\t\t\t\t\t\topacity: 0\n\t\t\t\t\t\t\t\t}, 200, function() {\n\t\t\t\t\t\t\t\t\t$( val ).css( 'visibility', 'hidden' )\n\t\t\t\t\t\t\t\t} );\n\t\t\t\t\t\t\t\t$( val ).addClass( 'hide-expand-search' );\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\twidth_next += $( val ).outerWidth( true );\n\n\t\t\t\t\t\t\tif ( width_next > width_form )\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t} );\n\n\t\t\t\t\t\tsetTimeout( handle_animate, 200 );\n\t\t\t\t\t} else {\n\t\t\t\t\t\thandle_animate();\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\t\t// Expand width form search\n\t\t\t\t\t\tform_search.stop( true, true ).css( {\n\t\t\t\t\t\t\tleft: width_open + 5,\n\t\t\t\t\t\t\twidth: 0,\n\t\t\t\t\t\t\toverflow: 'hidden',\n\t\t\t\t\t\t\tvisibility: 'initial'\n\t\t\t\t\t\t} ).animate( {\n\t\t\t\t\t\t\twidth: width_form\n\t\t\t\t\t\t}, 200, function() {\n\t\t\t\t\t\t\t$( this ).css( 'overflow', '' );\n\t\t\t\t\t\t} );\n\n\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// Expand left\n\t\t\t\t} else {\n\n\t\t\t\t\t/*** Hide elements left near element current ***/\n\t\t\t\t\tvar list_prev_all = parents.prevUntil();\n\n\t\t\t\t\tif ( list_prev_all.length ) {\n\t\t\t\t\t\tvar width_prev = 0;\n\n\t\t\t\t\t\tvar handle_animate = function() {\n\t\t\t\t\t\t\tform_search.stop( true, true ).css( {\n\t\t\t\t\t\t\t\tright: width_open + 5,\n\t\t\t\t\t\t\t\twidth: 0,\n\t\t\t\t\t\t\t\toverflow: 'hidden',\n\t\t\t\t\t\t\t\tvisibility: 'initial'\n\t\t\t\t\t\t\t} ).animate( {\n\t\t\t\t\t\t\t\twidth: width_form\n\t\t\t\t\t\t\t}, 200, function() {\n\t\t\t\t\t\t\t\t$( this ).css( 'overflow', '' );\n\t\t\t\t\t\t\t} );\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tif ( !is_vertical ) {\n\t\t\t\t\t\t\tlist_prev_all.each( function( key, val ) {\n\t\t\t\t\t\t\t\tif ( width_prev < width_form ) {\n\t\t\t\t\t\t\t\t\t$( val ).animate( {\n\t\t\t\t\t\t\t\t\t\topacity: 0\n\t\t\t\t\t\t\t\t\t}, 200, function() {\n\t\t\t\t\t\t\t\t\t\t$( val ).css( 'visibility', 'hidden' )\n\t\t\t\t\t\t\t\t\t} );\n\t\t\t\t\t\t\t\t\t$( val ).addClass( 'hide-expand-search' );\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\twidth_prev += $( val ).outerWidth( true );\n\n\t\t\t\t\t\t\t\tif ( width_prev > width_form )\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t} );\n\n\t\t\t\t\t\t\tsetTimeout( handle_animate, 200 );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\thandle_animate();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// Expand width form search\n\t\t\t\t\t\tform_search.stop( true, true ).css( {\n\t\t\t\t\t\t\tright: width_open + 5,\n\t\t\t\t\t\t\twidth: 0,\n\t\t\t\t\t\t\toverflow: 'hidden',\n\t\t\t\t\t\t\tvisibility: 'initial'\n\t\t\t\t\t\t} ).animate( {\n\t\t\t\t\t\t\twidth: width_form\n\t\t\t\t\t\t}, 200, function() {\n\t\t\t\t\t\t\t$( this ).css( 'overflow', '' );\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tparents.addClass( 'expan-width-active' );\n\n\t\t\t\tsetTimeout( function() {\n\t\t\t\t\tparents.find( '.txt-search' ).focus();\n\t\t\t\t}, 300 );\n\t\t\t}\n\t\t} );\n\n/* Action for Boxed */\n$( '.header .hb-search.boxed .open' ).on( 'click', function() {\n\tvar _this = $( this );\n\tvar parents = _this.parents( '.hb-search' );\n\tparents.find( 'input[type=\"submit\"]' ).trigger( 'click' );\n} );\n}", "function init_search() {\n\tif(Info.browser.isIEpre6) return;\n\t\n\t// get selectbox when clicking change on active filters\n\t\n\tif ($(\"search-filter-zone\")) {\n\t\t$(\"search-filter-zone\").setStyle({ left: '0'}); // show filter\n\t\t$(\"search-filter-zone\").select('div.active-filter').each(function(element) {\n\t\t\tvar name = element.id.replace(/^active-filter-/, '');\n\t\t\tvar filter = new ActiveSearchFilter(name);\n\t\t\t$(element).observe(\"click\",\n\t\t\t\tfunction(e) {\n\t\t\t\t\tfilter.load();\n\t\t\t\t\tEvent.stop(e);\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\t\t\n\t\t// 1st element after last gui.select hides layer\n\t\tvar resetButton = $$(\"fieldset.reset\")[0].down('a.generic-button');\n\t\tresetButton.observe(\"focus\", function() { Layer.closeCurrent(); });\n\t}\n\t\n\t// init auto complete layer\n\tnew AutoCompleteLayer($('query'));\n\n\t// correct minor IE6 layout issues\n\n\tif (Info.browser.isIEpre7) {\n\t\tvar suggestion = $$('div.search-suggestion').first();\n\t\tif (suggestion && suggestion.next().hasClassName('recommendations')) {\n\t\t\tsuggestion.next().style.marginTop = '-3px';\n\t\t}\n\t}\n\n}", "function SearchWatcher (search_selector) {\n this.search_selector = search_selector;\n this.tpl = null;\n this.directive = {\n 'li':{\n 'obj<-results':{\n '[data-title]': 'obj.title',\n '[data-css-icon]@class+': 'obj.css_icon',\n 'a@href': 'obj.url',\n 'a@class+': function(a) {\n return \" \" + a.item.type_name;\n },\n '[data-img]@src': 'obj.thumb_url',\n }\n }\n }\n this.delay_time = 1000;\n this.hide_delay = 3000;\n this.min_chars = 2;\n this.timer = null;\n this.timer_hide = null;\n this.has_results = false;\n\n this.search = function(search_field) {\n var form = search_field.parents('form')\n if (form.length == 1) {\n arche.actionmarker_feedback(form, true);\n var url = form.data('watch-url');\n if (!url) url = form.attr('action');\n var request = arche.do_request(url, {data: form.serialize(), method: form.attr('method')});\n request.done(this.handle_search_response.bind(this));\n request.always(function() {\n arche.actionmarker_feedback(form, false);\n });\n }\n }\n\n this.handle_change_event = function(event) {\n if (this.timer != null) {\n clearTimeout(this.timer);\n }\n var target = $(this.target_name);\n if (!target.hasClass('active')) target.removeClass('active');\n var search_field = $(event.currentTarget);\n if (search_field.val().length >= this.min_chars) {\n this.timer = setTimeout(\n function() { this.search(search_field) }.bind(this), this.delay_time);\n }\n }\n\n this.handle_search_response = function(response) {\n if (this.timer_hide != null) {\n clearTimeout(this.timer_hide);\n }\n if (!this.tpl) this.tpl = $(this.target_name).html();\n $(this.target_name).html(this.tpl);\n if (response.results.length > 0) {\n this.has_results = true;\n $(this.target_name).render(response, this.directive);\n } else {\n this.has_results = false;\n }\n var msg_elem = $(this.target_name).children('[data-search-msg]');\n if (response.msg) {\n msg_elem.html(response.msg);\n } else {\n msg_elem.html(\"\");\n }\n $(this.target_name).addClass('active');\n //this.start_close_timer();\n }\n\n this.handle_mouseon = function(event) {\n if (this.timer_hide != null) {\n clearTimeout(this.timer_hide);\n }\n }\n\n this.handle_mouseleave = function(event) {\n this.start_close_timer();\n }\n\n this.handle_mouseon_reopen = function(event) {\n if (this.has_results) $(this.target_name).addClass('active');\n }\n\n this.start_close_timer = function() {\n if (this.timer_hide != null) {\n clearTimeout(this.timer_hide);\n }\n this.timer_hide = setTimeout( function() {\n $(this.target_name).removeClass('active');\n }.bind(this), this.hide_delay);\n }\n\n $('body').on('input propertychange', this.search_selector, this.handle_change_event.bind(this));\n this.target_name = $(this.search_selector).data('watch-search');\n $('body').on('mouseleave', this.target_name, this.handle_mouseleave.bind(this));\n $('body').on('mouseover', this.target_name, this.handle_mouseon.bind(this));\n $('body').on('mouseleave', this.search_selector, this.handle_mouseleave.bind(this));\n $('body').on('mouseover', this.search_selector, this.handle_mouseon_reopen.bind(this));\n}", "function do_search() {\n var query = input_box.val();\n\n if(query && query.length) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= $(input).data(\"settings\").minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, $(input).data(\"settings\").searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }", "function do_search() {\n var query = input_box.val();\n\n if(query && query.length) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= $(input).data(\"settings\").minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, $(input).data(\"settings\").searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }", "function do_search() {\n var query = input_box.val();\n\n if(query && query.length) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= $(input).data(\"settings\").minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, $(input).data(\"settings\").searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }", "searchCallback(searchActive) {\n // Update the state to the state of the searchbar\n this.setState({\n searchActive,\n });\n }", "function onInit() {\n $scope.$on('search-posts_make-search', onSearchFinishedHandler);\n }", "constructor() {\n \t/*\n this.name = \"Jane\";\n this.eyeColor = \"green\";\n this.head = {};\n this.brain = {}; */\n\t/* This part makes the live search window, which was moved from footer.php.\n\t if web browser disables JavaScript, search window should not be displayed.\n\t this is the reason why it should be displayed by 'Search.js' file.\n\t It should be in the first line of constructor, since other function will work\n\t only after searh live window exists. */\n this.addSearchHTML();\n\n this.resultsDiv = $(\"#search-overlay__results\");\n this.openButton = $(\".js-search-trigger\");\n this.closeButton = $(\".search-overlay__close\");\n\tthis.searchOverlay = $(\".search-overlay\");\n\t// search-term is the ID of <input> HTML element\n this.searchField = $(\"#search-term\");\n\tthis.events();\n\t// this property will be used for openOverlay and closeOverlay methods.\n this.isOverlayOpen = false;\n this.isSpinnerVisible = false;\n\tthis.previousValue;\n\t/* this is used to keep from reset the timer of keyboard. whenever user press\n\t the keyboard in search window */\n this.typingTimer;\n }", "function searchForQuery(query) {\r\n toggleMainContainer(false);\r\n togglePreloader(true);\r\n showLoadMoreButtons();\r\n clearLists();\r\n search(query, false, 1);\r\n search(query, true, 1); \r\n setCurrentQuery(query);\r\n }", "refreshFromLocation()\n {\n let args = helpers.args.location;\n this.inputElement.value = args.hash.get(\"search\") || \"\";\n this.refreshClearButtonVisibility();\n }" ]
[ "0.7141043", "0.71293", "0.70905656", "0.70059466", "0.6953724", "0.6938725", "0.68812084", "0.6847683", "0.6769326", "0.672978", "0.6717628", "0.670147", "0.66973746", "0.66817653", "0.66776663", "0.66580904", "0.66459495", "0.66376024", "0.6603134", "0.65878576", "0.6581097", "0.65636015", "0.6556516", "0.6502914", "0.6500673", "0.6496574", "0.64878994", "0.6478698", "0.6472118", "0.64643735", "0.64535403", "0.6453516", "0.64481115", "0.6446032", "0.6437112", "0.6427599", "0.6424253", "0.6416388", "0.6408891", "0.64009684", "0.6398385", "0.63974565", "0.6395676", "0.6382248", "0.6381942", "0.6375514", "0.6370327", "0.63651204", "0.63641644", "0.63632435", "0.6362956", "0.6351863", "0.63483804", "0.63470656", "0.63424057", "0.63390744", "0.63260025", "0.63235", "0.631199", "0.6311424", "0.6310034", "0.63082796", "0.63082796", "0.629936", "0.62977827", "0.62908417", "0.6279012", "0.6277512", "0.627515", "0.6272451", "0.6270836", "0.62688357", "0.62645125", "0.6256112", "0.62550473", "0.62493485", "0.624847", "0.6242329", "0.623716", "0.62357867", "0.6233405", "0.623077", "0.6225542", "0.62249917", "0.6223209", "0.6223209", "0.6212364", "0.6212084", "0.620982", "0.6209365", "0.6208587", "0.62046", "0.61992675", "0.61934125", "0.61934125", "0.61934125", "0.6189881", "0.6181113", "0.61790836", "0.61699116", "0.6169218" ]
0.0
-1
either change of region or entity_id will trigger search bar rerendering
componentDidUpdate(prevProps, prevState) { const prevRegion = prevProps.entity.region; const currRegion = this.props.entity.region; const prevEntityId = prevProps.entity.entity_id; const currEntityId = this.props.entity.entity_id; if (prevRegion != currRegion || prevEntityId != currEntityId) { return getItemManifest(this.props.entity.region) .then((data) => { this.setState( { entity: {...this.props.entity}, EntityList: data, }); }); }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onRegionUpdate(updated_region) {\n this.viewing_region = updated_region;\n this.fetch_regions();\n }", "regionFilter(event) {\n const regionValue = event.target.value\n // updates search value to filter countries by region\n this.setState({ regionValue })\n }", "UpdateRegion() {\n\n }", "handleChangeRegion(e, index, region) {\n let flightData = this.state.flightData;\n flightData.region = region;\n\n this.setState({ flightData: flightData });\n\n //Get cities data by region\n this.getCities(region);\n this.setState({ disableCity: false });\n }", "onRegionSelected(region: Region) {\n this.viewing_region = region;\n }", "function setRegion(id){\n regionId = id;\n}", "toggleEditingRegionHighlight() {\n this.isHighlightEditRegion = !this.isHighlightEditRegion;\n }", "function searchRegion(regionID) {\n //Clear Form\n $('#district').prop('selectedIndex', 0);\n $('#store').prop('value', '');\n //Send Post Request\n $.get('/stores/findStoreByRegionManagerID/' + regionID, function (stores) {\n createTable(stores);\n });\n}", "onRegionChange(region) {\r\n this.setState({ region });\r\n }", "function regionUpdate(){\n setPlot(regionSel.value);\n}", "onSearchTermChange() {\n this.search();\n Metrics.getInstance().updateMetric(Filters.SEARCH, 1);\n }", "_changeCustomer() {\n this.customerRenderer.showCustomerSearch();\n }", "onRegionChange(region) {\n this.setState({ region });\n }", "function saveState () {\n if (self.searchTerm) {\n self.gridController.state[self.id] = self.searchTerm;\n } else {\n delete self.gridController.state[self.id];\n }\n }", "onRegionChange(region){\n this.setState({region})\n\n }", "onHighlight() {\n if (this.isHighlightEditRegion) {\n this.highlightEditRegion();\n }\n else {\n this.unHighlightEditRegion();\n }\n this.viewer.renderVisiblePages();\n }", "function searchUpdated(term) {\n setsearch(term);\n }", "onRegionChange(region) {\n this.setState({region})\n}", "_onSearch(event) {\n const searchDetails = event.detail;\n Object.assign(this.searchDetails, searchDetails);\n this.render();\n }", "updateSearchResults( evt ) {\n\t\tthis.setState( {\n\t\t\tsearchText: evt.target.value,\n\t\t} );\n\t}", "updateSearchResults( evt ) {\n\t\tthis.setState( {\n\t\t\tsearchText: evt.target.value,\n\t\t} );\n\t}", "function updateFilteredSearch(){\n \n if(typeof searchPnt != \"undefined\")\n findProviders(providerFS, searchPnt)\n }", "handleSearchOnChange(event) {\n\t\tthis.setState({search_term: event.target.value,\n\t\t\tsearch_term_query: event.target.value },()=>{\n\t\t\t\tthis.refreshSearchData();\n\t\t\t})\n\t}", "function _renderSearch() {\n _$navbar.setMod(_B_BAR, _M_SEARCH, false);\n setTimeout(function() {\n _$navbar.setMod(_B_BAR, _M_SEARCH, _searchIsActive);\n }, CFG.TIME.ANIMATION);\n }", "onUpdateContent() {\n this.checkAutocomplete();\n\n if (!this.search) {\n this.emmitEvent('');\n }\n }", "function changeLocalSearch(){\n gridManager.setLocalSearch($scope.data.localSearch);\n}", "async function onChange (event) {\n const { data, url } = await fetchData();\n\n // Update the page results\n updatePageUI(data, url);\n updateTrayText({ region: event.target });\n closeAllFilters();\n\n // Save to local storage\n localStorage.setItem('region', event.target.value);\n}", "function refresh() {\n let toEntities = $scope.entities;\n let toForm = $scope.search.form;\n $scope.results = SearchService.filter(SearchService.search(toEntities, toForm), $scope.search.filters);\n setMarkers();\n }", "setRegion(region) {\n this.setState({\n region: region \n });\n }", "onRegionChangeComplete( region ) {\n this.showNearbyParking(region);\n }", "function updateRadlkarteRegion(region) {\n\tvar configuration = rkGlobal.configurations[region];\n\tif(configuration === undefined) {\n\t\tconsole.warn('ignoring unknown region ' + region);\n\t\treturn;\n\t}\n\n\tremoveAllSegmentsAndMarkers();\n\tloadGeoJson(configuration.geoJsonFile);\n\t//rkGlobal.geocodingControl.options.geocoder.options.geocodingQueryParams.bounds = configuration.geocodingBounds;\n\n\t// virtual page hit in google analytics\n\tga('set', 'page', '/' + region);\n\tga('send', 'pageview');\n}", "function _searchFilterChanged() {\n saveSearchFilter();\n _updateState(hotelStates.CHANGE_SEARCH_FILTER, getSearchOptions());\n }", "handleSearchBar()\n {\n this._page = 1;\n this._searchBar = $(\"#searchBar\").val();\n this.getBooks();\n }", "setRegion(value) {\n super.put(\"region\", value);\n }", "function recolor_regions() {\n scope.regions_geojson.setStyle(get_region_style);\n }", "_deferredInvocUpdateSearch() {\n QuickFilterBarMuxer.updateSearch();\n }", "function handleSearchPerson(idPerson) {\n if (idPerson && !updateRegister) {\n loadDataPerson(idPerson);\n setUpdateRegister(false);\n setTitleUpdate(\"\");\n } else if (!updateRegister) {\n clearFields();\n }\n }", "function imageInfoRegionsSelectorChange(event) {\n gImageRegionListViewer.setTextureID(gTextureIDList[imageInfoRegionsSelector.selectedIndex]);\n}", "registerCollapseFiltersOnSearchbarSearch() {\n let pendingQueryUpdate = false;\n\n ANSWERS.core.globalStorage.on('update', 'query', () => {\n pendingQueryUpdate = true;\n });\n\n ANSWERS.core.globalStorage.on('update', 'vertical-results', verticalResults => {\n if (verticalResults.searchState !== 'search-complete' || !pendingQueryUpdate) {\n return;\n }\n this.collapseFilters();\n pendingQueryUpdate = false;\n });\n }", "function updateGanttChart_with_search(){\n var value = $('#poolTool_search').val();\n search(value, true);\n }", "function onChangeSearchAction(environmentId, currentQuery, repository, selectedOption) {\n var clonedQuery = cloneDeep(currentQuery);\n var filterData = splitQueryValue(selectedOption);\n clonedQuery\n .sortBy(apisearch_1[\"default\"]\n .createEmptySortBy()\n .byFieldValue(filterData.field, filterData.sort));\n clonedQuery.page = 1;\n var dispatcher = Container_1[\"default\"].get(Constants_1.APISEARCH_DISPATCHER + \"__\" + environmentId);\n repository\n .query(clonedQuery)\n .then(function (result) {\n dispatcher.dispatch({\n type: \"RENDER_FETCHED_DATA\",\n payload: {\n query: clonedQuery,\n result: result\n }\n });\n });\n}", "componentDidMount() {\n console.log('search bar mounted');\n getItemManifest(this.props.entity.region).then((data) => {\n this.setState(\n {\n entity: {...this.props.entity},\n EntityList: data,\n });\n });\n }", "function displayNewSearchResults(event) {\n let searchTerm = event.target.value;\n let currentSearch = giphy[\"query\"][\"q\"];\n if (searchTerm !== currentSearch && searchTerm !== \"\") {\n giphy[\"query\"][\"q\"] = searchTerm;\n updateOffset(true);\n update();\n }\n}", "clearSearchHighlight() {\n if (!isNullOrUndefined(this.searchHighlighters)) {\n this.searchHighlighters.clear();\n this.searchHighlighters = undefined;\n }\n let eventArgs = { source: this.viewer.owner };\n this.viewer.owner.trigger('searchResultsChange', eventArgs);\n }", "onSearchTermChanged(term) {\n this.setState({ searchTerm: term });\n }", "function restoreState () {\n var params = self.gridController.state;\n if (!(self.id in params)) {\n return null;\n }\n self.searchTerm = params[self.id];\n }", "searchAssets(domian) {\n let {equipmentSelectList} = this.state;\n let {index} = equipmentSelectList;\n let domain = domian ? domian : null;\n let cur = 1;\n let size = 10;\n let offset = 0;\n let model = equipmentSelectList.options[index].title;\n let name = this.state.searchText.value;\n getSearchAssets(domain, model, name, offset, size, data => {\n let newList = intersection(data, this.state.allPoleEquipmentsData);\n this.setState({\n allEquipmentsData: newList\n })\n })\n this.state.searchText.value = '';\n }", "inboundState() {\n var op = getUrlParameter('op');\n var value = decodeURIComponent(getUrlParameter('value'));\n \n if (op === 'setSearchTerm') {\n this.quickSearch(value);\n $('#search-value').val(value);\n } else {\n this.setDataOp('setQueryParameter',['dc:language','en']);\n this.retrieveData().extractItems().displayResults();\n }\n \n \n }", "onInputChangeTerms(terms_search) {\n console.log(\"onInputChangeTerms: \" + terms_search);\n let filters = this.props.filters;\n filters.terms_search = terms_search;\n filters.do_terms_search = true;\n this.props.setFilter( filters );\n }", "function replaceRegion(regionId) {\r\n let regionBtn = document.getElementById(\"regionBtn\");\r\n let region = document.getElementById(regionId).textContent;\r\n regionBtn.textContent = region;\r\n regionBtn.setAttribute(\"value\", regionId);\r\n /*After clicking on a Region hide the dropdown*/\r\n document.getElementById(\"dropdownCont\").style.visibility = \"hidden\";\r\n}", "function onChangeSearchAction(environmentId, currentQuery, repository, selectedOption) {\n var clonedQuery = cloneDeep(currentQuery);\n applySortByToQuery(clonedQuery, selectedOption);\n clonedQuery.page = 1;\n var dispatcher = Container_1[\"default\"].get(Constants_1.APISEARCH_DISPATCHER + \"__\" + environmentId);\n repository\n .query(clonedQuery)\n .then(function (result) {\n dispatcher.dispatch({\n type: \"RENDER_FETCHED_DATA\",\n payload: {\n query: clonedQuery,\n result: result\n }\n });\n })[\"catch\"](function (error) {\n // Do nothing\n });\n}", "FiltersChanged(\n newRadius,\n newMinOverall,\n newMinReliability,\n newMinVariety,\n newMinService,\n newMinPricing,\n newCity,\n useUserLocation,\n newDiets,\n )\n {\n //Init new filters.\n\t\tthis.setState({\n filters:{\n radius:newRadius,\n minOverall : newMinOverall,\n minReliability : newMinReliability,\n minVariety : newMinVariety,\n minService : newMinService,\n pricing: newMinPricing,\n city: newCity,\n diets:newDiets,\n }\n });\n //Check if the user wants to use own location in search.\n if(useUserLocation){\n // Set users location as a search location. And after that fetch new markers.\n this.setState({\n searchLoc:[this.props.coords.latitude,this.props.coords.longitude],\n showCurrentLocationMarker:true,\n errors:{errorWhileGeocoding:false}\n },() => this.GetRestaurantsMarkers(\"green\"));\n }\n else{\n // Change city name to location.\n Geocoder.from(newCity)\n .then(json => {\n //New location.\n var location = json.results[0].geometry.location;\n //Console print for debugging.\n //console.log(location);\n\n //init new location and fetch markers.\n this.setState(\n {\n showCurrentLocationMarker:false,\n searchLoc:[location.lat,location.lng],\n center:[location.lat,location.lng],\n errors:{errorWhileGeocoding:false}\n },() => this.GetRestaurantsMarkers(\"green\")\n );\n })\n .catch(error => {\n this.setState({showCurrentLocationMarker:false,errors:{errorWhileGeocoding:true}})\n console.warn(error)\n });\n }\n\t}", "toggleSearchLayer(e) {\n\t\tlet q = this.state.query;\n\t\tconst searchLayers = this.state.query.searchLayers;\n\t\tsearchLayers[e.target.id] = !searchLayers[e.target.id];\n\n\t\t//reset certain query properties\n\t\tq.searchLayers = searchLayers;\n\t\tq.offset = 0;\n\t\tq.term = this.refs.searchTerm.value;\n\n\t\tthis.doSearch(q, true);\n\t}", "setSearchState (newSearchState) {\n const newState = this.prependInputName (newSearchState, 'search');\n this.highlightMatches (newState.searchContent);\n this.setState (extend (newState, this.graphState()));\n }", "function filterChange() {\n updateFilter();\n pullEvents();\n //put events in page\n}", "function handleNewSearch(data){\n setNewNavigation(data);\n clearOldResults(data);\n renderResults(data);\n}", "function onFilterChange(event, payload) {\n\t\tconst entry = getEntry(props.titleMap, payload.value);\n\t\tupdateValue(event, entry, false);\n\t\tshowFilteredSuggestions();\n\n\t\t// resetting selection here in order to reinit the section + item indexes\n\t\tresetSelection();\n\t}", "function editSearchTerm(e){\r\n setSearch(e.target.value);\r\n }", "updateSearchTerm(text) {\n // this.setState is a method that lets us edit state while also letting React know that something might have changed\n // so it should re-render anything that is different \n this.setState({\n searchTerm: text,\n })\n }", "function searchMarkerRegion() {\n\t\t\tconsole.log(\"searchMarkerRegion()\");\n\n if (vm.markerRegionSearch == null) {\n addMarkerRegion();\n }\n\n\t\t\tif (\n vm.apiDomain.alleleKey == \"\"\n || vm.markerRegionSearch.chromosome == \"\"\n || vm.markerRegionSearch.chromosome == null\n || vm.markerRegionSearch.startCoordinate == \"\"\n || vm.markerRegionSearch.startCoordinate == null\n || vm.markerRegionSearch.endCoordinate == \"\"\n || vm.markerRegionSearch.endCoordinate == null\n || vm.markerRegionSearch.relationshipTermKey == \"\"\n || vm.markerRegionSearch.relationshipTermKey == null\n ) {\n alert(\"Search Marker Count Required Fields:\\n\\nAllele\\nChr\\nStart Coordinate\\nEnd Coordinate\\nRelationship Type\");\n\t\t\t\tdocument.getElementById(\"startCoordinate\").focus();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar params = {};\n\t\t\tparams.chromosome = vm.markerRegionSearch.chromosome;\n\t\t\tparams.startCoordinate = vm.markerRegionSearch.startCoordinate;\n\t\t\tparams.endCoordinate = vm.markerRegionSearch.endCoordinate;\n\t\t\tparams.alleleKey = vm.apiDomain.alleleKey;\n\t\t\tparams.relationshipTermKey = vm.markerRegionSearch.relationshipTermKey;\n \n\t\t\tpageScope.loadingStart();\n\n\t\t\tAlleleFearGetMarkerByRegionAPI.search(params, function(data) {\n\t\t\t\tif (data.length == 0) {\n vm.markerRegionSearch.markerCount = 0;\n\t\t\t\t\talert(\"No Markers Available for this Allele:\\n\\n\" + \n vm.markerRegionSearch.chromosome + \n \"\\n\" + vm.markerRegionSearch.startCoordinate + \n \"\\n\" + vm.markerRegionSearch.endCoordinate);\n\t\t\t\t\tdocument.getElementById(\"startCoordinate\").focus();\n\t\t\t pageScope.loadingEnd();\n\t\t\t\t} else {\n vm.markerRegion = data;\n vm.markerRegionSearch.markerCount = data.length;\n\t\t\t pageScope.loadingEnd();\n }\n\t\t\t}, function(err) {\n\t\t\t\tpageScope.handleError(vm, \"API ERROR: GetMarkerByRegionAPI.search\");\n\t\t\t pageScope.loadingEnd();\n\t\t\t\tdocument.getElementById(\"startCoordinate\").focus();\n\t\t\t});\n\t\t}", "applyFilter() {\r\n let obj = getForm(this.filterSchema, this.refs);\r\n if (obj.state || obj.propertyType) {\r\n this.refs.propertyGrid.onSelectAll(false, []);\r\n this.props.toggleButtonText(false);\r\n this.stateSet({ filterObj: { ...obj, companyId: this.companyId }, selectedData: [] });\r\n }\r\n else\r\n this.props.notifyToaster(NOTIFY_ERROR, { message: this.strings.SEARCH_WARNING });\r\n }", "function findRegion(country) {\n\tvar region = autoRegionMap[country];\n\tif (region) {\n\t\t$(\"#selRegion\").val(region);\n\t\t$(\"#selRegionEdit\").val(region);\n\t}\n}", "function wpsc_region_change() {\n\twpsc_copy_meta_value_to_similiar( jQuery( this ) );\n}", "function search(data){\n setSearch(data); \n }", "handleImageUpdate(query) {\n \n if(query !== this.state.searchText) {\n // sets a new query in the state which will trigger another call to the api\n this.setState((state) => ({\n searchText: query\n }))\n this.searchQuery(query)\n \n }\n \n }", "onSearch(e) {\n let term = e.target.value;\n // Clear the current projects/samples selection\n this.props.resetSelection();\n this.props.search(term);\n }", "function changeSearchFieldState(event) {\n if (event.type === \"load\" || event.type === \"resize\" || event.type === \"blur\") {\n isSearchFieldOpen = false;\n }\n else if (event.type === \"click\") {\n if (isSearchFieldOpen === false) {\n isSearchFieldOpen = true;\n }\n else if (isSearchFieldOpen === true) {\n isSearchFieldOpen = false;\n }\n }\n transformSearchField(isSearchFieldOpen);\n}", "function searchEntity(event) {\n\tif ((this.id == 'search_frame_input' && event.keyCode == 13) || // Enter key code\n\t\t(this.id == 'search_frame_image' && event.type == 'click')) {\n\t\t\tvar sQueryId = $('#search_frame_input').val();\n\t\t\twindow.location = \"search.html?query=\" + sQueryId;\n\t}\n}", "function setQuery() {\n getSearch(search.value);\n}", "updateSearch(event) {\n this.updateTable(event.target.value);\n }", "setLastRegionUpdate(value) {\n LAST_REGION_UPDATE = value\n }", "function OnSpecialItemChanged(specialItem) {\n selectionsSpecialItem = specialItem;\n OnFilterCriteriaChanged();\n}", "function handleSearch() {\n triggerSearch({}); // need empty braces here\n }", "onSearch(value) {\n this.model.query = value;\n }", "onSearch(value) {\n this.model.query = value;\n }", "onInputChangeUnit(units_search) {\n let filters = this.props.filters;\n filters.units_search = units_search;\n filters.do_units_filtering = true;\n this.props.setFilter( filters );\n this.setState( {unit_list_visible: true} );\n }", "function selectRegion(){\n let selectedOption = document.getElementById('region-filter')\n let selectedValue = selectedOption.options[selectedOption.selectedIndex].value\n if(selectedValue === 'Africa'){\n countryToShow = state.countryList.filter((country) =>\n country.region.includes(selectedValue)\n );\n renderCountries(countryToShow);\n }else if(selectedValue === 'America'){\n countryToShow = state.countryList.filter((country) =>\n country.region.includes(selectedValue)\n );\n renderCountries(countryToShow);\n }else if(selectedValue === 'Asia'){\n countryToShow = state.countryList.filter((country) =>\n country.region.includes(selectedValue)\n );\n renderCountries(countryToShow);\n }else if(selectedValue === 'Europe'){\n countryToShow = state.countryList.filter((country) =>\n country.region.includes(selectedValue)\n );\n renderCountries(countryToShow);\n }else if(selectedValue === 'Oceania'){\n countryToShow = state.countryList.filter((country) =>\n country.region.includes(selectedValue)\n );\n renderCountries(countryToShow);\n }else {\n renderCountries(state.countryList);\n return;\n }\n }", "handleFilterChange(filterBy, value){\n //toggle the search children box if they switch from group to ou\n let searchChildren = false;\n if (this.state.filterBy==='ou'){\n searchChildren=this.state.searchChildOUs;\n }\n\n this.setState({filter:value,filterBy:filterBy,searchChildOUs:searchChildren});\n this.getChildOUs();\n }", "async onRegionSubscription(store, snapshot) {\n\n /**\n * TODO:\n * - deal with deleted region (check if region is curently selected)\n * - deal with updating issues (list does not update)\n */\n // console.log('snapshot', snapshot)\n const user = await userService.getUser()\n const { items } = snapshot\n const updated = items.filter(\n (item) => item.dateLastUpdated > LAST_REGION_UPDATE && item.userLastUpdated !== user.name,\n )\n\n updated.forEach((item) => {\n item = new models.RegionModel(item)\n // record the new `lastUpdate`\n if (item.dateLastUpdated > LAST_REGION_UPDATE) {\n actions.setLastRegionUpdate(item.dateLastUpdated)\n }\n // update the region locally if need be\n const existing = store.getters.regionById(item.id)\n // don't overwrite indexes with `undefined` values\n delete item.index\n delete item.displayIndex\n\n if (existing) {\n if (item.dateLastUpdated > existing.dateLastUpdated) {\n store.dispatch('commitRegionUpdate', {\n update: item,\n region: existing\n })\n\n // only dispatch if the regionId matches the current selected region\n const selectedRegion = store.getters.selectedRegion\n if (selectedRegion && existing.id === selectedRegion.id) {\n // trigger update event for the RTE\n EventBus.$emit('realtime-region-update', item)\n }\n }\n } else {\n store.dispatch('commitRegionAdd', item)\n }\n })\n }", "updateFieldKv(event) {\n this.props.uiState.setFieldsUsingKvString(event.target.value);\n this.setSuggestions(event.target.value);\n if (this.state.suggestionIndex) {\n this.setState({\n suggestionIndex: 0\n });\n }\n }", "function replaceRegionFilter(region) {\n var match = matchVoiceToDataCase(data, columnIndex, region);\n activeSheet.applyFilterAsync(\n \"Region\",\n match,\n tableau.FilterUpdateType.REPLACE);\n }", "function getRegion($region_ville){\n $('input.autocomplete-region').autocomplete({\n data: $region_ville,\n limit: 20, // The max amount of results that can be shown at once. Default: Infinity.\n onAutocomplete: function(val) {\n // Callback function when value is autcompleted.\n $.ajax({\n url: '/booking/city_or_region/'+val,\n type: 'GET',\n cache: false,\n contentType: false,\n processData: false,\n beforeSend: function(){},\n success: function(data_json){\n data = $.parseJSON(data_json);\n if (data.status==\"ok\") {\n if (data.page==\"search\") {\n $('#autocompelet-center').empty();\n $('#autocompelet-center').html(data.html);\n $('select').material_select();\n }\n }\n },\n error: function() {\n alert(\"Une erreur est survenue\");\n }\n\n });\n },\n minLength: 1, // The minimum length of the input for the autocomplete to start. Default: 1.\n });\n }", "function themeChanged() { if (extSearchUI) extSearchUI.themeChanged(true); }", "function onWidgetsUpdate() {\n var metadata = getMetadata(store.getState().widgets);\n\n store.setState(_extends({}, store.getState(), {\n metadata: metadata,\n searching: true\n }));\n\n // Since the `getSearchParameters` method of widgets also depends on props,\n // the result search parameters might have changed.\n search();\n }", "function updateFilterChanged() {\n fillUpdateQuestions();\n fillUpdateForm();\n}", "updateSearch(e, data) {\n this.setState({filterText: data.value});\n }", "function onMapBoundsChanged() {\n console.log(\"Change search box bounds\");\n var bounds = map.getBounds();\n searchBox.setBounds(bounds);\n }", "function updateSearchArea(container, url) {\n var xhr = new XMLHttpRequest(),\n containerId = container.id,\n tmp = document.createElement('div'),\n fragment;\n\n xhr.onreadystatechange = function () {\n if (xhr.readyState === 4) {\n tmp.innerHTML = xhr.responseText;\n fragment = tmp.querySelector('#' + containerId);\n container.innerHTML = fragment.innerHTML;\n window.history.pushState('', '', url);\n\n searchArea = document.getElementById('search-area');\n\n attachAllRangeLabels();\n attachAllRangeConstraints();\n attachAllRangeChanges();\n colorizeAllPostLists();\n toggles.init();\n }\n };\n xhr.open('GET', url);\n xhr.send(null);\n }", "onPlaceChanged() {\n let place = this.autocomplete.getPlace();\n\n if (!place.geometry) {\n // User entered the name of a Place that was not suggested and\n // pressed the Enter key, or the Place Details request failed.\n this.$emit('no-results-found', place, this.id);\n return;\n }\n\n if (place.address_components !== undefined) {\n // return returnData object and PlaceResult object\n this.$emit('placechanged', this.formatResult(place), place, this.id);\n\n // update autocompleteText then emit change event\n this.autocompleteText = document.getElementById(this.id).value\n this.onChange()\n }\n }", "function pageChange() {\n\tsubmitSearch(true);\n}", "handleSearchInputChange(event){\n this.setState({\n search: event.target.value\n }, this.reloadResult);\n FilterUserInput.search = event.target.value;\n }", "afterSearch(searchText) {\r\n //this.setState({toggleUpdate: !this.state.toggleUpdate});\r\n console.log(\"Home react-bootstrap-table after search\")\r\n }", "function initSearchPage(){\n /* Resize Map callback */\n \n var resizeMap = function(){\n if(typeof mapResult !== 'undefined') mapResult.map.updateSize();\n }\n\n $(\"#facetH2\").addClass(\"ui-state-disabled\");\n var temporalWidget = new TemporalWidget();\n temporalWidget.temporal = temporal;\n temporalWidget.refreshTemporalSearch();\n \n temporalWidget.doTemporalSearch=true;\n resetCoordinates();\n \n \n if(param_q == -1){\n // show default facet here\n // don't show results\n }\n \n mapResult = initMap();\n populateSearchFields(temporalWidget,search_term);\n \n initPlaceName('geocode',mapResult);\n \n $(\".mapGoBtn\").bind('click',function(){\n // var geometry = mapWidget.getFeatureCoordinates();\n //update spatial coordinates from textboxes\n var nl=document.getElementById(\"spatial-north\");\n var sl=document.getElementById(\"spatial-south\");\n var el=document.getElementById(\"spatial-east\");\n var wl=document.getElementById(\"spatial-west\");\n \n n=nl.value;\n s=sl.value;\n e=el.value;\n w=wl.value; \n\n if(n==''){\n var geometry = mapResult.getFeatureCoordinates();\n polygeometry ='';\n for (var i=0; i<geometry.length; i++) {\n polygeometry += geometry[i].x + \" \" + geometry[i].y;\n if(i<geometry.length-1){\n polygeometry += \",\";\n }\n }\n if (polygeometry != ''){\n var bounds = mapResult.getFeatureBounds();\n polybounds.n = bounds.top;\n polybounds.s = bounds.bottom;\n polybounds.e = bounds.right;\n polybounds.w = bounds.left;\n }else{\n polybounds = Object();\n }\n }else{\n polygeometry = '';\n polybounds = Object();\n }\n\n mapSearch = 0;\n clearAll = 0; \n spatial_included_ids = '';\n $(\"#coordsOverlay\").hide();\n\n $(\"#coordsOverlay input\").trigger('change');\n changeHashTo(formatSearch(search_term, 1, classFilter)); \n\n });\n \n \n $('#search-panel input').keypress(function(e) {\n if(e.which == 13) {\n \n $('#refineSearchBtn').trigger('click');\n \n }\n });\n \n \n autocomplete('#refineSearchTextField');\n autocomplete('input[name^=keyword]');\n \n }", "function selectHandler(e) {\t\n\t// Get the selected region name\n\tvar selection = chart.getSelection();\n\tvar item = selection[0];\n\tvar countryname = data.getFormattedValue(item.row, 2);\n\t// Place it in the box \n\t$('#worldsearch').val(countryname);\n\t\n\t// If we have a query and we aren't already zoomed in\n\tif (currentQ != '' && currentView != 'provinces') {\n\t\t\n\t\t// Get the country code\n\t\tvar selection = chart.getSelection();\n\t\tvar item = selection[0];\n\t\tvar selectdata = data.getFormattedValue(item.row, 0);\n\t\t\n\t\t// Save globally\n\t\tcurrentCountry = selectdata;\n\t\t\n\t\t// Begin getting the data\n\t\tstartProgress()\n\t\tgetGTrends(currentQ, selectdata, function(successData) {\n\t\t\tcurrentView = 'provinces';\n\t\t\tvar ops = {\n\t\t\t\tregion: selectdata,\n\t\t\t\tresolution: 'provinces'\n\t\t\t};\n\t\t\t\n\t\t\t$('#back_col').text('Back to world map');\n\t\t\treDrawChart(successData, ops);\n\t\t});\n\t}\n}", "setSelectedDropDownValue(item) {\n switch (item.filterby) {\n case 'City':\n this.setFilteredFieldState('City', item.idx)\n break;\n }\n }", "function OnEggChanged(egg) {\n selectionsEgg = egg;\n OnFilterCriteriaChanged();\n}", "function eedbSearchGlobalCalloutClick(id) {\n eedbClearSearchTooltip();\n zenbuLoadViewConfig(id)\n}", "onClickHandlerTerms(id, type, name, event=null) {\n event ? event.preventDefault() : null;\n console.log(\"FilterMain: onClickHandlerSearch: type: \" + type + \" name: \" + name);\n let filters = this.props.filters;\n filters.terms_search = name;\n switch(type) {\n case \"RESOURCE\":\n filters.resource_filter = id ;\n break;\n case \"GROUP\":\n filters.group_filter = id;\n break;\n case \"UNIT\":\n filters.unit_filter = id;\n break;\n default:\n }\n filters.do_time_search = true;\n filters.next_day_search = 0;\n filters.previous_day = null;\n this.props.setFilter( filters );\n }", "function onFiltersUpdated() {\n // Close possible open offers\n if (vm.offer) {\n vm.offer = false;\n // Tells `SearchMapController` and `SearchSidebarController`\n // to close anything offer related\n $scope.$broadcast('search.closeOffer');\n }\n // Tells map controller to reset markers\n $scope.$broadcast('search.resetMarkers');\n }", "showAllEditingRegion() {\n if (this.editRangeCollection.length === 0) {\n this.updateEditRangeCollection();\n }\n this.viewer.clearSelectionHighlight();\n for (let j = 0; j < this.editRangeCollection.length; j++) {\n let editRangeStart = this.editRangeCollection[j];\n let positionInfo = this.getPosition(editRangeStart);\n let startPosition = positionInfo.startPosition;\n let endPosition = positionInfo.endPosition;\n this.highlightEditRegions(editRangeStart, startPosition, endPosition);\n }\n }", "function wpsc_change_regions_when_country_changes() {\n\twpsc_copy_meta_value_to_similiar( jQuery( this ) );\n\twpsc_update_regions_list_to_match_country( jQuery( this ) );\n\treturn true;\n}" ]
[ "0.6852377", "0.6463747", "0.6333217", "0.6124844", "0.6039995", "0.5998431", "0.59664583", "0.5940822", "0.59396416", "0.59047866", "0.5864491", "0.585949", "0.5846589", "0.581434", "0.5809582", "0.5804887", "0.5790324", "0.5679786", "0.5679088", "0.5671543", "0.5671543", "0.56506854", "0.56394863", "0.5621325", "0.5618807", "0.55824333", "0.5579718", "0.5569208", "0.5553522", "0.5535138", "0.5524023", "0.54980147", "0.54752934", "0.5473241", "0.5465675", "0.54642373", "0.5461181", "0.5456036", "0.5446349", "0.54463416", "0.5445165", "0.5440065", "0.54362214", "0.542626", "0.5421265", "0.54189074", "0.54044086", "0.5400281", "0.5397964", "0.53961587", "0.539497", "0.5374778", "0.53723687", "0.53687876", "0.53645", "0.53604865", "0.5346696", "0.5333389", "0.53198916", "0.53165305", "0.530661", "0.5305332", "0.5297003", "0.52940917", "0.5286485", "0.5284274", "0.52816474", "0.52680755", "0.52664244", "0.5259382", "0.52546453", "0.5242947", "0.5238312", "0.5236236", "0.5236236", "0.5232981", "0.5230483", "0.52265066", "0.52215433", "0.52157426", "0.5212247", "0.5210799", "0.52088314", "0.5206927", "0.5206356", "0.52051556", "0.5202505", "0.52021646", "0.5191921", "0.5187773", "0.51857156", "0.51852906", "0.51835495", "0.5177758", "0.5175429", "0.51699996", "0.51695216", "0.51655143", "0.51633835", "0.51627016", "0.51604325" ]
0.0
-1
Creates a Page timing Report object and gathers all related information at the same time. This reporst will be ready for dispatching after being created.
constructor() { super('page-timing'); let sourceInfo = {}; let timingInfo = {}; let timing = performance.timing; let timingEntries = ['connect', 'domainLookup', 'domContentLoadedEvent', 'loadEvent', 'redirect', 'response', 'unloadEvent']; let locationEntries = ['origin', 'protocol','pathname']; for (let entry of timingEntries) { let start = timing[entry + 'Start']; let end = timing[entry + 'End']; timingInfo[entry] = end - start; } sourceInfo['title'] = window.document.title; for (let entry of locationEntries) { sourceInfo[entry] = window.document.location[entry]; } this._data = { 'source' : sourceInfo, 'timing' : timingInfo }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async report() {\n const { logger, db } = this[OPTIONS];\n const testedPages = await db.read('tested_pages');\n\n logger.info('Saving JSON report');\n const json = new JSONReporter(this[OPTIONS]);\n await json.open();\n await json.write(testedPages);\n await json.close();\n\n logger.info('Saving HTML Report');\n const html = new HTMLReporter(this[OPTIONS]);\n await html.open();\n await html.write(testedPages);\n await html.close();\n }", "function create(sender_psid, stepNew) {\n\n var report = [];\n var d = new Date();\n\n //creates a report object\n report[0] = new Report({\n sender_id: sender_psid,\n step: stepNew,\n response: \"\",\n responseAux: { \"text\": \"Responda utilizando los botones por favor.\" },\n responseAuxIndicator: 0,\n fromApp: true,\n cause: \"no cause indicated\",\n damages: \"no damages indicates\",\n date: d.getTime(),\n observation: \".\",\n X: 0,\n Y: 0,\n address: \"no addresss indicated\",\n img: \"no image\",\n tomarControl: false,\n formatedDate: d.toLocaleString() + \" \" + d.toTimeString()\n });\n\n //saves the created report object into the mongo data base\n report[0].save(function () {\n console.log(\"creado\");\n });\n\n //returns the created report\n return report;\n}", "function _makeReport() {\n document.getElementById(\"reportTable\").hidden = false;\n document.getElementById(\"chartContainer\").hidden = false;\n updateReportFromDB();\n}", "function initTimeGraph(report) {\n var hoverDetail = new Rickshaw.Graph.HoverDetail( {\n graph: report.graph,\n xFormatter: function(x) {\n // Convert timestamp to date for use as the hover detail\n return timestampToDate(x);\n }\n } );\n\n var xAxis = new Rickshaw.Graph.Axis.Time({\n graph: report.graph\n });\n xAxis.render();\n\n var yAxis = new Rickshaw.Graph.Axis.Y({\n graph: report.graph\n });\n yAxis.render();\n\n var annotator = new Rickshaw.Graph.Annotate({\n graph: report.graph,\n element: report.tab.find('.timeline')[0]\n });\n\n _milestones.forEach(function(milestone) {\n annotator.add(dateToTimestamp(milestone.date), milestone.milestone);\n });\n}", "function createPage() {\n init();\n generateCard();\n makeCommentsWork();\n makeCommentIconsWork();\n makeReactionsWork();\n displayCharLimit();\n}", "function generateReport(){\n\t//create reports folder (if it doesn't already exist)\n\tif(!fs.existsSync(\"reports\")){\n\t\tfs.mkdirSync(\"reports\");\n\t}\n\t\n\t//create a file called by timestamp\n\tvar date = new Date();\n\treportfile = \"reports/\"+date.getDate()+\"-\"+date.getMonth()+\"-\"+date.getFullYear()+\"--\"+date.getHours()+\"h\"+date.getMinutes()+\"m.tex\";\n\t\n\twriteReport();\n\tvar err = createPDF();\n\tif(err){\n\t\tconsole.log(\"ERR : Error during creation of PDF report\");\n\t}\n}", "function GeneratePage() {\n\tthis.generatedPositions = [];\n\n\t// get the size of our sample div, then remove it, it's served it's purpose\n\tconst div = document.querySelector('[data-o-element-visibility-track]');\n\tif (!div) throw new Error('Demo base div missing');\n\tthis.div = div.getBoundingClientRect();\n\tdiv.parentNode.removeChild(div);\n\n\t// set the body size to be 20% larger than the viewport\n\tthis.body = this.setBodySize(1.2);\n\n\t// calculate a sensible amount of divs to display\n\tconst numDivs = this.numDivs = this.maxDivs();\n\tthis.addDivs(numDivs);\n\n\t// counters\n\tthis.inView = document.getElementsByClassName('inview');\n\n\t// initialise the info box\n\tthis.setupInfo();\n}", "constructor() { \n \n TrendedDataReport.initialize(this);\n }", "function TestReport() {\n\t\"use strict\";\n\tvar data = this.data = {\n\t\ttotal: 0,\n\t\tfail: 0,\n\t\tinconclusive: 0,\n\t\tsuccess: 0,\n\t\ttests: {}\n\t};\n\tthis.toString = function () {\n\t\treturn JSON.stringify(data, null, '\\t');\n\t};\n\tthis.start = function () {\n\t\tdata.start = new Date();\n\t\tdata.end = null;\n\t\tdata.duration = \"measuring\";\n\t};\n\tthis.stop = function () {\n\t\tdata.end = new Date();\n\t\tdata.duration = data.end - data.start;\n\t};\n\tthis.addTest = function (name) {\n\t\tdata.total += 1;\n\t\tdata.inconclusive += 1;\n\t\tvar testResultData = {\n\t\t\tname: name,\n\t\t\toutcome: \"inconclusive\"\n\t\t}\n\t\t\t, testResult = {\n\t\t\tstart: function () {\n\t\t\t\ttestResultData.start = new Date();\n\t\t\t\ttestResultData.end = null;\n\t\t\t\ttestResultData.duration = \"measuring\";\n\t\t\t},\n\t\t\tstop: function () {\n\t\t\t\ttestResultData.end = new Date();\n\t\t\t\ttestResultData.duration = testResultData.end - testResultData.start;\n\t\t\t},\n\t\t\tfailed: function (ex) {\n\t\t\t\tdata.fail += 1;\n\t\t\t\tdata.inconclusive -= 1;\n\t\t\t\ttestResultData.outcome = \"failed\";\n\t\t\t\ttestResultData.ex = ex;\n\t\t\t\ttestResultData.message = ex.toString();\n\t\t\t},\n\t\t\tsucceeded: function () {\n\t\t\t\tdata.success += 1;\n\t\t\t\tdata.inconclusive -= 1;\n\t\t\t\ttestResultData.outcome = \"success\";\n\t\t\t}\n\t\t};\n\t\tdata.tests[name] = testResultData;\n\t\treturn testResult;\n\t};\n}", "function ReportData() {\r\n\tthis.ReportType = ExtraTools.eReportType.None;\r\n\tthis.Subject = null;\r\n\tthis.Time = null;\r\n\tthis.AttackerUid = 0;\r\n\tthis.AttackerUname = null;\r\n\tthis.AttackerVid = 0;\r\n\tthis.AttackerVname = null;\r\n\tthis.AttackerSendUnit1 = 0;\r\n\tthis.AttackerSendUnit2 = 0;\r\n\tthis.AttackerSendUnit3 = 0;\r\n\tthis.AttackerSendUnit4 = 0;\r\n\tthis.AttackerSendUnit5 = 0;\r\n\tthis.AttackerSendUnit6 = 0;\r\n\tthis.AttackerSendUnit7 = 0;\r\n\tthis.AttackerSendUnit8 = 0;\r\n\tthis.AttackerSendUnit9 = 0;\r\n\tthis.AttackerSendUnit10 = 0;\r\n\tthis.AttackerSendUnitHero = 0;\r\n\tthis.AttackerLostUnit1 = 0;\r\n\tthis.AttackerLostUnit2 = 0;\r\n\tthis.AttackerLostUnit3 = 0;\r\n\tthis.AttackerLostUnit4 = 0;\r\n\tthis.AttackerLostUnit5 = 0;\r\n\tthis.AttackerLostUnit6 = 0;\r\n\tthis.AttackerLostUnit7 = 0;\r\n\tthis.AttackerLostUnit8 = 0;\r\n\tthis.AttackerLostUnit9 = 0;\r\n\tthis.AttackerLostUnit10 = 0;\r\n\tthis.AttackerLostUnitHero = 0;\r\n\tthis.AttackerPrisonersUnit1 = 0;\r\n\tthis.AttackerPrisonersUnit2 = 0;\r\n\tthis.AttackerPrisonersUnit3 = 0;\r\n\tthis.AttackerPrisonersUnit4 = 0;\r\n\tthis.AttackerPrisonersUnit5 = 0;\r\n\tthis.AttackerPrisonersUnit6 = 0;\r\n\tthis.AttackerPrisonersUnit7 = 0;\r\n\tthis.AttackerPrisonersUnit8 = 0;\r\n\tthis.AttackerPrisonersUnit9 = 0;\r\n\tthis.AttackerPrisonersUnit10 = 0;\r\n\tthis.AttackerPrisonersUnitHero = 0;\r\n\tthis.AttackerGoodsLumber = 0;\r\n\tthis.AttackerGoodsClay = 0;\r\n\tthis.AttackerGoodsIron = 0;\r\n\tthis.AttackerGoodsCrop = 0;\r\n\tthis.AttackerGoodsCaptured = 0;\r\n\tthis.AttackerGoodsMax = 0;\r\n\tthis.DefenderUid = 0;\r\n\tthis.DefenderUname = null;\r\n\tthis.DefenderVid = 0;\r\n\tthis.DefenderVname = null;\r\n\tthis.DefenderUnit1 = 0;\r\n\tthis.DefenderUnit2 = 0;\r\n\tthis.DefenderUnit3 = 0;\r\n\tthis.DefenderUnit4 = 0;\r\n\tthis.DefenderUnit5 = 0;\r\n\tthis.DefenderUnit6 = 0;\r\n\tthis.DefenderUnit7 = 0;\r\n\tthis.DefenderUnit8 = 0;\r\n\tthis.DefenderUnit9 = 0;\r\n\tthis.DefenderUnit10 = 0;\r\n\tthis.DefenderUnitHero = 0;\r\n}", "function init() {\n Reports.getReportTypeList().then(function(result) {\n angular.forEach(result, function(report, key) {\n var api = Reports.parse(report.api);\n self.apis[report.name] = api;\n\n // for ( var filter in self.filterTypes) {\n // if (api.params.indexOf(filter) != -1) {\n //\n // }\n // }\n });\n\n self.reportTypes = result;\n\n self.selectedReport = self.reportTypes[0];\n\n // reset filter to default before applying filter\n resetFilter();\n\n self.applyFilter();\n }, function(err) {\n console.log(err);\n });\n\n // reports page initialization setup\n\n $scope.server_first_name = $cookieStore.get(\"server_first_name\");\n\n self.serverTime = $rootScope.serverTime;\n self.serverTime = self.serverTime.replace(new RegExp('-', 'g'), '/');\n self.serverTime = self.serverTime.replace(/([\\d]{2})\\:([\\d]{2})\\:[\\d]{2}/, \"$1\\:$2\");\n\n self.location = $rootScope.location;\n\n resetFilter();\n\n }", "addNewReport() {\n \n }", "function makePageCalls(pageIdentifier, dataToSend) {\n\n\tvar newPage = new page;\n\tnewPage.pageIdentifier = pageIdentifier;\n\tnewPage.dataToSend = dataToSend;\n\n\t// init onjects and arrays\n\tnewPage.currentPageData = new Object();\n\tnewPage.currentPageSections = new Array();\n\tnewPage.currentPageBlocks = new Array();\n\tnewPage.sectionsRendered = new Array();\n\tnewPage.readyForRender = new Array();\n\tnewPage.currentPageAjaxCalls = new Object();\n\n\tnewPage.load();\n}", "function createPage() {\r\n\r\n clearSection(setPoolSize);\r\n clearSection(setPlayerNames);\r\n clearSection(setRatings);\r\n clearSection(playerPool);\r\n clearSection(generator);\r\n clearSection(prepTeam);\r\n\r\n homeTeam.className = \"col card bg-light border-dark\";\r\n awayTeam.className = \"col card bg-light border-dark\";\r\n \r\n populateSection(homeTeam, \"H3\", \"Home Team\");\r\n home.forEach((home)=>populateSection(homeTeam, \"P\", home.getName() + \" / \" + home.getRating() ));\r\n populateSection(homeTeam, \"H4\", \"Rating: \" + homeScore)\r\n \r\n populateSection(awayTeam, \"H3\", \"Away Team\");\r\n away.forEach((away)=>populateSection(awayTeam, \"P\", away.getName() + \" / \" + away.getRating() ));\r\n populateSection(awayTeam, \"H4\", \"Rating: \" + awayScore);\r\n\r\n reset.focus();\r\n }", "async page() {\n if ((this._targetInfo.type === 'page' ||\n this._targetInfo.type === 'background_page' ||\n this._targetInfo.type === 'webview') &&\n !this._pagePromise) {\n this._pagePromise = this._sessionFactory().then((client) => Page_js_1.Page.create(client, this, this._ignoreHTTPSErrors, this._defaultViewport));\n }\n return this._pagePromise;\n }", "async page() {\n if ((this._targetInfo.type === 'page' ||\n this._targetInfo.type === 'background_page' ||\n this._targetInfo.type === 'webview') &&\n !this._pagePromise) {\n this._pagePromise = this._sessionFactory().then((client) => Page_js_1.Page.create(client, this, this._ignoreHTTPSErrors, this._defaultViewport));\n }\n return this._pagePromise;\n }", "function createReport1(tmfile1) {\n\topenfile(tmfile1);\n\tif (reporttype == 0) {\n\t\toframe.ActiveDocument.Application.Run(\"createNormalReport\");\n\t} else {\n\t\toframe.ActiveDocument.Application.Run(\"analyze\");\n\t}\n}", "function init(){\n getReportData();\n }", "function createReport(options, create, createFromScreenBuilder) {\n // Valid options:\n // .folder\n // .typeId\n\n spReportPropertyDialog.showModalDialog(options).then(function (result) {\n if (!result)\n return;\n\n if (result.reportId && result.reportId > 0) {\n\n //var currentNavItem = spNavService.getCurrentItem();\n var parentNavItem = spNavService.getParentItem();\n\n if (parentNavItem) {\n if (parentNavItem.data && !sp.isNullOrUndefined(parentNavItem.data.createNewReport)) {\n parentNavItem.data.createNewReport = true;\n\n if (createFromScreenBuilder) {\n if (!sp.isNullOrUndefined(parentNavItem.data.createFromScreenBuilder)) {\n parentNavItem.data.createFromScreenBuilder = true;\n } else {\n parentNavItem.data = _.extend(\n parentNavItem.data || {},\n {\n createFromScreenBuilder: true\n });\n }\n }\n\n } else {\n parentNavItem.data = _.extend(\n parentNavItem.data || {},\n {\n createNewReport: true,\n createFromScreenBuilder: createFromScreenBuilder ? true : false\n });\n }\n }\n\n if (create) {\n spNavService.navigateToChildState(\n 'reportBuilder',\n result.reportId,\n {returnOnCompletion: true});\n } else {\n /////\n // TODO: Why was this done??\n /////\n\n //spNavService.navigateToChildState(\n // 'report',\n // result.reportId,\n // { returnOnCompletion: true });\n spNavService.navigateToSibling('report', result.reportId);\n }\n }\n else if (result.report) {\n /////\n // TODO: Where is this method?\n /////\n exports.updateReportModel(-1, result.report).then(function (reportModelResponse) {\n if (reportModelResponse) {\n spNavService.navigateToChildState(\n 'reportBuilder',\n reportModelResponse,\n {returnOnCompletion: true});\n }\n });\n }\n });\n }", "function generation() {\n\tclearTimeout(genTimer) ///stop additional clicks from initiating more timers\n\t// all methods that need to be done every second need to go here\n\taddToGraphs();\n\tchangeOnPageStats();\n\tif(!stopGen) {\n genTimer = setTimeout(function(){generation()},1000)\n\t}\n\t}", "function newPageTime() {\r\n pt = dt = performance.now();\r\n pgPauses = dvPauses = scrollPos = 0;\r\n}", "function createPage() {\n // Clear the preview div.\n $('#previewDiv').empty();\n \n // Add a new page.\n addPage(new Page());\n}", "function fillTimeReport(times) {\n\tvar tableBody = $('#time-pane tbody');\n\n\ttableBody.empty();\n\n\tvar categories = Object.keys(times);\n\tif(categories.length > 0) {\n\t\t$('#time-pane #no-categories').hide();\n\t\t$('#time-pane #categories').show();\n\n\t\tvar oneMinute = 60,\n\t\t\toneHour = oneMinute*60,\n\t\t\toneDay = oneHour*24;\n\n\t\tcategories.forEach(function (category) {\n\t\t\tvar line = $('<tr>');\n\t\t\tvar categoryCell = $('<td>', {'text': category.replace('_', ' ')});\n\n\t\t\tvar timeSpent = times[category].duration;\n\n\t\t\tvar days = Math.floor(timeSpent/oneDay),\n\t\t\t\thours = Math.floor((timeSpent%oneDay)/oneHour),\n\t\t\t\tminutes = Math.floor((timeSpent%oneDay)%oneHour/oneMinute),\n\t\t\t\tseconds = Math.floor(((timeSpent%oneDay)%oneHour)%oneMinute);\n\n\t\t\tvar daysString = days>0 ? days + ' day' + (days>1 ? 's ' : ' ') : '',\n\t\t\t\thoursString = hours>0 ? hours + ' hour' + (hours>1 ? 's ' : ' ') : '',\n\t\t\t\tminutesString = minutes>0 ? minutes + ' minute' + (minutes>1 ? 's ' : ' ') : '',\n\t\t\t\tsecondsString = seconds>0 ? seconds + ' second' + (seconds>1 ? 's' : '') : '';\n\n\t\t\tvar timeString = daysString + hoursString + minutesString + secondsString;\n\t\t\tif(timeString === '') {\n\t\t\t\ttimeString = self.options.no_time_spent;\n\t\t\t}\n\n\t\t\tvar timeSpentCell = $('<td>', {'text': timeString});\n\n\t\t\tline.append(categoryCell).append(timeSpentCell);\n\t\t\ttableBody.append(line);\n\t\t});\n\t} else {\n\t\t$('#time-pane #categories').hide();\n\t\t$('#time-pane #no-categories').show();\n\t}\n}", "function PerformanceReporter() {\n }", "function ReportService () {\n\tvar self = this;\n\t\n\tself.timing = 50;\n\t\n\tself.count = Game.cookiesd;\n\tself.cps = Game.cps;\n\tself.delta = 0;\n\tself.deltaBySecond = 0;\n\tself.index = 0;\n\tself.lastCount = 0;\n\tself.lastDelta = 0;\n\tself.lastCountBySecond = 0;\n\t\n\tself.subscribers = Array();\n\tself.reports = Array();\n\t\n\tself.tick = function() {\n\t\tsetTimeout(function(){\n\t\t\tself.refreshData();\n\t\t\tself.notifySubscribers();\n\t\t\tself.consoleReport();\n\t\t\tself.tick();\n\t\t}, self.timing);\n\t}\n\t\n\tself.subscribe = function(fn) {\n\t\tself.subscribers.push(fn);\n\t}\n\t\n\tself.addReport = function(fn) {\n\t\tself.reports.push(fn);\n\t}\n\t\n\tself.refreshData = function() {\n\t\tself.lastCount = self.count;\n\t\tself.count = Game.cookiesd;\n\t\tself.cps = Game.cookiesPs*(1-Game.cpsSucked);\n\t\tself.lastDelta = self.delta;\n\t\tself.delta = self.count - self.lastCount;\n\t\tself.index++;\n\t}\n\t\n\tself.notifySubscribers = function() {\n\t\tfor(var i = 0; i < self.subscribers.length; i++){\n\t\t\tself.subscribers[i]();\n\t\t}\n\t}\n\t\n\tself.getReports = function() {\n\t\tvar report = '';\n\t\tfor(var i = 0; i < self.reports.length; i++){\n\t\t\tvar curReport = self.reports[i]();\n\t\t\tif(curReport != ''){\n\t\t\t\treport = report + curReport;\n\t\t\t\tif(i < self.reports.length){\n\t\t\t\t\treport = report + '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn report;\n\t}\n\t\n\tself.consoleReport = function() {\n\t\t//Report every second\n\t\tif(self.index * self.timing % 1000 === 0){\n\t\t\tself.deltaBySecond = self.count - self.lastCountBySecond;\n\t\t\tself.lastCountBySecond = self.count;\n\t\t\tvar report = self.getReports();\n\t\t\tif(report != ''){\n\t\t\t\treport = '\\n' + report;\n\t\t\t}\n\t\t\tconsole.log('Cookies:\\t' + Beautify(self.count) + '\\nCPS:\\t\\t' + Beautify(self.cps) + '\\nDelta:\\t\\t' + Beautify(self.deltaBySecond) + report);\n\t\t}\n\t}\n\t\n\tself.tick();\n}", "function processGenerateReportButton() \n{ \n\t//console.log(\"Entereed generateReport\");\n\t//console.log(currentPage);\n\t\n\tif (currentPage == \"Campus\")\n\t{\n\t\tinitCampusReportGeneration();\n\t}\n\telse\n\t{ \n\t\tinitBuildingReportGeneration(currentPage);\n\t}\n\t\n}", "function initPage(){\r\n\t\t//add head class\r\n\t\t$(\"#headGeneralInformationLi\").addClass(\"active\");\r\n\t\tgetSeries();\r\n\t\t$(\"#divLeft,#divHead,#divFoot\").addClass(\"notPrintable\");\r\n\t\t$(\"#startTime\").val(window.byd.DateUtil.lastWorkDate());\r\n\r\n\t\tajaxQueryReplacementCost(\"monthly\");\r\n \tajaxQueryReplacementCost(\"yearly\");\r\n \tajaxQueryCostDistribute();\r\n\t\tresetAll();\r\n\t}", "function Report(name, id)\n {\n this.reportName = name;\n this.id = id;\n\n // Initialize Report object with an array of section objects\n this.initReport = function()\n {\n // Initialize all sections with respective object constructors\n this.general = new GeneralSection();\n this.personal = new PersonalSection();\n this.vehicle = new VehicleSection();\n this.other = new OtherSection();\n this.affirmation = new AffirmationSection();\n this.sectionc = new SectionC();\n\n // Initialize all sections to have one Item\n this.general.addItem();\n this.personal.addItem();\n this.vehicle.addItem();\n this.other.addItem();\n this.affirmation.addItem();\n this.sectionc.addItem();\n\n // Transfer reportName and id down to general section\n this.general.items[0].reportName = this.reportName;\n this.general.items[0].logNumber = this.id;\n }\n }", "async function createLabReport(patient, report, labs) {\n const labReport = new SampleDocument({patient, report, labs}, 'labs');\n console.log(`creating Lab Report ${labReport.id}`);\n createTxt(labReport);\n //await createPdf(labReport);\n}", "function Report() {\n this.json = new reportformat.Reportformat('json', '.json');\n this.txt = new reportformat.Reportformat('txt', '.txt');\n /**\n * Format of the report file.\n *\n * @private\n */\n this.format = this.json;\n /**\n * The report filepath.\n *\n * @private\n */\n this.filepath = 'report';\n}", "function renderReport(doc) {\n\n // ----------------------------------------------\n let br = document.createElement('br');\n let hr = document.createElement('hr');\n let page = document.createElement('span');\n\n let caption = document.createElement('h4'); //append caption\n let innerCaption = document.createElement('small');\n var t1 = document.createTextNode(\"PREVIOUS POSTS\");\n innerCaption.appendChild(t1);\n caption.appendChild(innerCaption)\n\n // append hr\n\n let title = document.createElement('h3'); //append title\n title.textContent = doc.data().studentUserName;\n\n let date = document.createElement('h5')//append date\n let icons = document.createElement('span')\n icons.classList.add('glyphicon');\n icons.classList.add('glyphicon-time');\n let time = document.createElement('span');\n time.textContent = doc.data().time;\n var t2 = document.createTextNode(' Posted on ');\n date.appendChild(icons);\n date.appendChild(t2);\n date.appendChild(time);\n\n\n let mainIcons = document.createElement('h5')//mainIcons\n let glyph1 = document.createElement('span');\n glyph1.classList.add('label');\n glyph1.classList.add('label-success');\n var t3 = document.createTextNode('created');\n var t5 = document.createTextNode(' ');\n glyph1.appendChild(t3);\n let glyph2 = document.createElement('span');\n glyph2.classList.add('label');\n glyph2.classList.add('label-primary');\n var t4 = document.createTextNode('read');\n glyph2.appendChild(t4);\n mainIcons.appendChild(glyph1);\n mainIcons.appendChild(t5);\n mainIcons.appendChild(glyph2);\n\n // append break (br)\n // append break (br)\n\n let comment = document.createElement('p')//append comment\n comment.textContent = doc.data().report;\n\n page.appendChild\n\n page.appendChild(caption);\n page.appendChild(hr);\n page.appendChild(title);\n page.appendChild(date);\n page.appendChild(mainIcons);\n page.appendChild(comment);\n page.appendChild(br);\n page.appendChild(br);\n page.appendChild(br);\n\n reportList.appendChild(page);\n\n}", "async function pageConstruct () {\n let i, bodyNode, emptyElement\n\n IMLibCalc.calculateRequiredObject = {}\n INTERMediator.currentEncNumber = 1\n INTERMediator.elementIds = []\n\n // Restoring original HTML Document from backup data.\n bodyNode = document.getElementsByTagName('BODY')[0]\n if (INTERMediator.rootEnclosure === null) {\n INTERMediator.rootEnclosure = bodyNode.innerHTML\n } else {\n bodyNode.innerHTML = INTERMediator.rootEnclosure\n }\n postSetFields = []\n INTERMediatorOnPage.setReferenceToTheme()\n IMLibPageNavigation.initializeStepInfo(false)\n\n IMLibLocalContext.bindingDescendant(document.documentElement)\n\n try {\n await seekEnclosureNode(bodyNode, null, null, null)\n } catch (ex) {\n if (ex.message === '_im_auth_required_') {\n throw ex\n } else {\n INTERMediatorLog.setErrorMessage(ex, 'EXCEPTION-9')\n }\n }\n\n // After work to set up popup menus.\n for (i = 0; i < postSetFields.length; i++) {\n if (postSetFields[i].value === '' &&\n document.getElementById(postSetFields[i].id).tagName === 'SELECT') {\n // for compatibility with Firefox when the value of select tag is empty.\n emptyElement = document.createElement('option')\n emptyElement.setAttribute('id', INTERMediator.nextIdValue())\n emptyElement.setAttribute('value', '')\n emptyElement.setAttribute('data-im-element', 'auto-generated')\n document.getElementById(postSetFields[i].id).insertBefore(\n emptyElement, document.getElementById(postSetFields[i].id).firstChild)\n }\n document.getElementById(postSetFields[i].id).value = postSetFields[i].value\n }\n IMLibCalc.updateCalculationFields()\n IMLibPageNavigation.navigationSetup()\n\n if (isAcceptNotify && INTERMediator.pusherAvailable) {\n let channelName = INTERMediatorOnPage.clientNotificationIdentifier()\n let appKey = INTERMediatorOnPage.clientNotificationKey()\n if (appKey && appKey !== '_im_key_isnt_supplied' && !INTERMediator.pusherObject) {\n try {\n Pusher.log = function (message) {\n if (window.console && window.console.log) {\n window.console.log(message)\n }\n }\n\n INTERMediator.pusherObject = new Pusher(appKey)\n INTERMediator.pusherChannel = INTERMediator.pusherObject.subscribe(channelName)\n INTERMediator.pusherChannel.bind('update', function (data) {\n IMLibContextPool.updateOnAnotherClient('update', data)\n })\n INTERMediator.pusherChannel.bind('create', function (data) {\n IMLibContextPool.updateOnAnotherClient('create', data)\n })\n INTERMediator.pusherChannel.bind('delete', function (data) {\n IMLibContextPool.updateOnAnotherClient('delete', data)\n })\n } catch (ex) {\n INTERMediatorLog.setErrorMessage(ex, 'EXCEPTION-47')\n }\n }\n }\n appendCredit()\n }", "constructor () {\n super()\n\n this.attachShadow({ mode: 'open' })\n .appendChild(template.content.cloneNode(true))\n\n this.attemptsCount = 0\n this.timer =\n this.timerSeconds = 0\n this.timerMinutes = 0\n\n this._startPage = this.shadowRoot.querySelector('.startpage')\n this._buttons = this.shadowRoot.querySelector('.button-container')\n this._smallButton = this.shadowRoot.querySelector('#small')\n this._mediumButton = this.shadowRoot.querySelector('#medium')\n this._largeButton = this.shadowRoot.querySelector('#large')\n this._gameBoard = this.shadowRoot.querySelector('.gameboard-grid')\n this._tracker = this.shadowRoot.querySelector('.tracker-container')\n this._finishPage = this.shadowRoot.querySelector('.finished-page-container')\n this._tryAgainBtn = this.shadowRoot.querySelector('.finished-page-window > button')\n\n this._createBoard = this._createBoard.bind(this)\n this._onFlip = this._onFlip.bind(this)\n this._onTryAgain = this._onTryAgain.bind(this)\n this._startStopWatch = this._startStopWatch.bind(this)\n }", "function addReportTime (data, id) {\r\n\t//Div element where the report time will be added\r\n\tvar div = document.getElementById(id);\r\n\t//Create the heading element\r\n\tvar head = document.createElement(\"h3\");\r\n\t//Create the text\r\n\thead.appendChild(document.createTextNode(\"Report generated on:\"));\r\n\tvar par = document.createElement(\"p\");\r\n\tpar.appendChild(document.createTextNode(data[\"DateTime\"]));\r\n\t//Add to DOM\r\n\tdiv.appendChild(head);\r\n\tdiv.appendChild(par);\r\n}", "function singleRender() {\n document.title = '' + CURRENT_RENDER_COUNT +\n ' — ' + CURRENTLY_RENDERED_PAGE_INDEX;\n const before = new Date().getTime();\n render(PAGES[CURRENTLY_RENDERED_PAGE_INDEX]);\n const after = new Date().getTime();\n\n const elapsed = after - before;\n TIMINGS[CURRENTLY_RENDERED_PAGE_INDEX].push(elapsed);\n CURRENTLY_RENDERED_PAGE_INDEX++;\n\n if (CURRENT_RENDER_COUNT >= RENDER_COUNT) {\n window.clearInterval(INTERVAL_ID);\n window.setTimeout(finish, 2 * SETTLE_DOWN_TIME_MS);\n } else {\n if (CURRENTLY_RENDERED_PAGE_INDEX >= PATHS.length) {\n CURRENTLY_RENDERED_PAGE_INDEX = 0;\n CURRENT_RENDER_COUNT++;\n }\n }\n}", "static create(web, pageName, title, pageLayoutType = \"Article\") {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n // patched because previously we used the full page name with the .aspx at the end\r\n // this allows folk's existing code to work after the re-write to the new API\r\n pageName = pageName.replace(/\\.aspx$/i, \"\");\r\n // this is the user data we will use to init the author field\r\n // const currentUserLogin = await ClientSidePage.getPoster(\"/_api/web/currentuser\").select(\"UserPrincipalName\").get<{ UserPrincipalName: string }>();\r\n // initialize the page, at this point a checked-out page with a junk filename will be created.\r\n const pageInitData = yield ClientSidePage.initFrom(web, \"_api/sitepages/pages\").postCore({\r\n body: jsS(Object.assign(metadata(\"SP.Publishing.SitePage\"), {\r\n PageLayoutType: pageLayoutType,\r\n })),\r\n });\r\n // now we can init our page with the save data\r\n const newPage = new ClientSidePage(web, \"\", pageInitData);\r\n // newPage.authors = [currentUserLogin.UserPrincipalName];\r\n newPage.title = pageName;\r\n yield newPage.save(false);\r\n newPage.title = title;\r\n return newPage;\r\n });\r\n }", "async generateReportData() {\n try {\n const date = new Date();\n const currentMonth =\n date.getMonth() < 9 ? `0${(date.getMonth() + 1)}` : `${(date.getMonth() + 1)}`;\n const currentDate = date.getDate() < 10 ? `0${date.getDate()}` : `${date.getDate()}`;\n const start = `${date.getFullYear()}-01-01 00:00:00+00`;\n // const start = `${date.getFullYear()}-${currentMonth}-01 00:00:00+00`;\n this.fileDate = `${date.getFullYear()}-${currentMonth}-${currentDate}`;\n const query = `select\n to_char(lead.created_at + interval '5 hours 30 min', 'DD-MM-YYYY') as date,\n to_char(lead.created_at + interval '5 hours 30 min', 'HH:MI:SSAM') as created_time,\n ( select name from zones where id = lead.zone_id ) as zone,\n ( select name from states where id = lead.state_id ) as state,\n ( select name from cities where id = lead.city_id ) as city,\n ( select name from dealer_categories dc where dc.id = lead.dealer_category_id ) as dealer_category,\n ( select name from dealers d where d.id = lead.dealer_id ) as name_of_the_dealer,\n lead.source_of_enquiry as source_of_enquiry,\n ( select first_name from users u where u.id = lead.assigned_to ) as name_of_the_dse,\n lead.pincode as pincode,\n ( CASE WHEN (lead.gender = 'male') THEN 'Mr.' ELSE 'Ms.' END ) as title_of_the_prospect,\n lead.name as name_of_the_prospect, lead.mobile_number as phone_number,\n ( select count(1) from lead_details where lead_id = lead.id and is_deleted = false ) as number_of_enquiries,\n ( select name from vehicles where id = ld.vehicle_id ) as product_enquired,\n (select color from variant_colours where id=ld.variant_colour_id ) as Product_Color,\n ( CASE WHEN (lead.category = 'NEW' and lead.is_lost = false and lead.is_invoiced = false\n and lead.is_booked = false ) THEN 'yes' ELSE 'no' END ) as new,\n ( CASE WHEN (lead.category = 'HOT' and lead.is_lost = false and lead.is_invoiced = false\n and lead.is_booked = false ) THEN 'yes' ELSE 'no' END ) as hot,\n ( CASE WHEN (lead.category = 'WARM' and lead.is_lost = false and lead.is_invoiced = false\n and lead.is_booked = false ) THEN 'yes' ELSE 'no' END ) as warm,\n ( CASE WHEN (lead.category = 'COLD' and lead.is_lost = false and lead.is_invoiced = false\n and lead.is_booked = false ) THEN 'yes' ELSE 'no' END ) as cold,\n ( CASE WHEN (ld.booked_on IS NOT NULL) THEN 'yes'\n ELSE 'no' END ) as is_booked,\n ( CASE WHEN (ld.invoiced_on IS NOT NULL) THEN 'yes'\n ELSE 'no' END ) as is_invoiced,\n ( CASE WHEN (lead.is_lost = true) THEN 'yes' ELSE 'no' END ) as lost,\n ( CASE WHEN (lead.lost_reason_text is NULL OR lead.lost_reason_text = '')\n THEN ( select reason from lost_reasons where id = lead.lost_reason_id )\n ELSE lead.lost_reason_text END ) as lost_reason,\n(CASE WHEN(lead.lost_reason_id is not NULL )Then\n(select category from lost_reasons where id = lead.lost_reason_id )\nElse '' END) as Lost_Category,\n lead.category as last_status,\n to_char(ld.booked_on + interval '5 hours 30 min', 'DD-MM-YYYY') as booked_date,\n to_char(ld.invoiced_on + interval '5 hours 30 min', 'DD-MM-YYYY') as invoiced_date,\n to_char(cast(lead.lost_on as timestamp with time zone) + interval '5 hours 30 min', 'DD-MM-YYYY') as Lost_Date,\n ( CASE WHEN (ld.test_ride_status is not null) THEN 'yes' ELSE 'no' END ) as test_ride_availed,\n (case ld.test_ride_status when 200 then 'Booked'\n when 300 then 'Ongoing' when 400 then 'Completed'\n when 500 then 'Cancelled' end) \"Test Ride Status\",\n ( CASE WHEN ( (select count(1) from exchange_vehicles where lead_id = lead.id ) = 0)\n THEN 'no' ELSE 'yes' END ) as exchange_vehicle_opted,\n ( select manufacturer from exchange_vehicles where lead_id = lead.id order by created_at DESC limit 1)\n as vehicle_make,\n ( select vehicle from exchange_vehicles where lead_id = lead.id order by created_at DESC limit 1)\n as vehicle_model,\n ( select variant_year from exchange_vehicles where lead_id = lead.id order by created_at DESC limit 1)\n as year_of_manufacturer,\n ( select condition from exchange_vehicles where lead_id = lead.id order by created_at DESC limit 1)\n as vehicle_condition,\n ( select remarks from exchange_vehicles where lead_id = lead.id order by created_at DESC limit 1)\n as vehicle_remarks,\n ( select quoted_value from exchange_vehicles where lead_id = lead.id order by created_at DESC limit 1)\n as exchange_value,\n ( CASE WHEN ( lead.income_status = 1 AND fl.id is not null) THEN 'self-employed'\n WHEN ( lead.income_status = 0 AND fl.id is not null) THEN 'salaried'\n ELSE '' END ) as income_status,\n ( CASE WHEN (fl.id is not null) THEN 'yes' ELSE 'no' END ) as finance_opted,\n ( select name from financiers f where f.id = fl.financier_id ) as financier_name,\n fl.loan_amount as loan_amount,\n fl.tenure as tenure,\n ( CASE WHEN (fl.status = 500) THEN 'active'\n WHEN (fl.status = 510) THEN 'disbursement-pending'\n WHEN (fl.status = 520) THEN 'converted'\n WHEN (fl.status = 930) THEN 'lost' END ) as finance_status,\n ( CASE WHEN ( (select count(1) from follow_ups where lead_id = lead.id ) = 0) THEN 'no' ELSE 'yes' END )\n as follow_up_scheduled,\n to_char(lead.next_followup_on + interval '5 hours 30 min', 'DD-MM-YYYY') as next_follow_up_date,\n to_char(lead.next_followup_on + interval '5 hours 30 min', 'HH:MI:SSAM') as next_follow_up_time,\n ( select to_char(completed_at + interval '5 hours 30 min', 'DD-MM-YYYY')\n from follow_ups where lead_id = lead.id and is_completed = true\n order by created_at DESC limit 1 ) as last_follow_up_date,\n ( select to_char(completed_at + interval '5 hours 30 min', 'HH:MI:SSAM')\n from follow_ups where lead_id = lead.id and is_completed = true\n order by created_at DESC limit 1 ) as last_follow_up_time,\n ( select comment from follow_ups where lead_id = lead.id and is_completed = true\n order by created_at DESC limit 1 ) as follow_up_comment,\n ( select count(1) from follow_ups where lead_id = lead.id and is_completed = true ) as number_of_follow_up_done,\n (SELECT string_agg(comment, '; ')\nFROM lead_activities where lead_id=lead.id and type='Comments Added') AS General_Comments\n from leads lead\n left join lead_details ld ON ld.lead_id = lead.id and ld.is_deleted = false\n left join financier_leads fl ON fl.lead_detail_id = ld.id and\n fl.created_at=(select max(created_at) from financier_leads fl_temp\n where fl_temp.lead_detail_id = ld.id)\n where\n ( lead.created_at between $1 and (select now()) ) or\n ( lead.invoiced_on between $1 and (select now()) ) or\n ( lead.lost_on between $1 and (select now()) )\n order by lead.created_at ASC, lead.name ASC`;\n const params = [start];\n this.result = await new Promise((resolve, reject) => {\n postgresDsConnector.query(query, params, (err, res) => {\n if (err) {\n logger.info('Error in preparing report data');\n reject(new InstabikeError(err));\n }\n return resolve(res);\n });\n });\n let csv = [];\n if (this.result.length) {\n const items = this.result;\n // specify how you want to handle null values here\n const replacer = (key, value) => (value === null ? '' : value);\n const header = Object.keys(items[0]);\n await Promise.all(items.map((row) => {\n const eachRow = header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',');\n csv.push(eachRow);\n }));\n csv.unshift(header.join(','));\n csv = csv.join('\\r\\n');\n } else {\n csv = constants.MIS_REPORT.DEFAULT_TITLE;\n }\n await this.saveReportAsCSV(csv);\n } catch (e) {\n logger.info(e);\n throw new InstabikeError(e);\n }\n }", "function setupBookingReport(parmFromDate, parmToDate, includeBookings, sortBookings, showAgent, showInv, bookingArray, receiptArray, invoiceArray, topHeadtxt) {\n\t\n\tdocument.title = topHeadtxt;\n\tvar htmlCode = '';\n\n\tconsole.log(\"parmFromDate: \" + parmFromDate)\n\tconsole.log(\"showAgent: \" + showAgent)\n\tconsole.log(\"includeBookings: \" + includeBookings)\n\tconsole.log(\"receiptArray: \" + receiptArray)\n\tconsole.log(\"sortBookings: \" + sortBookings)\n\n\t// Prepair the dates\n\tvar fromDate = new Date(parmFromDate*1000);\n\tvar toDate = new Date(parmToDate*1000);\n\tvar reportHead = 'Period from <b>' + fromDate.format('d M Y') + '</b> to <b>' + toDate.format('d M Y') + '</b>';\n\tvar showChannel = true;\n\tvar showStatus = true;\n\tvar showUnit = true;\n\n\t// Set the headline and the status conditions\n\tswitch(includeBookings) {\n\t\tcase 'ACTIVE':\n\t\t\tvar txtInclude = 'Active Bookings'\n\t\t\tbreak;\n\t\tcase 'ALL':\n\t\t\tvar txtInclude = 'All Bookings'\n\t\t\tbreak;\n\t\tcase 'NOPAY':\n\t\t\tvar txtInclude = 'Unpaid Bookings'\n\t\t\tbreak;\n\t\tcase '0':\n\t\t\tvar txtInclude = 'New Bookings'\n\t\t\tbreak;\n\t\tcase '1':\n\t\t\tvar txtInclude = 'Pending'\n\t\t\tbreak;\n\t\tcase '2':\n\t\t\tvar txtInclude = 'Booked'\n\t\t\tbreak;\n\t\tcase '3':\n\t\t\tvar txtInclude = 'Check-in'\n\t\t\tbreak;\n\t\tcase '4':\n\t\t\tvar txtInclude = 'Check-out'\n\t\t\tbreak;\n\t\tcase '5':\n\t\t\tvar txtInclude = 'Done'\n\t\t\tbreak;\n\t\tcase '6':\n\t\t\tvar txtInclude = 'Cancelled'\n\t\t\tbreak;\n\t}\n\n\n\t\n\t// Sort bookingArray by different things\n\tswitch(sortBookings) {\n\t\tcase 'DATE':\n\t\t\tvar txtSort = 'Checkin Date'\n\t\t\tsortBy(bookingArray, (o) => o.checkin);\n\t\t\tbreak;\n\t\tcase 'CHANNEL':\n\t\t\tvar txtSort = 'Booking Channel'\n \t\t\tsortBy(bookingArray, (o) => [o.source, o.checkin]);\n\t\t\tbreak;\n\t\tcase 'PROPERTY':\n\t\t\tvar txtSort = 'Property'\n\t\t\tsortBy(bookingArray, (o) => [o.property, o.checkin]); \n\t\t\tbreak;\n\t\tcase 'STATUS':\n\t\t\tvar txtSort = 'Booking Status'\n \t\t\tsortBy(bookingArray, (o) => [o.status, o.checkin]);\n\t\t\tbreak;\n\t}\n\n\tsortBy(invoiceArray, (o) => o._id);\n\n\t// Put page title the same as report headline\n\tdocument.title = txtInclude + ' sort by ' + txtSort;\n\ttopHeadtxt = txtInclude + ' sort by ' + txtSort ; \n\t\n\t// Render the report \n\tvar fldSort = ''\n\tvar htmlCode = ''\n\thtmlCode = '';\n\thtmlCode += topHeadline(topHeadtxt);\n\thtmlCode += reportHeadline(reportHead)\t\n\t\n\n\t// DATE\n\tif (sortBookings=='DATE') {\n\t\thtmlCode += renderBookingTableHeader(showChannel, showStatus, showUnit, showAgent, showInv);\n\t\n\t\t// Loop thru all bookings\n\t\tvar lines=0;\n\t\tfor (var i=0; i<bookingArray.length; i++) {\t\n\t\t\thtmlCode += renderBookings(i, includeBookings, sortBookings, showChannel, showStatus, showUnit, showAgent, showInv, bookingArray, receiptArray, invoiceArray);\n\n\t\t\t// Break every 28 lines \n\t\t\tlines += 1;\n\t\t\tif (lines>28) {\n\t\t\t\tlines = 0;\n\t\t\t\thtmlCode += '</table>';\n\t\t\t\thtmlCode += reportFooter();\t\t\t\n\t\t\t\thtmlCode += reportPageBreak();\n\t\t\t\thtmlCode += topHeadline(topHeadtxt);\n\t\t\t\thtmlCode += reportHeadline(txtSort)\t\n\t\t\t\thtmlCode += renderBookingTableHeader(showChannel, showStatus, showUnit, showAgent, showInv);\n\t\t\t}\n\t\t}\n\n\t} else {\n\n\t\n\t\t// CHANNEL\n\t\tif (sortBookings=='CHANNEL') {\n\n\t\t\tshowChannel = false;\n\t\t\thtmlCode += renderBookingTableHeader(showChannel, showStatus, showUnit, showAgent, showInv);\n\t\t\t\n\t\t\t// Loop thru all bookings\n\t\t\tvar lines = 0;\n\t\t\tfor (var i=0; i<bookingArray.length; i++) {\t\n\t\t\t\tif (fldSort != bookingArray[i].source || lines>26) {\n\t\t\t\t\tfldSort = bookingArray[i].source;\n\t\t\t\t\t// Break every 26 lines \n\t\t\t\t\tlines += 2;\n\t\t\t\t\tif (lines>26) {\n\t\t\t\t\t\tlines = 0;\n\t\t\t\t\t\thtmlCode += '</table>';\n\t\t\t\t\t\thtmlCode += reportFooter();\t\t\t\n\t\t\t\t\t\thtmlCode += reportPageBreak();\n\t\t\t\t\t\thtmlCode += topHeadline(topHeadtxt);\n\t\t\t\t\t\thtmlCode += reportHeadline(txtSort)\t\n\t\t\t\t\t\thtmlCode += renderBookingTableHeader(showChannel, showStatus, showUnit, showAgent, showInv);\n\t\t\t\t\t}\n\t\t\t\t\tvar htmlHead = '<tr><th colspan=\"20\" style=\"background-color:#EEEEEE; color:#000000; border:1px solid #AAAAAA; text-align:left; height:38px; padding-left:6px; white-space: nowrap;\">#FIELD#</th></tr>'\n\t\t\t\t\tvar txtStatus = '<div style=\"background-color:#999999; color:#FFFFFF; width:250px; display: block; text-align:center; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">UNKNOWN</div>'\n\t\t\t\t\tswitch(fldSort) {\n\t\t\t\t\t\tcase '':\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"background-color:#999999; color:#FFFFFF; width:250px; display: block; text-align:center; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">UNKNOWN</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'T':\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"background-color:#4CACCD; color:#FFFFFF; width:250px; display: block; text-align:center; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">THAIHOME</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'B':\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"background-color:#003580; color:#FFFFFF; width:250px; display: block; text-align:center; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">BOOKING.COM</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'A':\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"background-color:#FF8084; color:#FFFFFF; width:250px; display: block; text-align:center; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">AIRBNB</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'E':\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"background-color:#00355F; color:#FFCB00; width:250px; display: block; text-align:center; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">EXPEDIA</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'G':\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"background-color:#C59064; color:#FFFFFF; width:250px; display: block; text-align:center; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">AGENTS</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\thtmlCode += htmlHead.replace('#FIELD#', txtStatus);\n\t\t\t\t}\n\t\t\t\tif (fldSort != '') {\n\t\t\t\t\thtmlCode += renderBookings(i, includeBookings, sortBookings, showChannel, showStatus, showUnit, showAgent, showInv, bookingArray, receiptArray, invoiceArray);\n\t\t\t\t\tlines += 1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\n\t\t// PROPERTY\n\t\tif (sortBookings=='PROPERTY') {\n\n\t\t\t// Make the table header\n\t\t\tvar lines = 0;\n\t\t\tshowUnit = false;\n\t\t\thtmlCode += renderBookingTableHeader(showChannel, showStatus, showUnit, showAgent, showInv);\n\t\t\t\n\t\t\t// Loop thru all bookings\n\t\t\tvar lines = 0;\n\t\t\tfor (var i=0; i<bookingArray.length; i++) {\t\n\n\t\t\t\tif (fldSort != bookingArray[i].property || lines>24) {\n\t\t\t\t\tfldSort = bookingArray[i].property;\n\t\t\t\t\t// Break every 25 lines \n\t\t\t\t\tlines += 2;\n\t\t\t\t\tif (lines>24) {\n\t\t\t\t\t\tlines = 0;\n\t\t\t\t\t\thtmlCode += '</table>';\n\t\t\t\t\t\thtmlCode += reportFooter();\t\t\t\n\t\t\t\t\t\thtmlCode += reportPageBreak();\n\t\t\t\t\t\thtmlCode += topHeadline(topHeadtxt);\n\t\t\t\t\t\thtmlCode += reportHeadline(txtSort)\t\n\t\t\t\t\t\thtmlCode += renderBookingTableHeader(showChannel, showStatus, showUnit, showAgent, showInv);\n\t\t\t\t\t}\n\t\t\t\t\tvar htmlHead = '<tr><th colspan=\"20\" style=\"background-color:#EEEEEE; color:#000000; border:1px solid #AAAAAA; text-align:left; height:38px; padding-left:6px; white-space: nowrap;\">#FIELD#</th></tr>'\n\t\t\t\t\tvar txtStatus = '<div style=\"padding-left:10px; background-color:#FFFFFF; color:#333333; width:250px; display: block; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">Property: &nbsp; ' + bookingArray[i].property + '</div>'\n\t\t\t\t\thtmlCode += htmlHead.replace('#FIELD#', txtStatus);\n\t\t\t\t}\n\t\t\t\tif (fldSort != '') {\n\t\t\t\t\thtmlCode += renderBookings(i, includeBookings, sortBookings, showChannel, showStatus, showUnit, showAgent, showInv, bookingArray, receiptArray, invoiceArray);\n\t\t\t\t\tlines += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\t// STATUS\n\t\tif (sortBookings=='STATUS') {\n\n\t\t\t// Make the table header\n\t\t\tvar lines = 0;\n\t\t\tshowStatus = false;\n\t\t\thtmlCode += renderBookingTableHeader(showChannel, showStatus, showUnit, showAgent, showInv);\n\t\t\tfldSort = 99;\n\t\t\t\n\t\t\t// Loop thru all bookings\n\t\t\tvar lines = 0;\n\t\t\tfor (var i=0; i<bookingArray.length; i++) {\t\n\t\t\t\tif (fldSort != bookingArray[i].status || lines>24) {\n\t\t\t\t\tfldSort = bookingArray[i].status;\n\t\t\t\t\t// Break every 25 lines \n\t\t\t\t\tlines += 2;\n\t\t\t\t\tif (lines>24) {\n\t\t\t\t\t\tlines = 0;\n\t\t\t\t\t\thtmlCode += '</table>';\n\t\t\t\t\t\thtmlCode += reportFooter();\t\t\t\n\t\t\t\t\t\thtmlCode += reportPageBreak();\n\t\t\t\t\t\thtmlCode += topHeadline(topHeadtxt);\n\t\t\t\t\t\thtmlCode += reportHeadline(txtSort)\t\n\t\t\t\t\t\thtmlCode += renderBookingTableHeader(showChannel, showStatus, showUnit, showAgent, showInv);\n\t\t\t\t\t}\n\t\t\t\t\tvar htmlHead = '<tr><th colspan=\"20\" style=\"background-color:#EEEEEE; color:#000000; border:1px solid #AAAAAA; text-align:left; height:40px; padding-left:6px; white-space: nowrap;\">#FIELD#</th></tr>'\n\t\t\t\t\tvar txtStatus = '<div style=\"background-color:#999999; color:#FFFFFF; width:250px; display: block; text-align:center; font-weight:bold; font-size:18px; font-family:Roboto, Arial;\">UNKNOWN</div>'\n\t\t\t\t\tswitch(fldSort) {\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"padding-left:12px; font-family:Roboto, Arial; font-size:18px; background-color:#FFE5E5;border: 1px solid #804040; color:#804040; width:200px; display: block;\">NEW BOOKINGS</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"padding-left:12px; font-family:Roboto, Arial; font-size:18px; background-color:#FFE5E5;border: 1px solid #804040; color:#804040; width:200px; display: block;\">PENDING</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"padding-left:12px; font-family:Roboto, Arial; font-size:18px; background-color:#DDFFDD;border: 1px solid #007000; color:#007000; width:200px; display: block;\">BOOKED</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"padding-left:12px; font-family:Roboto, Arial; font-size:18px; background-color:#DDFFDD;border: 1px solid #007000; color:#007000; width:200px; display: block;\">CHECKIN</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 4:\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"padding-left:12px; font-family:Roboto, Arial; font-size:18px; background-color:#E0E0E0;border: 1px solid #808080; color:#404040; width:200px; display: block;\">CHECKOUT</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 5:\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"padding-left:12px; font-family:Roboto, Arial; font-size:18px; background-color:#E0E0E0;border: 1px solid #808080; color:#404040; width:200px; display: block;\">DONE</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 6:\n\t\t\t\t\t\t\tvar txtStatus = '<div style=\"padding-left:12px; font-family:Roboto, Arial; font-size:18px; background-color:#E0E0E0;border: 1px solid #808080; color:#404040; width:200px; display: block;\">CANCEL</div>'\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\thtmlCode += htmlHead.replace('#FIELD#', txtStatus);\n\t\t\t\t}\n\t\t\t\tif (fldSort != 99) {\n\t\t\t\t\thtmlCode += renderBookings(i, includeBookings, sortBookings, showChannel, showStatus, showUnit, showAgent, showInv, bookingArray, receiptArray, invoiceArray);\n\t\t\t\t\tlines += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\t\n\n\t// Render footer\n\thtmlCode += '</table>';\n\thtmlCode += reportFooter();\t\t\t\n\t\n\treturn htmlCode;\n}", "_recordInitialPageLoad() {\n\t\t\t// Not all browsers (e.g., mobile) support this, but most do.\n\t\t\tif (typeof window.performance === \"undefined\") return;\n\n\t\t\t// Record the time between when the browser was ready to fetch the\n\t\t\t// document, and when the document.readyState was changed to \"complete\".\n\t\t\t// i.e., the time it took to load the page.\n\t\t\tconst startTime = window.performance.timing.fetchStart;\n\t\t\tconst endTime = window.performance.timing.domComplete > 0 ? window.performance.timing.domComplete : new Date().getTime();\n\t\t\tconst routeName = getRouteName(this.state.routes);\n\t\t\trecordSpan({\n\t\t\t\tname: `load page ${routeName}`,\n\t\t\t\tstart: startTime,\n\t\t\t\tend: endTime,\n\t\t\t\tmetadata: {\n\t\t\t\t\tlocation: window.location.href,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Update the debug display on the page with the time.\n\t\t\tthis._updateDebugTimer(startTime, endTime);\n\t\t}", "function trapReportCreating(reportType){\n\t\t\n\t\tvar start_date = $(\"#event_start_date\").val();\n\t\tvar end_date = $(\"#event_end_date\").val();\n\t\tvar option=$(\"input[name='option']:checked\").val();\n\t\tvar agentId=$(\"#agentId\").val();\n\t\tvar eventType=$(\"#eventType\").val();\n\t\tvar M_obj=$(\"#M_obj\").val();\n\t\tvar M_name=$(\"#M_name\").val();\n\t\tvar camponent_id=$(\"#camponent_id\").val();\n\t\tspinStart($spinLoading,$spinMainLoading);\n\t\tvar cdate= new Date();\n\t\tvar str1 = $(\"#event_start_date\").val();\n\t\tvar str2 = $(\"#event_end_date\").val();\n\t\tvar str3 = $(\"#event_start_time\").val();\n\t\tvar str4 = $(\"#event_end_time\").val();\n\n\t\tstr1=str1.split(\"/\");\n\t\tstr2=str2.split(\"/\");\n\t\tstr3=str3.split(\":\");\n\t\tstr4=str4.split(\":\");\n\t\tvar date1 = new Date(str1[2],parseInt(str1[1],10)-1, str1[0],str3[0],str3[1]); \n\t\tvar date2 = new Date(str2[2],parseInt(str2[1],10)-1, str2[0],str4[0],str4[1]);\n\t\tif(date2 < date1)\n\t\t{\n\t\t\t $().toastmessage('showWarningToast', \"End Date can't be greater than Start Date\");\n\t\t\treturn false; \n\t\t}\n\t\telse if(cdate<date1 || cdate<date2)\n\t\t\t{\n\t\t\t \t$().toastmessage('showWarningToast', \"Dates can't be greater than current Date\");\n\t\t\t\treturn false; \n\t\t\t}\n\t\telse{\n\t\t\t$.ajax({\n\t\t\t\ttype:\"post\",\n\t\t\t\turl:\"trap_report_creating.py?option=\"+option+\"&serevity1=\"+serevity_value[1]+\"&serevity2=\"+serevity_value[2]+\"&serevity3=\"+serevity_value[3]+\"&serevity4=\"+serevity_value[4]+\"&serevity5=\"+serevity_value[5]+\"&agentId=\"+agentId+\"&eventType=\"+eventType+\"&M_obj=\"+M_obj+\"&M_name=\"+M_name+\"&camponent_id=\"+camponent_id+\"&report_type=\"+reportType+\"&start_date=\"+start_date+\"&end_date=\"+end_date+\"&start_time=\"+$(\"#event_start_time\").val()+\"&end_time=\"+$(\"#event_end_time\").val(),\n\t\t\t\tcache:false,\n\t\t\t\tsuccess:function(result){\n\t\t\t\t\tif (result.success==1 || result.success==\"1\")\n\t\t\t\t\t{\n\t\t\t\t\t\t$().toastmessage('showWarningToast',result.error_msg);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$().toastmessage('showSuccessToast', 'Report Generated Successfully');\n\t\t\t\t\t\twindow.location = \"download/\"+result.file_name;\n\t\t\t\t\t\tsetTimeout(\"$('#alarm_info_form').submit()\",1250);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\terror:function(req,status,err){}\n\t\t\t});\n\t\t}\t\t\t\n\t\tspinStop($spinLoading,$spinMainLoading);\n}", "function generateReport(options, successCallback) {\n Database.getFullPlan(options.plan, function success(plan) {\n // Initialise data objects\n var resultsMatrix = {};\n var calc = {total: 0, pass: 0, fail: 0, pending: 0};\n Database.getAllWhere(\"results\", \"plan\", options.plan, function(results) {\n // Organise results so they can be accessed by page and criterion ID\n results.forEach(function(result) {\n resultsMatrix[result.page] = resultsMatrix[result.page] || {};\n resultsMatrix[result.page][result.criterion] = result;\n });\n // Generate the report and pass it back as a string\n successCallback(\"<h1>Web Accessibility Report (\" + plan.details.name + \")</h1>\" +\n \"<h4>Generated: \" + Date() + \"</h4>\" +\n \"<hr>\" +\n // Go through each pages group\n plan.pages.map(function(pages_group) {\n return \"<h2>Web page group: \" + pages_group.name + \"</h2>\" +\n \"<ul>\" +\n (pages_group.items.length ?\n // List all pages in this group\n pages_group.items.map(function(page) {\n return \"<li>\" + page.title + \" (\" + page.url + \")</li>\";\n }).join(\"\") +\n \"</ul>\" +\n // Go through each criteria group\n plan.criteria.map(function(criteria_group) {\n return \"<h3>Criteria set: \" + criteria_group.name + \"</h3>\" +\n \"<ul>\" +\n (criteria_group.items.length ?\n // Go through each criterion in this group\n criteria_group.items.map(function(criterion) {\n return \"<li>\" +\n // Include criterion details (where they exist and are requested in the options)\n \"<h4>\" + criterion.name + \"</h4>\" +\n \"<p>\" + criterion.description.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\\n/g, \"<br>\") + \"</p>\" +\n (options.criteria_details ?\n \"<h5>Why is it important?</h5>\" +\n \"<p>\" + criterion.reasoning.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\\n/g, \"<br>\") + \"</p>\" +\n \"<h5>Guidance</h5>\" +\n \"<p>\" + criterion.guidance.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\\n/g, \"<br>\") + \"</p>\" +\n \"<h5>Documentation</h5>\" +\n \"<p>\" + criterion.links.map(function(link) { return \"<a href='\" + link + \"' target='_blank'>\" + link + \"</a>\"; }).join(\"<br>\") + \"</p>\"\n : \"\") +\n \"<h4>Results</h4>\" +\n // Work out result totals for all pages in this group\n pages_group.items.map(function(page, index) {\n if (index == 0) calc.total = calc.pass = calc.fail = calc.pending = 0;\n var result = (resultsMatrix[page.id] && resultsMatrix[page.id][criterion.id]) || {status: \"pending\"};\n if (options.statuses.indexOf(result.status) != -1) {\n calc.total++;\n calc[result.status]++;\n }\n return \"\";\n }).join(\"\") +\n // Calculate percentages from result totals (for status requested in the options)\n options.statuses.map(function(status) {\n return status.charAt(0).toUpperCase() + status.slice(1) + \": \" + calc[status] + \"/\" + calc.total + \" (\" + (calc.total > 0 ? (Math.round(calc[status] / calc.total * 100) + \"%\") : \"n/a\") + \")<br>\";\n }).join(\"\") +\n (options.level == \"individual\" ?\n // Include information about each individual test on each page (if requested in the options)\n \"<br><ul>\" +\n pages_group.items.map(function(page) {\n var result = (resultsMatrix[page.id] && resultsMatrix[page.id][criterion.id]) || {status: \"pending\"};\n // Only include this test result is it has one of the statuses requested\n return (options.statuses.indexOf(result.status) != -1) ?\n \"<li>\" +\n page.title + \" (\" + page.url + \") - \" + result.status +\n (options.results_annotations && result.annotation ?\n \"<p>\" + result.annotation.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\\n/g, \"<br>\") + \"</p>\"\n : \"\") +\n (options.results_images && result.image ?\n \"<p><img src='\" + result.image + \"'></p>\"\n : \"\") +\n \"</li>\"\n : \"\";\n }).join(\"\") +\n \"</ul>\"\n : \"\") +\n \"</li>\";\n }).join(\"\")\n : \"<li><em>No criteria</em></li>\") +\n \"</ul>\" +\n \"\";\n }).join(\"\") +\n (options.tables ?\n // Create a table overview of tests on all the pages in this group\n \"<table border='1' cellspacing='2' cellpadding='2'>\" +\n \"<tr>\" +\n \"<th></th>\" +\n // List all pages on the x-axis\n pages_group.items.map(function(page) {\n return \"<th>\" + page.title + \"</th>\";\n }).join(\"\") +\n \"</tr>\" +\n plan.criteria.map(function(criteria_group) {\n // Include criteria group names\n return \"<tr><td><strong>\" + criteria_group.name + \"</strong></td></tr>\" +\n (criteria_group.items.length ?\n // Go through each criterion in the group\n criteria_group.items.map(function(criterion) {\n return \"<tr>\" +\n \"<td>\" + criterion.name + \"</td>\" +\n pages_group.items.map(function(page) {\n var result = (resultsMatrix[page.id] && resultsMatrix[page.id][criterion.id]) || {status: \"pending\"};\n return \"<td>\" +\n (options.statuses.indexOf(result.status) != -1 ?\n // Include tick icon for passing results\n (result.status == \"pass\" ? \"<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjEwMPRyoQAAAMZJREFUOE/FjjEKwkAQRWezdiFJZ29toWfwEoJ6Bw/hRYR4Jru0whYO2AU06B+Z1Y1F1gTEB0N2d/77hP5CwYWV0Ws/REw4KWV6l+ScW8OmJKa7DEr2uoqTcdaSMTfLdqPrbiCKfPiQ17omco2T0FivLczZWAgtGb/+lqumEnmHhcNM9flJVBZU9oFXyVeygIItlk0QdHib4RuXPRCWCNWBcA3O3bIHJQuEL4Ho5ZVG4iA8h3QaJHsgTSAfB8melNORHn8N0QMwhI66An4NAgAAAABJRU5ErkJggg=='> \" : \"\") +\n // Include cross icon for failing results\n (result.status == \"fail\" ? \"<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjEwMPRyoQAAAKpJREFUOE+lU0EKgCAQ3CD7pPSK+kDQrd7qJehgkO2sJFHqoR0YCHdmWlclIBwHubYdXNctm7WNLGaAGjTQwiMI3kcz0ckMzph1n+dPCNZQEw20CGEvzGMy30TINKUQfD/MNxEyErf0LkSyYev7BsyYI9lLVYExizBfkx/UWiyTtc8tCl5DKhPmzJAFckyllkGu1Y5ZF6DagmqI6mNUXyT1VVY/JuD/cya6APHAd2wGj7MPAAAAAElFTkSuQmCC'> \" : \"\") +\n result.status.charAt(0).toUpperCase() + result.status.slice(1)\n : \"\") +\n \"</td>\";\n }).join(\"\") +\n \"</tr>\";\n }).join(\"\")\n : \"<tr><td colspan='\" + (pages_group.items.length + 1) + \"'><em>No criteria</em></td></tr>\")\n }).join(\"\") +\n \"</table>\"\n : \"\")\n : \"<li><em>No pages</em></li></ul>\");\n }).join(\"\") +\n \"\" +\n \"\");\n });\n });\n}", "init() {\n this._super(...arguments);\n this._createPages();\n }", "constructor() {\n this.pageId = '#reportlist-page';\n this.pageSelector = Selector(this.pageId);\n }", "async function step19(msgText, report) {\n report[0].response = byeReply;\n\n report = fillReport(\"observation\", msgText, report);\n return report;\n}", "async store ({ request, response }) {\n try {\n const { title, start_date, end_date, location, price } = request.all() // es-lint-ignore\n const page = await Page.create({\n title,\n start_date,\n end_date,\n location,\n price\n })\n\n return response.status(201).json({ page })\n } catch (e) {\n console.log(e.message)\n }\n }", "function timeLoop(){\n setTimeout(function () {\n\n /**\n * I added this alert to avoid the awkwardness of the \"wait\" feeling.\n * You will get a better understanding of this when you will reach the TIME LIMIT section.\n */\n alert(\"An Executive PDF will be generated.\");\n\n /**\n * By going to the 'inspect elements' category of the Reports side of the website, I believe that the\n * main part of the entire page, that contains all the information, the graphs and the further details\n * all of it comes under the ID=content. Therefore I have already predefined it here with my program to make\n * it a little easier.\n *\n * This part of the code is essentially taking all the information that is in the (content) ID- tag and\n * making that into a a PDF.\n *\n * In order for this to work for the execution of the ISORA program, you might have to change the line of\n * code to:\n * ...drawDOM($(\"#content\")).then(...){...} #73\n *\n * Since I am not able to run the code for the ISORA code myself, I cant help you with this check, but this is\n * a small thing, so I am certain that a line of code would be fine to change.\n */\n\n kendo.drawing.drawDOM(\"#content\").then(function(group) {\n kendo.drawing.pdf.saveAs(group, \"Converted PDF.pdf\");\n });\n\n /**\n * This is the TIME LIMIT.\n *\n * This is probably the most IMPORTANT number in the program as based on this only would you be able to\n * get the entire PDF, which includes the \"opened up\" ORG_UNIT_QUESTIONS.\n *\n * So the problem with the setTimeout() is that it would go about being executed, that is the first parameter,\n * only after the set number of time has completed. According to the documentation, it says that the second\n * parameter holds the number of milliseconds, but I am fairly certain that its not that. I am not sure what the\n * timer is based on though.\n *\n * So yeah, make sure that this number is big enough to handle the \"scrolling down\" of the ORG_UNIT_QUESTION\n * categories to give a detailed view of of each category, otherwise not all the details will be viewed on the\n * PDF or maybe not a single extra detail will be viewed, provided that the number becomes too small.\n *\n * So in order to avoid the awkwardness of the \"wait\" feeling, I added an alert at the beginning of this\n * function to make it appear that \"there is some background work occurring\".\n *\n * The mathematical approach, at least I think could be like a start, could possibly be:\n * Total # of Q. from all categories = x\n * Transition effect of an individual category = k (as it would most likely remain constant)\n *\n * Total TIME LIMIT = k*x*1000\n *\n * Also, about 30000 is roughly 30 seconds, so in case the math is completely flawed then you could\n * look at it more objectively as per each category and come up with a common number I guess...\n *\n */\n }, 900)\n}", "function generateTeamReport() {\n var dialog1 = {\n 'title': 'Response Form',\n 'customTitle': false,\n 'subText': 'Would you like to generate a team report?'\n };\n \n var dialog2 = {\n 'title': 'Enter Time Tracking Response Link',\n 'subText': 'Please enter the response link to generate team report:'\n };\n \n reportDialog(dialog1, createTeamReport, dialog2);\n}", "async function createInitialReports() {\n try {\n console.log('Trying to create reports...');\n\n const reportOne = await createReport({\n title: 'ET spotted outside of Area 51',\n location: 'Roswell, NM',\n description: 'I saw what can only be described as a very slender, very tall humanoid walking behind the fences at...',\n password: '51isTheKey'\n });\n\n const reportTwo = await createReport({\n title: 'Fairy lights in my backyard',\n location: 'Utica, NY',\n description: 'I saw floating lights in my backyard... on inspection they weren\\'t fireflies...',\n password: 'iLoveF4ri3s'\n });\n\n const reportThree = await createReport({\n title: 'Corner of metal object sticking up out of the ground in the woods...',\n location: 'Haven, Maine',\n description: 'Late last night and the night before\\n Tommyknockers, Tommyknockers\\n knocking at the door',\n password: 'kingwasright'\n })\n\n console.log('Success creating reports!');\n\n return [reportOne, reportTwo, reportThree]\n } catch (error) {\n console.error('Error while creating reports!');\n throw (error);\n }\n}", "function createIndexPage() {\n current_page = \"index\";\n \n clearInterval(page_timer);\n page_timer = null;\n \n \n /* Empty the old content */\n $(\"#main_cont\").empty();\n $(\".page-header\").empty();\n \n \n /* Add the new content */\n $(\".page-header\").append(\"Overview\");\n $(\"#main_cont\").append(\"<div class=\\\"row\\\"><img id=\\\"ov_img\\\" src=\\\"img/overview.jpg\\\"\" +\n \"alt=\\\"overview image\\\" class=\\\"img-rounded \" +\n \"center-block\\\"></div>\" +\n '<div id=\"index-text\" class=\"row\"><p> This page is the user frontend of the Web' +\n \" app for the Internet of Things project.\" +\n \"The system administrator can use this page \" +\n \"to manage remotely the vending machines and \" +\n \"to plan technical staff routes. In particular:\" + \n \"<ul> <li>The \\\"<strong>City Map</strong>\\\" page \" +\n \"shows machines locations on the city center map;\" +\n \"</li> <li>The \\\"<strong>Manage</strong>\\\" \" +\n \"page is used to monitor the actual machines \" +\n \"status and to edit the resource values;</li>\" +\n \"</ul></p></div>\");\n}", "function generate_all_reports()\n{\n report_ToAnswer_emails();\n report_FollowUp_emails();\n report_Work_FollowUp_emails();\n}", "function createPage(name, div, button, links, butRef) {\r\n\t// Create page object\r\n\tconst obj = {};\r\n\t// Assign the variables to the page object\r\n\tobj.name = name;\r\n\tobj.div = div;\r\n\tobj.button = button;\r\n\tobj.videoLinks = [];\r\n\tobj.id = \"#\"+name;\r\n\tobj.vidLinks = links;\r\n\tobj.buttonName = butRef;\r\n\t// Return the page object\r\n\treturn obj;\r\n}", "static get reports() {}", "static async addReport (report) {\n const db = await Mongo.instance().getDb();\n\n if (typeof report !== 'object') {\n throw new Error('Bad Parameter');\n }\n\n const isValid = await Report.isReport(report);\n\n if (!isValid.valid) {\n return new Error(' format of the report is not valid');\n }\n\n const addNewReport = await db.collection(collections.REPORT_COLL).insertOne({\n ...report,\n createdAt: new Date(),\n updatedAt: new Date()\n });\n\n if (!addNewReport) {\n return new Error('Can not create this new report');\n }\n return addNewReport;\n }", "_buildPageData() {\n const parsedFilePath = path.parse(this.filePath);\n\n const { data, content } = matter.read(`${this.filePath}`);\n\n const pageData = {\n ...data,\n content,\n };\n\n pageData.path = `/${parsedFilePath.name}.html`;\n\n return pageData;\n }", "function newPage(){\n userInProgress = 1;\n pages = 1\n savePage('pages',pages);\n savePage('options',JSON.stringify(options));\n}", "function getReport(){\n\n }", "function _class(postId){var _this=this;_classCallCheck(this,_class);// List of all times running on the page.\nthis.timers=[];// Firebase SDK.\nthis.database=firebase.database();this.storage=firebase.storage();this.auth=firebase.auth();$(document).ready(function(){_this.postPage=$('#page-post');// Pointers to DOM elements.\n_this.postElement=$(friendlyPix.Post.createPostHtml(postId));friendlyPix.MaterialUtils.upgradeTextFields(_this.postElement);_this.toast=$('.mdl-js-snackbar');_this.theatre=$('.fp-theatre')})}", "function createPage() {\n var pageInstance = new Page();\n\n function pageFn(/* args */) {\n return page.apply(pageInstance, arguments);\n }\n\n // Copy all of the things over. In 2.0 maybe we use setPrototypeOf\n pageFn.callbacks = pageInstance.callbacks;\n pageFn.exits = pageInstance.exits;\n pageFn.base = pageInstance.base.bind(pageInstance);\n pageFn.strict = pageInstance.strict.bind(pageInstance);\n pageFn.start = pageInstance.start.bind(pageInstance);\n pageFn.stop = pageInstance.stop.bind(pageInstance);\n pageFn.show = pageInstance.show.bind(pageInstance);\n pageFn.back = pageInstance.back.bind(pageInstance);\n pageFn.redirect = pageInstance.redirect.bind(pageInstance);\n pageFn.replace = pageInstance.replace.bind(pageInstance);\n pageFn.dispatch = pageInstance.dispatch.bind(pageInstance);\n pageFn.exit = pageInstance.exit.bind(pageInstance);\n pageFn.configure = pageInstance.configure.bind(pageInstance);\n pageFn.sameOrigin = pageInstance.sameOrigin.bind(pageInstance);\n pageFn.clickHandler = pageInstance.clickHandler.bind(pageInstance);\n\n pageFn.create = createPage;\n\n Object.defineProperty(pageFn, 'len', {\n get: function(){\n return pageInstance.len;\n },\n set: function(val) {\n pageInstance.len = val;\n }\n });\n\n Object.defineProperty(pageFn, 'current', {\n get: function(){\n return pageInstance.current;\n },\n set: function(val) {\n pageInstance.current = val;\n }\n });\n\n // In 2.0 these can be named exports\n pageFn.Context = Context;\n pageFn.Route = Route;\n\n return pageFn;\n }", "function pageResponse() {\n var Promise = require('promise');\n var self = this;\n this._id = \"\";\n this.title = \"\";\n this.tags = [];\n this.pollsCount = 0;\n\n this.fromDBObject = function (inputObject) {\n return new Promise(function(resolve, reject){\n self.title = inputObject.title;\n self._id = inputObject._id;\n self.tags = inputObject.tags;\n self.pollsCount = inputObject.pollsCount;\n resolve(self);\n });\n };\n\n}", "async start() {\n // Clear out existing screenshots (one by one)\n try {\n let files = fs.readdirSync(SMASHTEST_SS_DIR);\n for(let file of files) {\n let match = file.match(/[^\\_]+/);\n let hash = match ? match[0] : null;\n // If we're doing --skip-passed, delete a screenshot only if the branch didn't pass last time\n if(!this.runner.skipPassed || !this.tree.branches.find(branch => branch.hash == hash && branch.passedLastTime)) {\n fs.unlinkSync(path.join(SMASHTEST_SS_DIR, file));\n }\n }\n }\n catch(e) {\n if(!e.message.includes(`no such file or directory, scandir`)) { // not finding the dir is ok\n throw e;\n }\n }\n\n // Load template\n let buffers = await readFiles([path.join(path.dirname(require.main.filename), `report-template.html`)] , {encoding: 'utf8'});\n if(!buffers || !buffers[0]) {\n utils.error(`report-template.html not found`);\n }\n this.reportTemplate = buffers[0];\n\n // Start server\n if(this.isReportServer) {\n await this.startServer();\n }\n\n // Kick off write functions\n await this.writeFull();\n if(this.isReportServer) {\n await this.writeSnapshot();\n }\n }", "function createPage () {\n if (config.wgCanonicalNamespace + ':' + config.wgTitle !== 'Special:DiscussionsActivity') {\n return;\n }\n document.title = i18n('document_title_new').escape() + ' |' + document.title.split('|').slice(1).join('|');\n document.getElementById('PageHeader').getElementsByTagName('h1')[0].textContent = i18n('document_title_new').plain();\n container = document.getElementById('mw-content-text');\n container.innerHTML = '<span class=\"rda-loading\">' + i18n('loading_discussions').escape() + '</span>';\n }", "function singleClickGenerateAllReports(){\n\n\n\t //PENDING --> TOTAL CALCULATED ROUND OFFFFF\n\t console.log('PENDING API --> TOTAL CALCULATED ROUND OFFFFF')\n\t \n\n\t\trunReportAnimation(95); //of Step 11 which completed the data processing\n\n\n\t\t//Get staff info.\n\t\tvar loggedInStaffInfo = window.localStorage.loggedInStaffData ? JSON.parse(window.localStorage.loggedInStaffData) : {};\n\t\t\n\t\tif(jQuery.isEmptyObject(loggedInStaffInfo)){\n\t\t\tloggedInStaffInfo.name = 'Staff';\n\t\t\tloggedInStaffInfo.code = '0000000000';\n\t\t}\t\n\n\n\t\tvar reportInfo_branch = window.localStorage.accelerate_licence_branch_name ? window.localStorage.accelerate_licence_branch_name : '';\n\t\t\t\n\t\tif(reportInfo_branch == ''){\n\t\t\tshowToast('System Error: Branch name not found. Please contact Accelerate Support.', '#e74c3c');\n\t\t\treturn '';\n\t\t}\n\n\t\tvar temp_address_modified = (window.localStorage.accelerate_licence_branch_name ? window.localStorage.accelerate_licence_branch_name : '') + ' - ' + (window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name : '');\n\t\tvar data_custom_footer_address = window.localStorage.bill_custom_footer_address ? window.localStorage.bill_custom_footer_address : '';\n\n\t\tvar reportInfo_admin = loggedInStaffInfo.name;\n\t\tvar reportInfo_time = moment().format('h:mm a, DD-MM-YYYY');\n\t\tvar reportInfo_address = data_custom_footer_address != '' ? data_custom_footer_address : temp_address_modified;\n\n\n\t\t//Reset Token Number and KOT Number (if preference set)\n\t\tresetBillingCounters();\n\n\t\tgenerateReportContentDownload();\n\n\t\tfunction generateReportContentDownload(){\n\n\t\t\t//To display weekly graph or not\n\t\t\tvar hasWeeklyGraphAttached = false;\n\t\t\tif(window.localStorage.graphImageDataWeekly && window.localStorage.graphImageDataWeekly != ''){\n\t\t\t\thasWeeklyGraphAttached = true;\n\t\t\t}\n\n\t\t\tvar graphRenderSectionContent = '';\n\t\t\tvar fancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY - dddd');\n\n\t\t\tvar reportInfo_title = 'Sales Report of <b>'+fancy_from_date+'</b>';\n\t\t\tvar temp_report_title = 'Sales Report of '+fancy_from_date;\n\t\t\tif(fromDate != toDate){\n\t\t\t\tfancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\t\t\t\tvar fancy_to_date = moment(toDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\n\t\t\t\treportInfo_title = 'Sales Report from <b>'+fancy_from_date+'</b> to <b>'+fancy_to_date+'</b>';\n\t\t\t\ttemp_report_title = 'Sales Report from '+fancy_from_date+' to '+fancy_to_date;\n\t\t\t}\n\t\t else{ //Render graph only if report is for a day\n\n\t\t if(hasWeeklyGraphAttached){\n\n\t\t \tvar temp_image_name = reportInfo_branch+'_'+fromDate;\n\t\t \ttemp_image_name = temp_image_name.replace(/\\s/g,'');\n\n\t\t graphRenderSectionContent = ''+\n\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t '<div class=\"summaryTableSection\">'+\n\t\t '<div class=\"tableQuickHeader\">'+\n\t\t '<h1 class=\"tableQuickHeaderText\">WEEKLY SALES TREND</h1>'+\n\t\t '</div>'+\n\t\t '<div class=\"weeklyGraph\">'+\n\t\t '<img src=\"'+window.localStorage.graphImageDataWeekly+'\" style=\"max-width: 90%\">'+\n\t\t '</div>'+\n\t\t '</div>'+\n\t\t '</div>';\n\t\t }\n\t\t }\n\n\t\t var fancy_report_title_name = reportInfo_branch+' - '+temp_report_title;\n\n\t\t //Quick Summary Content\n\t\t var quickSummaryRendererContent = '';\n\n\t\t var a = 0;\n\t\t while(reportInfoExtras[a]){\n\t\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+reportInfoExtras[a].name+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(reportInfoExtras[a].value).toFixed(2)+'</td></tr>';\n\t\t a++;\n\t\t }\n\n\n\t\t var b = 1; //first one contains total paid\n\t\t while(completeReportInfo[b]){\n\t\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+completeReportInfo[b].name+'</td><td class=\"tableQuickAmount\">'+(completeReportInfo[b].type == 'NEGATIVE' && completeReportInfo[b].value != 0 ? '- ' : '')+'<span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[b].value).toFixed(2)+'</td></tr>';\n\t\t b++;\n\t\t }\n\n\n\t\t //Sales by Billing Modes Content\n\t\t var salesByBillingModeRenderContent = '';\n\t\t var c = 0;\n\t\t var billSharePercentage = 0;\n\t\t while(detailedListByBillingMode[c]){\n\t\t billSharePercentage = parseFloat((100*detailedListByBillingMode[c].value)/completeReportInfo[0].value).toFixed(0);\n\t\t salesByBillingModeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByBillingMode[c].name+' '+(billSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+billSharePercentage+'%)</span>' : '')+(detailedListByBillingMode[c].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByBillingMode[c].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByBillingMode[c].value).toFixed(0)+'</td></tr>';\n\t\t c++;\n\t\t }\n\n\t\t\t//To display bills graph or not\n\t\t\tvar hasBillsGraphAttached = false;\n\t\t\tif(window.localStorage.graphImageDataBills && window.localStorage.graphImageDataBills != '' && window.localStorage.graphImageDataBills != 'data:,'){\n\t\t\t\thasBillsGraphAttached = true;\n\t\t\t}\n\n\t\t var salesByBillingModeRenderContentFinal = '';\n\t\t if(salesByBillingModeRenderContent != ''){\n\n\t\t \tif(hasBillsGraphAttached){\n\t\t\t\t salesByBillingModeRenderContentFinal = ''+\n\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t \t'<div class=\"tableQuickHeader\">'+\n\t\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY BILLS</h1>'+\n\t\t\t\t \t'</div>'+\n\t\t\t\t \t'<div class=\"tableGraphRow\">'+\n\t\t\t\t\t\t '<div class=\"tableGraph_Graph\"> <img src=\"'+window.localStorage.graphImageDataBills+'\" width=\"200px\"> </div>'+\n\t\t\t\t\t\t '<div class=\"tableGraph_Table\">'+\t\n\t\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t\t salesByBillingModeRenderContent+\n\t\t\t\t\t '</table>'+\n\t\t\t\t\t '</div>'+\n\t\t\t\t\t '</div>'+\t\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t salesByBillingModeRenderContentFinal = ''+\n\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY BILLS</h1>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t salesByBillingModeRenderContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>';\t\t\t\t\n\t\t\t\t}\n\t\t }\n\n\n\t\t //Sales by Payment Types Content\n\t\t var salesByPaymentTypeRenderContent = '';\n\t\t var d = 0;\n\t\t var paymentSharePercentage = 0;\n\t\t while(detailedListByPaymentMode[d]){\n\t\t paymentSharePercentage = parseFloat((100*detailedListByPaymentMode[d].value)/completeReportInfo[0].value).toFixed(0);\n\t\t salesByPaymentTypeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByPaymentMode[d].name+' '+(paymentSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+paymentSharePercentage+'%)</span>' : '')+(detailedListByPaymentMode[d].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByPaymentMode[d].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByPaymentMode[d].value).toFixed(0)+'</td></tr>';\n\t\t d++;\n\t\t }\n\n\t\t\t//To display payment graph or not\n\t\t\tvar hasPaymentsGraphAttached = false;\n\t\t\tif(window.localStorage.graphImageDataPayments && window.localStorage.graphImageDataPayments != '' && window.localStorage.graphImageDataPayments != 'data:,'){\n\t\t\t\thasPaymentsGraphAttached = true;\n\t\t\t}\n\n\t\t var salesByPaymentTypeRenderContentFinal = '';\n\t\t if(salesByPaymentTypeRenderContent != ''){\n\n\t\t \tif(hasPaymentsGraphAttached){\n\t\t\t salesByPaymentTypeRenderContentFinal = ''+\n\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t \t'<div class=\"tableQuickHeader\">'+\n\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY PAYMENT</h1>'+\n\t\t\t \t'</div>'+\n\t\t\t \t'<div class=\"tableGraphRow\">'+\n\t\t\t\t\t '<div class=\"tableGraph_Graph\"> <img src=\"'+window.localStorage.graphImageDataPayments+'\" width=\"200px\"> </div>'+\n\t\t\t\t\t '<div class=\"tableGraph_Table\">'+\t\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t salesByPaymentTypeRenderContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>';\n\t\t\t }\n\t\t\t else{\n\t\t\t \tsalesByPaymentTypeRenderContentFinal = ''+\n\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY PAYMENT</h1>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t salesByPaymentTypeRenderContent+\n\t\t\t '</table>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>';\n\t\t\t }\n\t\t }\n\n\t\t var temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\t\t var cssData = '<head> <style type=\"text/css\"> body{font-family:sans-serif;margin:0}#logo{min-height:60px;width:100%}.mainHeader{background:url(https://accelerateengine.app/clients/'+temp_licenced_client+'/pattern.jpg) #c63931;width:100%;min-height:95px;padding:10px 0;border-bottom:2px solid #a8302b}.headerLeftBox{width:55%;display:inline-block;padding-left:25px}.headerRightBox{width:35%;float:right;display:inline-block;text-align:right;padding-right:25px}.headerAddress{margin:0 0 5px;font-size:14px;color:#e4a1a6}.headerBranch{margin:10px 0;font-weight:700;text-transform:uppercase;font-size:21px;padding:3px 8px;color:#c63931;display:inline-block;background:#FFF}.headerAdmin{margin:0 0 3px;font-size:16px;color:#FFF}.headerTimestamp{margin:0 0 5px;font-size:12px;color:#e4a1a6}.reportTitle{margin:15px 0;font-size:26px;font-weight:400;text-align:center;color:#3498db}.introFacts{background:0 0;width:100%;min-height:95px;padding:10px 0}.factsArea{display:block;padding:10px;text-align:center}.factsBox{margin-right: 5px; width:18%; display:inline-block;text-align:left;padding:20px 15px;border:2px solid #a8302b;border-radius:5px;color:#FFF;height:65px;background:#c63931}.factsBoxFigure{margin:0 0 8px;font-weight:700;font-size:32px}.factsBoxFigure .factsPrice{font-weight:400;font-size:40%;color:#e4a1a6;margin-left:2px}.factsBoxBrief{margin:0;font-size:16px;color:#F1C40F;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.summaryTableSectionHolder{width:100%}.summaryTableSection{padding:0 25px;margin-top:30px}.summaryTableSection table{border-collapse:collapse}.summaryTableSection td{border-bottom:1px solid #fdebed}.tableQuick{padding:10px}.tableQuickHeader{min-height:40px;background:#c63931;border-bottom:3px solid #a8302b;border-top-right-radius:15px;color:#FFF}.tableQuickHeaderText{margin:0 0 0 25px;font-size:18px;letter-spacing:2px;text-transform:uppercase;padding-top:10px;font-weight:700}.smallOrderCount{font-size:80%;margin-left:15px;color:#aba9a9;font-style:italic;}.tableQuickBrief{padding:10px;font-size:16px;color:#a71a14}.tableQuickAmount{padding:10px;font-size:18px;text-align:right;color:#a71a14}.tableQuickAmount .price{font-size:70%;margin-right:2px}.tableGraphRow{position:relative}.tableGraph_Graph{width:35%;display:block;text-align:center;float:right;position:absolute;top:20px;left:62%}.footerNote,.weeklyGraph{text-align:center;margin:0}.tableGraph_Table{padding:10px;width:55%;display:block;min-height:250px;}.weeklyGraph{padding:25px;border:1px solid #f2f2f2;border-top:none}.footerNote{font-size:12px;color:#595959}@media screen and (max-width:1000px){.headerLeftBox{display:none!important}.headerRightBox{padding-right:5px!important;width:90%!important}.reportTitle{font-size:18px!important}.tableQuick{padding:0 0 5px!important}.factsArea{padding:5px!important}.factsBox{width:90%!important;margin:0 0 5px!important}.smallOrderCount{margin:0!important;display:block!important}.summaryTableSection{padding:0 5px!important}}</style> </head>';\n\t\t \n\t\t var finalReport_downloadContent = cssData+\n\t\t\t '<body>'+\n\t\t\t '<div class=\"mainHeader\">'+\n\t\t\t '<div class=\"headerLeftBox\">'+\n\t\t\t '<div id=\"logo\">'+\n\t\t\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/email_logo.png\">'+\n\t\t\t '</div>'+\n\t\t\t '<p class=\"headerAddress\">'+reportInfo_address+'</p>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"headerRightBox\">'+\n\t\t\t '<h1 class=\"headerBranch\">'+reportInfo_branch+'</h1>'+\n\t\t\t '<p class=\"headerAdmin\">'+reportInfo_admin+'</p>'+\n\t\t\t '<p class=\"headerTimestamp\">'+reportInfo_time+'</p>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"introFacts\">'+\n\t\t\t '<h1 class=\"reportTitle\">'+reportInfo_title+'</h1>'+\n\t\t\t '<div class=\"factsArea\">'+\n\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(0)+' <span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Net Sales</p></div>'+ \n\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(netSalesWorth).toFixed(0)+'<span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Gross Sales</p></div>'+ \n\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+netGuestsCount+'</h1><p class=\"factsBoxBrief\">Guests</p></div>'+ \n\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+completeReportInfo[0].count+'</h1><p class=\"factsBoxBrief\">Bills</p></div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+graphRenderSectionContent+\n\t\t\t (hasWeeklyGraphAttached ? '<div style=\"page-break-before: always; margin-top: 20px\"></div><div style=\"height: 30px; width: 100%; display: block\"></div>' : '')+\n\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t '<h1 class=\"tableQuickHeaderText\">Quick Summary</h1>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t '<tr><td class=\"tableQuickBrief\" style=\"font-weight: bold;\">Gross Amount</td><td class=\"tableQuickAmount\" style=\"font-weight: bold;\"><span class=\"price\">Rs.</span>'+parseFloat(netSalesWorth).toFixed(2)+'</td></tr>'+\n\t\t\t quickSummaryRendererContent+\n\t\t\t '<tr><td class=\"tableQuickBrief\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\">Net Sales</td><td class=\"tableQuickAmount\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\"><span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(2)+'</td></tr>'+\n\t\t\t '</table>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '<div style=\"page-break-before: always; margin-top: 20px\"></div><div style=\"height: 30px; width: 100%; display: block\"></div>'+\n\t\t\t salesByBillingModeRenderContentFinal+\n\t\t\t salesByPaymentTypeRenderContentFinal+\n\t\t\t '<div style=\"border-top: 2px solid #989898; padding: 12px; background: #f2f2f2;\">'+\n\t\t\t '<p class=\"footerNote\">www.accelerate.net.in | [email protected]</p>'+\n\t\t\t '</div>'+\n\t\t\t '</body>';\n\n\t\t\t\tvar finalContent_EncodedDownload = encodeURI(finalReport_downloadContent);\n\t\t\t\t$('#reportActionButtonDownload').attr('data-hold', finalContent_EncodedDownload);\n\n\t\t\t\tvar finalContent_EncodedText = encodeURI(fancy_report_title_name);\n\t\t\t\t$('#reportActionButtonDownload').attr('text-hold', finalContent_EncodedText);\n\n\t\t\t\tgenerateReportContentEmail();\n\n\t\t}\n\n\t\tfunction generateReportContentEmail(){\n\n\t\t\t\trunReportAnimation(97);\n\n\t\t\t\t//To display weekly graph or not\n\t\t\t\tvar hasWeeklyGraphAttached = false;\n\t\t\t\tif(window.localStorage.graphImageDataWeekly && window.localStorage.graphImageDataWeekly != ''){\n\t\t\t\t\thasWeeklyGraphAttached = true;\n\t\t\t\t}\n\n\t\t\t\tvar temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\n\t\t\t\tvar graphRenderSectionContent = '';\n\t\t\t\tvar fancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY - dddd');\n\n\t\t\t\tvar reportInfo_title = 'Sales Report of <b>'+fancy_from_date+'</b>';\n\t\t\t\tvar temp_report_title = 'Sales Report of '+fancy_from_date;\n\t\t\t\tif(fromDate != toDate){\n\t\t\t\t\tfancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\t\t\t\t\tvar fancy_to_date = moment(toDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\n\t\t\t\t\treportInfo_title = 'Sales Report from <b>'+fancy_from_date+'</b> to <b>'+fancy_to_date+'</b>';\n\t\t\t\t\ttemp_report_title = 'Sales Report from '+fancy_from_date+' to '+fancy_to_date;\n\t\t\t\t}\n\t\t\t else{ //Render graph only if report is for a day\n\n\t\t\t if(hasWeeklyGraphAttached){\n\n\t\t\t \tvar temp_image_name = reportInfo_branch+'_'+fromDate;\n\t\t\t \ttemp_image_name = temp_image_name.replace(/\\s/g,'');\n\n\t\t\t graphRenderSectionContent = ''+\n\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t '<h1 class=\"tableQuickHeaderText\">WEEKLY SALES TREND</h1>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"weeklyGraph\">'+\n\t\t\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/report_trend_images_repo/'+temp_image_name+'.png\" style=\"max-width: 90%\">'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>';\n\t\t\t }\n\t\t\t }\n\n\t\t\t var fancy_report_title_name = reportInfo_branch+' - '+temp_report_title;\n\n\t\t\t //Quick Summary Content\n\t\t\t var quickSummaryRendererContent = '';\n\n\t\t\t var a = 0;\n\t\t\t while(reportInfoExtras[a]){\n\t\t\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+reportInfoExtras[a].name+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(reportInfoExtras[a].value).toFixed(2)+'</td></tr>';\n\t\t\t a++;\n\t\t\t }\n\n\n\t\t\t var b = 1; //first one contains total paid\n\t\t\t while(completeReportInfo[b]){\n\t\t\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+completeReportInfo[b].name+'</td><td class=\"tableQuickAmount\">'+(completeReportInfo[b].type == 'NEGATIVE' && completeReportInfo[b].value != 0 ? '- ' : '')+'<span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[b].value).toFixed(2)+'</td></tr>';\n\t\t\t b++;\n\t\t\t }\n\n\n\t\t\t //Sales by Billing Modes Content\n\t\t\t var salesByBillingModeRenderContent = '';\n\t\t\t var c = 0;\n\t\t\t var billSharePercentage = 0;\n\t\t\t while(detailedListByBillingMode[c]){\n\t\t\t billSharePercentage = parseFloat((100*detailedListByBillingMode[c].value)/completeReportInfo[0].value).toFixed(0);\n\t\t\t salesByBillingModeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByBillingMode[c].name+' '+(billSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+billSharePercentage+'%)</span>' : '')+(detailedListByBillingMode[c].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByBillingMode[c].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByBillingMode[c].value).toFixed(0)+'</td></tr>';\n\t\t\t c++;\n\t\t\t }\n\n\t\t\t\t//To display bills graph or not\n\t\t\t\tvar hasBillsGraphAttached = false;\n\t\t\t\tif(window.localStorage.graphImageDataBills && window.localStorage.graphImageDataBills != '' && window.localStorage.graphImageDataBills != 'data:,'){\n\t\t\t\t\thasBillsGraphAttached = true;\n\t\t\t\t}\n\n\t\t\t var salesByBillingModeRenderContentFinal = '';\n\t\t\t if(salesByBillingModeRenderContent != ''){\n\t\t\t\t\t salesByBillingModeRenderContentFinal = ''+\n\t\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY BILLS</h1>'+\n\t\t\t\t\t '</div>'+\n\t\t\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t\t salesByBillingModeRenderContent+\n\t\t\t\t\t '</table>'+\n\t\t\t\t\t '</div>'+\n\t\t\t\t\t '</div>'+\n\t\t\t\t\t '</div>';\n\t\t\t }\n\n\n\t\t\t //Sales by Payment Types Content\n\t\t\t var salesByPaymentTypeRenderContent = '';\n\t\t\t var d = 0;\n\t\t\t var paymentSharePercentage = 0;\n\t\t\t while(detailedListByPaymentMode[d]){\n\t\t\t paymentSharePercentage = parseFloat((100*detailedListByPaymentMode[d].value)/completeReportInfo[0].value).toFixed(0);\n\t\t\t salesByPaymentTypeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByPaymentMode[d].name+' '+(paymentSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+paymentSharePercentage+'%)</span>' : '')+(detailedListByPaymentMode[d].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByPaymentMode[d].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByPaymentMode[d].value).toFixed(0)+'</td></tr>';\n\t\t\t d++;\n\t\t\t }\n\n\t\t\t var salesByPaymentTypeRenderContentFinal = '';\n\t\t\t if(salesByPaymentTypeRenderContent != ''){\n\t\t\t\t \tsalesByPaymentTypeRenderContentFinal = ''+\n\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY PAYMENT</h1>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t salesByPaymentTypeRenderContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>';\n\t\t\t }\n\n\t\t\t var temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\t\t\t var cssData = '<head> <style type=\"text/css\"> body{font-family:sans-serif;margin:0}#logo{min-height:60px;width:100%}.mainHeader{background:url(https://accelerateengine.app/clients/'+temp_licenced_client+'/pattern.jpg) #c63931;width:100%;min-height:95px;padding:10px 0;border-bottom:2px solid #a8302b}.headerLeftBox{width:55%;display:inline-block;padding-left:25px}.headerRightBox{width:35%;float:right;display:inline-block;text-align:right;padding-right:25px}.headerAddress{margin:0 0 5px;font-size:14px;color:#e4a1a6}.headerBranch{margin:10px 0;font-weight:700;text-transform:uppercase;font-size:21px;padding:3px 8px;color:#c63931;display:inline-block;background:#FFF}.headerAdmin{margin:0 0 3px;font-size:16px;color:#FFF}.headerTimestamp{margin:0 0 5px;font-size:12px;color:#e4a1a6}.reportTitle{margin:15px 0;font-size:26px;font-weight:400;text-align:center;color:#3498db}.introFacts{background:0 0;width:100%;min-height:95px;padding:10px 0}.factsArea{display:block;padding:10px;text-align:center}.factsBox{margin-right: 5px; width:18%; display:inline-block;text-align:left;padding:20px 15px;border:2px solid #a8302b;border-radius:5px;color:#FFF;height:65px;background:#c63931}.factsBoxFigure{margin:0 0 8px;font-weight:700;font-size:32px}.factsBoxFigure .factsPrice{font-weight:400;font-size:40%;color:#e4a1a6;margin-left:2px}.factsBoxBrief{margin:0;font-size:16px;color:#F1C40F;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.summaryTableSectionHolder{width:100%}.summaryTableSection{padding:0 25px;margin-top:30px}.summaryTableSection table{border-collapse:collapse}.summaryTableSection td{border-bottom:1px solid #fdebed}.tableQuick{padding:10px}.tableQuickHeader{min-height:40px;background:#c63931;border-bottom:3px solid #a8302b;border-top-right-radius:15px;color:#FFF}.tableQuickHeaderText{margin:0 0 0 25px;font-size:18px;letter-spacing:2px;text-transform:uppercase;padding-top:10px;font-weight:700}.smallOrderCount{font-size:80%;margin-left:15px;color:#aba9a9;font-style:italic;}.tableQuickBrief{padding:10px;font-size:16px;color:#a71a14}.tableQuickAmount{padding:10px;font-size:18px;text-align:right;color:#a71a14}.tableQuickAmount .price{font-size:70%;margin-right:2px}.tableGraphRow{position:relative}.tableGraph_Graph{width:35%;display:block;text-align:center;float:right;position:absolute;top:20px;left:62%}.footerNote,.weeklyGraph{text-align:center;margin:0}.tableGraph_Table{padding:10px;width:55%;display:block;min-height:250px;}.weeklyGraph{padding:25px;border:1px solid #f2f2f2;border-top:none}.footerNote{font-size:12px;color:#595959}@media screen and (max-width:1000px){.headerLeftBox{display:none!important}.headerRightBox{padding-right:5px!important;width:90%!important}.reportTitle{font-size:18px!important}.tableQuick{padding:0 0 5px!important}.factsArea{padding:5px!important}.factsBox{width:90%!important;margin:0 0 5px!important}.smallOrderCount{margin:0!important;display:block!important}.summaryTableSection{padding:0 5px!important}}</style> </head>';\n\t\t\t \n\t\t\t var finalReport_emailContent = '<html>'+cssData+\n\t\t\t\t '<body>'+\n\t\t\t\t '<div class=\"mainHeader\">'+\n\t\t\t\t '<div class=\"headerLeftBox\">'+\n\t\t\t\t '<div id=\"logo\">'+\n\t\t\t\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/email_logo.png\">'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<p class=\"headerAddress\">'+reportInfo_address+'</p>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"headerRightBox\">'+\n\t\t\t\t '<h1 class=\"headerBranch\">'+reportInfo_branch+'</h1>'+\n\t\t\t\t '<p class=\"headerAdmin\">'+reportInfo_admin+'</p>'+\n\t\t\t\t '<p class=\"headerTimestamp\">'+reportInfo_time+'</p>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"introFacts\">'+\n\t\t\t\t '<h1 class=\"reportTitle\">'+reportInfo_title+'</h1>'+\n\t\t\t\t '<div class=\"factsArea\">'+\n\t\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(0)+' <span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Net Sales</p></div>'+ \n\t\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(netSalesWorth).toFixed(0)+'<span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Gross Sales</p></div>'+ \n\t\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+netGuestsCount+'</h1><p class=\"factsBoxBrief\">Guests</p></div>'+ \n\t\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+completeReportInfo[0].count+'</h1><p class=\"factsBoxBrief\">Bills</p></div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+graphRenderSectionContent+\n\t\t\t\t (hasWeeklyGraphAttached ? '<div style=\"page-break-before: always; margin-top: 20px\"></div><div style=\"height: 30px; width: 100%; display: block\"></div>' : '')+\n\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t\t '<h1 class=\"tableQuickHeaderText\">Quick Summary</h1>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t '<tr><td class=\"tableQuickBrief\" style=\"font-weight: bold;\">Gross Sales</td><td class=\"tableQuickAmount\" style=\"font-weight: bold;\"><span class=\"price\">Rs.</span>'+parseFloat(netSalesWorth).toFixed(2)+'</td></tr>'+\n\t\t\t\t quickSummaryRendererContent+\n\t\t\t\t '<tr><td class=\"tableQuickBrief\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\">Net Sales</td><td class=\"tableQuickAmount\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\"><span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(2)+'</td></tr>'+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div style=\"page-break-before: always; margin-top: 20px\"></div><div style=\"height: 30px; width: 100%; display: block\"></div>'+\n\t\t\t\t salesByBillingModeRenderContentFinal+\n\t\t\t\t salesByPaymentTypeRenderContentFinal+\n\t\t\t\t '<div style=\"border-top: 2px solid #989898; padding: 12px; background: #f2f2f2;\">'+\n\t\t\t\t '<p class=\"footerNote\">www.accelerate.net.in | [email protected]</p>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</body>'+\n\t\t\t\t '<html>';\n\n\t\t\t\tvar finalContent_EncodedEmail = encodeURI(finalReport_emailContent);\n\t\t\t\t$('#reportActionButtonEmail').attr('data-hold', finalContent_EncodedEmail);\n\n\t\t\t\tvar myFinalCollectionText = {\n\t\t\t\t\t\"reportTitle\" : fancy_report_title_name,\n\t\t\t\t\t\"imageName\": reportInfo_branch+'_'+fromDate\n\t\t\t\t}\n\n\t\t\t\tvar finalContent_EncodedText = encodeURI(JSON.stringify(myFinalCollectionText));\n\t\t\t\t$('#reportActionButtonEmail').attr('text-hold', finalContent_EncodedText);\t\n\n\t\t\t\tgenerateReportContentPrint();\t\t\n\t\t}\n\n\t\tfunction generateReportContentPrint(){\n\n\t\t\trunReportAnimation(99);\n\n\t\t\tvar graphRenderSectionContent = '';\n\t\t\tvar fancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY - dddd');\n\n\t\t\tvar reportInfo_title = 'Sales Report of <b>'+fancy_from_date+'</b>';\n\t\t\tvar temp_report_title = 'Sales Report of '+fancy_from_date;\n\t\t\tif(fromDate != toDate){\n\t\t\t\tfancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\t\t\t\tvar fancy_to_date = moment(toDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\n\t\t\t\treportInfo_title = 'Sales Report from <b>'+fancy_from_date+'</b> to <b>'+fancy_to_date+'</b>';\n\t\t\t\ttemp_report_title = 'Sales Report from '+fancy_from_date+' to '+fancy_to_date;\n\t\t\t}\n\n\n\t\t //Quick Summary Content\n\t\t var quickSummaryRendererContent = '';\n\n\t\t var a = 0;\n\t\t while(reportInfoExtras[a]){\n\t\t quickSummaryRendererContent += '<tr><td style=\"font-size: 11px\">'+reportInfoExtras[a].name+'</td><td style=\"font-size: 11px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(reportInfoExtras[a].value).toFixed(2)+'</td></tr>';\n\t\t a++;\n\t\t }\n\n\t\t var b = 1; //first one contains total paid\n\t\t while(completeReportInfo[b]){\n\t\t quickSummaryRendererContent += '<tr><td style=\"font-size: 11px\">'+completeReportInfo[b].name+'</td><td style=\"font-size: 11px; text-align: right\">'+(completeReportInfo[b].type == 'NEGATIVE' && completeReportInfo[b].value != 0 ? '- ' : '')+'<span style=\"font-size: 60%\">Rs.</span>'+parseFloat(completeReportInfo[b].value).toFixed(2)+'</td></tr>';\n\t\t b++;\n\t\t }\n\n\t\t var printSummaryAll = ''+\n\t\t \t'<div class=\"KOTContent\">'+\n\t\t \t\t '<h2 style=\"text-align: center; margin: 5px 0 3px 0; font-weight: bold; border-bottom: 1px solid #444;\">OVERALL SUMMARY</h2>'+\n\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t '<col style=\"width: 85%\">'+\n\t\t\t '<col style=\"width: 15%\">'+ \n\t\t\t '<tr><td style=\"font-size: 11px\"><b>Gross Sales</b></td><td style=\"font-size: 11px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(netSalesWorth).toFixed(2)+'</td></tr>'+\n\t\t\t quickSummaryRendererContent+\n\t\t\t '<tr><td style=\"font-size: 13px\"><b>Net Sales</b></td><td style=\"font-size: 13px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(2)+'</td></tr>'+\n\t\t\t '</table>'+\n\t\t\t '</div>';\n\n\t\t //Sales by Billing Modes Content\n\t\t var printSummaryBillsContent = '';\n\t\t var c = 0;\n\t\t var billSharePercentage = 0;\n\t\t while(detailedListByBillingMode[c]){\n\t\t billSharePercentage = parseFloat((100*detailedListByBillingMode[c].value)/completeReportInfo[0].value).toFixed(0);\n\t\t printSummaryBillsContent += '<tr><td style=\"font-size: 11px\">'+detailedListByBillingMode[c].name+' '+(billSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+billSharePercentage+'%)</span>' : '')+(detailedListByBillingMode[c].count > 0 ? '<span style=\"font-style:italic; font-size: 60%; display: block;\">'+detailedListByBillingMode[c].count+' orders</span>' : '')+'</td><td style=\"font-size: 11px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(detailedListByBillingMode[c].value).toFixed(0)+'</td></tr>';\n\t\t c++;\n\t\t }\n\n\t\t var printSummaryBills = '';\n\t\t if(printSummaryBillsContent != ''){\n\t\t\t\tprintSummaryBills = ''+\n\t\t\t \t'<div class=\"KOTContent\">'+\n\t\t\t \t\t '<h2 style=\"text-align: center; margin: 5px 0 3px 0; font-weight: bold; border-bottom: 1px solid #444;\">BILLING MODES</h2>'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 85%\">'+\n\t\t\t\t '<col style=\"width: 15%\">'+ \n\t\t\t\t printSummaryBillsContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>';\t\n\t\t }\n\n\n\t\t //Sales by Payment Types Content\n\t\t var printSummaryPaymentContent = '';\n\t\t var d = 0;\n\t\t var paymentSharePercentage = 0;\n\t\t while(detailedListByPaymentMode[d]){\n\t\t paymentSharePercentage = parseFloat((100*detailedListByPaymentMode[d].value)/completeReportInfo[0].value).toFixed(0);\n\t\t printSummaryPaymentContent += '<tr><td style=\"font-size: 11px\">'+detailedListByPaymentMode[d].name+' '+(paymentSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+paymentSharePercentage+'%)</span>' : '')+(detailedListByPaymentMode[d].count > 0 ? '<span style=\"font-style:italic; font-size: 60%; display: block;\">'+detailedListByPaymentMode[d].count+' orders</span>' : '')+'</td><td style=\"font-size: 11px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(detailedListByPaymentMode[d].value).toFixed(0)+'</td></tr>'; \n\t\t d++;\n\t\t }\n\n\t\t var printSummaryPayment = '';\n\t\t if(printSummaryPaymentContent != ''){\n\t\t\t printSummaryPayment = ''+\n\t\t\t \t'<div class=\"KOTContent\">'+\n\t\t\t \t\t '<h2 style=\"text-align: center; margin: 5px 0 3px 0; font-weight: bold; border-bottom: 1px solid #444;\">PAYMENT TYPES</h2>'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 85%\">'+\n\t\t\t\t '<col style=\"width: 15%\">'+ \n\t\t\t\t printSummaryPaymentContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>';\t\n\t\t }\n\n\n\t\t var printSummaryCounts = ''+\n\t\t\t \t'<div class=\"KOTContent\">'+\n\t\t\t \t\t '<h2 style=\"text-align: center; margin: 5px 0 3px 0; font-weight: bold; border-bottom: 1px solid #444;\">OTHER DETAILS</h2>'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 85%\">'+\n\t\t\t\t '<col style=\"width: 15%\">'+ \n\t\t\t\t '<tr><td style=\"font-size: 10px\">Total Guests</td><td style=\"font-size: 13px\">'+netGuestsCount+'</td></tr>'+\n\t\t\t\t '<tr><td style=\"font-size: 10px\">Total Bills</td><td style=\"font-size: 13px\">'+completeReportInfo[0].count+'</td></tr>'+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>';\n\n\n\n\n\t\t var cssData = '<head> <style type=\"text/css\"> .KOTContent,.KOTHeader,.KOTNumberArea,.KOTSummary{width:100%;background-color:none}.subLabel,body{font-family:sans-serif}.KOTNumber,.invoiceNumber,.subLabel{letter-spacing:2px}#logo{min-height:60px;width:100%;border-bottom:2px solid #000}.KOTHeader,.KOTNumberArea{min-height:30px;padding:5px 0;border-bottom:1px solid #7b7b7b}.KOTContent{min-height:100px;font-size:11px;padding-top:6px;border-bottom:2px solid}.KOTSummary{font-size:11px;padding:5px 0;border-bottom:1px solid}.KOTContent td,.KOTContent table{border-collapse:collapse}.KOTContent td{border-bottom:1px dashed #444;padding:7px 0}.invoiceHeader,.invoiceNumberArea{padding:5px 0;border-bottom:1px solid #7b7b7b;width:100%;background-color:none}.KOTSpecialComments{min-height:20px;width:100%;background-color:none;padding:5px 0}.invoiceNumberArea{min-height:30px}.invoiceContent{min-height:100px;width:100%;background-color:none;font-size:11px;padding-top:6px;border-bottom:1px solid}.invoiceCharges{min-height:90px;font-size:11px;width:100%;background-color:none;padding:5px 0;border-bottom:2px solid}.invoiceCustomText,.invoicePaymentsLink{background-color:none;border-bottom:1px solid;width:100%}.invoicePaymentsLink{min-height:72px}.invoiceCustomText{padding:5px 0;font-size:12px;text-align:center}.subLabel{display:block;font-size:8px;font-weight:300;text-transform:uppercase;margin-bottom:5px}p{margin:0}.itemComments,.itemOldComments{font-style:italic;margin-left:10px}.serviceType{border:1px solid;padding:4px;font-size:12px;display:block;text-align:center;margin-bottom:8px}.tokenNumber{display:block;font-size:16px;font-weight:700}.billingAddress,.timeStamp{font-weight:300;display:block}.billingAddress{font-size:12px;line-height:1.2em}.mobileNumber{display:block;margin-top:8px;font-size:12px}.timeStamp{font-size:11px}.KOTNumber{font-size:15px;font-weight:700}.commentsSubText{font-size:12px;font-style:italic;font-weight:300;display:block}.invoiceNumber{font-size:15px;font-weight:700}.timeDisplay{font-size:75%;display:block}.rs{font-size:60%}.paymentSubText{font-size:10px;font-weight:300;display:block}.paymentSubHead{font-size:12px;font-weight:700;display:block}.qrCode{width:100%;max-width:120px;text-align:right}.addressContact,.addressText{color:gray;text-align:center}.addressText{font-size:10px;padding:5px 0}.addressContact{font-size:9px;padding:0 0 5px}.gstNumber{font-weight:700;font-size:10px}.attendantName,.itemQuantity{font-size:12px}#defaultScreen{position:fixed;left:0;top:0;z-index:100001;width:100%;height:100%;overflow:visible;background-image:url(../data/photos/brand/pattern.jpg);background-repeat:repeat;padding-top:100px}.attendantName{font-weight:300;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.itemComments,.itemQuantity{font-weight:700;display:block}.itemOldComments{display:block;text-decoration:line-through}.itemOldQuantity{font-size:12px;text-decoration:line-through;display:block} </style> </head>';\n\n\t\t var data_custom_header_image = window.localStorage.bill_custom_header_image ? window.localStorage.bill_custom_header_image : '';\n\n\t\t var data_custom_header_client_name = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name : '';\n\t\t\tif(data_custom_header_client_name == ''){\n\t\t\t data_custom_header_client_name = 'Report';\n\t\t\t}\n\n\t\t var finalReport_printContent = cssData +\n\t\t \t'<body>'+\n\t\t\t '<div id=\"logo\">'+\n\t\t\t (data_custom_header_image != '' ? '<center><img style=\"max-width: 90%\" src=\\''+data_custom_header_image+'\\'/></center>' : '<h1 style=\"text-align: center\">'+data_custom_header_client_name+'</h1>')+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"KOTHeader\" style=\"padding: 0; background: #444;\">'+\n\t\t\t \t'<p style=\"text-align: center; font-size: 16px; font-weight: bold; text-transform: uppercase; padding-top: 6px; color: #FFF;\">'+reportInfo_branch+'</p>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"KOTNumberArea\">'+\n\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t '<col style=\"width: 50%\">'+\n\t\t\t '<col style=\"width: 50%\">'+\n\t\t\t '<tr>'+\n\t\t\t '<td style=\"vertical-align: top\">'+\n\t\t\t '<p>'+\n\t\t\t '<tag class=\"subLabel\">Admin</tag>'+\n\t\t\t '<tag class=\"KOTNumber\" style=\"font-size: 13; font-weight: 300; letter-spacing: unset;\">'+reportInfo_admin+'</tag>'+\n\t\t\t '</p>'+\n\t\t\t '</td>'+\n\t\t\t '<td style=\"vertical-align: top\">'+\n\t\t\t '<p style=\" text-align: right; float: right\">'+\n\t\t\t '<tag class=\"subLabel\">TIME STAMP</tag>'+\n\t\t\t '<tag class=\"timeStamp\">'+reportInfo_time+'</tag>'+\n\t\t\t '</p>'+\n\t\t\t '</td>'+\n\t\t\t '</tr>'+\n\t\t\t '</table>'+\n\t\t\t '</div>'+\n\t\t\t '<h1 style=\"margin: 6px 3px; padding-bottom: 5px; font-weight: 400; text-align: center; font-size: 15px; border-bottom: 2px solid; }\">'+reportInfo_title+'</h1>'+\n\t\t\t \t printSummaryAll+printSummaryBills+printSummaryPayment+printSummaryCounts+\n\t\t\t \t'</body>';\n\n\t\t\t\tvar finalContent_EncodedPrint = encodeURI(finalReport_printContent);\n\t\t\t\t$('#reportActionButtonPrint').attr('data-hold', finalContent_EncodedPrint);\n\n\t\t\t\trunReportAnimation(100); //Done!\n\t\t}\n\t}", "initialize() {\n return new Promise((resolve, reject) => {\n phantom.create(this.app.config.pdf.options).then((instance) => {\n this.phantom = instance\n return resolve(instance)\n }).catch(reject)\n })\n }", "generateFinalReport() {\n const obj = {\n environment: \"Dev\",\n numberOfTestSuites: this._numberOfTestSuites,\n totalTests: this._numberOfTests,\n browsers: this.browsers,\n testsState: [{\n state: this.standardTestState('Passed'),\n total: this._numberOfPassedTests\n }, {\n state: this.standardTestState('Failed'),\n total: this._numberOfFailedTests\n }, {\n state: this.standardTestState('Skipped'),\n total: this._numberOfSkippedTests\n\n }],\n testsPerBrowserPerState: this._testsCountPerBrowserPerState,\n testsPerSuitePerState: this._testsCountPerSuitePerState,\n testsWeatherState: this.weatherState,\n totalDuration: this._totalDuration,\n testsPerBrowser: this._testsPerBrowser\n };\n\n jsonfile.writeFile(this._finalReport, obj, {\n spaces: 2\n }, function(err) {\n if (err !== null) {\n console.error('Error saving JSON to file:', err)\n }\n console.info('Report generated successfully.');\n });\n }", "constructor() {\n super('resources-timing-digest');\n\n let resources = performance.getEntries();\n let initiators = {};\n let mimeTypes = {};\n let timing = {\n 'longest': {\n 'duration': 0\n },\n 'shortest': {\n 'duration': 0\n }\n }\n \n for (let resource of resources) {\n\n // Keep full record of the shortest and longest resource\n // request time\n if (resource.duration > timing.longest.duration) {\n timing.longest.duration = Math.round(resource.duration);\n timing.longest.resource = resource;\n }\n\n if (resource.duration < timing.shortest.duration ||\n timing.shortest.duration == 0) {\n timing.shortest.duration = Math.round(resource.duration);\n timing.shortest.resource = resource;\n }\n\n // Sum the time for resource request initiators\n let initiatorType = resource.initiatorType;\n\n if (!initiators[initiatorType]) {\n initiators[initiatorType] = {\n 'count': 0,\n 'total': 0\n };\n }\n\n initiators[initiatorType].count += 1;\n initiators[initiatorType].total += Math.round(resource.duration);\n\n //Sum the time for different mime types when available\n let mimeType = mime.lookup(resource.name);\n\n if (!mimeType) continue;\n\n if (!mimeTypes[mimeType]) {\n mimeTypes[mimeType] = {\n 'count': 0,\n 'total': 0\n };\n }\n\n mimeTypes[mimeType].count += 1;\n mimeTypes[mimeType].total += Math.round(resource.duration);\n }\n\n // After keeping the longest and shortest loading time related resources\n // get sure only to keep it's own properties and get rid of the reast of\n // the object in order to pass it trough the dispatcher worker safely\n timing.longest.resource = Util.copyObject(timing.longest.resource);\n timing.shortest.resource = Util.copyObject(timing.shortest.resource);\n\n this._data = {\n 'timing': timing,\n 'initiators': initiators,\n 'mimeTypes': mimeTypes\n };\n }", "newPage() {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n let scope;\n // ask for the \"scope\" if the scope feature is enabled\n if (this.props.features.scopes &&\n Object.keys((_a = this._scopes) !== null && _a !== void 0 ? _a : {}).length) {\n // ask for the page scope\n scope = yield this._ask('scope', {\n image: {\n url: 'https://picsum.photos/600/600?v=scope',\n },\n });\n }\n const result = yield this._ask('pageMetas', {\n image: {\n url: 'https://picsum.photos/600/600?v=pageMetas',\n },\n scope,\n });\n _console.log('COCO', result);\n });\n }", "function fetchSingleClickReport(){\n\n\n\t$( \"#summaryRenderArea\" ).children().css( \"display\", \"none\" );\n\tdocument.getElementById(\"singleClickReport_RenderArea\").style.display = \"block\";\n\n\t//Initialise animation contents\n\tdocument.getElementById(\"singleClickReport_RenderContent\").innerHTML = ''+\n '<center><div class=\"reportDemo\">'+\n '<svg class=\"progress\" width=\"120\"> <circle class=\"progress__meter\" cx=\"60\" cy=\"60\" r=\"54\" stroke-width=\"12\" /> <circle class=\"progress__value\" cx=\"60\" cy=\"60\" r=\"54\" stroke-width=\"12\" /> </svg>'+\n '<tag class=\"reportPercentage\" id=\"reportPercentageArea\"><span id=\"reportPercentageFigure\">0</span><span style=\"font-size: 60%\">%</span></tag>'+\n '<p class=\"generatingText\">Generating Report</p>'+\n '</div>'+\n '<div id=\"postReportActions\" style=\"display: none\">'+\n '<p style=\"font-size: 26px; color: #777; font-weight: 300; margin-top: -15px\">Your Report is Ready!</p>'+\n '<button data-hold=\"\" text-hold=\"\" id=\"reportActionButtonDownload\" onclick=\"reportActionDownload()\" style=\"margin-right: 5px\" class=\"btn btn-success btn-sm\"><i class=\"fa fa-download\"></i> Download</button>'+\n '<button data-hold=\"\" id=\"reportActionButtonPrint\" onclick=\"reportActionPrint()\" style=\"margin-right: 5px\" class=\"btn btn-success btn-sm\"><i class=\"fa fa-print\"></i> Print</button>'+\n '<button data-hold=\"\" text-hold=\"\" id=\"reportActionButtonEmail\" onclick=\"reportActionEmail()\" class=\"btn btn-success btn-sm\"><i class=\"fa fa-envelope\"></i> Email</button>'+\n '</div></center>';\t\n\n document.getElementById(\"singleClickReport_ErrorContent\").style.display = 'none';\n\n\n //Clear all graph data\n window.localStorage.graphImageDataWeeklyBW = '';\n window.localStorage.graphImageDataWeekly = '';\n window.localStorage.graphImageDataPayments = '';\n window.localStorage.graphImageDataBills = '';\n\n \n //Initialise animation\n\tvar progressValue = document.querySelector('.progress__value');\n\tvar RADIUS = 54;\n\tvar CIRCUMFERENCE = 2 * Math.PI * RADIUS;\n\n\tfunction runReportAnimation(value){\n\n\t\tif(value > 100){\n\t\t \tvalue = 100;\n\t\t}\n\n\t var progress = value / 100;\n\t var dashoffset = CIRCUMFERENCE * (1 - progress);\n\t progressValue.style.strokeDashoffset = dashoffset;\n\t document.getElementById(\"reportPercentageFigure\").innerHTML = value;\n\n\t //When it is 100%\n\t if(value == 100){\n\t \tsetTimeout(function(){\n\t \t\tdocument.getElementById(\"reportPercentageArea\").innerHTML = '<img src=\"images/common/report_ready.png\" class=\"staryDoneIcon\">';\n\t \t\t$('#reportPercentageArea').addClass('zoomIn');\n\t \t\t$('.progress__value').css(\"stroke\", \"#FFF\");\n\t \t\t$('.progress__meter').css(\"stroke\", \"#FFF\");\n\t \t\t$('.generatingText').css(\"display\", \"none\");\n\t \t\t$('#postReportActions').css(\"display\", \"block\");\n\n\t \t\tplayNotificationSound('DONE');\n\t \t}, 10);\n\t }\n\t\n\t\tprogressValue.style.strokeDasharray = CIRCUMFERENCE;\t\t\n\t}\n\n\tfunction stopReportAnimation(optionalSource){\t\t\n\t\tif(optionalSource == 'ERROR'){\n\t \t\tdocument.getElementById(\"reportPercentageArea\").innerHTML = '<img src=\"images/common/error_triangle.png\" class=\"staryDoneIcon\">';\n\t \t\t$('#reportPercentageArea').addClass('animateShake');\n\t \t\t$('.progress__value').css(\"stroke\", \"#FFF\");\n\t \t\t$('.progress__meter').css(\"stroke\", \"#FFF\");\n\t \t\t$('.generatingText').css(\"display\", \"none\");\n\t \t\t$('#postReportActions').css(\"display\", \"none\");\n\n\t \t\tplayNotificationSound('DISABLE');\n\t\t}\n\t\telse{\n\n\t\t}\n\t}\n\n\n\n\n\t//Note: Dates in YYYYMMDD format\n\tvar fromDate = document.getElementById(\"reportFromDate\").value;\n\tfromDate = fromDate && fromDate != '' ? fromDate : '01-01-2018'; //Since the launch of Vega POS\n\tfromDate = getSummaryStandardDate(fromDate);\n\n\tvar toDate = document.getElementById(\"reportToDate\").value;\n\ttoDate = toDate && toDate != '' ? toDate : getCurrentTime('DATE_STAMP');\n\ttoDate = getSummaryStandardDate(toDate);\n\n\tvar completeReportInfo = [];\n\tvar netSalesWorth = 0;\n\tvar netGuestsCount = '###';\n\tvar netRefundsProcessed = 0;\n\tvar reportInfoExtras = [];\n\tvar completeErrorList = []; //In case any API call causes Error\n\tvar detailedListByBillingMode = []; //Billing mode wise\n\tvar detailedListByPaymentMode = []; //Payment mode wise\n\tvar weeklyProgressThisWeek = []; //This Week sales\n\tvar weeklyProgressLastWeek = []; //Last Week sales\n\tvar paymentGraphData = []; //For payment graphs\n\tvar billsGraphData = []; //For bills graphs\n\n\n\t//Net Sales Worth = Total Paid - (All the other charges) - (Discounts & Refunds) + (Tips)\n\n\t//Starting point\n\trunReportAnimation(0);\n\tsetTimeout(singleClickTotalPaid, 1000);\n\n\n\t//Step 1: Total Paid Amount\n\tfunction singleClickTotalPaid(){\n\t\t$.ajax({\n\t\t type: 'GET',\n\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/grandtotal_paidamount?startkey=[\"'+fromDate+'\"]&endkey=[\"'+toDate+'\"]',\n\t\t\ttimeout: 10000,\n\t\t\tsuccess: function(data) {\n\n\t\t\t\tvar temp_totalOrders = 0;\n\t\t\t\tvar temp_totalPaid = 0;\n\n\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\ttemp_totalOrders = data.rows[0].value.count;\n\t\t\t\t\ttemp_totalPaid = data.rows[0].value.sum;\n\t\t\t\t}\n\n\t\t\t\tcompleteReportInfo.push({\n\t\t\t\t\t\t\"name\": \"Total Paid Amount\",\n\t\t\t\t\t\t\"value\": temp_totalPaid,\n\t\t\t\t\t\t\"count\": temp_totalOrders,\n\t\t\t\t\t\t\"split\": []\n\t\t\t\t});\n\n\t\t\t\tnetSalesWorth = temp_totalPaid;\n\n\t\t\t\t//Step 1-2:\n\t\t\t\tsingleClickTotalGuests();\n\n\t\t\t},\n\t\t\terror: function(data){\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 1,\n\t\t\t\t\t\"error\": \"Failed to load net sales figure. Report can not be generated.\"\n\t\t\t\t});\n\t\t\t\tstopReportAnimation('ERROR');\n\t\t\t\tsingleClickLoadErrors();\n\t\t\t\treturn '';\n\t\t\t}\n\t\t}); \n\t}\t\n\n\n\t//Step 1-2: Total Number of Guests\n\tfunction singleClickTotalGuests(){\n\n\t\trunReportAnimation(3); //of Step 1 which takes 3 units\n\n\t\t$.ajax({\n\t\t type: 'GET',\n\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/totalguests?startkey=[\"'+fromDate+'\"]&endkey=[\"'+toDate+'\"]',\n\t\t\ttimeout: 10000,\n\t\t\tsuccess: function(data) {\n\n\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\tnetGuestsCount = data.rows[0].value.sum;\n\t\t\t\t}\n\n\t\t\t\t//Step 2:\n\t\t\t\tsingleClickExtraCharges();\n\n\t\t\t},\n\t\t\terror: function(data){\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 1.2,\n\t\t\t\t\t\"error\": \"Failed to sum up the number of guests\"\n\t\t\t\t});\n\t\t\t\treturn '';\n\t\t\t}\n\t\t}); \n\t}\t\t\n\n\n\t//Step 2: \n\tfunction singleClickExtraCharges(){\n\n\t\trunReportAnimation(5); //of Step 1-2 which takes 2 units\n\n\t var requestData = {\n\t \"selector\" :{ \n\t \"identifierTag\": \"ACCELERATE_BILLING_PARAMETERS\" \n\t },\n\t \"fields\" : [\"identifierTag\", \"value\"]\n\t }\n\n\t $.ajax({\n\t type: 'POST',\n\t url: COMMON_LOCAL_SERVER_IP+'/accelerate_settings/_find',\n\t data: JSON.stringify(requestData),\n\t contentType: \"application/json\",\n\t dataType: 'json',\n\t timeout: 10000,\n\t success: function(data) {\n\n\t if(data.docs.length > 0){\n\t if(data.docs[0].identifierTag == 'ACCELERATE_BILLING_PARAMETERS'){\n\n\t\t \tvar modes = data.docs[0].value;\n\t\t \tmodes.sort(); //alphabetical sorting \n\n\t\t \tif(modes.length == 0){\n\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t \"step\": 2,\n\t\t\t\t\t\t\t\"error\": \"Failed to read applied charges\"\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\tsingleClickDiscountsOffered(); \n\t\t\t\t\t\treturn '';\n\t\t \t}\n\t\t \telse{\n\n\t\t \t //For a given BILLING PARAMETER, the total Sales in the given DATE RANGE\n\t\t\t\t\t $.ajax({\n\t\t\t\t\t type: 'GET',\n\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbyextras?startkey=[\"'+modes[0].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[0].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t success: function(data) {\n\t\t\t\t\t \t\n\t\t\t\t\t \tvar temp_count = 0;\n\t\t\t\t\t \tvar temp_sum = 0;\n\n\t\t\t\t\t \tif(data.rows.length > 0){\n\t\t\t\t\t \t\ttemp_count = data.rows[0].value.count;\n\t\t\t\t\t \t\ttemp_sum = data.rows[0].value.sum;\n\t\t\t\t\t \t}\n\n\t\t\t\t\t \t\t//Now check in custom extras\n\t\t\t\t\t\t \t$.ajax({\n\t\t\t\t\t\t\t\t\ttype: 'GET',\n\t\t\t\t\t\t\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbyextras_custom?startkey=[\"'+modes[0].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[0].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\ttimeout: 10000,\n\t\t\t\t\t\t\t\t\tsuccess: function(data) {\n\n\t\t\t\t\t\t\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t temp_count += data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t temp_sum += data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tnetSalesWorth -= temp_sum;\n\n\t\t\t\t\t\t\t\t\t\treportInfoExtras.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\"name\": modes[0].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\"value\": temp_sum\n\t\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t \t//Check if next mode exists...\n\t\t\t\t\t\t\t\t \tif(modes[1]){\n\t\t\t\t\t\t\t\t \t\tsingleClickExtraChargesCallback(1, modes);\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\t//Step 3: Total Discount offered\n\t\t\t\t\t\t\t\t \t\tsingleClickDiscountsOffered();\n\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\terror: function(data){\n\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t \"step\": 2,\n\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to read applied charges\"\n\t\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\tsingleClickDiscountsOffered(); \n\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}); \n\n\t\t\t\t\t },\n\t\t\t\t\t error: function(data){\n\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t \"step\": 2,\n\t\t\t\t\t\t\t\t\"error\": \"Failed to read applied charges\"\n\t\t\t\t\t\t\t});\t\n\n\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\tsingleClickDiscountsOffered(); \n\t\t\t\t\t\t\treturn '';\t \t\n\t\t\t\t\t }\n\t\t\t\t\t }); \n\t\t\t\t\t} //else - modes\n\t }\n\t else{\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 2,\n\t\t\t\t\t\"error\": \"Failed to read applied charges\"\n\t\t\t\t});\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickDiscountsOffered(); \n\t\t\t\treturn '';\n\t }\n\t }\n\t else{\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 2,\n\t\t\t\t\t\"error\": \"Failed to read applied charges\"\n\t\t\t\t});\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickDiscountsOffered(); \n\t\t\t\treturn '';\n\t }\n\t },\n\t error: function(data) {\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 2,\n\t\t\t\t\t\"error\": \"Failed to read applied charges\"\n\t\t\t\t});\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickDiscountsOffered(); \n\t\t\t\treturn '';\n\t }\n\n\t });\t\n\t}\n\n\n\t//Step 2 - Callback\n\tfunction singleClickExtraChargesCallback(index, modes){\n\n\t\t\t\t $.ajax({\n\t\t\t\t type: 'GET',\n\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbyextras?startkey=[\"'+modes[index].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[index].name+'\",\"'+toDate+'\"]',\n\t\t\t\t timeout: 10000,\n\t\t\t\t success: function(data) {\n\n\t\t\t\t \tvar temp_count = 0;\n\t\t\t\t \tvar temp_sum = 0;\n\n\t\t\t\t \tif(data.rows.length > 0){\n\t\t\t\t \t\ttemp_count = data.rows[0].value.count;\n\t\t\t\t \t\ttemp_sum = data.rows[0].value.sum;\n\t\t\t\t \t}\n\t\t\t\t \t\n\n\t\t\t\t \t\t//Now check in custom extras\n\t\t\t\t\t \t$.ajax({\n\t\t\t\t\t\t\t\ttype: 'GET',\n\t\t\t\t\t\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbyextras_custom?startkey=[\"'+modes[index].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[index].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\ttimeout: 10000,\n\t\t\t\t\t\t\t\tsuccess: function(data) {\n\n\t\t\t\t\t\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t temp_count += data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t temp_sum += data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tnetSalesWorth -= temp_sum;\n\n\n\t\t\t\t\t\t\t\t\treportInfoExtras.push({\n\t\t\t\t\t\t\t\t\t\t\"name\": modes[index].name,\n\t\t\t\t\t\t\t\t\t\t\"value\": temp_sum\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t \t//Check if next mode exists...\n\t\t\t\t\t\t\t \tif(modes[index+1]){\n\t\t\t\t\t\t\t \t\tsingleClickExtraChargesCallback(index+1, modes);\n\t\t\t\t\t\t\t \t}\n\t\t\t\t\t\t\t \telse{\n\t\t\t\t\t\t\t \t\t//Step 3: Total Discount offered\n\t\t\t\t\t\t\t \t\tsingleClickDiscountsOffered();\n\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\terror: function(data){\n\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t \"step\": 2,\n\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to read applied charges\"\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\tsingleClickDiscountsOffered(); \n\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}); \n\t\t\t\t },\n\t\t\t\t error: function(data){\n\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t \"step\": 2,\n\t\t\t\t\t\t\t\"error\": \"Failed to read applied charges\"\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\tsingleClickDiscountsOffered(); \n\t\t\t\t\t\treturn '';\n\t\t\t\t }\n\t\t\t\t }); \n\n\t}\t//End step 2 callback\n\n\n\t//Step 3: Discounts Offered\n\tfunction singleClickDiscountsOffered(){\n\n\t\trunReportAnimation(15); //of Step 2 which takes 10 units\n\n\t\t$.ajax({\n\t\t type: 'GET',\n\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/grandtotal_discounts?startkey=[\"'+fromDate+'\"]&endkey=[\"'+toDate+'\"]',\n\t\t\ttimeout: 10000,\n\t\t\tsuccess: function(data) {\n\n\t\t\t\tvar temp_discountedOrdersCount = 0;\n\t\t\t\tvar temp_discountedOrdersSum = 0;\n\n\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\ttemp_discountedOrdersCount = data.rows[0].value.count;\n\t\t\t\t\ttemp_discountedOrdersSum = data.rows[0].value.sum;\n\t\t\t\t}\n\n\t\t\t\tnetSalesWorth += temp_discountedOrdersSum;\n\n\t\t\t\tcompleteReportInfo.push({\n\t\t\t\t\t\t\"name\": \"Discounts\",\n\t\t\t\t\t\t\"type\": \"NEGATIVE\",\n\t\t\t\t\t\t\"value\": temp_discountedOrdersSum,\n\t\t\t\t\t\t\"count\": temp_discountedOrdersCount\n\t\t\t\t});\t\n\n\t\t\t\t//Step 4: Total Round Off made\n\t\t\t\tsingleClickRoundOffsMade();\n\n\t\t\t},\n\t\t\terror: function(data){\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 3,\n\t\t\t\t\t\"error\": \"Failed to read discounts offered\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickRoundOffsMade(); \n\t\t\t\treturn '';\n\t\t\t}\n\t\t}); \t\t\t\n\t}\n\n\n\n\t//Step 4: RoundOffs made\n\tfunction singleClickRoundOffsMade(){\n\n\t\trunReportAnimation(20); //of Step 3 which takes 5 units\n\n\t\t$.ajax({\n\t\t type: 'GET',\n\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/grandtotal_roundoff?startkey=[\"'+fromDate+'\"]&endkey=[\"'+toDate+'\"]',\n\t\t\ttimeout: 10000,\n\t\t\tsuccess: function(data) {\n\n\t\t\t\tvar temp_roundOffCount = 0;\n\t\t\t\tvar temp_roundOffSum = 0;\n\n\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\ttemp_roundOffCount = data.rows[0].value.count;\n\t\t\t\t\ttemp_roundOffSum = data.rows[0].value.sum;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tnetSalesWorth += temp_roundOffSum;\n\n\t\t\t\tcompleteReportInfo.push({\n\t\t\t\t\t\t\"name\": \"Round Off\",\n\t\t\t\t\t\t\"type\": \"NEGATIVE\",\n\t\t\t\t\t\t\"value\": temp_roundOffSum,\n\t\t\t\t\t\t\"count\": temp_roundOffCount\n\t\t\t\t});\t\n\n\t\t\t\t//Step 5: Total Tips received\n\t\t\t\tsingleClickTipsReceived();\n\n\t\t\t},\n\t\t\terror: function(data){\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 4,\n\t\t\t\t\t\"error\": \"Failed to read round-off amount\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickTipsReceived(); \n\t\t\t\treturn '';\n\t\t\t}\n\t\t}); \t\n\t}\n\n\n\n\t//Step 5: Total Tips Received\n\tfunction singleClickTipsReceived(){\n\n\t\trunReportAnimation(25); //of Step 4 which takes 5 units\n\n\t\t$.ajax({\n\t\t type: 'GET',\n\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/grandtotal_tips?startkey=[\"'+fromDate+'\"]&endkey=[\"'+toDate+'\"]',\n\t\t\ttimeout: 10000,\n\t\t\tsuccess: function(data) {\n\n\t\t\t\tvar temp_tipsCount = 0;\n\t\t\t\tvar temp_tipsSum = 0;\n\n\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\ttemp_tipsCount = data.rows[0].value.count;\n\t\t\t\t\ttemp_tipsSum = data.rows[0].value.sum;\n\t\t\t\t}\n\n\t\t\t\tnetSalesWorth -= temp_tipsSum;\n\n\n\t\t\t\tcompleteReportInfo.push({\n\t\t\t\t\t\t\"name\": \"Tips\",\n\t\t\t\t\t\t\"type\": \"POSITIVE\",\n\t\t\t\t\t\t\"value\": temp_tipsSum,\n\t\t\t\t\t\t\"count\": temp_tipsCount\n\t\t\t\t});\t\n\n\t\t\t\t//Step 6: Refunds Issued\n\t\t\t\tsingleClickRefundsIssued();\n\n\t\t\t},\n\t\t\terror: function(data){\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 5,\n\t\t\t\t\t\"error\": \"Failed to read tips received\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickRefundsIssued(); \n\t\t\t\treturn '';\n\t\t\t}\n\t\t}); \t\t\n\t}\n\n\n\t//Step 6: Total Refunds Issued\n\tfunction singleClickRefundsIssued(){\n\n\t\trunReportAnimation(30); //of Step 5 which takes 5 units\n\n\t\t//Refunded but NOT cancelled\n\t\t$.ajax({\n\t\t type: 'GET',\n\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/refund-summary/_view/allrefunds?startkey=[\"'+fromDate+'\"]&endkey=[\"'+toDate+'\"]',\n\t\t\ttimeout: 10000,\n\t\t\tsuccess: function(data) {\n\n\t\t\t\tvar temp_refundCount = 0;\n\t\t\t\tvar temp_refundSum = 0;\n\n\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\ttemp_refundCount = data.rows[0].value.count;\n\t\t\t\t\ttemp_refundSum = data.rows[0].value.sum;\n\t\t\t\t}\n\n\n\t\t\t\t//Cancelled and Refunded Orders\n\t\t\t\t$.ajax({\n\t\t\t\t type: 'GET',\n\t\t\t\t\turl: COMMON_LOCAL_SERVER_IP+'/accelerate_cancelled_invoices/_design/refund-summary/_view/allrefunds?startkey=[\"'+fromDate+'\"]&endkey=[\"'+toDate+'\"]',\n\t\t\t\t\ttimeout: 10000,\n\t\t\t\t\tsuccess: function(seconddata) {\n\n\t\t\t\t\t\tif(seconddata.rows.length > 0){\n\t\t\t\t\t\t\ttemp_refundCount += seconddata.rows[0].value.count;\n\t\t\t\t\t\t\ttemp_refundSum += seconddata.rows[0].value.sum;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//netSalesWorth -= temp_refundSum;\n\t\t\t\t\t\tnetRefundsProcessed = temp_refundSum;\n\n\t\t\t\t\t\tcompleteReportInfo.push({\n\t\t\t\t\t\t\t\t\"name\": \"Refunds Issued\",\n\t\t\t\t\t\t\t\t\"type\": \"NEGATIVE\",\n\t\t\t\t\t\t\t\t\"value\": temp_refundSum,\n\t\t\t\t\t\t\t\t\"count\": temp_refundCount\n\t\t\t\t\t\t});\t\n\n\t\t\t\t\t\t//Step 7: Render everything \n\t\t\t\t\t\tsingleClickSummaryFinal();\n\n\t\t\t\t\t},\n\t\t\t\t\terror: function(data){\n\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t \"step\": 6,\n\t\t\t\t\t\t\t\"error\": \"Failed to read refunds issued\"\n\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\tsingleClickSummaryFinal(); \n\t\t\t\t\t\treturn '';\n\t\t\t\t\t}\n\t\t\t\t}); \n\n\n\t\t\t},\n\t\t\terror: function(data){\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 6,\n\t\t\t\t\t\"error\": \"Failed to read refunds issued\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickSummaryFinal(); \n\t\t\t\treturn '';\n\t\t\t}\n\t\t}); \t\t\n\t}\n\n\n\t//Step 7 : Render \n\tfunction singleClickSummaryFinal(){\n\n\t\t/*\n\t\t\tIntermediate validation pit-stop:\n\t\t\tEnsure if all the data so far is good to render the\n\t\t\tfinal report, in the final step.\n\n\t\t\tIf it fails at this step, terminate the process here\n\t\t\tand kill the progress status animation\n\t\t*/\n\n\t\t//Step 8: Detailed by Billing Modes\n\t\tsingleClickDetailedByModes();\n\t}\n\n\n\t//Step 8: Details by Billing Modes\n\tfunction singleClickDetailedByModes(){\n\n\t\trunReportAnimation(40); //of Step 6 which takes 10 units\n\n\t\tbillsGraphData = [];\n\n\t\t//Preload Billing Parameters\n\t var requestParamData = {\n\t \"selector\" :{ \n\t \"identifierTag\": \"ACCELERATE_BILLING_PARAMETERS\" \n\t },\n\t \"fields\" : [\"identifierTag\", \"value\"]\n\t }\n\n\t $.ajax({\n\t type: 'POST',\n\t url: COMMON_LOCAL_SERVER_IP+'/accelerate_settings/_find',\n\t data: JSON.stringify(requestParamData),\n\t contentType: \"application/json\",\n\t dataType: 'json',\n\t timeout: 10000,\n\t success: function(data) {\n\n\t if(data.docs.length > 0){\n\t if(data.docs[0].identifierTag == 'ACCELERATE_BILLING_PARAMETERS'){\n\n\t\t \tvar billingExtras = data.docs[0].value;\n\n\t\t \tif(billingExtras.length == 0){\n\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\treturn '';\n\t\t \t}\n\t\t \telse{\n\n\n\t\t\t\t\t var requestData = {\n\t\t\t\t\t \"selector\" :{ \n\t\t\t\t\t \"identifierTag\": \"ACCELERATE_BILLING_MODES\" \n\t\t\t\t\t },\n\t\t\t\t\t \"fields\" : [\"identifierTag\", \"value\"]\n\t\t\t\t\t }\n\n\t\t\t\t\t $.ajax({\n\t\t\t\t\t type: 'POST',\n\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/accelerate_settings/_find',\n\t\t\t\t\t data: JSON.stringify(requestData),\n\t\t\t\t\t contentType: \"application/json\",\n\t\t\t\t\t dataType: 'json',\n\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t success: function(data) {\n\t\t\t\t\t if(data.docs.length > 0){\n\t\t\t\t\t if(data.docs[0].identifierTag == 'ACCELERATE_BILLING_MODES'){\n\n\t\t\t\t\t \tvar modes = data.docs[0].value;\n\n\t\t\t\t\t\t \tif(modes.length == 0){\n\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t \t}\n\t\t\t\t\t\t \telse{\n\n\t\t\t\t\t\t\t \t//For a given BILLING MODE, the total Sales in the given DATE RANGE\n\t\t\t\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\t\t\t type: 'GET',\n\t\t\t\t\t\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbybillingmode?startkey=[\"'+modes[0].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[0].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t\t\t\t\t\t success: function(data) {\n\n\t\t\t\t\t\t\t\t\t\t \tvar preserved_sum = 0;\n\t\t\t\t\t\t\t\t\t\t \tvar preserved_count = 0;\n\t\t\t\t\t\t\t\t\t\t \tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t \t\tpreserved_sum = data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t \t\tpreserved_count = data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t\t \t//Extras in this given Billing Mode\n\t\t\t\t\t\t\t\t\t\t \tvar splitExtrasInGivenMode = [];\n\n\t\t\t\t\t\t\t\t\t\t \tif(billingExtras[0]){\n\t\t\t\t\t\t\t\t\t\t \t\tpreProcessBillingSplits(0, billingExtras, splitExtrasInGivenMode)\n\t\t\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t\t \tfunction preProcessBillingSplits(splitIndex, paramsList, formedSplitList){\n\n\n\t\t\t\t\t\t\t\t\t\t \t//For a given Billing Mode, amount split by billing params\n\t\t\t\t\t\t\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\t\t\t\t\t\t type: 'GET',\n\t\t\t\t\t\t\t\t\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbyrefundmodes_splitbyextras?startkey=[\"'+modes[0].name+'\", \"'+paramsList[splitIndex].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[0].name+'\", \"'+paramsList[splitIndex].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t\t\t\t\t\t\t\t\t success: function(data) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\n\t\t\t\t\t\t\t\t\t\t\t\t\t \tvar temp_count = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t \tvar temp_sum = 0;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t \tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\ttemp_count = data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\ttemp_sum = data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t//Now check in custom extras also\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t$.ajax({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: 'GET',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbyrefundmodes_splitbycustomextras?startkey=[\"'+modes[0].name+'\", \"'+paramsList[splitIndex].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[0].name+'\", \"'+paramsList[splitIndex].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttimeout: 10000,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: function(data) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t temp_count += data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t temp_sum += data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//Finally, push it\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\tsplitExtrasInGivenMode.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\"name\": paramsList[splitIndex].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\"value\": temp_sum,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\"count\": temp_count\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t});\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t//Check if next exists in params list:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\tif(paramsList[splitIndex + 1]){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\tpreProcessBillingSplits(splitIndex + 1, paramsList, splitExtrasInGivenMode);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\telse{ \t//Proceed to next BILLING MODE\n\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\t\t\t\t\t\t\t\t\t\t\t\t \tdetailedListByBillingMode.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"name\": modes[0].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\"value\": preserved_sum,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\"count\": preserved_count,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\"split\": splitExtrasInGivenMode\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbillsGraphData.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"name\": modes[0].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"value\": preserved_sum \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t//Check if next exits in BILLING_MODES\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \tif(modes[1]){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\tsingleClickDetailedByModesCallback(1, modes, paramsList);\n\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\t\t\t\t\t\t\t\t\t\t\t\t \telse{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\tsingleClickRenderBillsGraph();\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\t\t\t\t\t\t\t\t\t\t \t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\terror: function(data){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}); \n\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t\t\t\t error: function(data){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t}); \n\t\t\t\t\t\t\t\t\t\t \t} //end - pre process\n\n\n\n\n\n\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t error: function(data){\n\t\t\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\t\t\t\t\t\t\treturn '';\t\t\t\t\t\t\t\t\t\t \t\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t}); \n\t\t\t\t\t\t\t\t\t} //else - mode\n\t\t\t\t\t }\n\t\t\t\t\t }\n\t\t\t\t\t },\n\t\t\t\t\t error: function(data){\n\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t }\n\t\t\t\t\t });\n\n\n\t\t \t}\n\t }\n\t else{\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 8,\n\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\treturn '';\n\t }\n\t }\n\t else{\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 8,\n\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\treturn '';\n\t }\n\t \n\t },\n\t error: function(data) {\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 8,\n\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\treturn '';\n\t }\n\n\t });\t\n\n\t}\n\n\n\t//Step 8 : Callback\n\tfunction singleClickDetailedByModesCallback(index, modes, paramsList){\n\n\t\t\t\t\t\t\t \t//For a given BILLING MODE, the total Sales in the given DATE RANGE\n\t\t\t\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\t\t\t type: 'GET',\n\t\t\t\t\t\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbybillingmode?startkey=[\"'+modes[index].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[index].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t\t\t\t\t\t success: function(data) {\n\n\t\t\t\t\t\t\t\t\t\t \tvar preserved_sum = 0;\n\t\t\t\t\t\t\t\t\t\t \tvar preserved_count = 0;\n\t\t\t\t\t\t\t\t\t\t \tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t \t\tpreserved_sum = data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t \t\tpreserved_count = data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t\t \t//Extras in this given Billing Mode\n\t\t\t\t\t\t\t\t\t\t \tvar splitExtrasInGivenMode = [];\n\n\t\t\t\t\t\t\t\t\t\t \tif(paramsList[0]){\n\t\t\t\t\t\t\t\t\t\t \t\tpreProcessBillingSplits(0, paramsList, splitExtrasInGivenMode)\n\t\t\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t\t \tfunction preProcessBillingSplits(splitIndex, paramsList, formedSplitList){\n\n\t\t\t\t\t\t\t\t\t\t \t//For a given Billing Mode, amount split by billing params\n\t\t\t\t\t\t\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\t\t\t\t\t\t type: 'GET',\n\t\t\t\t\t\t\t\t\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbyrefundmodes_splitbyextras?startkey=[\"'+modes[index].name+'\", \"'+paramsList[splitIndex].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[index].name+'\", \"'+paramsList[splitIndex].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t\t\t\t\t\t\t\t\t success: function(data) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\n\t\t\t\t\t\t\t\t\t\t\t\t\t \tvar temp_count = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t \tvar temp_sum = 0;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t \tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\ttemp_count = data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\ttemp_sum = data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t//Now check in custom extras also\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t$.ajax({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttype: 'GET',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbyrefundmodes_splitbycustomextras?startkey=[\"'+modes[index].name+'\", \"'+paramsList[splitIndex].name+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[index].name+'\", \"'+paramsList[splitIndex].name+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttimeout: 10000,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: function(data) {\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t temp_count += data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t temp_sum += data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//Finally, push it\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\tsplitExtrasInGivenMode.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\"name\": paramsList[splitIndex].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\"value\": temp_sum,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\"count\": temp_count\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t});\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t//Check if next exists in params list:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\tif(paramsList[splitIndex + 1]){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\tpreProcessBillingSplits(splitIndex + 1, paramsList, splitExtrasInGivenMode);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\telse{ \t//Proceed to next BILLING MODE\n\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\t\t\t\t\t\t\t\t\t\t\t\t \tdetailedListByBillingMode.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"name\": modes[index].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\"value\": preserved_sum,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\"count\": preserved_count,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\"split\": splitExtrasInGivenMode\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbillsGraphData.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"name\": modes[index].name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"value\": preserved_sum \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t//Check if next exits in BILLING_MODES\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \tif(modes[index+1]){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\tsingleClickDetailedByModesCallback(index+1, modes, paramsList);\n\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\t\t\t\t\t\t\t\t\t\t\t\t \telse{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\tsingleClickRenderBillsGraph();\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\t\t\t\t\t\t\t\t\t\t \t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\terror: function(data){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}); \n\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t\t\t\t error: function(data){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t}); \n\t\t\t\t\t\t\t\t\t\t \t} //end - pre process\n\n\n\t\t\t\t\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t\t\t error: function(data){\n\t\t\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t\t\t \"step\": 8,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different billing modes\"\n\t\t\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\t\t\t\t\t\t\t\t\treturn '';\t\t\t\t\t\t\t\t\t\t \t\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t}); \n\n\t}\n\n\n\n\t//Step 8-9: Render Graph (Bills)\n\tfunction singleClickRenderBillsGraph(){\n\n\t\t\twindow.localStorage.graphImageDataBills = '';\n\n\t\t\tif(billsGraphData.length == 0){\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickDetailedByPayment(); \n\t\t\t\treturn '';\n\t\t\t}\n\n\t\t\tvar graph_labels = [];\n\t\t\tvar graph_data = [];\n\t\t\tvar graph_background = [];\n\t\t\tvar graph_border = [];\n\n\t\t\tvar m = 0;\n\t\t\tvar totalBaseSum = 0;\n\t\t\twhile(billsGraphData[m]){\n\t\t\t\ttotalBaseSum += billsGraphData[m].value;\n\t\t\t\tm++;\n\t\t\t} \n\n\t\t\tvar n = 0;\n\t\t\twhile(billsGraphData[n]){\n\t\t\t\tvar colorSet = random_rgba_color_set();\n\n\t\t\t\tgraph_labels.push(billsGraphData[n].name);\n\t\t\t\tgraph_data.push(parseFloat(((billsGraphData[n].value/totalBaseSum)*100)).toFixed(1))\n\t\t\t\tgraph_background.push(colorSet[0])\n\t\t\t\tgraph_border.push(colorSet[1])\n\n\t\t\t\tn++;\n\t\t\t}\n\n\n\t\t\tvar ctx = document.getElementById(\"reportGraphBills\").getContext('2d');\n\t\t\tvar myChart = new Chart(ctx, {\n\t\t\t type: 'pie',\n\t\t\t data: {\n\t\t\t labels: graph_labels,\n\t\t\t datasets: [{\n\t\t\t label: 'Billing Modes',\n\t\t\t data: graph_data,\n\t\t\t backgroundColor: graph_background,\n\t\t\t borderColor: graph_border,\n\t\t\t borderWidth: 1\n\t\t\t }]\n\t\t\t },\n\t\t\t options: { \t\n\t\t\t scales: {\n\t\t\t yAxes: [{\n\t\t\t \tdisplay:false,\n\t\t\t ticks: {\n\t\t\t beginAtZero:true,\n\t\t\t display: false\n\t\t\t },\n\t\t\t gridLines: {\n\t\t \tdisplay:false\n\t\t \t}\n\t\t\t }]\n\t\t\t },\n\t\t\t animation: {\n\t\t onComplete: convertGraph\n\t\t }\n\t\t\t }\n\t\t\t});\t\n\n\t\t\tfunction convertGraph(){\n\t\t\t\tvar temp_graph = myChart.toBase64Image();\n\n\t\t\t\twindow.localStorage.graphImageDataBills = temp_graph;\n\n\t\t\t\t//Go to Step 9\n\t\t\t\tsingleClickDetailedByPayment();\n\t\t\t}\n\t}\n\n\n\t//Step 9: Details by Payment types\n\tfunction singleClickDetailedByPayment(){\n\n\t\trunReportAnimation(65); //of Step 8 which takes 25 units\n\n\t\tpaymentGraphData = [];\n\n\t var requestData = {\n\t \"selector\" :{ \n\t \"identifierTag\": \"ACCELERATE_PAYMENT_MODES\" \n\t },\n\t \"fields\" : [\"identifierTag\", \"value\"]\n\t }\n\n\t $.ajax({\n\t type: 'POST',\n\t url: COMMON_LOCAL_SERVER_IP+'/accelerate_settings/_find',\n\t data: JSON.stringify(requestData),\n\t contentType: \"application/json\",\n\t dataType: 'json',\n\t timeout: 10000,\n\t success: function(data) {\n\n\t if(data.docs.length > 0){\n\t if(data.docs[0].identifierTag == 'ACCELERATE_PAYMENT_MODES'){\n\n\t \tvar modes = data.docs[0].value;\n\n\t \tif(modes.length == 0){\n\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t \"step\": 9,\n\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\tsingleClickWeeklyProgress(); \n\t\t\t\t\t\treturn '';\n\t\t \t}\n\t\t \telse{\n\t\t\t\t\t\t\n\t\t\t\t\t\t //For a given PAYMENT MODE, the total Sales in the given DATE RANGE\n\n\t\t\t\t\t\t $.ajax({\n\t\t\t\t\t\t type: 'GET',\n\t\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbypaymentmode?startkey=[\"'+modes[0].code+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[0].code+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t\t success: function(data) {\n\t\t\t\t\t\t \t\n\t\t\t\t\t\t \tvar temp_count = 0;\n\t\t\t\t\t\t \tvar temp_sum = 0;\n\n\t\t\t\t\t\t \tif(data.rows.length > 0){\n\t\t\t\t\t\t \t\ttemp_count = data.rows[0].value.count;\n\t\t\t\t\t\t \t\ttemp_sum = data.rows[0].value.sum;\n\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t \t\t//Now check in split payments\n\t\t\t\t\t\t\t \t$.ajax({\n\t\t\t\t\t\t\t\t\t\ttype: 'GET',\n\t\t\t\t\t\t\t\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbypaymentmode_multiple?startkey=[\"'+modes[0].code+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[0].code+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\t\ttimeout: 10000,\n\t\t\t\t\t\t\t\t\t\tsuccess: function(data) {\n\n\t\t\t\t\t\t\t\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t\t temp_count += data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t\t temp_sum += data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t \t\tif(temp_sum > 0){\n\t\t\t\t\t\t\t\t \t\t\tpaymentGraphData.push({\n\t\t\t\t\t\t\t\t\t\t \t\t\"name\": modes[0].name,\n\t\t\t\t\t\t\t\t\t\t \t\t\"value\": temp_sum\n\t\t\t\t\t\t\t\t\t\t \t})\n\t\t\t\t\t\t\t\t \t\t}\t\n\n\t\t\t\t\t\t\t\t \t\tdetailedListByPaymentMode.push({\n\t\t\t\t\t\t\t\t \t\t\t\"name\": modes[0].name,\n\t\t\t\t\t\t\t\t \t\t\t\"value\": temp_sum,\n\t\t\t\t\t\t\t\t \t\t\t\"count\": temp_count\n\t\t\t\t\t\t\t\t \t\t});\t\t\t\t\t\t\t\t\t\n\n\n\t\t\t\t\t\t\t\t\t \t//Check if next mode exists...\n\t\t\t\t\t\t\t\t\t \tif(modes[1]){\n\t\t\t\t\t\t\t\t\t \t\tsingleClickDetailedByPaymentCallback(1, modes, paymentGraphData);\n\t\t\t\t\t\t\t\t\t \t}\n\t\t\t\t\t\t\t\t\t \telse{\n\t\t\t\t\t\t\t\t\t \t\t//Step 10: Weekly Progress\n\t\t\t\t\t\t\t\t\t \t\tsingleClickWeeklyProgress();\n\t\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\terror: function(data){\n\t\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t\t \"step\": 9,\n\t\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\t\tsingleClickWeeklyProgress(); \n\t\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}); \n\n\n\t\t\t\t\t\t },\n\t\t\t\t\t\t error: function(data){\n\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t \"step\": 9,\n\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t//Step 9-10: Render the Payment Graph \n\t\t\t\t\t\t\t\tsingleClickRenderPaymentsGraph(); \n\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t }\n\t\t\t\t\t\t }); \n\t\t\t\t\t} \n\n\t }\n\t else{\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 9,\n\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickWeeklyProgress(); \n\t\t\t\treturn '';\n\t }\n\t }\n\t else{\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 9,\n\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickWeeklyProgress(); \n\t\t\t\treturn '';\n\t }\n\t },\n\t error: function(data) {\n\t\t\t\tcompleteErrorList.push({\n\t\t\t\t \"step\": 9,\n\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t});\t\t\t\t\n\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickWeeklyProgress(); \n\t\t\t\treturn '';\n\t }\n\n\t });\n\t}\n\n\t//Step 9: Callback\n\tfunction singleClickDetailedByPaymentCallback(index, modes, paymentGraphData){\n\n\t\t\t\t\t\t //For a given PAYMENT MODE, the total Sales in the given DATE RANGE\n\n\t\t\t\t\t\t $.ajax({\n\t\t\t\t\t\t type: 'GET',\n\t\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbypaymentmode?startkey=[\"'+modes[index].code+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[index].code+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t\t success: function(data) {\n\t\t\t\t\t\t \t\n\t\t\t\t\t\t \tvar temp_count = 0;\n\t\t\t\t\t\t \tvar temp_sum = 0;\n\n\t\t\t\t\t\t \tif(data.rows.length > 0){\n\t\t\t\t\t\t \t\ttemp_count = data.rows[0].value.count;\n\t\t\t\t\t\t \t\ttemp_sum = data.rows[0].value.sum;\n\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t \t\t//Now check in split payments\n\t\t\t\t\t\t\t \t$.ajax({\n\t\t\t\t\t\t\t\t\t\ttype: 'GET',\n\t\t\t\t\t\t\t\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/sumbypaymentmode_multiple?startkey=[\"'+modes[index].code+'\",\"'+fromDate+'\"]&endkey=[\"'+modes[index].code+'\",\"'+toDate+'\"]',\n\t\t\t\t\t\t\t\t\t\ttimeout: 10000,\n\t\t\t\t\t\t\t\t\t\tsuccess: function(data) {\n\n\t\t\t\t\t\t\t\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\t\t\t\t\t\t\t temp_count += data.rows[0].value.count;\n\t\t\t\t\t\t\t\t\t\t\t temp_sum += data.rows[0].value.sum;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t \t\tif(temp_sum > 0){\n\t\t\t\t\t\t\t\t \t\t\tpaymentGraphData.push({\n\t\t\t\t\t\t\t\t\t\t \t\t\"name\": modes[index].name,\n\t\t\t\t\t\t\t\t\t\t \t\t\"value\": temp_sum\n\t\t\t\t\t\t\t\t\t\t \t})\n\t\t\t\t\t\t\t\t \t\t}\t\n\n\t\t\t\t\t\t\t\t \t\tdetailedListByPaymentMode.push({\n\t\t\t\t\t\t\t\t \t\t\t\"name\": modes[index].name,\n\t\t\t\t\t\t\t\t \t\t\t\"value\": temp_sum,\n\t\t\t\t\t\t\t\t \t\t\t\"count\": temp_count\n\t\t\t\t\t\t\t\t \t\t});\t\t\t\t\t\t\t\t\t\n\n\n\t\t\t\t\t\t\t\t\t \t//Check if next mode exists...\n\t\t\t\t\t\t\t\t\t \tif(modes[index+1]){\n\t\t\t\t\t\t\t\t\t \t\tsingleClickDetailedByPaymentCallback(index+1, modes, paymentGraphData);\n\t\t\t\t\t\t\t\t\t \t}\n\t\t\t\t\t\t\t\t\t \telse{\n\t\t\t\t\t\t\t\t\t \t\t//Step 9-10: Render the Payment Graph \n\t\t\t\t\t\t\t\t\t \t\tsingleClickRenderPaymentsGraph();\n\t\t\t\t\t\t\t\t\t \t}\n\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\terror: function(data){\n\t\t\t\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t\t\t\t \"step\": 9,\n\t\t\t\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\t\t\t\tsingleClickWeeklyProgress(); \n\t\t\t\t\t\t\t\t\t\t\treturn '';\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}); \n\t\t\t\t\t\t\t},\n\t\t\t\t\t \terror: function(data) {\n\t\t\t\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t\t\t\t \"step\": 9,\n\t\t\t\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\t\t\t\tsingleClickWeeklyProgress(); \n\t\t\t\t\t\t\t\treturn '';\t\t\t\t\t \t\n\t\t\t\t\t \t}\n\t\t\t\t\t });\n\t}\n\n\n\t//Step 9-10: Render Graph (Payments)\n\tfunction singleClickRenderPaymentsGraph(){\n\n\t\t\twindow.localStorage.graphImageDataPayments = '';\n\n\t\t\tif(paymentGraphData.length == 0){\n\t\t\t\t//Skip and go to next step\n\t\t\t\tsingleClickWeeklyProgress(); \n\t\t\t\treturn '';\n\t\t\t}\n\n\t\t\tvar graph_labels = [];\n\t\t\tvar graph_data = [];\n\t\t\tvar graph_background = [];\n\t\t\tvar graph_border = [];\n\n\t\t\tvar m = 0;\n\t\t\tvar totalBaseSum = 0;\n\t\t\twhile(paymentGraphData[m]){\n\t\t\t\ttotalBaseSum += paymentGraphData[m].value;\n\t\t\t\tm++;\n\t\t\t} \n\n\t\t\tvar n = 0;\n\t\t\twhile(paymentGraphData[n]){\n\t\t\t\tvar colorSet = random_rgba_color_set();\n\n\t\t\t\tgraph_labels.push(paymentGraphData[n].name);\n\t\t\t\tgraph_data.push(parseFloat(((paymentGraphData[n].value/totalBaseSum)*100)).toFixed(1))\n\t\t\t\tgraph_background.push(colorSet[0])\n\t\t\t\tgraph_border.push(colorSet[1])\n\n\t\t\t\tn++;\n\t\t\t}\n\n\n\t\t\tvar ctx = document.getElementById(\"reportGraphPayments\").getContext('2d');\n\t\t\tvar myChart = new Chart(ctx, {\n\t\t\t type: 'pie',\n\t\t\t data: {\n\t\t\t labels: graph_labels,\n\t\t\t datasets: [{\n\t\t\t label: 'Payment Types',\n\t\t\t data: graph_data,\n\t\t\t backgroundColor: graph_background,\n\t\t\t borderColor: graph_border,\n\t\t\t borderWidth: 1\n\t\t\t }]\n\t\t\t },\n\t\t\t options: {\t \t\n\t\t\t scales: {\n\t\t\t yAxes: [{\n\t\t\t \tdisplay:false,\n\t\t\t ticks: {\n\t\t\t beginAtZero:true,\n\t\t\t display: false\n\t\t\t },\n\t\t\t gridLines: {\n\t\t \tdisplay:false\n\t\t \t}\n\t\t\t }]\n\t\t\t },\n\t\t\t animation: {\n\t\t onComplete: convertGraph\n\t\t }\n\t\t\t }\n\t\t\t});\t\n\t\t\tfunction convertGraph(){\n\t\t\t\tvar temp_graph = myChart.toBase64Image();\n\n\t\t\t\twindow.localStorage.graphImageDataPayments = temp_graph;\n\n\t\t\t\t//Go to Step 10\n\t\t\t\tsingleClickWeeklyProgress();\n\t\t\t}\n\t}\n\n\n\t//Step 10: Weekly Progress\n\tfunction singleClickWeeklyProgress(){\n\n\t\trunReportAnimation(75); //of Step 9 which takes 10 units\n\t\t\n\t\t/*\n\t\t\tNote: Rough figure only, refunds not included.\n\t\t*/\n\n\t\tvar lastWeek_start = moment(fromDate, 'YYYYMMDD').subtract(13, 'days').format('YYYYMMDD');\n\n\t\tvar currentIndex = 1;\n\n\t\tcalculateSalesByDate(currentIndex, lastWeek_start)\n\n\t\tfunction calculateSalesByDate(index, mydate){\n\n\t\t\trunReportAnimation(74 + index);\n\n\t\t\t$.ajax({\n\t\t\t type: 'GET',\n\t\t\t\turl: COMMON_LOCAL_SERVER_IP+'/'+SELECTED_INVOICE_SOURCE_DB+'/_design/invoice-summary/_view/grandtotal_paidamount?startkey=[\"'+mydate+'\"]&endkey=[\"'+mydate+'\"]',\n\t\t\t\ttimeout: 10000,\n\t\t\t\tsuccess: function(data) {\n\n\t\t\t\t\tvar temp_totalOrders = 0;\n\t\t\t\t\tvar temp_totalPaid = 0;\n\t\t\t\t\tvar fancyDay = moment(mydate, 'YYYYMMDD').format('ddd');\n\t\t\t\t\tvar fancyDate = moment(mydate, 'YYYYMMDD').format('MMM D');\n\n\t\t\t\t\tif(data.rows.length > 0){\n\t\t\t\t\t\ttemp_totalOrders = data.rows[0].value.count;\n\t\t\t\t\t\ttemp_totalPaid = data.rows[0].value.sum;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(index <= 7){\n\t\t\t\t\t\tweeklyProgressLastWeek.push({\n\t\t\t\t\t\t\t\"name\": fancyDay+' ('+fancyDate+')',\n\t\t\t\t\t\t\t\"value\": temp_totalPaid\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse if(index <= 14){\n\t\t\t\t\t\tweeklyProgressThisWeek.push({\n\t\t\t\t\t\t\t\"name\": fancyDay+' ('+fancyDate+')',\n\t\t\t\t\t\t\t\"value\": temp_totalPaid\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\n\t\t\t\t\t//Next iterations\n\t\t\t\t\tif(index < 14){\n\t\t\t\t\t\tvar nextDate = moment(fromDate, 'YYYYMMDD').subtract((13 - index), 'days').format('YYYYMMDD');\n\t\t\t\t\t\tcalculateSalesByDate(index+1, nextDate);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tsingleClickWeeklyWeeklyGraphRenderer();\n\t\t\t\t\t}\n\n\t\t\t\t},\n\t\t\t\terror: function(data){\n\t\t\t\t\tcompleteErrorList.push({\n\t\t\t\t\t \"step\": 9,\n\t\t\t\t\t\t\"error\": \"Failed to calculate sales by different payment modes\"\n\t\t\t\t\t});\t\t\t\t\n\n\t\t\t\t\t//Skip and go to next step\n\t\t\t\t\tsingleClickWeeklyWeeklyGraphRenderer(); \n\t\t\t\t\treturn '';\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}); \n\t\t}\n\n\t}\n\n\t//Step 11: Render Weekly Graph\n\tfunction singleClickWeeklyWeeklyGraphRenderer(){\n\n\t\trunReportAnimation(90); //of Step 10 which takes 14 units\n\n\t\tif(fromDate != toDate){\n\t\t\t//Skip and go to next step\n\t\t\tsingleClickGenerateAllReports();\n\t\t\treturn '';\n\t\t}\n\t\telse{\n\t\t\twindow.localStorage.graphImageDataWeekly = '';\n\t\t\twindow.localStorage.graphImageDataWeeklyBW = '';\n\t\t\tweeklyGraphBW();\n\t\t}\n\n\t\tfunction weeklyGraphBW(){\n\n\t\t\tvar graph_labels = [];\n\t\t\tvar graph_data = [];\n\n\t\t\tvar graph_border = [\"rgba(0, 0, 0, 1)\"];\n\t\t\tvar graph_border_last = [\"rgba(144, 144, 144, 1)\"];\n\n\t\t\t//This Weeks data\n\t\t\tvar n = 0;\n\t\t\twhile(weeklyProgressThisWeek[n]){\n\t\t\t\tgraph_labels.push(weeklyProgressThisWeek[n].name);\n\t\t\t\tgraph_data.push(parseInt(weeklyProgressThisWeek[n].value));\n\n\t\t\t\tn++;\n\t\t\t}\n\n\t\t\t//Last Weeks (exclude labels)\n\t\t\tvar graph_data_last = [];\n\t\t\tvar k = 0;\n\t\t\twhile(weeklyProgressLastWeek[k]){\n\t\t\t\tgraph_data_last.push(parseInt(weeklyProgressLastWeek[k].value));\n\t\t\t\t\n\t\t\t\tk++;\n\t\t\t}\n\n\t\t\tvar ctx = document.getElementById(\"weeklyTrendLineChartBW\").getContext('2d');\n\t\t\tvar myChart = new Chart(ctx, {\n\t\t\t type: 'line',\n\t\t\t data: {\n\t\t\t labels: graph_labels,\n\t\t\t datasets: [{\n\t\t\t label: 'This Week',\n\t\t\t data: graph_data,\n\t\t\t fill: false,\n\t\t\t borderColor: graph_border,\n\t\t\t borderWidth: 2\n\t\t\t \n\t\t\t },{\n\t\t\t label: 'Last Week',\n\t\t\t data: graph_data_last,\n\t\t\t fill: false,\n\t\t\t borderColor: graph_border_last,\n\t\t\t borderWidth: 2,\n\t\t\t borderDash: [10,5]\n\t\t\t }]\n\t\t\t },\n\t\t\t options: {\t \t\n\t\t\t scales: {\n\t\t\t yAxes: [{\n\t\t\t \tdisplay:true,\n\t\t\t ticks: {\n\t\t\t beginAtZero:true,\n\t\t\t display: true\n\t\t\t },\n\t\t\t gridLines: {\n\t\t \tdisplay:true\n\t\t \t}\n\t\t\t }],\n\t\t\t xAxes: [{\n\t\t\t \tdisplay:true,\n\t\t\t ticks: {\n\t\t\t beginAtZero:true,\n\t\t\t display: true\n\t\t\t },\n\t\t\t gridLines: {\n\t\t \tdisplay:false\n\t\t \t}\n\t\t\t }]\n\t\t\t },\n\t\t\t animation: {\n\t\t onComplete: convertGraph\n\t\t }\n\t\t\t }\n\t\t\t});\t\n\n\t\t\tfunction convertGraph(){\n\t\t\t\tvar temp_graph = myChart.toBase64Image();\n\t\t\t\twindow.localStorage.graphImageDataWeeklyBW = temp_graph;\n\n\t\t\t\tweeklyGraphColored();\t\t\t\n\t\t\t}\n\t\t}\n\n\n\n\t\tfunction weeklyGraphColored(){ //Colorfull Graph!\n\n\t\t\tvar graph_labels = [];\n\t\t\tvar graph_data = [];\n\n\t\t\tvar graph_background = [\"rgba(103, 210, 131, 0.2)\"];\n\t\t\tvar graph_background_last = [\"rgba(255, 177, 0, 0.2)\"];\n\n\t\t\tvar graph_border = [\"rgba(103, 210, 131, 1)\"];\n\t\t\tvar graph_border_last = [\"rgba(255, 177, 0, 1)\"];\n\n\t\t\t//This Weeks data\n\t\t\tvar n = 0;\n\t\t\twhile(weeklyProgressThisWeek[n]){\n\t\t\t\tgraph_labels.push(weeklyProgressThisWeek[n].name);\n\t\t\t\tgraph_data.push(parseInt(weeklyProgressThisWeek[n].value));\n\n\t\t\t\tn++;\n\t\t\t}\n\n\n\t\t\t//Last Weeks (exclude labels)\n\t\t\tvar graph_data_last = [];\n\t\t\tvar k = 0;\n\t\t\twhile(weeklyProgressLastWeek[k]){\n\t\t\t\tgraph_data_last.push(parseInt(weeklyProgressLastWeek[k].value));\n\t\t\t\t\n\t\t\t\tk++;\n\t\t\t}\n\n\t\t\tvar ctx = document.getElementById(\"weeklyTrendLineChart\").getContext('2d');\n\t\t\tvar myChart = new Chart(ctx, {\n\t\t\t type: 'line',\n\t\t\t data: {\n\t\t\t labels: graph_labels,\n\t\t\t datasets: [{\n\t\t\t label: 'This Week',\n\t\t\t data: graph_data,\n\t\t\t borderColor: graph_border,\n\t\t\t backgroundColor: graph_background,\n\t\t\t borderWidth: 2\n\t\t\t \n\t\t\t },{\n\t\t\t label: 'Last Week',\n\t\t\t data: graph_data_last,\n\t\t\t backgroundColor: graph_background_last,\n\t\t\t borderColor: graph_border_last,\n\t\t\t borderWidth: 2,\n\t\t\t borderDash: [10,5]\n\t\t\t }]\n\t\t\t },\n\t\t\t options: {\t \t\n\t\t\t scales: {\n\t\t\t yAxes: [{\n\t\t\t \tdisplay:true,\n\t\t\t ticks: {\n\t\t\t beginAtZero:true,\n\t\t\t display: true\n\t\t\t },\n\t\t\t gridLines: {\n\t\t \tdisplay:true\n\t\t \t}\n\t\t\t }],\n\t\t\t xAxes: [{\n\t\t\t \tdisplay:true,\n\t\t\t ticks: {\n\t\t\t beginAtZero:true,\n\t\t\t display: true\n\t\t\t },\n\t\t\t gridLines: {\n\t\t \tdisplay:false\n\t\t \t}\n\t\t\t }]\n\t\t\t },\n\t\t\t animation: {\n\t\t onComplete: convertGraph\n\t\t }\n\t\t\t }\n\t\t\t});\t\n\n\t\t\tfunction convertGraph(){\n\t\t\t\tvar temp_graph = myChart.toBase64Image();\n\t\t\t\twindow.localStorage.graphImageDataWeekly = temp_graph;\n\n\t\t\t\tsingleClickGenerateAllReports();\n\t\t\t}\n\t\t}\n\t}\n\n\n\t//Step 12: Final Reports Render Stage\n\tfunction singleClickGenerateAllReports(){\n\n\n\t //PENDING --> TOTAL CALCULATED ROUND OFFFFF\n\t console.log('PENDING API --> TOTAL CALCULATED ROUND OFFFFF')\n\t \n\n\t\trunReportAnimation(95); //of Step 11 which completed the data processing\n\n\n\t\t//Get staff info.\n\t\tvar loggedInStaffInfo = window.localStorage.loggedInStaffData ? JSON.parse(window.localStorage.loggedInStaffData) : {};\n\t\t\n\t\tif(jQuery.isEmptyObject(loggedInStaffInfo)){\n\t\t\tloggedInStaffInfo.name = 'Staff';\n\t\t\tloggedInStaffInfo.code = '0000000000';\n\t\t}\t\n\n\n\t\tvar reportInfo_branch = window.localStorage.accelerate_licence_branch_name ? window.localStorage.accelerate_licence_branch_name : '';\n\t\t\t\n\t\tif(reportInfo_branch == ''){\n\t\t\tshowToast('System Error: Branch name not found. Please contact Accelerate Support.', '#e74c3c');\n\t\t\treturn '';\n\t\t}\n\n\t\tvar temp_address_modified = (window.localStorage.accelerate_licence_branch_name ? window.localStorage.accelerate_licence_branch_name : '') + ' - ' + (window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name : '');\n\t\tvar data_custom_footer_address = window.localStorage.bill_custom_footer_address ? window.localStorage.bill_custom_footer_address : '';\n\n\t\tvar reportInfo_admin = loggedInStaffInfo.name;\n\t\tvar reportInfo_time = moment().format('h:mm a, DD-MM-YYYY');\n\t\tvar reportInfo_address = data_custom_footer_address != '' ? data_custom_footer_address : temp_address_modified;\n\n\n\t\t//Reset Token Number and KOT Number (if preference set)\n\t\tresetBillingCounters();\n\n\t\tgenerateReportContentDownload();\n\n\t\tfunction generateReportContentDownload(){\n\n\t\t\t//To display weekly graph or not\n\t\t\tvar hasWeeklyGraphAttached = false;\n\t\t\tif(window.localStorage.graphImageDataWeekly && window.localStorage.graphImageDataWeekly != ''){\n\t\t\t\thasWeeklyGraphAttached = true;\n\t\t\t}\n\n\t\t\tvar graphRenderSectionContent = '';\n\t\t\tvar fancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY - dddd');\n\n\t\t\tvar reportInfo_title = 'Sales Report of <b>'+fancy_from_date+'</b>';\n\t\t\tvar temp_report_title = 'Sales Report of '+fancy_from_date;\n\t\t\tif(fromDate != toDate){\n\t\t\t\tfancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\t\t\t\tvar fancy_to_date = moment(toDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\n\t\t\t\treportInfo_title = 'Sales Report from <b>'+fancy_from_date+'</b> to <b>'+fancy_to_date+'</b>';\n\t\t\t\ttemp_report_title = 'Sales Report from '+fancy_from_date+' to '+fancy_to_date;\n\t\t\t}\n\t\t else{ //Render graph only if report is for a day\n\n\t\t if(hasWeeklyGraphAttached){\n\n\t\t \tvar temp_image_name = reportInfo_branch+'_'+fromDate;\n\t\t \ttemp_image_name = temp_image_name.replace(/\\s/g,'');\n\n\t\t graphRenderSectionContent = ''+\n\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t '<div class=\"summaryTableSection\">'+\n\t\t '<div class=\"tableQuickHeader\">'+\n\t\t '<h1 class=\"tableQuickHeaderText\">WEEKLY SALES TREND</h1>'+\n\t\t '</div>'+\n\t\t '<div class=\"weeklyGraph\">'+\n\t\t '<img src=\"'+window.localStorage.graphImageDataWeekly+'\" style=\"max-width: 90%\">'+\n\t\t '</div>'+\n\t\t '</div>'+\n\t\t '</div>';\n\t\t }\n\t\t }\n\n\t\t var fancy_report_title_name = reportInfo_branch+' - '+temp_report_title;\n\n\t\t //Quick Summary Content\n\t\t var quickSummaryRendererContent = '';\n\n\t\t var a = 0;\n\t\t while(reportInfoExtras[a]){\n\t\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+reportInfoExtras[a].name+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(reportInfoExtras[a].value).toFixed(2)+'</td></tr>';\n\t\t a++;\n\t\t }\n\n\n\t\t var b = 1; //first one contains total paid\n\t\t while(completeReportInfo[b]){\n\t\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+completeReportInfo[b].name+'</td><td class=\"tableQuickAmount\">'+(completeReportInfo[b].type == 'NEGATIVE' && completeReportInfo[b].value != 0 ? '- ' : '')+'<span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[b].value).toFixed(2)+'</td></tr>';\n\t\t b++;\n\t\t }\n\n\n\t\t //Sales by Billing Modes Content\n\t\t var salesByBillingModeRenderContent = '';\n\t\t var c = 0;\n\t\t var billSharePercentage = 0;\n\t\t while(detailedListByBillingMode[c]){\n\t\t billSharePercentage = parseFloat((100*detailedListByBillingMode[c].value)/completeReportInfo[0].value).toFixed(0);\n\t\t salesByBillingModeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByBillingMode[c].name+' '+(billSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+billSharePercentage+'%)</span>' : '')+(detailedListByBillingMode[c].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByBillingMode[c].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByBillingMode[c].value).toFixed(0)+'</td></tr>';\n\t\t c++;\n\t\t }\n\n\t\t\t//To display bills graph or not\n\t\t\tvar hasBillsGraphAttached = false;\n\t\t\tif(window.localStorage.graphImageDataBills && window.localStorage.graphImageDataBills != '' && window.localStorage.graphImageDataBills != 'data:,'){\n\t\t\t\thasBillsGraphAttached = true;\n\t\t\t}\n\n\t\t var salesByBillingModeRenderContentFinal = '';\n\t\t if(salesByBillingModeRenderContent != ''){\n\n\t\t \tif(hasBillsGraphAttached){\n\t\t\t\t salesByBillingModeRenderContentFinal = ''+\n\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t \t'<div class=\"tableQuickHeader\">'+\n\t\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY BILLS</h1>'+\n\t\t\t\t \t'</div>'+\n\t\t\t\t \t'<div class=\"tableGraphRow\">'+\n\t\t\t\t\t\t '<div class=\"tableGraph_Graph\"> <img src=\"'+window.localStorage.graphImageDataBills+'\" width=\"200px\"> </div>'+\n\t\t\t\t\t\t '<div class=\"tableGraph_Table\">'+\t\n\t\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t\t salesByBillingModeRenderContent+\n\t\t\t\t\t '</table>'+\n\t\t\t\t\t '</div>'+\n\t\t\t\t\t '</div>'+\t\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t salesByBillingModeRenderContentFinal = ''+\n\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY BILLS</h1>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t salesByBillingModeRenderContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>';\t\t\t\t\n\t\t\t\t}\n\t\t }\n\n\n\t\t //Sales by Payment Types Content\n\t\t var salesByPaymentTypeRenderContent = '';\n\t\t var d = 0;\n\t\t var paymentSharePercentage = 0;\n\t\t while(detailedListByPaymentMode[d]){\n\t\t paymentSharePercentage = parseFloat((100*detailedListByPaymentMode[d].value)/completeReportInfo[0].value).toFixed(0);\n\t\t salesByPaymentTypeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByPaymentMode[d].name+' '+(paymentSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+paymentSharePercentage+'%)</span>' : '')+(detailedListByPaymentMode[d].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByPaymentMode[d].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByPaymentMode[d].value).toFixed(0)+'</td></tr>';\n\t\t d++;\n\t\t }\n\n\t\t\t//To display payment graph or not\n\t\t\tvar hasPaymentsGraphAttached = false;\n\t\t\tif(window.localStorage.graphImageDataPayments && window.localStorage.graphImageDataPayments != '' && window.localStorage.graphImageDataPayments != 'data:,'){\n\t\t\t\thasPaymentsGraphAttached = true;\n\t\t\t}\n\n\t\t var salesByPaymentTypeRenderContentFinal = '';\n\t\t if(salesByPaymentTypeRenderContent != ''){\n\n\t\t \tif(hasPaymentsGraphAttached){\n\t\t\t salesByPaymentTypeRenderContentFinal = ''+\n\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t \t'<div class=\"tableQuickHeader\">'+\n\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY PAYMENT</h1>'+\n\t\t\t \t'</div>'+\n\t\t\t \t'<div class=\"tableGraphRow\">'+\n\t\t\t\t\t '<div class=\"tableGraph_Graph\"> <img src=\"'+window.localStorage.graphImageDataPayments+'\" width=\"200px\"> </div>'+\n\t\t\t\t\t '<div class=\"tableGraph_Table\">'+\t\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t salesByPaymentTypeRenderContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>';\n\t\t\t }\n\t\t\t else{\n\t\t\t \tsalesByPaymentTypeRenderContentFinal = ''+\n\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY PAYMENT</h1>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t salesByPaymentTypeRenderContent+\n\t\t\t '</table>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>';\n\t\t\t }\n\t\t }\n\n\t\t var temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\t\t var cssData = '<head> <style type=\"text/css\"> body{font-family:sans-serif;margin:0}#logo{min-height:60px;width:100%}.mainHeader{background:url(https://accelerateengine.app/clients/'+temp_licenced_client+'/pattern.jpg) #c63931;width:100%;min-height:95px;padding:10px 0;border-bottom:2px solid #a8302b}.headerLeftBox{width:55%;display:inline-block;padding-left:25px}.headerRightBox{width:35%;float:right;display:inline-block;text-align:right;padding-right:25px}.headerAddress{margin:0 0 5px;font-size:14px;color:#e4a1a6}.headerBranch{margin:10px 0;font-weight:700;text-transform:uppercase;font-size:21px;padding:3px 8px;color:#c63931;display:inline-block;background:#FFF}.headerAdmin{margin:0 0 3px;font-size:16px;color:#FFF}.headerTimestamp{margin:0 0 5px;font-size:12px;color:#e4a1a6}.reportTitle{margin:15px 0;font-size:26px;font-weight:400;text-align:center;color:#3498db}.introFacts{background:0 0;width:100%;min-height:95px;padding:10px 0}.factsArea{display:block;padding:10px;text-align:center}.factsBox{margin-right: 5px; width:18%; display:inline-block;text-align:left;padding:20px 15px;border:2px solid #a8302b;border-radius:5px;color:#FFF;height:65px;background:#c63931}.factsBoxFigure{margin:0 0 8px;font-weight:700;font-size:32px}.factsBoxFigure .factsPrice{font-weight:400;font-size:40%;color:#e4a1a6;margin-left:2px}.factsBoxBrief{margin:0;font-size:16px;color:#F1C40F;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.summaryTableSectionHolder{width:100%}.summaryTableSection{padding:0 25px;margin-top:30px}.summaryTableSection table{border-collapse:collapse}.summaryTableSection td{border-bottom:1px solid #fdebed}.tableQuick{padding:10px}.tableQuickHeader{min-height:40px;background:#c63931;border-bottom:3px solid #a8302b;border-top-right-radius:15px;color:#FFF}.tableQuickHeaderText{margin:0 0 0 25px;font-size:18px;letter-spacing:2px;text-transform:uppercase;padding-top:10px;font-weight:700}.smallOrderCount{font-size:80%;margin-left:15px;color:#aba9a9;font-style:italic;}.tableQuickBrief{padding:10px;font-size:16px;color:#a71a14}.tableQuickAmount{padding:10px;font-size:18px;text-align:right;color:#a71a14}.tableQuickAmount .price{font-size:70%;margin-right:2px}.tableGraphRow{position:relative}.tableGraph_Graph{width:35%;display:block;text-align:center;float:right;position:absolute;top:20px;left:62%}.footerNote,.weeklyGraph{text-align:center;margin:0}.tableGraph_Table{padding:10px;width:55%;display:block;min-height:250px;}.weeklyGraph{padding:25px;border:1px solid #f2f2f2;border-top:none}.footerNote{font-size:12px;color:#595959}@media screen and (max-width:1000px){.headerLeftBox{display:none!important}.headerRightBox{padding-right:5px!important;width:90%!important}.reportTitle{font-size:18px!important}.tableQuick{padding:0 0 5px!important}.factsArea{padding:5px!important}.factsBox{width:90%!important;margin:0 0 5px!important}.smallOrderCount{margin:0!important;display:block!important}.summaryTableSection{padding:0 5px!important}}</style> </head>';\n\t\t \n\t\t var finalReport_downloadContent = cssData+\n\t\t\t '<body>'+\n\t\t\t '<div class=\"mainHeader\">'+\n\t\t\t '<div class=\"headerLeftBox\">'+\n\t\t\t '<div id=\"logo\">'+\n\t\t\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/email_logo.png\">'+\n\t\t\t '</div>'+\n\t\t\t '<p class=\"headerAddress\">'+reportInfo_address+'</p>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"headerRightBox\">'+\n\t\t\t '<h1 class=\"headerBranch\">'+reportInfo_branch+'</h1>'+\n\t\t\t '<p class=\"headerAdmin\">'+reportInfo_admin+'</p>'+\n\t\t\t '<p class=\"headerTimestamp\">'+reportInfo_time+'</p>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"introFacts\">'+\n\t\t\t '<h1 class=\"reportTitle\">'+reportInfo_title+'</h1>'+\n\t\t\t '<div class=\"factsArea\">'+\n\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(0)+' <span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Net Sales</p></div>'+ \n\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(netSalesWorth).toFixed(0)+'<span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Gross Sales</p></div>'+ \n\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+netGuestsCount+'</h1><p class=\"factsBoxBrief\">Guests</p></div>'+ \n\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+completeReportInfo[0].count+'</h1><p class=\"factsBoxBrief\">Bills</p></div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+graphRenderSectionContent+\n\t\t\t (hasWeeklyGraphAttached ? '<div style=\"page-break-before: always; margin-top: 20px\"></div><div style=\"height: 30px; width: 100%; display: block\"></div>' : '')+\n\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t '<h1 class=\"tableQuickHeaderText\">Quick Summary</h1>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t '<tr><td class=\"tableQuickBrief\" style=\"font-weight: bold;\">Gross Amount</td><td class=\"tableQuickAmount\" style=\"font-weight: bold;\"><span class=\"price\">Rs.</span>'+parseFloat(netSalesWorth).toFixed(2)+'</td></tr>'+\n\t\t\t quickSummaryRendererContent+\n\t\t\t '<tr><td class=\"tableQuickBrief\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\">Net Sales</td><td class=\"tableQuickAmount\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\"><span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(2)+'</td></tr>'+\n\t\t\t '</table>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '<div style=\"page-break-before: always; margin-top: 20px\"></div><div style=\"height: 30px; width: 100%; display: block\"></div>'+\n\t\t\t salesByBillingModeRenderContentFinal+\n\t\t\t salesByPaymentTypeRenderContentFinal+\n\t\t\t '<div style=\"border-top: 2px solid #989898; padding: 12px; background: #f2f2f2;\">'+\n\t\t\t '<p class=\"footerNote\">www.accelerate.net.in | [email protected]</p>'+\n\t\t\t '</div>'+\n\t\t\t '</body>';\n\n\t\t\t\tvar finalContent_EncodedDownload = encodeURI(finalReport_downloadContent);\n\t\t\t\t$('#reportActionButtonDownload').attr('data-hold', finalContent_EncodedDownload);\n\n\t\t\t\tvar finalContent_EncodedText = encodeURI(fancy_report_title_name);\n\t\t\t\t$('#reportActionButtonDownload').attr('text-hold', finalContent_EncodedText);\n\n\t\t\t\tgenerateReportContentEmail();\n\n\t\t}\n\n\t\tfunction generateReportContentEmail(){\n\n\t\t\t\trunReportAnimation(97);\n\n\t\t\t\t//To display weekly graph or not\n\t\t\t\tvar hasWeeklyGraphAttached = false;\n\t\t\t\tif(window.localStorage.graphImageDataWeekly && window.localStorage.graphImageDataWeekly != ''){\n\t\t\t\t\thasWeeklyGraphAttached = true;\n\t\t\t\t}\n\n\t\t\t\tvar temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\n\t\t\t\tvar graphRenderSectionContent = '';\n\t\t\t\tvar fancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY - dddd');\n\n\t\t\t\tvar reportInfo_title = 'Sales Report of <b>'+fancy_from_date+'</b>';\n\t\t\t\tvar temp_report_title = 'Sales Report of '+fancy_from_date;\n\t\t\t\tif(fromDate != toDate){\n\t\t\t\t\tfancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\t\t\t\t\tvar fancy_to_date = moment(toDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\n\t\t\t\t\treportInfo_title = 'Sales Report from <b>'+fancy_from_date+'</b> to <b>'+fancy_to_date+'</b>';\n\t\t\t\t\ttemp_report_title = 'Sales Report from '+fancy_from_date+' to '+fancy_to_date;\n\t\t\t\t}\n\t\t\t else{ //Render graph only if report is for a day\n\n\t\t\t if(hasWeeklyGraphAttached){\n\n\t\t\t \tvar temp_image_name = reportInfo_branch+'_'+fromDate;\n\t\t\t \ttemp_image_name = temp_image_name.replace(/\\s/g,'');\n\n\t\t\t graphRenderSectionContent = ''+\n\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t '<h1 class=\"tableQuickHeaderText\">WEEKLY SALES TREND</h1>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"weeklyGraph\">'+\n\t\t\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/report_trend_images_repo/'+temp_image_name+'.png\" style=\"max-width: 90%\">'+\n\t\t\t '</div>'+\n\t\t\t '</div>'+\n\t\t\t '</div>';\n\t\t\t }\n\t\t\t }\n\n\t\t\t var fancy_report_title_name = reportInfo_branch+' - '+temp_report_title;\n\n\t\t\t //Quick Summary Content\n\t\t\t var quickSummaryRendererContent = '';\n\n\t\t\t var a = 0;\n\t\t\t while(reportInfoExtras[a]){\n\t\t\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+reportInfoExtras[a].name+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(reportInfoExtras[a].value).toFixed(2)+'</td></tr>';\n\t\t\t a++;\n\t\t\t }\n\n\n\t\t\t var b = 1; //first one contains total paid\n\t\t\t while(completeReportInfo[b]){\n\t\t\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+completeReportInfo[b].name+'</td><td class=\"tableQuickAmount\">'+(completeReportInfo[b].type == 'NEGATIVE' && completeReportInfo[b].value != 0 ? '- ' : '')+'<span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[b].value).toFixed(2)+'</td></tr>';\n\t\t\t b++;\n\t\t\t }\n\n\n\t\t\t //Sales by Billing Modes Content\n\t\t\t var salesByBillingModeRenderContent = '';\n\t\t\t var c = 0;\n\t\t\t var billSharePercentage = 0;\n\t\t\t while(detailedListByBillingMode[c]){\n\t\t\t billSharePercentage = parseFloat((100*detailedListByBillingMode[c].value)/completeReportInfo[0].value).toFixed(0);\n\t\t\t salesByBillingModeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByBillingMode[c].name+' '+(billSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+billSharePercentage+'%)</span>' : '')+(detailedListByBillingMode[c].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByBillingMode[c].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByBillingMode[c].value).toFixed(0)+'</td></tr>';\n\t\t\t c++;\n\t\t\t }\n\n\t\t\t\t//To display bills graph or not\n\t\t\t\tvar hasBillsGraphAttached = false;\n\t\t\t\tif(window.localStorage.graphImageDataBills && window.localStorage.graphImageDataBills != '' && window.localStorage.graphImageDataBills != 'data:,'){\n\t\t\t\t\thasBillsGraphAttached = true;\n\t\t\t\t}\n\n\t\t\t var salesByBillingModeRenderContentFinal = '';\n\t\t\t if(salesByBillingModeRenderContent != ''){\n\t\t\t\t\t salesByBillingModeRenderContentFinal = ''+\n\t\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY BILLS</h1>'+\n\t\t\t\t\t '</div>'+\n\t\t\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t\t salesByBillingModeRenderContent+\n\t\t\t\t\t '</table>'+\n\t\t\t\t\t '</div>'+\n\t\t\t\t\t '</div>'+\n\t\t\t\t\t '</div>';\n\t\t\t }\n\n\n\t\t\t //Sales by Payment Types Content\n\t\t\t var salesByPaymentTypeRenderContent = '';\n\t\t\t var d = 0;\n\t\t\t var paymentSharePercentage = 0;\n\t\t\t while(detailedListByPaymentMode[d]){\n\t\t\t paymentSharePercentage = parseFloat((100*detailedListByPaymentMode[d].value)/completeReportInfo[0].value).toFixed(0);\n\t\t\t salesByPaymentTypeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByPaymentMode[d].name+' '+(paymentSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+paymentSharePercentage+'%)</span>' : '')+(detailedListByPaymentMode[d].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByPaymentMode[d].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByPaymentMode[d].value).toFixed(0)+'</td></tr>';\n\t\t\t d++;\n\t\t\t }\n\n\t\t\t var salesByPaymentTypeRenderContentFinal = '';\n\t\t\t if(salesByPaymentTypeRenderContent != ''){\n\t\t\t\t \tsalesByPaymentTypeRenderContentFinal = ''+\n\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY PAYMENT</h1>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t salesByPaymentTypeRenderContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>';\n\t\t\t }\n\n\t\t\t var temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\t\t\t var cssData = '<head> <style type=\"text/css\"> body{font-family:sans-serif;margin:0}#logo{min-height:60px;width:100%}.mainHeader{background:url(https://accelerateengine.app/clients/'+temp_licenced_client+'/pattern.jpg) #c63931;width:100%;min-height:95px;padding:10px 0;border-bottom:2px solid #a8302b}.headerLeftBox{width:55%;display:inline-block;padding-left:25px}.headerRightBox{width:35%;float:right;display:inline-block;text-align:right;padding-right:25px}.headerAddress{margin:0 0 5px;font-size:14px;color:#e4a1a6}.headerBranch{margin:10px 0;font-weight:700;text-transform:uppercase;font-size:21px;padding:3px 8px;color:#c63931;display:inline-block;background:#FFF}.headerAdmin{margin:0 0 3px;font-size:16px;color:#FFF}.headerTimestamp{margin:0 0 5px;font-size:12px;color:#e4a1a6}.reportTitle{margin:15px 0;font-size:26px;font-weight:400;text-align:center;color:#3498db}.introFacts{background:0 0;width:100%;min-height:95px;padding:10px 0}.factsArea{display:block;padding:10px;text-align:center}.factsBox{margin-right: 5px; width:18%; display:inline-block;text-align:left;padding:20px 15px;border:2px solid #a8302b;border-radius:5px;color:#FFF;height:65px;background:#c63931}.factsBoxFigure{margin:0 0 8px;font-weight:700;font-size:32px}.factsBoxFigure .factsPrice{font-weight:400;font-size:40%;color:#e4a1a6;margin-left:2px}.factsBoxBrief{margin:0;font-size:16px;color:#F1C40F;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.summaryTableSectionHolder{width:100%}.summaryTableSection{padding:0 25px;margin-top:30px}.summaryTableSection table{border-collapse:collapse}.summaryTableSection td{border-bottom:1px solid #fdebed}.tableQuick{padding:10px}.tableQuickHeader{min-height:40px;background:#c63931;border-bottom:3px solid #a8302b;border-top-right-radius:15px;color:#FFF}.tableQuickHeaderText{margin:0 0 0 25px;font-size:18px;letter-spacing:2px;text-transform:uppercase;padding-top:10px;font-weight:700}.smallOrderCount{font-size:80%;margin-left:15px;color:#aba9a9;font-style:italic;}.tableQuickBrief{padding:10px;font-size:16px;color:#a71a14}.tableQuickAmount{padding:10px;font-size:18px;text-align:right;color:#a71a14}.tableQuickAmount .price{font-size:70%;margin-right:2px}.tableGraphRow{position:relative}.tableGraph_Graph{width:35%;display:block;text-align:center;float:right;position:absolute;top:20px;left:62%}.footerNote,.weeklyGraph{text-align:center;margin:0}.tableGraph_Table{padding:10px;width:55%;display:block;min-height:250px;}.weeklyGraph{padding:25px;border:1px solid #f2f2f2;border-top:none}.footerNote{font-size:12px;color:#595959}@media screen and (max-width:1000px){.headerLeftBox{display:none!important}.headerRightBox{padding-right:5px!important;width:90%!important}.reportTitle{font-size:18px!important}.tableQuick{padding:0 0 5px!important}.factsArea{padding:5px!important}.factsBox{width:90%!important;margin:0 0 5px!important}.smallOrderCount{margin:0!important;display:block!important}.summaryTableSection{padding:0 5px!important}}</style> </head>';\n\t\t\t \n\t\t\t var finalReport_emailContent = '<html>'+cssData+\n\t\t\t\t '<body>'+\n\t\t\t\t '<div class=\"mainHeader\">'+\n\t\t\t\t '<div class=\"headerLeftBox\">'+\n\t\t\t\t '<div id=\"logo\">'+\n\t\t\t\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/email_logo.png\">'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<p class=\"headerAddress\">'+reportInfo_address+'</p>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"headerRightBox\">'+\n\t\t\t\t '<h1 class=\"headerBranch\">'+reportInfo_branch+'</h1>'+\n\t\t\t\t '<p class=\"headerAdmin\">'+reportInfo_admin+'</p>'+\n\t\t\t\t '<p class=\"headerTimestamp\">'+reportInfo_time+'</p>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"introFacts\">'+\n\t\t\t\t '<h1 class=\"reportTitle\">'+reportInfo_title+'</h1>'+\n\t\t\t\t '<div class=\"factsArea\">'+\n\t\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(0)+' <span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Net Sales</p></div>'+ \n\t\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(netSalesWorth).toFixed(0)+'<span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Gross Sales</p></div>'+ \n\t\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+netGuestsCount+'</h1><p class=\"factsBoxBrief\">Guests</p></div>'+ \n\t\t\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+completeReportInfo[0].count+'</h1><p class=\"factsBoxBrief\">Bills</p></div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+graphRenderSectionContent+\n\t\t\t\t (hasWeeklyGraphAttached ? '<div style=\"page-break-before: always; margin-top: 20px\"></div><div style=\"height: 30px; width: 100%; display: block\"></div>' : '')+\n\t\t\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t\t\t '<div class=\"summaryTableSection\">'+\n\t\t\t\t '<div class=\"tableQuickHeader\">'+\n\t\t\t\t '<h1 class=\"tableQuickHeaderText\">Quick Summary</h1>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div class=\"tableQuick\">'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 70%\">'+\n\t\t\t\t '<col style=\"width: 30%\">'+\n\t\t\t\t '<tr><td class=\"tableQuickBrief\" style=\"font-weight: bold;\">Gross Sales</td><td class=\"tableQuickAmount\" style=\"font-weight: bold;\"><span class=\"price\">Rs.</span>'+parseFloat(netSalesWorth).toFixed(2)+'</td></tr>'+\n\t\t\t\t quickSummaryRendererContent+\n\t\t\t\t '<tr><td class=\"tableQuickBrief\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\">Net Sales</td><td class=\"tableQuickAmount\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\"><span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(2)+'</td></tr>'+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '<div style=\"page-break-before: always; margin-top: 20px\"></div><div style=\"height: 30px; width: 100%; display: block\"></div>'+\n\t\t\t\t salesByBillingModeRenderContentFinal+\n\t\t\t\t salesByPaymentTypeRenderContentFinal+\n\t\t\t\t '<div style=\"border-top: 2px solid #989898; padding: 12px; background: #f2f2f2;\">'+\n\t\t\t\t '<p class=\"footerNote\">www.accelerate.net.in | [email protected]</p>'+\n\t\t\t\t '</div>'+\n\t\t\t\t '</body>'+\n\t\t\t\t '<html>';\n\n\t\t\t\tvar finalContent_EncodedEmail = encodeURI(finalReport_emailContent);\n\t\t\t\t$('#reportActionButtonEmail').attr('data-hold', finalContent_EncodedEmail);\n\n\t\t\t\tvar myFinalCollectionText = {\n\t\t\t\t\t\"reportTitle\" : fancy_report_title_name,\n\t\t\t\t\t\"imageName\": reportInfo_branch+'_'+fromDate\n\t\t\t\t}\n\n\t\t\t\tvar finalContent_EncodedText = encodeURI(JSON.stringify(myFinalCollectionText));\n\t\t\t\t$('#reportActionButtonEmail').attr('text-hold', finalContent_EncodedText);\t\n\n\t\t\t\tgenerateReportContentPrint();\t\t\n\t\t}\n\n\t\tfunction generateReportContentPrint(){\n\n\t\t\trunReportAnimation(99);\n\n\t\t\tvar graphRenderSectionContent = '';\n\t\t\tvar fancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY - dddd');\n\n\t\t\tvar reportInfo_title = 'Sales Report of <b>'+fancy_from_date+'</b>';\n\t\t\tvar temp_report_title = 'Sales Report of '+fancy_from_date;\n\t\t\tif(fromDate != toDate){\n\t\t\t\tfancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\t\t\t\tvar fancy_to_date = moment(toDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\n\t\t\t\treportInfo_title = 'Sales Report from <b>'+fancy_from_date+'</b> to <b>'+fancy_to_date+'</b>';\n\t\t\t\ttemp_report_title = 'Sales Report from '+fancy_from_date+' to '+fancy_to_date;\n\t\t\t}\n\n\n\t\t //Quick Summary Content\n\t\t var quickSummaryRendererContent = '';\n\n\t\t var a = 0;\n\t\t while(reportInfoExtras[a]){\n\t\t quickSummaryRendererContent += '<tr><td style=\"font-size: 11px\">'+reportInfoExtras[a].name+'</td><td style=\"font-size: 11px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(reportInfoExtras[a].value).toFixed(2)+'</td></tr>';\n\t\t a++;\n\t\t }\n\n\t\t var b = 1; //first one contains total paid\n\t\t while(completeReportInfo[b]){\n\t\t quickSummaryRendererContent += '<tr><td style=\"font-size: 11px\">'+completeReportInfo[b].name+'</td><td style=\"font-size: 11px; text-align: right\">'+(completeReportInfo[b].type == 'NEGATIVE' && completeReportInfo[b].value != 0 ? '- ' : '')+'<span style=\"font-size: 60%\">Rs.</span>'+parseFloat(completeReportInfo[b].value).toFixed(2)+'</td></tr>';\n\t\t b++;\n\t\t }\n\n\t\t var printSummaryAll = ''+\n\t\t \t'<div class=\"KOTContent\">'+\n\t\t \t\t '<h2 style=\"text-align: center; margin: 5px 0 3px 0; font-weight: bold; border-bottom: 1px solid #444;\">OVERALL SUMMARY</h2>'+\n\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t '<col style=\"width: 85%\">'+\n\t\t\t '<col style=\"width: 15%\">'+ \n\t\t\t '<tr><td style=\"font-size: 11px\"><b>Gross Sales</b></td><td style=\"font-size: 11px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(netSalesWorth).toFixed(2)+'</td></tr>'+\n\t\t\t quickSummaryRendererContent+\n\t\t\t '<tr><td style=\"font-size: 13px\"><b>Net Sales</b></td><td style=\"font-size: 13px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(2)+'</td></tr>'+\n\t\t\t '</table>'+\n\t\t\t '</div>';\n\n\t\t //Sales by Billing Modes Content\n\t\t var printSummaryBillsContent = '';\n\t\t var c = 0;\n\t\t var billSharePercentage = 0;\n\t\t while(detailedListByBillingMode[c]){\n\t\t billSharePercentage = parseFloat((100*detailedListByBillingMode[c].value)/completeReportInfo[0].value).toFixed(0);\n\t\t printSummaryBillsContent += '<tr><td style=\"font-size: 11px\">'+detailedListByBillingMode[c].name+' '+(billSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+billSharePercentage+'%)</span>' : '')+(detailedListByBillingMode[c].count > 0 ? '<span style=\"font-style:italic; font-size: 60%; display: block;\">'+detailedListByBillingMode[c].count+' orders</span>' : '')+'</td><td style=\"font-size: 11px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(detailedListByBillingMode[c].value).toFixed(0)+'</td></tr>';\n\t\t c++;\n\t\t }\n\n\t\t var printSummaryBills = '';\n\t\t if(printSummaryBillsContent != ''){\n\t\t\t\tprintSummaryBills = ''+\n\t\t\t \t'<div class=\"KOTContent\">'+\n\t\t\t \t\t '<h2 style=\"text-align: center; margin: 5px 0 3px 0; font-weight: bold; border-bottom: 1px solid #444;\">BILLING MODES</h2>'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 85%\">'+\n\t\t\t\t '<col style=\"width: 15%\">'+ \n\t\t\t\t printSummaryBillsContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>';\t\n\t\t }\n\n\n\t\t //Sales by Payment Types Content\n\t\t var printSummaryPaymentContent = '';\n\t\t var d = 0;\n\t\t var paymentSharePercentage = 0;\n\t\t while(detailedListByPaymentMode[d]){\n\t\t paymentSharePercentage = parseFloat((100*detailedListByPaymentMode[d].value)/completeReportInfo[0].value).toFixed(0);\n\t\t printSummaryPaymentContent += '<tr><td style=\"font-size: 11px\">'+detailedListByPaymentMode[d].name+' '+(paymentSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+paymentSharePercentage+'%)</span>' : '')+(detailedListByPaymentMode[d].count > 0 ? '<span style=\"font-style:italic; font-size: 60%; display: block;\">'+detailedListByPaymentMode[d].count+' orders</span>' : '')+'</td><td style=\"font-size: 11px; text-align: right\"><span style=\"font-size: 60%\">Rs.</span>'+parseFloat(detailedListByPaymentMode[d].value).toFixed(0)+'</td></tr>'; \n\t\t d++;\n\t\t }\n\n\t\t var printSummaryPayment = '';\n\t\t if(printSummaryPaymentContent != ''){\n\t\t\t printSummaryPayment = ''+\n\t\t\t \t'<div class=\"KOTContent\">'+\n\t\t\t \t\t '<h2 style=\"text-align: center; margin: 5px 0 3px 0; font-weight: bold; border-bottom: 1px solid #444;\">PAYMENT TYPES</h2>'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 85%\">'+\n\t\t\t\t '<col style=\"width: 15%\">'+ \n\t\t\t\t printSummaryPaymentContent+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>';\t\n\t\t }\n\n\n\t\t var printSummaryCounts = ''+\n\t\t\t \t'<div class=\"KOTContent\">'+\n\t\t\t \t\t '<h2 style=\"text-align: center; margin: 5px 0 3px 0; font-weight: bold; border-bottom: 1px solid #444;\">OTHER DETAILS</h2>'+\n\t\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t\t '<col style=\"width: 85%\">'+\n\t\t\t\t '<col style=\"width: 15%\">'+ \n\t\t\t\t '<tr><td style=\"font-size: 10px\">Total Guests</td><td style=\"font-size: 13px\">'+netGuestsCount+'</td></tr>'+\n\t\t\t\t '<tr><td style=\"font-size: 10px\">Total Bills</td><td style=\"font-size: 13px\">'+completeReportInfo[0].count+'</td></tr>'+\n\t\t\t\t '</table>'+\n\t\t\t\t '</div>';\n\n\n\n\n\t\t var cssData = '<head> <style type=\"text/css\"> .KOTContent,.KOTHeader,.KOTNumberArea,.KOTSummary{width:100%;background-color:none}.subLabel,body{font-family:sans-serif}.KOTNumber,.invoiceNumber,.subLabel{letter-spacing:2px}#logo{min-height:60px;width:100%;border-bottom:2px solid #000}.KOTHeader,.KOTNumberArea{min-height:30px;padding:5px 0;border-bottom:1px solid #7b7b7b}.KOTContent{min-height:100px;font-size:11px;padding-top:6px;border-bottom:2px solid}.KOTSummary{font-size:11px;padding:5px 0;border-bottom:1px solid}.KOTContent td,.KOTContent table{border-collapse:collapse}.KOTContent td{border-bottom:1px dashed #444;padding:7px 0}.invoiceHeader,.invoiceNumberArea{padding:5px 0;border-bottom:1px solid #7b7b7b;width:100%;background-color:none}.KOTSpecialComments{min-height:20px;width:100%;background-color:none;padding:5px 0}.invoiceNumberArea{min-height:30px}.invoiceContent{min-height:100px;width:100%;background-color:none;font-size:11px;padding-top:6px;border-bottom:1px solid}.invoiceCharges{min-height:90px;font-size:11px;width:100%;background-color:none;padding:5px 0;border-bottom:2px solid}.invoiceCustomText,.invoicePaymentsLink{background-color:none;border-bottom:1px solid;width:100%}.invoicePaymentsLink{min-height:72px}.invoiceCustomText{padding:5px 0;font-size:12px;text-align:center}.subLabel{display:block;font-size:8px;font-weight:300;text-transform:uppercase;margin-bottom:5px}p{margin:0}.itemComments,.itemOldComments{font-style:italic;margin-left:10px}.serviceType{border:1px solid;padding:4px;font-size:12px;display:block;text-align:center;margin-bottom:8px}.tokenNumber{display:block;font-size:16px;font-weight:700}.billingAddress,.timeStamp{font-weight:300;display:block}.billingAddress{font-size:12px;line-height:1.2em}.mobileNumber{display:block;margin-top:8px;font-size:12px}.timeStamp{font-size:11px}.KOTNumber{font-size:15px;font-weight:700}.commentsSubText{font-size:12px;font-style:italic;font-weight:300;display:block}.invoiceNumber{font-size:15px;font-weight:700}.timeDisplay{font-size:75%;display:block}.rs{font-size:60%}.paymentSubText{font-size:10px;font-weight:300;display:block}.paymentSubHead{font-size:12px;font-weight:700;display:block}.qrCode{width:100%;max-width:120px;text-align:right}.addressContact,.addressText{color:gray;text-align:center}.addressText{font-size:10px;padding:5px 0}.addressContact{font-size:9px;padding:0 0 5px}.gstNumber{font-weight:700;font-size:10px}.attendantName,.itemQuantity{font-size:12px}#defaultScreen{position:fixed;left:0;top:0;z-index:100001;width:100%;height:100%;overflow:visible;background-image:url(../data/photos/brand/pattern.jpg);background-repeat:repeat;padding-top:100px}.attendantName{font-weight:300;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.itemComments,.itemQuantity{font-weight:700;display:block}.itemOldComments{display:block;text-decoration:line-through}.itemOldQuantity{font-size:12px;text-decoration:line-through;display:block} </style> </head>';\n\n\t\t var data_custom_header_image = window.localStorage.bill_custom_header_image ? window.localStorage.bill_custom_header_image : '';\n\n\t\t var data_custom_header_client_name = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name : '';\n\t\t\tif(data_custom_header_client_name == ''){\n\t\t\t data_custom_header_client_name = 'Report';\n\t\t\t}\n\n\t\t var finalReport_printContent = cssData +\n\t\t \t'<body>'+\n\t\t\t '<div id=\"logo\">'+\n\t\t\t (data_custom_header_image != '' ? '<center><img style=\"max-width: 90%\" src=\\''+data_custom_header_image+'\\'/></center>' : '<h1 style=\"text-align: center\">'+data_custom_header_client_name+'</h1>')+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"KOTHeader\" style=\"padding: 0; background: #444;\">'+\n\t\t\t \t'<p style=\"text-align: center; font-size: 16px; font-weight: bold; text-transform: uppercase; padding-top: 6px; color: #FFF;\">'+reportInfo_branch+'</p>'+\n\t\t\t '</div>'+\n\t\t\t '<div class=\"KOTNumberArea\">'+\n\t\t\t '<table style=\"width: 100%\">'+\n\t\t\t '<col style=\"width: 50%\">'+\n\t\t\t '<col style=\"width: 50%\">'+\n\t\t\t '<tr>'+\n\t\t\t '<td style=\"vertical-align: top\">'+\n\t\t\t '<p>'+\n\t\t\t '<tag class=\"subLabel\">Admin</tag>'+\n\t\t\t '<tag class=\"KOTNumber\" style=\"font-size: 13; font-weight: 300; letter-spacing: unset;\">'+reportInfo_admin+'</tag>'+\n\t\t\t '</p>'+\n\t\t\t '</td>'+\n\t\t\t '<td style=\"vertical-align: top\">'+\n\t\t\t '<p style=\" text-align: right; float: right\">'+\n\t\t\t '<tag class=\"subLabel\">TIME STAMP</tag>'+\n\t\t\t '<tag class=\"timeStamp\">'+reportInfo_time+'</tag>'+\n\t\t\t '</p>'+\n\t\t\t '</td>'+\n\t\t\t '</tr>'+\n\t\t\t '</table>'+\n\t\t\t '</div>'+\n\t\t\t '<h1 style=\"margin: 6px 3px; padding-bottom: 5px; font-weight: 400; text-align: center; font-size: 15px; border-bottom: 2px solid; }\">'+reportInfo_title+'</h1>'+\n\t\t\t \t printSummaryAll+printSummaryBills+printSummaryPayment+printSummaryCounts+\n\t\t\t \t'</body>';\n\n\t\t\t\tvar finalContent_EncodedPrint = encodeURI(finalReport_printContent);\n\t\t\t\t$('#reportActionButtonPrint').attr('data-hold', finalContent_EncodedPrint);\n\n\t\t\t\trunReportAnimation(100); //Done!\n\t\t}\n\t}\t\n\n\n\n\n\t//Step 12: Final Render Stage - EMAIL\n\tfunction singleClickWeeklyFinalReportRender(graphImage){\n\t\trunReportAnimation(100); //of Step 11 which completed the data processing\n\n\t\t//Get staff info.\n\t\tvar loggedInStaffInfo = window.localStorage.loggedInStaffData ? JSON.parse(window.localStorage.loggedInStaffData) : {};\n\t\t\n\t\tif(jQuery.isEmptyObject(loggedInStaffInfo)){\n\t\t\tloggedInStaffInfo.name = 'Staff';\n\t\t\tloggedInStaffInfo.code = '0000000000';\n\t\t}\t\n\n\n\t\tvar reportInfo_branch = window.localStorage.accelerate_licence_branch_name ? window.localStorage.accelerate_licence_branch_name : '';\n\t\tvar temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\n\t\tif(reportInfo_branch == ''){\n\t\t\tshowToast('System Error: Branch name not found. Please contact Accelerate Support.', '#e74c3c');\n\t\t\treturn '';\n\t\t}\n\n\t\tvar temp_address_modified = (window.localStorage.accelerate_licence_branch_name ? window.localStorage.accelerate_licence_branch_name : '') + ' - ' + (window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name : '');\n\t\tvar data_custom_footer_address = window.localStorage.bill_custom_footer_address ? window.localStorage.bill_custom_footer_address : '';\n\n\t\tvar reportInfo_admin = loggedInStaffInfo.name;\n\t\tvar reportInfo_time = moment().format('h:mm a, DD-MM-YYYY');\n\t\tvar reportInfo_address = data_custom_footer_address != '' ? data_custom_footer_address : temp_address_modified;\n\n\n\t\tif(graphImage && graphImage != ''){\n\t\t\twindow.localStorage.graphImageDataWeekly = graphImage;\n\t\t}\n\t\telse{\n\t\t\twindow.localStorage.graphImageDataWeekly = '';\n\t\t}\n\n\n\t\tvar graphRenderSectionContent = '';\n\t\tvar fancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY - dddd');\n\n\t\tvar reportInfo_title = 'Sales Report of <b>'+fancy_from_date+'</b>';\n\t\tvar temp_report_title = 'Sales Report of '+fancy_from_date;\n\t\tif(fromDate != toDate){\n\t\t\tfancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\t\t\tvar fancy_to_date = moment(toDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\n\t\t\treportInfo_title = 'Sales Report from <b>'+fancy_from_date+'</b> to <b>'+fancy_to_date+'</b>';\n\t\t\ttemp_report_title = 'Sales Report from '+fancy_from_date+' to '+fancy_to_date;\n\t\t}\n\t else{ //Render graph only if report is for a day\n\n\t if(graphImage){\n\n\t \tvar temp_image_name = reportInfo_branch+'_'+fromDate;\n\t \ttemp_image_name = temp_image_name.replace(/\\s/g,'');\n\n\t graphRenderSectionContent = ''+\n\t '<div class=\"summaryTableSectionHolder\">'+\n\t '<div class=\"summaryTableSection\">'+\n\t '<div class=\"tableQuickHeader\">'+\n\t '<h1 class=\"tableQuickHeaderText\">WEEKLY SALES TREND</h1>'+\n\t '</div>'+\n\t '<div class=\"weeklyGraph\">'+\n\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/report_trend_images_repo/'+temp_image_name+'.png\" style=\"max-width: 90%\">'+\n\t '</div>'+\n\t '</div>'+\n\t '</div>';\n\t }\n\t }\n\n\t var fancy_report_title_name = reportInfo_branch+' - '+temp_report_title;\n\n\n\t //Quick Summary Content\n\t var quickSummaryRendererContent = '';\n\n\t var a = 0;\n\t while(reportInfoExtras[a]){\n\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+reportInfoExtras[a].name+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(reportInfoExtras[a].value).toFixed(2)+'</td></tr>';\n\t a++;\n\t }\n\n\t //PENDING --> TOTAL CALCULATED ROUND OFFFFF\n\t console.log('PENDING API --> TOTAL CALCULATED ROUND OFFFFF')\n\n\t var b = 1; //first one contains total paid\n\t while(completeReportInfo[b]){\n\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+completeReportInfo[b].name+'</td><td class=\"tableQuickAmount\">'+(completeReportInfo[b].type == 'NEGATIVE' && completeReportInfo[b].value != 0 ? '- ' : '')+'<span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[b].value).toFixed(2)+'</td></tr>';\n\t b++;\n\t }\n\n\n\t //Sales by Billing Modes Content\n\t var salesByBillingModeRenderContent = '';\n\t var c = 0;\n\t var billSharePercentage = 0;\n\t while(detailedListByBillingMode[c]){\n\t billSharePercentage = parseFloat((100*detailedListByBillingMode[c].value)/completeReportInfo[0].value).toFixed(0);\n\t salesByBillingModeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByBillingMode[c].name+' '+(billSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+billSharePercentage+'%)</span>' : '')+(detailedListByBillingMode[c].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByBillingMode[c].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByBillingMode[c].value).toFixed(0)+'</td></tr>';\n\t c++;\n\t }\n\n\t var salesByBillingModeRenderContentFinal = '';\n\t if(salesByBillingModeRenderContent != ''){\n\t salesByBillingModeRenderContentFinal = ''+\n\t '<div class=\"summaryTableSectionHolder\">'+\n\t '<div class=\"summaryTableSection\">'+\n\t '<div class=\"tableQuickHeader\">'+\n\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY BILLS</h1>'+\n\t '</div>'+\n\t '<div class=\"tableQuick\">'+\n\t '<table style=\"width: 100%\">'+\n\t '<col style=\"width: 70%\">'+\n\t '<col style=\"width: 30%\">'+\n\t salesByBillingModeRenderContent+\n\t '</table>'+\n\t '</div>'+\n\t '</div>'+\n\t '</div>';\n\t }\n\n\t //Sales by Payment Types Content\n\t var salesByPaymentTypeRenderContent = '';\n\t var d = 0;\n\t var paymentSharePercentage = 0;\n\t while(detailedListByPaymentMode[d]){\n\t paymentSharePercentage = parseFloat((100*detailedListByPaymentMode[d].value)/completeReportInfo[0].value).toFixed(0);\n\t salesByPaymentTypeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByPaymentMode[d].name+' '+(paymentSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+paymentSharePercentage+'%)</span>' : '')+(detailedListByPaymentMode[d].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByPaymentMode[d].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByPaymentMode[d].value).toFixed(0)+'</td></tr>';\n\t d++;\n\t }\n\n\t var salesByPaymentTypeRenderContentFinal = '';\n\t if(salesByPaymentTypeRenderContent != ''){\n\t salesByPaymentTypeRenderContentFinal = ''+\n\t '<div class=\"summaryTableSectionHolder\">'+\n\t '<div class=\"summaryTableSection\">'+\n\t '<div class=\"tableQuickHeader\">'+\n\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY PAYMENT</h1>'+\n\t '</div>'+\n\t '<div class=\"tableQuick\">'+\n\t '<table style=\"width: 100%\">'+\n\t '<col style=\"width: 70%\">'+\n\t '<col style=\"width: 30%\">'+\n\t salesByPaymentTypeRenderContent+\n\t '</table>'+\n\t '</div>'+\n\t '</div>'+\n\t '</div>';\n\t }\n\n\n\n\n\t var temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\t var cssData = '<head> <style type=\"text/css\"> body{font-family:sans-serif;margin:0}#logo{min-height:60px;width:100%}.mainHeader{background:url(https://accelerateengine.app/clients/'+temp_licenced_client+'/pattern.jpg) #c63931;width:100%;min-height:95px;padding:10px 0;border-bottom:2px solid #a8302b}.headerLeftBox{width:55%;display:inline-block;padding-left:25px}.headerRightBox{width:35%;float:right;display:inline-block;text-align:right;padding-right:25px}.headerAddress{margin:0 0 5px;font-size:14px;color:#e4a1a6}.headerBranch{margin:10px 0;font-weight:700;text-transform:uppercase;font-size:21px;padding:3px 8px;color:#c63931;display:inline-block;background:#FFF}.headerAdmin{margin:0 0 3px;font-size:16px;color:#FFF}.headerTimestamp{margin:0 0 5px;font-size:12px;color:#e4a1a6}.reportTitle{margin:15px 0;font-size:26px;font-weight:400;text-align:center;color:#3498db}.introFacts{background:0 0;width:100%;min-height:95px;padding:10px 0}.factsArea{display:block;padding:10px 25px;text-align:center}.factsBox{margin-right: 5px; width:20%;display:inline-block;text-align:left;padding:20px 15px;border:2px solid #a8302b;border-radius:5px;color:#FFF;height:65px;background:#c63931}.factsBoxFigure{margin:0 0 8px;font-weight:700;font-size:32px}.factsBoxFigure .factsPrice{font-weight:400;font-size:40%;color:#e4a1a6;margin-left:2px}.factsBoxBrief{margin:0;font-size:16px;color:#F1C40F;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.summaryTableSectionHolder{width:100%}.summaryTableSection{padding:0 25px;margin-top:30px}.summaryTableSection table{border-collapse:collapse}.summaryTableSection td{border-bottom:1px solid #fdebed}.tableQuick{padding:10px}.tableQuickHeader{min-height:40px;background:#c63931;border-bottom:3px solid #a8302b;border-top-right-radius:15px;color:#FFF}.tableQuickHeaderText{margin:0 0 0 25px;font-size:18px;letter-spacing:2px;text-transform:uppercase;padding-top:10px;font-weight:700}.smallOrderCount{font-size:80%;margin-left:15px;color:#aba9a9;font-style:italic;}.tableQuickBrief{padding:10px;font-size:16px;color:#a71a14}.tableQuickAmount{padding:10px;font-size:18px;text-align:right;color:#a71a14}.tableQuickAmount .price{font-size:70%;margin-right:2px}.tableGraphRow{position:relative}.tableGraph_Graph{width:30%;display:inline-block;text-align:center;float:right;margin-top:30px}.footerNote,.weeklyGraph{text-align:center;margin:0}.tableGraph_Table{padding:10px;width:65%;display:inline-block}.weeklyGraph{padding:25px;border:1px solid #f2f2f2;border-top:none}.footerNote{font-size:12px;color:#595959}@media screen and (max-width:1000px){.headerLeftBox{display:none!important}.headerRightBox{padding-right:5px!important;width:90%!important}.reportTitle{font-size:18px!important}.tableQuick{padding:0 0 5px!important}.factsArea{padding:5px!important}.factsBox{width:90%!important;margin:0 0 5px!important}.smallOrderCount{margin:0!important;display:block!important}.summaryTableSection{padding:0 5px!important}}</style> </head>';\n\t \n\n\t var finalReport_emailContent = '<html>'+cssData+\n\t\t '<body>'+\n\t\t '<div class=\"mainHeader\">'+\n\t\t '<div class=\"headerLeftBox\">'+\n\t\t '<div id=\"logo\">'+\n\t\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/email_logo.png\">'+\n\t\t '</div>'+\n\t\t '<p class=\"headerAddress\">'+reportInfo_address+'</p>'+\n\t\t '</div>'+\n\t\t '<div class=\"headerRightBox\">'+\n\t\t '<h1 class=\"headerBranch\">'+reportInfo_branch+'</h1>'+\n\t\t '<p class=\"headerAdmin\">'+reportInfo_admin+'</p>'+\n\t\t '<p class=\"headerTimestamp\">'+reportInfo_time+'</p>'+\n\t\t '</div>'+\n\t\t '</div>'+\n\t\t '<div class=\"introFacts\">'+\n\t\t '<h1 class=\"reportTitle\">'+reportInfo_title+'</h1>'+\n\t\t '<div class=\"factsArea\">'+\n\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(0)+' <span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Net Sales</p></div>'+ \n\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(netSalesWorth).toFixed(0)+'<span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Gross Sales</p></div>'+ \n\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+netGuestsCount+'</h1><p class=\"factsBoxBrief\">Guests</p></div>'+ \n\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+completeReportInfo[0].count+'</h1><p class=\"factsBoxBrief\">Bills</p></div>'+\n\t\t '</div>'+\n\t\t '</div>'+graphRenderSectionContent+\n\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t '<div class=\"summaryTableSection\">'+\n\t\t '<div class=\"tableQuickHeader\">'+\n\t\t '<h1 class=\"tableQuickHeaderText\">Quick Summary</h1>'+\n\t\t '</div>'+\n\t\t '<div class=\"tableQuick\">'+\n\t\t '<table style=\"width: 100%\">'+\n\t\t '<col style=\"width: 70%\">'+\n\t\t '<col style=\"width: 30%\">'+\n\t\t '<tr><td class=\"tableQuickBrief\" style=\"font-weight: bold;\">Gross Sales</td><td class=\"tableQuickAmount\" style=\"font-weight: bold;\"><span class=\"price\">Rs.</span>'+parseFloat(netSalesWorth).toFixed(2)+'</td></tr>'+\n\t\t quickSummaryRendererContent+\n\t\t '<tr><td class=\"tableQuickBrief\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\">Net Sales</td><td class=\"tableQuickAmount\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\"><span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(2)+'</td></tr>'+\n\t\t '</table>'+\n\t\t '</div>'+\n\t\t '</div>'+\n\t\t '</div>'+\n\t\t salesByBillingModeRenderContentFinal+\n\t\t salesByPaymentTypeRenderContentFinal+\n\t\t '<div style=\"border-top: 2px solid #989898; padding: 12px; background: #f2f2f2;\">'+\n\t\t '<p class=\"footerNote\">www.accelerate.net.in | [email protected]</p>'+\n\t\t '</div>'+\n\t\t '</body>'+\n\t\t '<html>';\n\t}\t\n\n\tfunction singleClickLoadErrors(){\n\t\t//Display if any errors\n\t\tif(completeErrorList.length > 0){\n\t\t\tvar renderError = '<b style=\"color: #ff5050\">Report might contain Errors</b><br><i style=\"color: #ffb836; font-size: 80%\">The following errors occured while generating the Report and it might show incorrect figures. Try again.</i><br><br>';\n\t\t\tvar n = 0;\n\t\t\twhile(completeErrorList[n]){\n\t\t\t\trenderError += 'E'+completeErrorList[n].step+': '+completeErrorList[n].error+'<br>';\n\t\t\t\tn++;\n\t\t\t}\n\n\t\t\tdocument.getElementById(\"singleClickReport_ErrorContent\").style.display = 'block';\n\t\t\tdocument.getElementById(\"singleClickReport_ErrorContent\").innerHTML = renderError;\n\t\t}\n\t}\n\n\tfunction resetBillingCounters(){\n\t\tvar isEnabledVariabled = window.localStorage.appOtherPreferences_resetCountersAfterReport ? window.localStorage.appOtherPreferences_resetCountersAfterReport : '';\n\t\tif(isEnabledVariabled == 1){\n\t\t\tvar present_day_today = getCurrentTime('DATE_STAMP');\n\t\t\tif(fromDate == toDate && fromDate == present_day_today){\n\t\t\t\tresetBillingKOTIndex();\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction resetBillingKOTIndex(){\n \n\t //Check for KOT index on Server\n\t var requestData = {\n\t \"selector\" :{ \n\t \"identifierTag\": \"ACCELERATE_KOT_INDEX\" \n\t },\n\t \"fields\" : [\"_rev\", \"identifierTag\", \"value\"]\n\t }\n\n\t $.ajax({\n\t type: 'POST',\n\t url: COMMON_LOCAL_SERVER_IP+'/accelerate_settings/_find',\n\t data: JSON.stringify(requestData),\n\t contentType: \"application/json\",\n\t dataType: 'json',\n\t timeout: 10000,\n\t success: function(data) {\n\t if(data.docs.length > 0){\n\t if(data.docs[0].identifierTag == 'ACCELERATE_KOT_INDEX'){\n\n\t \t\tvar temp_value = parseInt(data.docs[0].value);\n\n\t \t\t//TWEAK\n\t \t\t/* to be safe with KOT number. 2 different KOTs with same KOTNumber should not exists at a time */\n\t \t\t/* assuming a max of 100 KOTs active at a time */\n\t \t\tif(temp_value < 100){\n\t \t\t\tresetBillingTokenIndex();\n\t \t\t\treturn '';\n\t \t\t}\n\n\t\t \tvar memory_revID = data.docs[0]._rev;\n\n\t \t //Update KOT number on server\n\t var updateData = {\n\t \"_rev\": memory_revID,\n\t \"identifierTag\": \"ACCELERATE_KOT_INDEX\",\n\t \"value\": 1\n\t }\n\n\t $.ajax({\n\t type: 'PUT',\n\t url: COMMON_LOCAL_SERVER_IP+'accelerate_settings/ACCELERATE_KOT_INDEX/',\n\t data: JSON.stringify(updateData),\n\t contentType: \"application/json\",\n\t dataType: 'json',\n\t timeout: 10000,\n\t success: function(data) {\n\t resetBillingTokenIndex();\n\t },\n\t error: function(data) {\n\t resetBillingTokenIndex();\n\t }\n\t });\n\t \n\t }\n\t else{\n\t resetBillingTokenIndex();\n\t }\n\t }\n\t else{\n\t resetBillingTokenIndex();\n\t }\n\n\t },\n\t error: function(data) {\n\t resetBillingTokenIndex();\n\t }\n\n\t });\t\t\n\t}\n\n\tfunction resetBillingTokenIndex(){\n\n\t\t\t\t\t\t var requestData = {\n\t\t\t\t\t\t \"selector\" :{ \n\t\t\t\t\t\t \"identifierTag\": \"ACCELERATE_TOKEN_INDEX\" \n\t\t\t\t\t\t },\n\t\t\t\t\t\t \"fields\" : [\"_rev\", \"identifierTag\", \"value\"]\n\t\t\t\t\t\t }\n\n\t\t\t\t\t\t $.ajax({\n\t\t\t\t\t\t type: 'POST',\n\t\t\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'/accelerate_settings/_find',\n\t\t\t\t\t\t data: JSON.stringify(requestData),\n\t\t\t\t\t\t contentType: \"application/json\",\n\t\t\t\t\t\t dataType: 'json',\n\t\t\t\t\t\t timeout: 10000,\n\t\t\t\t\t\t success: function(data) {\n\t\t\t\t\t\t if(data.docs.length > 0){\n\t\t\t\t\t\t if(data.docs[0].identifierTag == 'ACCELERATE_TOKEN_INDEX'){\n\n\t\t\t\t\t\t\t\t\t\twindow.localStorage.claimedTokenNumber = 1;\n\t\t\t\t\t\t\t\t\t\twindow.localStorage.claimedTokenNumberTimestamp = new Date();\n\n\t\t\t\t //Update token number on server\n\t\t\t\t var updateData = {\n\t\t\t\t \"_rev\": data.docs[0]._rev,\n\t\t\t\t \"identifierTag\": \"ACCELERATE_TOKEN_INDEX\",\n\t\t\t\t \"value\": 2\n\t\t\t\t }\n\n\t\t\t\t $.ajax({\n\t\t\t\t type: 'PUT',\n\t\t\t\t url: COMMON_LOCAL_SERVER_IP+'accelerate_settings/ACCELERATE_TOKEN_INDEX/',\n\t\t\t\t data: JSON.stringify(updateData),\n\t\t\t\t contentType: \"application/json\",\n\t\t\t\t dataType: 'json',\n\t\t\t\t timeout: 10000,\n\t\t\t\t success: function(data) {\n\t\t\t\t \tshowToast('KOT and Token Numbers are automatically reset. Change your preferences from System Options.', '#27ae60'); \n\t\t\t\t }\n\t\t\t\t }); \n\n\t\t\t\t\t\t }\n\n\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t\t\t\t });\n\t}\n}", "function newReportEntry(key, allcanteens, idx, allstalls, alldata){\n var res;\n var pCount;\n if(key==\"monthly\"){\n res = tmpl_mentry.clone();\n pCount=12;\n }\n else if(key==\"daily\"){\n res = tmpl_dentry.clone();\n pCount=10;\n }\n // class for stall entries that belong to this canteen\n res.childrenClass=\"ReportEntry\"+key+\"For\"+idx;\n // copykeys(res, allcanteens);\n // get canteen and stalls\n var canobj = allcanteens[idx];\n // stall obj, not report data\n var stallobjs = findMultipleInArray(allstalls, \"canteen\", canobj.id);\n // report data\n var stalls = [];\n for(var i = 0; i<stallobjs.length; i++)\n stalls.push(findInArray(alldata, \"stall\", stallobjs[i].id));\n // calculate stall totals\n var stallTR = []; // total revenue\n var stallTO = []; // total order count\n for(var i = 0; i<stalls.length; i++){\n stallTR.push(repMgr.SumStallTotal(stalls[i], key, \"revenue\"));\n stallTO.push(repMgr.SumStallTotal(stalls[i], key, \"order_count\"));\n }\n // calculate canteen stats\n var canStats = repMgr.SumForCanteen(stalls, key);\n\n // fill in first and last\n res.find(\".First\").html(canobj.name);\n var total = canStats[canStats.length-1];\n res.find(\".Last\").html(toStr(total.order_count, total.revenue));\n // fill in periods\n for( var i = 0; i<pCount; i++){\n var str;\n if(canStats.length==1)\n str = toStr(0,0);\n else\n str = toStr(canStats[i].order_count, canStats[i].revenue);\n res.find(\".P\"+(i+1)).html(str);\n }\n\n // now, build one entry for each stall\n // if no stall in this canteen, then append tmpl_can_empty\n res.detailsShown = false;\n res.Toggle = function(){\n if(res.detailsShown){\n res.details.find(\".DetailContent\").slideUp(400, function(){\n res.details.hide();\n });\n res.detailsShown = false;\n }\n else{\n res.details.show();\n res.details.find(\".DetailContent\").slideDown();\n res.detailsShown = true;\n }\n };\n res.click(res.Toggle);\n res.details = tmpl_can_details.clone().hide();\n res.details.find(\".DetailContent\").hide();\n res.details.find(\".ReportCanteenName\").html(canobj.name);\n // if it's empty, we simply return\n if(stalls.length==0)\n return [res, res.details];\n // if it's not, we hide empty message, and show stall table\n res.hasStall = true;\n res.details.find(\".ReportCanEmptyMsg\").hide();\n res.stalltable=res.details.find(\".ReportStallContainer\");\n res.stalltable.show();\n // set inner header\n res.stalltable.find(\".RCH\").append($(key==\"monthly\"?\"#HeadRowMonthly\":\"#HeadRowDaily\").clone());\n // set inner body\n var ibody = res.stalltable.find(\".RCB\");\n for(var i = 0; i<stalls.length; i++){\n var stentry=newReportStallEntry(key, stalls[i], stallobjs[i].name, \n stallTR[i], stallTO[i]);\n ibody.append(stentry);\n }\n return [res, res.details];\n}", "static async build(){\n const browser = await puppeteer.launch({\n headless: true,\n args: ['--no-sandbox']\n });\n\n const page = await browser.newPage();\n const customPage = new CustomPage(page);\n\n return new Proxy(customPage, {\n get: function(target, property){\n // we include browser because in our test suite,\n // we use browser to get a page and then close the browser and page\n // by including browser here, we never have to work with the browser obj anymore\n // we let our proxy handle all browser functions such as creating a page\n // browser is given a higher priority than page here so that when page.close()\n // is called it calls browser's close fn and not page's close fn\n return customPage[property] || browser[property] || page[property];\n }\n });\n }", "function createReport(req,res,childFound){\n var childAge = req.body.childAge;\n var teacherName = req.user.details[0].firstname +' '+ req.user.details[0].lastname;\n var comments = req.body.comments;\n var intellectual = req.body.intellectual;\n var social = req.body.social;\n var physical = req.body.physical;\n var realValueIntellectual = calculateValuesIntellectual(intellectual,childAge);\n var realValueSocial = calculateValuesSocial(social,childAge);\n var realValuePhysical = calculateValuesPhysical(physical,childAge);\n \n var avgValue = (realValueIntellectual + realValueSocial +realValuePhysical)/3;\n avgValue = Math.round(avgValue);\n \n var reportObject = new Report();//Report object, you need to save it for it to be added to the DB\n \n reportObject.childAge = childAge;\n reportObject.nursery.id = req.user.nursery.id;\n reportObject.children.id = req.params.childId;\n reportObject.avgValue = avgValue;\n reportObject.comments = comments ;\n \n \n reportObject.teacher = { \n id:req.user._id,\n name: teacherName,\n label:'teacher',\n username:req.user.username\n \n };\n\n \n reportObject.intellectual.push({\n skills : intellectual,\n realValue: realValueIntellectual\n \n }); \n \n reportObject.social.push({\n skills : social,\n realValue : realValueSocial\n });\n \n reportObject.physical.push({\n skills: physical,\n realValue: realValuePhysical\n }); \n\n\n reportObject.save(function(err,reportCreated){\n if(err){\n req.flash('error','Error creating Report');\n res.redirect('/');\n console.log(err);\n }else{\n \n if(notifyParent==true){\n sendEmail.warnParent(req,res,childFound, comments,function(statusCode){\n if (statusCode == 202) {\n req.flash('success','Success creating Report and \"Notification of low mark in a High Priority skill\" email successfully sent to parents.');\n res.redirect('/dashboard/teacher/'+req.user._id+'/children'); \n }else{\n req.flash('error','Success creating Report, but Warning email could not be sent to parents');\n res.redirect('/dashboard/teacher/'+req.user._id+'/children'); \n }\n \n });\n }else{\n req.flash('success','Success creating Report.');\n res.redirect('/dashboard/teacher/'+req.user._id+'/children'); \n }\n \n }\n }); \n}", "async createPage() {\r\n try {\r\n const db = await this.$axios.post(\"/apiV1/set_current_db\", {\r\n id: this.user.id,\r\n currentDB: this.currentDatabase,\r\n });\r\n\r\n // setting page tab values from backend\r\n const pages = await this.$axios.get(\"/apiV1/get_pages\");\r\n if (pages.data.status === 304) {\r\n this.noDisplayData();\r\n return;\r\n }\r\n\r\n this.filteredData = pages.data.map(function(item) {\r\n return item.name;\r\n });\r\n const firstTab = this.filteredData[0];\r\n this.tab = firstTab;\r\n\r\n // grabbing translations from backend and parsing editItemData\r\n const res = await this.$axios.get(\"/apiV1/get_translations\");\r\n this.allData = res.data;\r\n\r\n if (!!this.allData.length) {\r\n this.editItemData = JSON.parse(JSON.stringify(this.allData[0]));\r\n this.currentKey = this.editItemData.key;\r\n }\r\n\r\n this.noDisplayData();\r\n\r\n // deep clone of data for change tracking\r\n this.currentData.splice(0, this.currentData.length);\r\n this.allData.forEach((item) => {\r\n const clone = JSON.parse(JSON.stringify(item));\r\n this.currentData.push(clone);\r\n });\r\n\r\n // filter for first load\r\n this.setDisplayData(firstTab);\r\n } catch (err) {\r\n this.noDisplayData();\r\n this.serverError(err);\r\n }\r\n }", "_trackPage() {\n scheduleOnce('afterRender', null, () => {\n const page = get(this, 'location').getURL();\n const title = getWithDefault(this, 'currentRouteName', 'unknown.page.title');\n const metrics = get(this, 'metrics');\n\n /**\n * Manually track Piwik siteSearch using the `trackSiteSearch` api\n * rather than using Piwik's default reading of url's containing the\n * \"search\", \"q\", \"query\", \"s\", \"searchword\", \"k\" and \"keyword\", keywords\n * @link https://developer.piwik.org/guides/tracking-javascript-guide#internal-search-tracking\n */\n if (title.includes('search')) {\n // Reference to the _paq queue\n // check if we are in a browser env\n const paq = window && window._paq ? window._paq : [];\n const routerJs = get(this, 'router');\n const queryParams = routerJs ? get(routerJs, 'state.queryParams') : {};\n const { keyword, category = 'datasets', page = 1 } = queryParams;\n\n // Early exit once we track search, so we do not invoke the\n // default op by invoking `trackPageView` event\n return paq.push(['trackSiteSearch', keyword, category, page]);\n }\n\n metrics.trackPage({ page, title });\n });\n }", "function start(paths, renderCount) {\n const now = new Date().getTime();\n RENDER_COUNT = renderCount;\n PATHS = paths\n for (let i = 0; i < PATHS.length; i++) {\n fetchOnePage(PATHS[i], i, now);\n }\n\n for (let i = 0; i < PATHS.length; i++) {\n TIMINGS.push([]);\n PAGES.push(\"\");\n }\n}", "function generateReport (data, outputPdfPath) {\n return webServer.start(webServerPortNo, data)\n .then(server => {\n const urlToCapture = \"http://localhost:\" + webServerPortNo;\n return captureReport(urlToCapture, \"svg\", outputPdfPath)\n .then(() => server.close());\n });\n}", "function PerformanceCollect(configs){\n console.log('配置文件');\n console.log(configs);\n resourceTiming();\n console.log('====');\n timing.getTimes();\n //\n PerformanceData.site_id = configs.site_id; //汇报前带上站点id\n console.log('打印获得到的性能数据,包含各个元素的性能和整个页面的性能时间');\n\n console.log(PerformanceData);\n\n //doPost(configs.report_url,{'data':'test'})\n //do_jsonp(configs.report_url,PerformanceData);\n}", "async start() {\n\t\tawait this.#preprocessor.execQueue();\n\t\tawait this.#pageGen.generatePages();\n\n\t\tthis.#emitter.emit('end');\n\t}", "function initStepGraph(report) {\n // hover details\n var hoverDetail = new Rickshaw.Graph.HoverDetail( {\n graph: report.graph,\n yFormatter: function(y) { // Display percentage of total users\n return (report.total === 0) ? '0' : Math.round(y / report.total * 100) + '%';\n }\n } );\n\n // y axis\n var yAxis = new Rickshaw.Graph.Axis.Y({\n graph: report.graph\n });\n\n yAxis.render();\n\n var labels = function(step) {\n var map = {\n 1.5: report.steps[1].substr(4),\n 2.5: report.steps[2].substr(4),\n 3.5: report.steps[3].substr(4),\n 4.5: report.steps[4].substr(4)\n };\n return map[step];\n }\n\n // Show steps as x axis labels\n var xAxis = new Rickshaw.Graph.Axis.X({\n graph: report.graph,\n element: report.tab.find('.x_axis')[0],\n orientation: 'bottom',\n tickFormat: labels\n });\n\n xAxis.render();\n\n initStepTable(report);\n}", "function createReports() {\r\n var RawDataReport = AdWordsApp.report(\"SELECT Domain, Clicks \" + \"FROM AUTOMATIC_PLACEMENTS_PERFORMANCE_REPORT \" + \"WHERE Clicks > 0 \" + \"AND Conversions < 1 \" + \"DURING LAST_7_DAYS\");\r\n RawDataReport.exportToSheet(RawDataReportSheet);\r\n}", "function generateReport(id, name)\r\n{\r\n\t//Tracker#13895.Removing the invalid Record check and the changed fields check(Previous logic).\r\n\r\n // Tracker#: 13709 ADD ROW_NO FIELD TO CONSTRUCTION_D AND CONST_MODEL_D\r\n\t// Check for valid record to execute process(New logic).\r\n \tif(!isValidRecord(true))\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\t//Tracker# 13972 NO MSG IS SHOWN TO THE USER IF THERE ARE CHANGES ON THE SCREEN WHEN USER CLICKS ON THE REPORT LINK\r\n\t//Check for the field data modified or not.\r\n\tvar objHtmlData = _getWorkAreaDefaultObj().checkForNavigation();\r\n\r\n\tif(objHtmlData!=null && objHtmlData.hasUserModifiedData()==true)\r\n {\r\n //perform save operation\r\n objHtmlData.performSaveChanges(_defaultWorkAreaSave);\r\n }\r\n else\r\n {\r\n\t\tvar str = 'report.do?id=' + id + '&reportname=' + name;\r\n \toW('report', str, 800, 650);\r\n }\r\n\r\n}", "function customTracker_Page ( page ) {\n return customTracker( {\n _upage: page \n });\n}", "function init() {\n pageID = 1;\n page01 = document.getElementById(\"page01\");\n page02 = document.getElementById(\"page02\");\n page03 = document.getElementById(\"page03\");\n pageTracker();\n}", "function init(){\n\n\t//grab all posts from the pageData\n\tfor (var i = 0; i <= pageData.posts.length - 1; i++) {\n\t\tvar newPost = new WisePost();\n\t\tnewPost.setTitle(pageData.posts[i].subject);\n\t\tnewPost.setContent(pageData.posts[i].content);\n\t};\n}", "function TimeoutCallBack()\n{\n let data=page.evaluate(()=>{\n let titre=document.getElementsByClassName(\"annonce_titre\");\n let text=document.getElementsByClassName(\"annonce_text\");\n\n let data_length=titre.length<=text.length?titre.length:text.length;\n let data=new Array();\n \n for (let index = 0; index < data_length; index++) {\n data.push({\n title:titre[index].innerText,\n text_content:text[index].innerText\n });\n }\n return data;\n });\n data.forEach(element => {\n element.page_number=page_index;\n });\n\n page_index++;\n DAL.WriteToFile(\"jobs.txt\",data);\n console.log(\"jobs are logged\");\n\n if(page_index<=n_pages)\n {\n page.evaluate(()=>{\n document.querySelector(\"#divPages > a.page_arrow\").click();\n });\n window.setTimeout(TimeoutCallBack,periode_ms);\n }\n else\n {\n phantom.exit();\n }\n}", "function singleClickWeeklyFinalReportRender(graphImage){\n\t\trunReportAnimation(100); //of Step 11 which completed the data processing\n\n\t\t//Get staff info.\n\t\tvar loggedInStaffInfo = window.localStorage.loggedInStaffData ? JSON.parse(window.localStorage.loggedInStaffData) : {};\n\t\t\n\t\tif(jQuery.isEmptyObject(loggedInStaffInfo)){\n\t\t\tloggedInStaffInfo.name = 'Staff';\n\t\t\tloggedInStaffInfo.code = '0000000000';\n\t\t}\t\n\n\n\t\tvar reportInfo_branch = window.localStorage.accelerate_licence_branch_name ? window.localStorage.accelerate_licence_branch_name : '';\n\t\tvar temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\n\t\tif(reportInfo_branch == ''){\n\t\t\tshowToast('System Error: Branch name not found. Please contact Accelerate Support.', '#e74c3c');\n\t\t\treturn '';\n\t\t}\n\n\t\tvar temp_address_modified = (window.localStorage.accelerate_licence_branch_name ? window.localStorage.accelerate_licence_branch_name : '') + ' - ' + (window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name : '');\n\t\tvar data_custom_footer_address = window.localStorage.bill_custom_footer_address ? window.localStorage.bill_custom_footer_address : '';\n\n\t\tvar reportInfo_admin = loggedInStaffInfo.name;\n\t\tvar reportInfo_time = moment().format('h:mm a, DD-MM-YYYY');\n\t\tvar reportInfo_address = data_custom_footer_address != '' ? data_custom_footer_address : temp_address_modified;\n\n\n\t\tif(graphImage && graphImage != ''){\n\t\t\twindow.localStorage.graphImageDataWeekly = graphImage;\n\t\t}\n\t\telse{\n\t\t\twindow.localStorage.graphImageDataWeekly = '';\n\t\t}\n\n\n\t\tvar graphRenderSectionContent = '';\n\t\tvar fancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY - dddd');\n\n\t\tvar reportInfo_title = 'Sales Report of <b>'+fancy_from_date+'</b>';\n\t\tvar temp_report_title = 'Sales Report of '+fancy_from_date;\n\t\tif(fromDate != toDate){\n\t\t\tfancy_from_date = moment(fromDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\t\t\tvar fancy_to_date = moment(toDate, 'YYYYMMDD').format('Do MMMM YYYY');\n\n\t\t\treportInfo_title = 'Sales Report from <b>'+fancy_from_date+'</b> to <b>'+fancy_to_date+'</b>';\n\t\t\ttemp_report_title = 'Sales Report from '+fancy_from_date+' to '+fancy_to_date;\n\t\t}\n\t else{ //Render graph only if report is for a day\n\n\t if(graphImage){\n\n\t \tvar temp_image_name = reportInfo_branch+'_'+fromDate;\n\t \ttemp_image_name = temp_image_name.replace(/\\s/g,'');\n\n\t graphRenderSectionContent = ''+\n\t '<div class=\"summaryTableSectionHolder\">'+\n\t '<div class=\"summaryTableSection\">'+\n\t '<div class=\"tableQuickHeader\">'+\n\t '<h1 class=\"tableQuickHeaderText\">WEEKLY SALES TREND</h1>'+\n\t '</div>'+\n\t '<div class=\"weeklyGraph\">'+\n\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/report_trend_images_repo/'+temp_image_name+'.png\" style=\"max-width: 90%\">'+\n\t '</div>'+\n\t '</div>'+\n\t '</div>';\n\t }\n\t }\n\n\t var fancy_report_title_name = reportInfo_branch+' - '+temp_report_title;\n\n\n\t //Quick Summary Content\n\t var quickSummaryRendererContent = '';\n\n\t var a = 0;\n\t while(reportInfoExtras[a]){\n\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+reportInfoExtras[a].name+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(reportInfoExtras[a].value).toFixed(2)+'</td></tr>';\n\t a++;\n\t }\n\n\t //PENDING --> TOTAL CALCULATED ROUND OFFFFF\n\t console.log('PENDING API --> TOTAL CALCULATED ROUND OFFFFF')\n\n\t var b = 1; //first one contains total paid\n\t while(completeReportInfo[b]){\n\t quickSummaryRendererContent += '<tr><td class=\"tableQuickBrief\">'+completeReportInfo[b].name+'</td><td class=\"tableQuickAmount\">'+(completeReportInfo[b].type == 'NEGATIVE' && completeReportInfo[b].value != 0 ? '- ' : '')+'<span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[b].value).toFixed(2)+'</td></tr>';\n\t b++;\n\t }\n\n\n\t //Sales by Billing Modes Content\n\t var salesByBillingModeRenderContent = '';\n\t var c = 0;\n\t var billSharePercentage = 0;\n\t while(detailedListByBillingMode[c]){\n\t billSharePercentage = parseFloat((100*detailedListByBillingMode[c].value)/completeReportInfo[0].value).toFixed(0);\n\t salesByBillingModeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByBillingMode[c].name+' '+(billSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+billSharePercentage+'%)</span>' : '')+(detailedListByBillingMode[c].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByBillingMode[c].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByBillingMode[c].value).toFixed(0)+'</td></tr>';\n\t c++;\n\t }\n\n\t var salesByBillingModeRenderContentFinal = '';\n\t if(salesByBillingModeRenderContent != ''){\n\t salesByBillingModeRenderContentFinal = ''+\n\t '<div class=\"summaryTableSectionHolder\">'+\n\t '<div class=\"summaryTableSection\">'+\n\t '<div class=\"tableQuickHeader\">'+\n\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY BILLS</h1>'+\n\t '</div>'+\n\t '<div class=\"tableQuick\">'+\n\t '<table style=\"width: 100%\">'+\n\t '<col style=\"width: 70%\">'+\n\t '<col style=\"width: 30%\">'+\n\t salesByBillingModeRenderContent+\n\t '</table>'+\n\t '</div>'+\n\t '</div>'+\n\t '</div>';\n\t }\n\n\t //Sales by Payment Types Content\n\t var salesByPaymentTypeRenderContent = '';\n\t var d = 0;\n\t var paymentSharePercentage = 0;\n\t while(detailedListByPaymentMode[d]){\n\t paymentSharePercentage = parseFloat((100*detailedListByPaymentMode[d].value)/completeReportInfo[0].value).toFixed(0);\n\t salesByPaymentTypeRenderContent += '<tr><td class=\"tableQuickBrief\">'+detailedListByPaymentMode[d].name+' '+(paymentSharePercentage > 0 ? '<span style=\"color: #5a5757\">('+paymentSharePercentage+'%)</span>' : '')+(detailedListByPaymentMode[d].count > 0 ? '<span class=\"smallOrderCount\">'+detailedListByPaymentMode[d].count+' orders</span>' : '')+'</td><td class=\"tableQuickAmount\"><span class=\"price\">Rs.</span>'+parseFloat(detailedListByPaymentMode[d].value).toFixed(0)+'</td></tr>';\n\t d++;\n\t }\n\n\t var salesByPaymentTypeRenderContentFinal = '';\n\t if(salesByPaymentTypeRenderContent != ''){\n\t salesByPaymentTypeRenderContentFinal = ''+\n\t '<div class=\"summaryTableSectionHolder\">'+\n\t '<div class=\"summaryTableSection\">'+\n\t '<div class=\"tableQuickHeader\">'+\n\t '<h1 class=\"tableQuickHeaderText\">SUMMARY BY PAYMENT</h1>'+\n\t '</div>'+\n\t '<div class=\"tableQuick\">'+\n\t '<table style=\"width: 100%\">'+\n\t '<col style=\"width: 70%\">'+\n\t '<col style=\"width: 30%\">'+\n\t salesByPaymentTypeRenderContent+\n\t '</table>'+\n\t '</div>'+\n\t '</div>'+\n\t '</div>';\n\t }\n\n\n\n\n\t var temp_licenced_client = window.localStorage.accelerate_licence_client_name ? window.localStorage.accelerate_licence_client_name.toLowerCase() : 'common';\n\t var cssData = '<head> <style type=\"text/css\"> body{font-family:sans-serif;margin:0}#logo{min-height:60px;width:100%}.mainHeader{background:url(https://accelerateengine.app/clients/'+temp_licenced_client+'/pattern.jpg) #c63931;width:100%;min-height:95px;padding:10px 0;border-bottom:2px solid #a8302b}.headerLeftBox{width:55%;display:inline-block;padding-left:25px}.headerRightBox{width:35%;float:right;display:inline-block;text-align:right;padding-right:25px}.headerAddress{margin:0 0 5px;font-size:14px;color:#e4a1a6}.headerBranch{margin:10px 0;font-weight:700;text-transform:uppercase;font-size:21px;padding:3px 8px;color:#c63931;display:inline-block;background:#FFF}.headerAdmin{margin:0 0 3px;font-size:16px;color:#FFF}.headerTimestamp{margin:0 0 5px;font-size:12px;color:#e4a1a6}.reportTitle{margin:15px 0;font-size:26px;font-weight:400;text-align:center;color:#3498db}.introFacts{background:0 0;width:100%;min-height:95px;padding:10px 0}.factsArea{display:block;padding:10px 25px;text-align:center}.factsBox{margin-right: 5px; width:20%;display:inline-block;text-align:left;padding:20px 15px;border:2px solid #a8302b;border-radius:5px;color:#FFF;height:65px;background:#c63931}.factsBoxFigure{margin:0 0 8px;font-weight:700;font-size:32px}.factsBoxFigure .factsPrice{font-weight:400;font-size:40%;color:#e4a1a6;margin-left:2px}.factsBoxBrief{margin:0;font-size:16px;color:#F1C40F;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.summaryTableSectionHolder{width:100%}.summaryTableSection{padding:0 25px;margin-top:30px}.summaryTableSection table{border-collapse:collapse}.summaryTableSection td{border-bottom:1px solid #fdebed}.tableQuick{padding:10px}.tableQuickHeader{min-height:40px;background:#c63931;border-bottom:3px solid #a8302b;border-top-right-radius:15px;color:#FFF}.tableQuickHeaderText{margin:0 0 0 25px;font-size:18px;letter-spacing:2px;text-transform:uppercase;padding-top:10px;font-weight:700}.smallOrderCount{font-size:80%;margin-left:15px;color:#aba9a9;font-style:italic;}.tableQuickBrief{padding:10px;font-size:16px;color:#a71a14}.tableQuickAmount{padding:10px;font-size:18px;text-align:right;color:#a71a14}.tableQuickAmount .price{font-size:70%;margin-right:2px}.tableGraphRow{position:relative}.tableGraph_Graph{width:30%;display:inline-block;text-align:center;float:right;margin-top:30px}.footerNote,.weeklyGraph{text-align:center;margin:0}.tableGraph_Table{padding:10px;width:65%;display:inline-block}.weeklyGraph{padding:25px;border:1px solid #f2f2f2;border-top:none}.footerNote{font-size:12px;color:#595959}@media screen and (max-width:1000px){.headerLeftBox{display:none!important}.headerRightBox{padding-right:5px!important;width:90%!important}.reportTitle{font-size:18px!important}.tableQuick{padding:0 0 5px!important}.factsArea{padding:5px!important}.factsBox{width:90%!important;margin:0 0 5px!important}.smallOrderCount{margin:0!important;display:block!important}.summaryTableSection{padding:0 5px!important}}</style> </head>';\n\t \n\n\t var finalReport_emailContent = '<html>'+cssData+\n\t\t '<body>'+\n\t\t '<div class=\"mainHeader\">'+\n\t\t '<div class=\"headerLeftBox\">'+\n\t\t '<div id=\"logo\">'+\n\t\t '<img src=\"https://accelerateengine.app/clients/'+temp_licenced_client+'/email_logo.png\">'+\n\t\t '</div>'+\n\t\t '<p class=\"headerAddress\">'+reportInfo_address+'</p>'+\n\t\t '</div>'+\n\t\t '<div class=\"headerRightBox\">'+\n\t\t '<h1 class=\"headerBranch\">'+reportInfo_branch+'</h1>'+\n\t\t '<p class=\"headerAdmin\">'+reportInfo_admin+'</p>'+\n\t\t '<p class=\"headerTimestamp\">'+reportInfo_time+'</p>'+\n\t\t '</div>'+\n\t\t '</div>'+\n\t\t '<div class=\"introFacts\">'+\n\t\t '<h1 class=\"reportTitle\">'+reportInfo_title+'</h1>'+\n\t\t '<div class=\"factsArea\">'+\n\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(0)+' <span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Net Sales</p></div>'+ \n\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+parseFloat(netSalesWorth).toFixed(0)+'<span class=\"factsPrice\">INR</span></h1><p class=\"factsBoxBrief\">Gross Sales</p></div>'+ \n\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+netGuestsCount+'</h1><p class=\"factsBoxBrief\">Guests</p></div>'+ \n\t\t '<div class=\"factsBox\"><h1 class=\"factsBoxFigure\">'+completeReportInfo[0].count+'</h1><p class=\"factsBoxBrief\">Bills</p></div>'+\n\t\t '</div>'+\n\t\t '</div>'+graphRenderSectionContent+\n\t\t '<div class=\"summaryTableSectionHolder\">'+\n\t\t '<div class=\"summaryTableSection\">'+\n\t\t '<div class=\"tableQuickHeader\">'+\n\t\t '<h1 class=\"tableQuickHeaderText\">Quick Summary</h1>'+\n\t\t '</div>'+\n\t\t '<div class=\"tableQuick\">'+\n\t\t '<table style=\"width: 100%\">'+\n\t\t '<col style=\"width: 70%\">'+\n\t\t '<col style=\"width: 30%\">'+\n\t\t '<tr><td class=\"tableQuickBrief\" style=\"font-weight: bold;\">Gross Sales</td><td class=\"tableQuickAmount\" style=\"font-weight: bold;\"><span class=\"price\">Rs.</span>'+parseFloat(netSalesWorth).toFixed(2)+'</td></tr>'+\n\t\t quickSummaryRendererContent+\n\t\t '<tr><td class=\"tableQuickBrief\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\">Net Sales</td><td class=\"tableQuickAmount\" style=\"background: #f3eced; font-size: 120%; font-weight: bold; color: #292727; border-bottom: 2px solid #b03c3e\"><span class=\"price\">Rs.</span>'+parseFloat(completeReportInfo[0].value - netRefundsProcessed).toFixed(2)+'</td></tr>'+\n\t\t '</table>'+\n\t\t '</div>'+\n\t\t '</div>'+\n\t\t '</div>'+\n\t\t salesByBillingModeRenderContentFinal+\n\t\t salesByPaymentTypeRenderContentFinal+\n\t\t '<div style=\"border-top: 2px solid #989898; padding: 12px; background: #f2f2f2;\">'+\n\t\t '<p class=\"footerNote\">www.accelerate.net.in | [email protected]</p>'+\n\t\t '</div>'+\n\t\t '</body>'+\n\t\t '<html>';\n\t}", "function setupPage() {\n getMonsters()\n setNewMonsterHandler()\n pageHandler()\n console.log('%cRan all setup functions', 'color: green')\n}", "function createPage(websiteId, page) {\n page.websiteId = websiteId;\n pages.push(page);\n }", "function resultPage(){\n page.empty();\n page.append($(\"<p>\").text(\"Number Correct: \" + numCorrect));\n page.append($(\"<p>\").text(\"Number Wrong: \" + numWrong));\n page.append($(\"<p>\").text(\"Number Unanswered: \" + numTimeLimit));\n\n currentQuestion = 0;\n numWrong = 0;\n numCorrect = 0;\n numTimeLimit = 0;\n\n setTimeout(function(){\n startPage();\n }, 3300);\n \n }", "setupSchedule(){\n // setup the schedule\n\n SchedulerUtils.addInstructionsToSchedule(this);\n\n let n_trials = (this.practice)? constants.PRACTICE_LEN : 25;\n // added for feedback\n this.feedbacks = [];\n for(let i= 0;i<n_trials;i++)\n {\n this.add(this.loopHead);\n this.add(this.loopBodyEachFrame);\n this.add(this.loopEnd);\n\n // added for feedback\n if(this.practice){\n this.feedbacks.push(new Scheduler(this.psychojs));\n this.add(this.feedbacks[i]);\n }\n }\n this.add(this.saveData);\n }", "function Page() {}", "function Page() {\n\n /**\n * ResultSet of the page\n * @name Page#data\n * @type {ResultSet}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.data = undefined;\n /**\n * References the query results contained in this page.\n * @name QueryPage#pagedData\n * @type {PagedData}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.pagedData = undefined;\n /**\n * The range of query results for this page.\n * @name QueryPage#pageRange\n * @type {PageRange}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.pageRange = undefined;\n /**\n * Indicates whether the page is the first of the paged query results.\n * @name Page#isFirst\n * @type {boolean}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.isFirst = undefined;\n /**\n * Indication whether this page is the last one\n * @name Page#isLast\n * @type {boolean}\n * @readonly\n * @throws {SuiteScriptError} READ_ONLY when setting the property is attempted\n *\n * @since 2018.1\n */\n this.isLast = undefined;\n /**\n * Returns the object type name (query.Page)\n * @governance none\n * @return {string}\n *\n * @since 2018.1\n */\n this.toString = function () { };\n\n /**\n * get JSON format of the object\n * @governance none\n * @return {Object}\n *\n * @since 2020.1\n */\n this.toJSON = function () { };\n }", "function generateTimelineReport(statusID, type, sessionUser, batchTime) {\n return getCommentOrRetweetedStatus(statusID, type).then(function (objs) {\n if (!objs || objs.length <= 0){\n throw new Error('can not find user by given status comments');\n }\n var timeFormater = 'YYYY/MM/DD HH:mm';\n\n // created time will be loss of accuracy 10min\n var createTimes = _.sortBy(_.map(objs, function (obj) {\n var timestamp = obj.created_at.valueOf();\n var perTenMin = Math.ceil(timestamp/1000/60/10);\n var tenMinTimeStamp = perTenMin * 1000 * 60 * 10;\n return moment(tenMinTimeStamp).format(timeFormater);\n }));\n\n // generate xAxisData\n var maxTime = moment(_.last(createTimes), timeFormater).valueOf();\n var minTime = moment(_.first(createTimes), timeFormater).valueOf();\n var temMin = 1000 * 60 * 10;\n var scopeTime = [];\n for (var i = 0; minTime + (i * temMin) < maxTime ; i++) {\n scopeTime.push(minTime + (i * temMin));\n }\n scopeTime.push(maxTime);\n var xAxisData = _.map(scopeTime, function (time) {\n return moment(time).format(timeFormater);\n });\n\n // group by timestamp\n var timeGroup = _.groupBy(createTimes);\n\n // generate seriesData\n var seriesData = _.map(xAxisData, function (key) {\n return timeGroup[key] && timeGroup[key].length || 0;\n });\n\n // calculate the max y number\n var maxLength = _.last(_.sortBy(_.map(timeGroup, function (time) {\n return time.length;\n })));\n var yAxisMax = Math.ceil(maxLength / 5) * 5;\n\n // init report template\n var rainbowBarTpl = reportTemplates.area;\n rainbowBarTpl.title.text = '评论时间曲线报告';\n rainbowBarTpl.series[0].name = '评论';\n rainbowBarTpl.yAxis[0].name = '评论';\n rainbowBarTpl.yAxis[0].max = yAxisMax;\n rainbowBarTpl.xAxis[0].data = xAxisData;\n rainbowBarTpl.series[0].data = seriesData;\n\n // generate the new report\n var newReport = {\n type : 1,\n data : JSON.stringify(rainbowBarTpl),\n status : statusID,\n reportType : reportTypes.timeline.id,\n creater : sessionUser,\n batch : batchTime\n };\n return Report.create(newReport).then(function (report) {\n if (!report){\n throw new Error('can not create the new report');\n }\n sails.log.info('A new report has been created:');\n sails.log.info(report);\n return report;\n });\n })\n}", "function HtmlReportFile(htmlFileName) {\n this.fileName = htmlFileName;\n \tthis.htmlFile = new IloOplOutputFile( this.fileName, false);\n\n \t// Add the object methods\n \tthis.generateReport = _generateReport;\n \tthis.generateHeaderReport = _generateHeaderReport;\n \tthis.generateFooterReport = _generateFooterReport;\n}", "function fillHistoryReport(visits) {\n\t$('#history-pane tbody').empty();\n\t$('#table-history').trigger('destroy.pager');\n\t$(\"#table-history\").trigger(\"update\"); //trigger an update after emptying\n\t//pad(number) function adds zeros in front of number, used to get consistent date / time display. \n\tfunction pad (number) {\n\t\treturn (\"00\" + number).slice(-2);\n\t}\n\n\tif(visits.length === 0) {\n\t\t$('#history-pane #visits').hide();\n\t\t$('#history-pane #no-visit').show();\n\t} else {\n\t\t$('#history-pane #no-visit').hide();\n\t\t$('#history-pane #visits').show();\n\t\t//for each visit found in the log add a row to the table\n\t\tvisits.forEach(function (visitElement) {\n\t\t\tif(visitElement) {\n\t\t\t\t//prepare the data for display\n\t\t\t\tvar visit = {};\n\t\t\t\t\n\t\t\t\tvar visitDate = new Date(+visitElement.timestamp);\n\t\t\t\tvisit.date = visitDate.getFullYear() + \"-\"+ \n\t\t\t\t\t\t\tpad((visitDate.getMonth()+1))+ \"-\" +\n\t\t\t\t\t\t\tpad(visitDate.getDate())+\" \"+\n\t\t\t\t\t\t\tpad(visitDate.getHours())+\":\"+\n\t\t\t\t\t\t\tpad(visitDate.getMinutes());\n\n\t\t\t\tvisit.title = decodeURI(visitElement.title);\n\t\t\t\t//visit.url = $('<a>', {'href': visitElement.url, 'text': removeUrlPrefix(visitElement.url)});\n\t\t\t\t//visit.url.attr(\"target\",\"_blank\");\n\n\t\t\t\t//create a row that will hold the data\n\t\t\t\tvar line = $('<tr>'); \n\t\t\t\t\n\t\t\t\t//for each attribute of the visit, create a table data element and put it in the row\n\t\t\t\tfor (var name in visit) {\n\t\t\t\t\tif (visit.hasOwnProperty(name)) {\n\t\t\t\t\t\tline.append($('<td>', {'text': visit[name]}));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar url_cell=$('<td>').append($('<a>', {'href': decodeURI(visitElement.url), 'text': decodeURI(removeUrlPrefix(visitElement.url)), 'target':\"_blank\"}));\n\t\t\t\tline.append(url_cell);\n\t\t\t\t\n\t\t\t\t//append the line to the table\n\t\t\t\t$('#table-history')\n\t\t\t\t\t.find('tbody').append(line)\n\t\t\t\t\t.trigger('addRows',[$(line)]);\n\t\t\t}\n\t\t});\n\t\t$('#table-history').tablesorterPager(pagerOptions);\n\t\t$(\"#table-history\").trigger(\"update\"); //trigger update so that tablesorter reloads the table\n\t\t$(\".tablesorter-filter\").addClass(\"form-control input-md\");\n\t}\n}", "function PageElementWriter(context, tracker) {\n\tthis.transactionLevel = 0;\n\tthis.repeatables = [];\n\tthis.tracker = tracker;\n\tthis.writer = new ElementWriter(context, tracker);\n}", "function PageElementWriter(context, tracker) {\n\tthis.transactionLevel = 0;\n\tthis.repeatables = [];\n\tthis.tracker = tracker;\n\tthis.writer = new ElementWriter(context, tracker);\n}", "function createRowWithTicketReport(pOneTicketData, pOrder) {\n\n//----------------- <REPORTS>\n//------- USE ONLY ONE FOR A SPECIFIC 'REPORT'\n//------- OR NONE FOR REGULAR USAGE\n //Activate for when I only want to see laptops\n //if(pOneTicketData.eqType != \"Laptop\") {\n // return;\n //}\n\n //Activate for when I only want to see equipments that have been paid for\n //if(!pOneTicketData.paymentCompleted) {\n // return;\n //}\n\n //Activate for when I only want to see equipments paid for with Card (debit or credit)\n // if(pOneTicketData.paymentMethod.indexOf(\"Tarjeta\") == -1) {\n // return;\n // }\n//----------------- </REPORTS>\n\n var tableBody = $(\"#table-body\");\n var mainRow = $(\"#table-body-main-row\");\n var newRow = $(\"<tr>\");\n newRow.attr('data-ticket-DBID', pOneTicketData.ticketID);\n newRow.attr('data-ticket-custDBID', pOneTicketData.custID);\n newRow.addClass('ticket');\n\t\tvar tdTicketCompleted = $(\"<td>\");\n\t\t\n\t\tif (pOneTicketData.deliverCompleted ) {\n tdTicketCompleted.text('Yes');\n } else {\n tdTicketCompleted.text('No');\n }\n\t\tif(pOneTicketData.deliverCompleted != true){\n\t\t\tnewRow.css('color', 'Red');\n\t\t}\n\t\tnumTickets = numTickets + 1;\n\t\tdocument.getElementById(\"search-text\").textContent = numTickets + \" Total Tickets in All Stores\";\n\n\n var tdTicketNum = $(\"<td>\");\n\t\t\ttdTicketNum.text(pOneTicketData.fullTicketNum);\n\t\t\tnewRow.append(tdTicketNum);\n\t\t\t\n\t\t\t var tdTicketLoc = $(\"<td>\");\n\t\t\ttdTicketLoc.text(pOneTicketData.location);\n\t\t\tnewRow.append(tdTicketLoc);\n\n\t\t\tvar tdTicketDate= $(\"<td>\");\n\t\t\tvar sliceDate = pOneTicketData.date;\n\t\t\ttdTicketDate.text(sliceDate.slice(0, sliceDate.lastIndexOf(\"\")));\n\t\t\tnewRow.append(tdTicketDate);\n\n\t\t\tvar fulloneCustomerName = pOneTicketData.custName + ' ' + (pOneTicketData.custLastName);\n\t\t\tvar tdCustName = $(\"<td>\");\n\t\t\ttdCustName.text(fulloneCustomerName);\n\t\t\tnewRow.append(tdCustName);\n\n\t\t\tvar tdEqType = $(\"<td>\");\n\t\t\ttdEqType.text(pOneTicketData.eqType);\n\t\t\tnewRow.append(tdEqType);\n\n\t\t\tvar tdEqBrand = $(\"<td>\");\n\t\t\ttdEqBrand.text(pOneTicketData.eqBrand);\n\t\t\tnewRow.append(tdEqBrand);\n\n\t\t\tvar tdEqModel = $(\"<td>\");\n\t\t\ttdEqModel.text(pOneTicketData.eqModel);\n\t\t\tnewRow.append(tdEqModel);\n\n\t\t\t//newRow.append(tdTicketCompleted);\n\n\t\t\tvar tdIssues = $(\"<td>\");\n\t\t\ttdIssues.text(pOneTicketData.characteristics);\n\t\t\tnewRow.append(tdIssues);\n\n //Finally, append or prepend the whole row to the tablebody\n if (pOrder == 'prepend') {\n tableBody.prepend(newRow);\n } else if (pOrder == 'append') {\n tableBody.append(newRow);\n }\n \n }", "_createPages() {\n let self = this,\n size = Math.floor(self.get('queryCount') / self.get('pageSize')) + 1,\n range = Array(size),\n pagesArray = self.get('pagesArray');\n\n pagesArray.clear();\n let i = 1;\n for (i = 1; i <= range.length; i++) {\n var obj = Ember.Object.create({text: i, className: self.get('pageNumber') === i ? \"active\": \"\"});\n pagesArray.pushObject(obj);\n }\n }", "function produceReport(){\n // this is were most functions are called\n\n userURL = getuserURL();\n\n // add this into the website\n vertifyHttps(userURL); // check if the url is http/s\n googleSafeBrowsingAPI(userURL);\n virusTotalAPI(userURL);\n apilityCheck(userURL);\n}", "function makeTimetable() {\n renderer.draw('.timetable'); // any css selector\n\n\n // Call database and get classes\n getData();\n}", "function buildHTMLPage() {\n\n buildFooter();\n buildNavbar();\n checkRes();\n checkTheme();\n frameshiftNotice();\n //setTimeout(() => noAds(), 5000);\n\n}" ]
[ "0.6146375", "0.55507445", "0.5533378", "0.5457022", "0.541526", "0.5398608", "0.53963065", "0.5384655", "0.53707755", "0.5368844", "0.53672594", "0.5346646", "0.53383744", "0.5328297", "0.5260353", "0.5260353", "0.52383643", "0.519164", "0.51885295", "0.5183171", "0.518133", "0.51754886", "0.5168391", "0.51370007", "0.5126256", "0.51198757", "0.51142246", "0.5113665", "0.5091588", "0.5081667", "0.5079182", "0.5077784", "0.5063141", "0.50473297", "0.50402033", "0.50128967", "0.4996789", "0.49782237", "0.4970095", "0.4958526", "0.49427104", "0.49423775", "0.49219447", "0.49171883", "0.49132127", "0.4908954", "0.49040574", "0.48978698", "0.4890615", "0.48876336", "0.48586217", "0.48518583", "0.48500565", "0.484753", "0.48466352", "0.48366246", "0.4821344", "0.48184747", "0.4817933", "0.4813619", "0.48103723", "0.48063457", "0.48020476", "0.4798329", "0.4798021", "0.4791194", "0.47895056", "0.47872096", "0.47841293", "0.4776728", "0.47664812", "0.47663805", "0.47648147", "0.4761993", "0.47582835", "0.47472018", "0.47416216", "0.4740507", "0.47345936", "0.47342908", "0.47306827", "0.47274682", "0.4716631", "0.47159466", "0.47102275", "0.47076663", "0.47065565", "0.47000548", "0.46872637", "0.46862194", "0.4684998", "0.46839982", "0.46808076", "0.46798795", "0.46798795", "0.46738553", "0.46707398", "0.4667834", "0.4661341", "0.4658302" ]
0.6049583
1
naujo paketo siuntimo formavimas
function netwSend(aceObj,txPack) { // jeigu paketas nenurodytas tada vadinasi reikia siutimą vykdyti iš cache if(txPack===null){ txPack = aceObj.TxCache; // console.log("ACEPRO-NET UDP Sent from Cache."); }else{ aceObj.TxCache = txPack; // console.log("ACEPRO-NET UDP Sent. No Cache used."); } const TxBuf = Buffer.allocUnsafe(28); TxBuf.writeUInt32BE(txPack.CMD, 0); TxBuf.writeUInt32BE(txPack.Src, 4); TxBuf.writeUInt32BE(txPack.Dst, 8); TxBuf.writeInt32BE(txPack.State, 12); TxBuf.writeUInt32BE(txPack.IOID, 16); TxBuf.writeDoubleBE(txPack.val, 20); srv.send(TxBuf, 0, TxBuf.length, port, BrCastAddr, function() { // console.log("ACEPRO-NET UDP Sent '" + JSON.stringify(txPack) + "'"); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "verificaDados(){\n this.verificaEndereco();\n if(!this.verificaVazio()) this.criaMensagem('Campo vazio detectado', true);\n if(!this.verificaIdade()) this.criaMensagem('Proibido cadastro de menores de idade', true);\n if(!this.verificaCpf()) this.criaMensagem('Cpf deve ser válido', true);\n if(!this.verificaUsuario()) this.criaMensagem('Nome de usuario deve respeitar regras acima', true);\n if(!this.verificaSenhas()) this.criaMensagem('Senha deve ter os critérios acima', true)\n else{\n this.criaMensagem();\n // this.formulario.submit();\n }\n }", "function limparUltimosCampos(tipo){\r\n\tvar form = document.ImovelOutrosCriteriosActionForm;\r\n\t\r\n\t//if(form.idMunicipio.value == \"\")\r\n\t\t//limparUltimosCampos(1);\r\n\t\r\n\tswitch(tipo){\r\n\t\tcase 1: //municipio\r\n\t\t\tform.nomeMunicipio.value = \"\";\r\n\t\t\tform.idBairro.value = \"\";\r\n\t\tcase 2: //bairro\r\n\t\t\tform.nomeBairro.value = \"\";\r\n\t\t\tform.idLogradouro.value =\"\";\t\t\t\r\n\t\tcase 3://logradouro\r\n\t\t\tform.nomeLogradouro.value = \"\";\r\n\t\t\tform.CEP.value = \"\";\r\n\t\tcase 4://cep\r\n\t\t\tform.descricaoCep.value = \"\";\r\n\t}\r\n}", "function puliziaForm() {\n var action = $(this).data(\"href\");\n // Invio il form\n $(\"#formInserisciPrimaNotaLibera\").attr(\"action\", action)\n .submit();\n }", "function oqituvchiYozish() {\n let tugma = document.getElementById('oqituvchiQushish');\n let ism = document.forms['createOqituvchiForm']['ism'].value;\n let familiya = document.forms['createOqituvchiForm']['familiya'].value;\n let nomer = document.forms['createOqituvchiForm']['nomer'].value;\n let tajriba = document.forms['createOqituvchiForm']['tajriba'].value;\n let togilganYili = document.forms['createOqituvchiForm']['togilganYili'].value;\n let qisqaMalumot = document.forms['createOqituvchiForm']['qisqaMalumot'].value;\n if (ism == \"\" || familiya == \"\" || nomer == \"\" || tajriba == \"\" || togilganYili == \"\" || qisqaMalumot == \"\") {\n tugma.disabled = true;\n } else {\n tugma.disabled = false;\n }\n}", "anularPropuesta(form) {\n form.value.nombrePropuesta = \"ANULACION\";\n this.poliza.selectPoliza.nombrePropuesta = \"ANULACION\";\n if (form.valid) {\n this.poliza.endPoliza(form.value, this.items)\n .subscribe(res => console.log('Propuesta Añadida(anulacion)'));\n this.toastrSucces(\"Se ha generado correctamente la propuesta, será redirigido pronto a su descarga\", \"Anulación exitosa!!\");\n }\n else {\n this.toastrError(\"Error interno no deja realizar la accion de anular\", \"Error\");\n }\n }", "function avisoFormulario(inf){\n var datos = inf || {}\n \n switch(datos[\"aviso\"]){\n case \"obligatorio\": \n $.notify(`<span class=${datos[\"alerta\"]}>Los campos con * son abligatorios.</span>`); \n break\n case \"errorServidor\":\n $.notify(`<span class=${datos[\"alerta\"]}>No se pudo conectar con el servidor. Verifique su conexión a internet y vuelva a realizar la petición.</span>`);\n break\n } \n}", "function ohodnot(frm)\r\n{\r\n\t// \r\n\t// nazov class pomocou ktorej sa hladaju input elementy\r\n\tvar MOZNOST_CLASS_NAME = 'odpoved';\r\n\r\n\t//\r\n\t// nazov triedy, ktorou bude oznaceny rodicovsky element spravnej odpovede\r\n\tvar SPRAVNA_CLASS_NAME = 'spravna';\r\n\t\r\n\t//\r\n\t// nazov triedy, ktorou bude oznaceny rodicovsky element spravnej odpovede\r\n\tvar NESPRAVNA_CLASS_NAME = 'nespravna';\t\r\n\r\n\r\n\t// \r\n\t// najdi vsetky odpovede\r\n\tvar odpovede = document.getElementsByClassName( MOZNOST_CLASS_NAME, frm);\r\n\t\r\n\t//\r\n\t// ziskaj z nich unique zoznam \"name\"\r\n\tvar nazvy = Array();\r\n\todpovede.each(function (item) { \r\n\t\tnazvy.push(item.name); \r\n\t});\r\n\tnazvy = nazvy.uniq();\r\n\t\r\n\t// \r\n\t// over ci su vsetky zaskrtnute\r\n\tfor (var i=0; i<nazvy.length; i++) {\r\n\t\tvar nazov = nazvy[i];\r\n\t\t\r\n\t\t\t\t\r\n\t\t// zoznam item v nich\r\n\t\tvar moznosti = frm.getInputs('radio', nazov);\r\n\t\t\r\n\t\t// prelistuj ich a zisti ci je aspon 1 zaskrtnuty (viac nemoze byt, lebo maju rovnake meno)\r\n\t\tvar zaskrtnute = false;\r\n\t\tvar spravne_moznosti = 0;\r\n\t\tmoznosti.each(function (moznost) {\r\n\t\t\tif (moznost.checked) {\r\n\t\t\t\tzaskrtnute = true;\r\n\t\t\t}\r\n\t\t\tif (moznost.value == 1) {\t\r\n\t\t\t\tspravne_moznosti++;\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\t\t// ak nie je zakrtnuty, tak zrus validaciu\r\n\t\tif (!zaskrtnute) {\r\n\t\t\talert('Musíte zodpovedať všetky otázky!');\r\n\t\t\treturn false;\r\n\t\t}\t\t\r\n\t\tdocument.getElementById(nazov).style.visibility = 'visible';\r\n\t\t//\r\n\t\t// ak otazka nema ani jednu spravnu odpoved v kode, alebo ma viac moznosti\r\n\t\t// upozorni autora\r\n\t\tif (spravne_moznosti != 1) {\r\n\t\t\tif (spravne_moznosti > 1) {\r\n\t\t\t\talert('Otazka s parametrom name: '+ nazov + ' musi mat len 1 spravnu odpoved!');\r\n\t\t\t} else {\r\n\t\t\t\talert('Otazka s parametrom name: '+ nazov + ' musi mat 1 spravnu odpoved !');\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\t};\r\n\t\r\n\t//\r\n\t// statistiky vyhodnocovania\r\n\tvar pocet_otazok = nazvy.length;\r\n\tvar pocet_nespravnych = 0;\r\n\tvar pocet_spravnych = 0;\r\n\t\r\n\t// \r\n\t// vyhodnot jednotlive moznosti\r\n\tnazvy.each(function (nazov) {\r\n\t\t\r\n\t\t// zoznam item v nich\r\n\t\tvar moznosti = frm.getInputs('radio', nazov);\r\n\t\t\r\n\t\t// prelistuj a ohodnot\r\n\t\tmoznosti.each(function (moznost) {\r\n\t\t\tif (moznost.checked) {\r\n\t\t\t\tif (moznost.value == 1) {\r\n\t\t\t\t\tpocet_spravnych++;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tpocet_nespravnych++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n\t\r\n\t// \r\n\t// zvyrazni spravne a nespravne vysledky\r\n\tnazvy.each(function (nazov) {\r\n\t\t\r\n\t\t// zoznam item v nich\r\n\t\tvar moznosti = frm.getInputs('radio', nazov);\r\n\t\t\r\n\t\t// prelistuj a ohodnot\r\n\t\tmoznosti.each(function (moznost) {\r\n\t\t\r\n\t\t\t// odstran predchadzajuce\r\n\t\t\tmoznost.parentNode.removeClassName(SPRAVNA_CLASS_NAME);\t\t\t\r\n\t\t\tmoznost.parentNode.removeClassName(NESPRAVNA_CLASS_NAME);\r\n\t\t\t\r\n\t\t\tif (moznost.checked) {\r\n\t\t\t\tif (moznost.value == 1) {\r\n\t\t\t\t\t// spravna odpoved + celkovo spravna\r\n\t\t\t\t\tmoznost.parentNode.addClassName(SPRAVNA_CLASS_NAME);\r\n\t\t\t\t\tmoznost.parentNode.parentNode.removeClassName(NESPRAVNA_CLASS_NAME);\r\n\t\t\t\t\tmoznost.parentNode.parentNode.removeClassName('otazka');\r\n\t\t\t\t\tmoznost.parentNode.parentNode.addClassName('otazka'+SPRAVNA_CLASS_NAME);\r\n\t\t\t\t\t\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// nespravna odpoved + celkovo nespravna\r\n\t\t\t\t\tmoznost.parentNode.addClassName(NESPRAVNA_CLASS_NAME);\r\n\t\t\t\t\tmoznost.parentNode.parentNode.removeClassName(SPRAVNA_CLASS_NAME);\r\n\t\t\t\t\tmoznost.parentNode.parentNode.removeClassName('otazka');\r\n\t\t\t\t\tmoznost.parentNode.parentNode.addClassName('otazka'+NESPRAVNA_CLASS_NAME);\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (moznost.value == 1) {\r\n\t\t\t\t\t// spravna odpoved\r\n\t\t\t\t\tmoznost.parentNode.addClassName(SPRAVNA_CLASS_NAME);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n\t\r\n\t//\r\n\t// zobraz vysledok za pomoci alert\r\n\tif (pocet_otazok == pocet_spravnych) {\r\n\t\talert('Gratulujem !!!, zodpovedali ste všetky otázky správne!');\r\n\t} else {\r\n\t\talert('Zodpovedali ste správne ' + pocet_spravnych + ' otázok z ' + pocet_otazok + ' možných.');\r\n\t}\r\n\t\r\n\t// \r\n\t// allways return false - do not redirect\r\n\treturn false;\r\n}", "function limpiarAutorForm() {\n nombre.value = '';\n apellido.value = '';\n document.querySelector('#slc_autor_pais').value = '0'\n /**\n * Primero se selecciona el radio por su atributo \"name\"\n * posteriormente se recorre con el ciclo \"for\" para poder\n * establecer que ninguno de los elementos será seleccionado\n */\n genero = document.getElementsByName('genero');\n for (var i = 0; i < genero.length; i++)\n genero[i].checked = false;\n nacimiento.value = '';\n muerte.value = '';\n document.querySelector('#txt_ingreso_fecha_autor').value = dateToday;\n}", "crtajUnosZaNovuKarticu(host){//Host je kontejner gde idu forme za unos\r\n\r\n const formaZaUnosNoveKartice = document.createElement(\"div\");//Forma je kontejner gde idu elementi za unos\r\n formaZaUnosNoveKartice.className = \"forme\"\r\n this.formaZaUnosNoveKartice = formaZaUnosNoveKartice;\r\n host.appendChild(formaZaUnosNoveKartice);\r\n\r\n let labelaNaslov = document.createElement(\"h3\");//Naslov za formu za unos nove kartice\r\n labelaNaslov.innerHTML = \"Dodavanje nove VIP kartice\";\r\n labelaNaslov.className = \"labelaNaslov\";\r\n formaZaUnosNoveKartice.appendChild(labelaNaslov);\r\n\r\n let elementiForme = [\"Ime\", \"Prezime\", \"JMBG\", \"E-mail\", \"Vrsta kartice\"];//Elementi na formi\r\n let nizInputa=[];\r\n elementiForme.forEach(el => {//Dodavanje elementa na formu\r\n let input = document.createElement(\"input\");//input za elemente za projekciju\r\n input.classList = \"inputi\";\r\n input.placeholder = el;\r\n\r\n formaZaUnosNoveKartice.appendChild(input);\r\n \r\n if(el == \"JMBG\"){input.type = \"number\"}\r\n else if(el == \"E-mail\"){input.type = \"email\"}\r\n \r\n nizInputa.push(input);\r\n if(el == \"Vrsta kartice\"){\r\n input.classList = \"inputi inputi1\";\r\n input.disabled = true;\r\n nizInputa.pop();\r\n };\r\n });\r\n\r\n let radioButtons = document.createElement(\"div\");//Kontejner za radio buttone\r\n radioButtons.className = \"radioButtonsClass\";\r\n let radioOpcije = [\"Silver(10%)\", \"Gold(20%)\", \"Platinum(30%)\"];\r\n\r\n radioOpcije.forEach(el => {//Dodavanje radio buttona u njihov kotejner\r\n\r\n let labelaRadio = document.createElement(\"label\");\r\n labelaRadio.className = \"labelaRadio\";\r\n labelaRadio.innerHTML = el;\r\n radioButtons.appendChild(labelaRadio);\r\n let radioButton = document.createElement(\"input\");\r\n radioButton.type = \"radio\";\r\n radioButton.value = el;\r\n radioButton.name = \"radioGrupa1\";\r\n radioButtons.appendChild(radioButton);\r\n });\r\n formaZaUnosNoveKartice.appendChild(radioButtons);//Dodajemo kontejner za radio buttone na formu\r\n\r\n let buttonDodaj = document.createElement(\"button\");//dugme za dodavanje nove kartice\r\n buttonDodaj.innerHTML = \"Dodaj\";\r\n buttonDodaj.className = \"btnDodaj\";\r\n\r\n buttonDodaj.onclick=ev=>{\r\n \r\n var vredPop=document.getElementsByName(\"radioGrupa1\");\r\n var valuee=\"\";\r\n for(let i=0;i<vredPop.length;i++)\r\n {\r\n if(vredPop[i].checked)\r\n {\r\n valuee=vredPop[i].value;\r\n break;\r\n }\r\n }\r\n var proveraElemenata=0;\r\n nizInputa.forEach(el=>{\r\n if(el.value==\"\")\r\n {\r\n proveraElemenata=1;\r\n }\r\n else if(nizInputa[2].value.length!=13)\r\n {\r\n proveraElemenata=1;\r\n }\r\n })\r\n if(proveraElemenata==0 && valuee!=\"\")\r\n {\r\n let datee=new Date();\r\n let id=Math.round(Math.random()*1000+datee.getMinutes()+datee.getSeconds());\r\n fetch(\"https://localhost:5001/Bioskop/UpisKartice/\", {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\"\r\n },\r\n body: JSON.stringify({/*Kroz body upisujemo u bazu podataka*/\r\n \"ime\": nizInputa[0].value,\r\n \"prezime\": nizInputa[1].value,\r\n \"jmbg\": nizInputa[2].value,\r\n \"eMail\": nizInputa[3].value,\r\n \"vrstaKartice\": valuee,\r\n \"idKartice\" : id\r\n })\r\n })\r\n alert(`Cestitamo, postali ste korisnik VIP karrtice\\n Vas ID je: ${id}`);\r\n nizInputa.forEach(p=>{p.value=\"\"});\r\n }\r\n else\r\n {\r\n alert(\"Podaci nisu ispravno uneti\");\r\n }\r\n };\r\n\r\n formaZaUnosNoveKartice.appendChild(buttonDodaj);\r\n }", "function validarform(e) {\n let personaNueva = {\n nombre : nombreDom.value;\n apellido : apellidoDom.value;\n numeroTarjeta : numeroTarjetaDom.value;\n fechaVence : fechaDom.value;\n pin : valorPinDom.value;\n }", "function destacaCamposComProblemaEmForms( erros ){\n\n tabela.find('.form-group').removeClass('has-error');\n\n $.each( erros, function( index, erro ){\n\n $(\"[name='\"+index+\"']\").parents(\".form-group\").addClass('has-error');\n\n });\n\n }", "function init_inpt_formulario_cargar_recorrido() {\n // Inputs del formulario para inicializar\n}", "function chequearRequeridos() {\n\n oPublicar=document.forms[0];\n for (i=0; i < oPublicar.elements.length; i++) {\n \n if (oPublicar.elements[i].getAttribute(\"Requerido\")!= null){\n if (oPublicar.elements[i].getAttribute(\"Requerido\") == \"Si\"){\n //if (!oPublicar.elements[i].readOnly && !oPublicar.elements[i].disabled) {\n if (!oPublicar.elements[i].disabled) {\n if (oPublicar.elements[i].value.length==0) {\n alert(\"Debe ingresar el dato '\" + oPublicar.elements[i].getAttribute(\"Dato\")+ \"'\");\n oPublicar.elements[i].focus();\n if (oPublicar.elements[i].tagName!=\"SELECT\"){\n oPublicar.elements[i].select(); \n }\n return false;\n }\n }\n }\n }\n\n if (oPublicar.elements[i].value.length>0) {\n if (oPublicar.elements[i].getAttribute(\"Tipo\") != null) {\n if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"Fecha\"){\n if (!checkdate(oPublicar.elements[i].value)) {\n alert('Fecha inv�lida, vualva a ingresarla');\n oPublicar.elements[i].focus();\n oPublicar.elements[i].select();\n return false;\n } // end if\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"Integer\") {\n if (!valNumericInt(oPublicar.elements[i].value)) {\n var strErrorMsg = display_name(oPublicar.elements[i]) + \" no debe poseer letras, puntos o decimales.\";\n alert(strErrorMsg);\n oPublicar.elements[i].focus();\n oPublicar.elements[i].select();\n return false;\n } // end if\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"Decimal\") {\n if (!valNumeric(oPublicar.elements[i].value)) {\n var strErrorMsg = display_name(oPublicar.elements[i]) + \" no debe poseer letras, puntos.\";\n alert(strErrorMsg);\n oPublicar.elements[i].focus();\n oPublicar.elements[i].select();\n return false;\n } // end if\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"email\") {\n if (!validEmail(oPublicar.elements[i])) {\n oPublicar.elements[i].focus();\n oPublicar.elements[i].select();\n return false;\n } // end if\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"clave\") {\n oClave = oPublicar.elements[i];\n if (oClave.value.length<6) {\n alert(\"La contrase�a debe tener entre 6 y 10 digitos\");\n return false;\n }\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"clave2\") {\n if (oClave.value!=oPublicar.elements[i].value) {\n alert(\"Las contrase�as no coinciden.\\nIngrese ambas nuevamente.\");\n oClave.value=\"\";\n oPublicar.elements[i].value=\"\";\n oClave.focus()\n return false;\n }\n //}\n \n //control de tipo dni y nro para form preinsc. - juan\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"dnitipo\") {\n oTipo = oPublicar.elements[i];\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"dnitipo2\") {\n if (oTipo.value!=oPublicar.elements[i].value) {\n alert(\"Los Tipos de Documento no coinciden.\\n Verifique su selecci�n.\");\n oPublicar.elements[i].value=\"\";\n //oPublicar.elements[i].focus();\n //lo vuelvo al boton corregir para que se vea lo que ingres� en rojo\n window.document.forms[0].corregir.focus();\n return false;\n }\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"dninro\") {\n oNro = oPublicar.elements[i];\n } else if (oPublicar.elements[i].getAttribute(\"Tipo\") == \"dninro2\") {\n if (oNro.value!=oPublicar.elements[i].value) {\n alert(\"Los N�meros de Documento no coinciden.\\n Verif�quelo y vuelva a ingresarlo.\");\n oPublicar.elements[i].value=\"\";\n //oPublicar.elements[i].focus();\n //lo vuelvo al boton corregir para que se vea lo que ingres� en rojo\n window.document.forms[0].corregir.focus();\n return false;\n }\n }\n //hasta aca es lo que agregue para el form_preinsc - juan\n \n }// End If Publicar.elements[i].Tipo != null)\n }\n } // Fin For\n return true;\n}//End Function", "limparCampoForm(form) {\n form.id.value = \"\";\n form.nome.value = \"\";\n form.descricao.value = \"\";\n form.detalhes.value = \"\";\n }", "function registrarPrepago(){\r\n\t//alert('registrar datos prepago');\r\n\tvar frm = document.forms[0];\r\n\tfrm.buttonActualizar.disabled = false;\r\n\tfrm.buttonActualizar.value=\"Registrar\";\r\n\tfrm.tipo.value=\"registrar\";\r\n\tfrm.buttonActualizarCuenta.disabled = true;\r\n\tdocument.getElementById('botoncuenta').style.display='none';\r\n\tfrm.nombre.disabled=false;\r\n\tfrm.apePat.disabled=false;\r\n\tfrm.tipoDoc.disabled=false;\r\n\tfrm.numeDoc.disabled=false;\r\n\tfrm.teleRef.disabled=false;\r\n\tfrm.sexo[0].disabled=false;\r\n\tfrm.sexo[1].disabled=false;\r\n\tfrm.fechaNaci.disabled=false;\r\n\tfrm.emailUsuario.disabled=false;\r\n\tfrm.lugarNaci.disabled=false;\r\n\t\r\n for (i = 0; i < frm.lugarNaci.length; i++) {\r\n if (frm.lugarNaci[i].value == 'Peru') {\r\n frm.lugarNaci[i].selected = true;\r\n } \r\n }\r\n}", "function puliziaForm() {\n var action = $(this).data(\"href\");\n // Invio il form\n $(\"#formRichiestaEconomale\").attr(\"action\", action)\n .submit();\n }", "function puliziaForm() {\n var action = $(this).data(\"href\");\n // Invio il form\n $(\"#formRichiestaEconomale\").attr(\"action\", action)\n .submit();\n }", "function dadosForamPreenchidos(form) {\n\tif(form.nome.value != \"\" && form.peso.value != \"\" && form.altura.value != \"\" && form.gordura.value != \"\"){\n\t\treturn true;\n\t}else{\n\t\treturn false;\n\t}\n}", "function cambiar(){\n \t var compania;\n \t //Se toma el valor de la \"compañia seleccionarda\"\n \t compania = document.formulariorecargas.compania[document.formulariorecargas.compania.selectedIndex].value;\n \t //se chequea si la \"compañia\" esta definida\n \t \n \t if(compania!=0){\n \t\t //Seleccionamos las cosas correctas\n \t\t \n \t\t mis_tipos=eval(\"tipo_\" + compania);\n \t\t //se calcula el numero de compania\n \t\t num_tipos=mis_tipos.length;\n \t\t //marco el numero de tipos en el select\n \t\t document.formulariorecargas.tipo.length = num_tipos;\n \t\t //para cada tipo del array, la pongo en el select\n \t\t for(i=0; i<num_tipos; i++){\n \t\t\t document.formulariorecargas.tipo.options[i].value=mis_tipos[i];\n \t\t\t document.formulariorecargas.tipo.options[i].text=mis_tipos[i];\n \t\t }\n \t\t \n \t\t }else{\n \t\t\t //sino habia ningun tipo seleccionado,elimino las cosas del select\n \t\t\t document.formulariocompania.tipo.length = 1;\n \t\t\t //ponemos un guion en la unica opcion que he dejado\n \t\t\t document.formulariorecargas.tipo.options[0].value=\"seleccionar\";\n \t\t\t document.formulariorecargas.tipo.options[0].text=\"seleccionar\";\n \t\t\t \n \t\t }\n \t \n \t\n \t \n \t \n \t\t //hacer un reset de los tipos\n \t document.formulariorecargas.tipo.options[0].selected=true;\n\n }", "function populateJs2Form(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('cobEtapaDeudaFrm.accion'), \n\t\tget('cobEtapaDeudaFrm.origen'));\n\n\n\tset('cobEtapaDeudaFrm.id', jsCobEtapaDeudaId);\n\tset('cobEtapaDeudaFrm.codEtapDeud', jsCobEtapaDeudaCodEtapDeud);\n\tset('cobEtapaDeudaFrm.valDesc', jsCobEtapaDeudaValDesc);\n\tset('cobEtapaDeudaFrm.indExcl', jsCobEtapaDeudaIndExcl);\n\tset('cobEtapaDeudaFrm.valEdadInic', jsCobEtapaDeudaValEdadInic);\n\tset('cobEtapaDeudaFrm.valEdadFina', jsCobEtapaDeudaValEdadFina);\n\tset('cobEtapaDeudaFrm.indTelf', jsCobEtapaDeudaIndTelf);\n\tset('cobEtapaDeudaFrm.impDesd', jsCobEtapaDeudaImpDesd);\n\tset('cobEtapaDeudaFrm.impHast', jsCobEtapaDeudaImpHast);\n\tset('cobEtapaDeudaFrm.numDiasGracCompPago', jsCobEtapaDeudaNumDiasGracCompPago);\n\tset('cobEtapaDeudaFrm.valPorcIncu', jsCobEtapaDeudaValPorcIncu);\n\tset('cobEtapaDeudaFrm.mensOidMens', [jsCobEtapaDeudaMensOidMens]);\n\tset('cobEtapaDeudaFrm.melcOidMetoLiquCobr', [jsCobEtapaDeudaMelcOidMetoLiquCobr]);\n\tset('cobEtapaDeudaFrm.tbalOidTipoBala', [jsCobEtapaDeudaTbalOidTipoBala]);\n\tset('cobEtapaDeudaFrm.gacaOidGuioArguCabe', [jsCobEtapaDeudaGacaOidGuioArguCabe]);\n\tset('cobEtapaDeudaFrm.paisOidPais', [jsCobEtapaDeudaPaisOidPais]);\n\tset('cobEtapaDeudaFrm.oredOidEtapDeu1', [jsCobEtapaDeudaOredOidEtapDeu1]);\n\tset('cobEtapaDeudaFrm.oredOidEtapDeu2', [jsCobEtapaDeudaOredOidEtapDeu2]);\n\tset('cobEtapaDeudaFrm.oredOidEtapDeu3', [jsCobEtapaDeudaOredOidEtapDeu3]);\n\t\n}", "function limparMBCL(tipo){\r\n\tvar form = document.ImovelOutrosCriteriosActionForm;\r\n\tswitch(tipo){\r\n\t\tcase 1:\r\n\t\t\tform.idMunicipio.value = \"\";\r\n\t\t\tform.nomeMunicipio.value = \"\";\r\n\t\tcase 2:\r\n\t\t\tform.idBairro.value = \"\";\r\n\t\t\tform.nomeBairro.value = \"\";\r\n\t\tcase 3:\r\n\t\t\tform.idLogradouro.value = \"\";\r\n\t\t\tform.nomeLogradouro.value = \"\";\r\n\t\tcase 4:\r\n\t\t\tform.CEP.value = \"\";\r\n\t\t\tform.descricaoCep.value = \"\";\r\n\r\n\t}\r\n}", "function ObtemPessoaDoFormulario(form) {\r\n var pessoa = {\r\n nome : form.nome.value,\r\n matricula : form.matricula.value,\r\n sala : form.sala.value,\r\n horario : form.horario.value\r\n }\r\n return pessoa;\r\n}", "function recuperarDadosQuatroParametros(idRegistro, descricaoRegistro, codigoRegistro, tipoConsulta) {\r\n\r\n\tvar form = document.ImovelOutrosCriteriosActionForm;\r\n\r\n\tif (tipoConsulta == 'setorComercialOrigem') {\r\n form.setorComercialOrigemCD.value = codigoRegistro;\r\n form.setorComercialOrigemID.value = idRegistro;\r\n\t form.nomeSetorComercialOrigem.value = descricaoRegistro;\r\n\t form.nomeSetorComercialOrigem.style.color = \"#000000\";\r\n\t \r\n\t form.setorComercialDestinoCD.value = codigoRegistro;\r\n form.setorComercialDestinoID.value = idRegistro;\r\n\t form.nomeSetorComercialDestino.value = descricaoRegistro;\r\n\t form.nomeSetorComercialDestino.style.color = \"#000000\";\r\n\t form.quadraOrigemNM.focus();\r\n\t}\r\n\r\n\tif (tipoConsulta == 'setorComercialDestino') {\r\n form.setorComercialDestinoCD.value = codigoRegistro;\r\n form.setorComercialDestinoID.value = idRegistro;\r\n\t form.nomeSetorComercialDestino.value = descricaoRegistro;\r\n\t form.nomeSetorComercialDestino.style.color = \"#000000\"; \r\n\t form.quadraDestinoNM.focus();\r\n\t}\r\n\r\n//\tif (tipoConsulta == 'quadraOrigem') {\r\n // form.quadraOrigemNM.value = codigoRegistro;\r\n\t// form.quadraOrigemID.value = idRegistro;\r\n//\t form.quadraMensagemOrigem.value = descricaoRegistro;\r\n\t// form.quadraMensagemOrigem.style.color = \"#000000\";\r\n\t \r\n//\t form.quadraDestinoNM.value = codigoRegistro;\r\n\t// form.quadraDestinoID.value = idRegistro;\r\n\t //form.quadraMensagemDestino.value = descricaoRegistro;\r\n// }\r\n\r\n//\tif (tipoConsulta == 'quadraDestino') {\r\n // form.quadraDestinoNM.value = codigoRegistro;\r\n\t// form.quadraDestinoID.value = idRegistro;\r\n// \t form.quadraMensagemDestino.value = descricaoRegistro;\r\n //\t form.quadraMensagemDestino.style.color = \"#000000\";\r\n\t//}\r\n\tform.action = 'exibirFiltrarImovelOutrosCriteriosConsumidoresInscricao.do?menu=sim&gerarRelatorio=RelatorioCadastroConsumidoresInscricao&limpar=S';\r\n\tform.submit();\r\n\r\n}", "function faltante(formulario,campo,msj,enfermedades){\n\n var tipo = $('body').find(formulario+' *[name=\"'+campo+'\"]').prop('type');\n // alert(tipo+' > '+campo+ '='+($('body').find(formulario+' *[name=\"'+campo+'\"]').val()));\n if((tipo=='text') || (tipo=='email') || (tipo=='select-one')){\n if(($('body').find(formulario+' *[name=\"'+campo+'\"]').val()=='') || ($('body').find(formulario+' *[name=\"'+campo+'\"]').val()==0)){\n faltan.push(msj);\n }\n }else{\n if($('input[name=\"'+campo+'\"]:checked').val()==undefined){\n faltan.push(msj);\n }\n }\n }", "function mostrarFormulario(){\n var acum; \n //variable que permite saber que es un registrar\n encontrado=0; \n if(ventana==null) \n ventana = Ext.create ('App.miVentanaBanco')\n limpiar();\n ventana.show();\n }", "function populateJs2Form(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('cobUsuarEtapaCobraDetalFrm.accion'), \n\t\tget('cobUsuarEtapaCobraDetalFrm.origen'));\n\n\n\tset('cobUsuarEtapaCobraDetalFrm.id', jsCobUsuarEtapaCobraDetalId);\n\tset('cobUsuarEtapaCobraDetalFrm.ueccOidUsuaEtapCobr', [jsCobUsuarEtapaCobraDetalUeccOidUsuaEtapCobr]);\n\tset('cobUsuarEtapaCobraDetalFrm.edtcOidEtapDeudTipoCarg', [jsCobUsuarEtapaCobraDetalEdtcOidEtapDeudTipoCarg]);\n\tset('cobUsuarEtapaCobraDetalFrm.zsgvOidSubgVent', [jsCobUsuarEtapaCobraDetalZsgvOidSubgVent]);\n\tset('cobUsuarEtapaCobraDetalFrm.zorgOidRegi', [jsCobUsuarEtapaCobraDetalZorgOidRegi]);\n\tset('cobUsuarEtapaCobraDetalFrm.zzonOidZona', [jsCobUsuarEtapaCobraDetalZzonOidZona]);\n\tset('cobUsuarEtapaCobraDetalFrm.zsccOidSecc', [jsCobUsuarEtapaCobraDetalZsccOidSecc]);\n\tset('cobUsuarEtapaCobraDetalFrm.terrOidTerr', [jsCobUsuarEtapaCobraDetalTerrOidTerr]);\n\tset('cobUsuarEtapaCobraDetalFrm.melcOidMetoLiquCobr', [jsCobUsuarEtapaCobraDetalMelcOidMetoLiquCobr]);\n\tset('cobUsuarEtapaCobraDetalFrm.eucoOidEstaUsuaEtapCobr', [jsCobUsuarEtapaCobraDetalEucoOidEstaUsuaEtapCobr]);\n\tset('cobUsuarEtapaCobraDetalFrm.gacaOidGuioArguCabe', [jsCobUsuarEtapaCobraDetalGacaOidGuioArguCabe]);\n\tset('cobUsuarEtapaCobraDetalFrm.valObse', jsCobUsuarEtapaCobraDetalValObse);\n\t\n}", "function fanTuriYozish() {\n let nomi = document.forms['createFanTuriForm']['nomi'].value;\n let tugma = document.getElementById('fanTuriQushish');\n if (nomi == \"\") {\n tugma.disabled = true;\n } else {\n tugma.disabled = false;\n }\n}", "function limpa_formulário_cep() {\n //Limpa valores do formulário de cep.\n document.getElementById('id_logradouro').value = (\"\");\n document.getElementById('id_bairro').value = (\"\");\n document.getElementById('id_cidade').value = (\"\");\n document.getElementById('id_estado').value = (\"\");\n}", "function Exo_4_8_jsform()\r\n //Début\r\n {\r\n var iJour, iMois, iAnnee, bBis, bTrente;\r\n\r\n //Ecrire \"Entrez le jour\"\r\n // Lire iJour\r\n iJour=document.getElementById(\"iJour\").value;\r\n // Ecrire \"Entre le mois\"\r\n // Lire iMois\r\n iMois=document.getElementById(\"iMois\").value;\r\n // Ecrire \"Entrez l'année\"\r\n // Lire iAnnee\r\n iAnnee=document.getElementById(\"iAnnee\").value;\r\n\r\n bBis= iAnnee%4===0 && iAnnee%100!=0 || iAnnee%400===0; \r\n bTrente=(iMois===\"avr\") || (iMois===\"jui\") || (iMois===\"sep\") || (iMois===\"nov\");\r\n\r\n\r\n\r\n if ((iMois===\"fev\" && ((iJour>\"28\" && !bBis) || iJour>\"29\")) || (iJour>\"30\" && bTrente) || (iJour>\"31\"))\r\n {\r\n document.getElementById(\"sp_resultat_code\").innerHTML=\"votre date est incorrect\";\r\n }\r\n else \r\n {\r\n document.getElementById(\"sp_resultat_code\").innerHTML=\"votre date est valide\";\r\n }\r\n\r\n }", "function ocu_form()\n\t{\n\t$('alta_modi').style.display='none';\n\tif($('mod_buscador') != undefined)\n\t\t{\n\t\t$('mod_buscador').style.display='none';\n\t\t}\n\t$('mod_listado').style.display='block';\n\t}", "incorporarPropuesta(form) {\n form.value.nombrePropuesta = \"INCORPORACION\";\n this.poliza.selectPoliza.nombrePropuesta = \"INCORPORACION\";\n if (form.valid) {\n this.poliza.endPoliza(form.value, this.items)\n .subscribe(res => console.log('Propuesta Añadida(incorporacion)'));\n this.toastrSucces(\"Se ha generado correctamente la propuesta, será redirigido pronto a su descarga\", \"Incorporación exitosa!!\");\n }\n else {\n this.toastrError(\"Error interno no deja realizar la accion de incorporar\", \"Error\");\n }\n }", "function iniFormPeticion(){\n if(gestor.getLocal()[\"idPeticion\"] != \"\"){\n peticionManager.getPeticion(\"id=\" + gestor.getLocal()[\"idPeticion\"], 'formPeticion');\n }\n else { iniFormPeticionNuevo(); }\n}", "function populateJs2Form(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('segPaisViewFrm.accion'), \n\t\tget('segPaisViewFrm.origen'));\n\n\n\tset('segPaisViewFrm.id', jsSegPaisViewId);\n\tset('segPaisViewFrm.codPais', jsSegPaisViewCodPais);\n\tset('segPaisViewFrm.moneOidMone', [jsSegPaisViewMoneOidMone]);\n\tset('segPaisViewFrm.moneOidMoneAlt', [jsSegPaisViewMoneOidMoneAlt]);\n\tif(mode == MMG_MODE_CREATE || mode == MMG_MODE_UPDATE_FORM){\n\t\tunbuildLocalizedString('segPaisViewFrm', 1, jsSegPaisViewDescripcion)\n\t\tloadLocalizationWidget('segPaisViewFrm', 'Descripcion', 1);\n\t}else{\n\t\tset('segPaisViewFrm.Descripcion', jsSegPaisViewDescripcion);\t\t\n\t}\n\tset('segPaisViewFrm.indInteGis', [jsSegPaisViewIndInteGis]);\n\tset('segPaisViewFrm.valIden', [jsSegPaisViewValIden]);\n\tset('segPaisViewFrm.indSaldUnic', jsSegPaisViewIndSaldUnic);\n\tset('segPaisViewFrm.valProgEjec', jsSegPaisViewValProgEjec);\n\tset('segPaisViewFrm.valPorcAlar', jsSegPaisViewValPorcAlar);\n\tset('segPaisViewFrm.indCompAuto', jsSegPaisViewIndCompAuto);\n\tset('segPaisViewFrm.numDiasMora', jsSegPaisViewNumDiasMora);\n\tset('segPaisViewFrm.indTratAcumDesc', jsSegPaisViewIndTratAcumDesc);\n\tset('segPaisViewFrm.valTiemRezo', jsSegPaisViewValTiemRezo);\n\tset('segPaisViewFrm.valConfSecuCcc', [jsSegPaisViewValConfSecuCcc]);\n\tset('segPaisViewFrm.numDiasFact', jsSegPaisViewNumDiasFact);\n\tset('segPaisViewFrm.numLimiDifePago', jsSegPaisViewNumLimiDifePago);\n\tset('segPaisViewFrm.indEmisVenc', jsSegPaisViewIndEmisVenc);\n\tset('segPaisViewFrm.valMaxiDifeAnlsComb', jsSegPaisViewValMaxiDifeAnlsComb);\n\tset('segPaisViewFrm.numPosiNumeClie', jsSegPaisViewNumPosiNumeClie);\n\tset('segPaisViewFrm.valFormFech', [jsSegPaisViewValFormFech]);\n\tset('segPaisViewFrm.valSepaMile', [jsSegPaisViewValSepaMile]);\n\tset('segPaisViewFrm.valSepaDeci', [jsSegPaisViewValSepaDeci]);\n\tset('segPaisViewFrm.numPeriEgre', jsSegPaisViewNumPeriEgre);\n\tset('segPaisViewFrm.numPeriReti', jsSegPaisViewNumPeriReti);\n\tset('segPaisViewFrm.fopaOidFormPago', [jsSegPaisViewFopaOidFormPago]);\n\tset('segPaisViewFrm.valCompTele', jsSegPaisViewValCompTele);\n\tset('segPaisViewFrm.indFletZonaUbig', [jsSegPaisViewIndFletZonaUbig]);\n\tset('segPaisViewFrm.valIndiSecuMoni', jsSegPaisViewValIndiSecuMoni);\n\tset('segPaisViewFrm.indSecu', [jsSegPaisViewIndSecu]);\n\tset('segPaisViewFrm.indBalaAreaCheq', [jsSegPaisViewIndBalaAreaCheq]);\n\tset('segPaisViewFrm.valUrl', jsSegPaisViewValUrl);\n\t\n}", "function atribuirSiglaGrupo(sSigla, sGrupo) {\n document.forms[0].txt_Sigla.value = sSigla;\n document.forms[0].txt_GrupoCorrente.value = sGrupo;\n}", "function agregarform_alcap(datos){\n d=datos.split('||');\n $('#codigoalcas').val(d[0]);\n $('#nombres').val(d[1]); \n $('#apellidos').val(d[2]); \n $('#tipos').val(d[3]); \n \n \n \n}", "function Exo_4_7_jsform()\r\n //Début\r\n {\r\n var iConducteur, iPermis, iAccident, iFidelite, sRouge, sOrange, sVert, sBleu, bConducteur, bPermis ;\r\n\r\n //Ecrire \"Entrez l'age du conducteur :\"\r\n //Lire iConducteur\r\n iConducteur= document.getElementById(\"iConducteur\").value;\r\n // Ecrire \"Entrez l'age du permis :\"\r\n // Lire iPermis\r\n iPermis= document.getElementById(\"iPermis\").value;\r\n //Ecrire \"Entrez le nombre d'accident responsable :\"\r\n //Lire iConducteur\r\n iAccident= document.getElementById(\"iAccident\").value;\r\n //Ecrire \"Entrez le nombre d'année d'inscription à la compagnie d'assurance :\"\r\n // Lire iPermis\r\n iFidelite= document.getElementById(\"iFidelite\").value;\r\n\r\n\r\n bConducteur = iConducteur>25;\r\n bPermis = iPermis>2;\r\n\r\n sRouge = \"rouge\";\r\n sOrange = \"orange\";\r\n sVert = \"vert\";\r\n sBleu = \"bleu\";\r\n\r\n if (iFidelite >5)\r\n {\r\n sRouge=sOrange;\r\n sOrange=sVert;\r\n sVert=sBleu; \r\n }\r\n\r\n if ((!bConducteur && !bPermis) && iAccident==0 || ((!bConducteur && bPermis) || (bConducteur && !bPermis)) && iAccident==1 || (bConducteur && bPermis) && iAccident==2)\r\n {\r\n document.getElementById(\"sp_resultat_code\").innerHTML=\"La couleur de votre contrat : \" + sRouge;\r\n }\r\n\r\n else if (((!bConducteur && bPermis) || (bConducteur && !bPermis)) && iAccident==0 || (bConducteur && bPermis) && iAccident==1)\r\n {\r\n document.getElementById(\"sp_resultat_code\").innerHTML=\"La couleur de votre contrat : \" + sOrange;\r\n }\r\n\r\n else if ((bConducteur && bPermis) && iAccident==0)\r\n {\r\n document.getElementById(\"sp_resultat_code\").innerHTML=\"La couleur de votre contrat : \" + sVert;\r\n }\r\n\r\n else \r\n {\r\n document.getElementById(\"sp_resultat_code\").innerHTML=\"Nous ne pouvons pas vous assurer\";\r\n }\r\n //FIN\r\n }", "function obligatorio(element,form){\nalert(\"obligatorio=\"+element.value);\nNumer=parseInt(element.value);\n\tif (isNaN(Numer)){\n\t\t//if (element.value == \"\"){\n\t\t//alert(\"noMayor=\"+element.name);\n\t\tif(element.name == \"cod_canton\")\n\t\t\tIndex = 1;\t\t\n\t\tif(element.name == \"cod_parroquia\")\n\t\t\tIndex = 2;\t\t\n\t\t\t\n\t\tif(element.name == \"apellidos\")\n\t\t\tIndex = 14;\t\t\n\t\tif(element.name == \"nombres\")\n\t\t\tIndex = 15;\t\t\n\t\telement.value=\"\";\n\t\tform.elements[Index].focus();\n\t\talert(\"El campo es obligatorio \"+element.name);\n\t\treturn false;\n\t}\n}", "function datosFormulario(frm) {\n let nombre= frm.nombre.value;\n let email = frm.email.value;\n let asunto= frm.asunto.value;\n let mensaje = frm.mensaje.value\n \n console.log(\"Nombre \",nombre);\n console.log(\"Email \",email);\n console.log(\"Asunto \",asunto);\n console.log(\"Mensaje \",mensaje);\n\n}", "function tikrinaForma(event) {\n if (forma.firstname.value == \"\" || forma.lastname.value == \"\" || forma.email.value == \"\") {\n event.preventDefault();\n // duomenu siuntimo nutraukimas jei neuzpildyta\n if (!forma.querySelector('.alert-warning')) {\n var errorZinute = document.createElement(\"div\");\n errorZinute.innerHTML += \"<p class='alert alert-warning'> Jus uzpildete ne visus laukus </p>\";\n forma.appendChild(errorZinute);\n }\n } else {\n\n }\n\n console.log(\"first name: \", forma.firstname.value);\n // if (form.firstname.value == \"\") {\n //\n // }\n }", "function camposVaciosFormularios(inf){\n\n let datos = inf || {}\n let formulario = datos[\"formulario\"].getElementsByClassName(\"campo\");\n let vacio = false;\n \n Array.from(formulario).forEach(function(campo,index){\n\n if(!datos[\"excepto\"].includes(campo.id)){\n \n if(campo.nodeName === \"SELECT\" && campo.classList.contains(\"selectpicker\")){\n\n let select = $(`#${campo.id}`).val();\n\n if(select == \"0\" || select == null || select == 0 ){ \n \n query(`.${campo.id}_`).classList.add(\"errorForm\")\n\n vacio = true; \n }\n }else{\n if(campo.nodeName !== \"DIV\")\n if(campo.value.trim() === \"\" || campo.value === \"0\" || campo.value === null){ \n \n query(`.${campo.id}_`).classList.add(\"errorForm\")\n \n vacio = true; \n }\n } \n }\n \n \n })\n \n return vacio;\n}", "function cargarDisponiblesProcesar(form) {\r\n\tvar frm = document.getElementById(\"frmentrada\");\r\n\tvar forganismo = document.getElementById(\"forganismo\").value;\r\n\tvar ftiponom = document.getElementById(\"ftiponom\").value;\r\n\tvar fperiodo = document.getElementById(\"fperiodo\").value;\r\n\tvar ftproceso = document.getElementById(\"ftproceso\").value;\r\n\t\r\n\tif (ftiponom==\"\" || fperiodo==\"\") { alert(\"¡DEBE SELECCIONAR EL TIPO DE NOMINA Y PERIODO!\"); return false; }\r\n\telse if (ftproceso==\"\") { alert(\"¡DEBE SELECCIONAR EL TIPO DE PROCESO!\"); return false; }\r\n\telse return true;\r\n}", "function limparOrigem(tipo){\r\n\tvar form = document.ImovelOutrosCriteriosActionForm;\r\n\r\n\t\t\r\n\tswitch(tipo){\r\n\t\tcase 1: //De localidade pra baixo\r\n\r\n\t\t\tform.nomeLocalidadeOrigem.value = \"\";\r\n\t\t\tform.localidadeDestinoID.value = \"\";\r\n\t\t\tform.nomeLocalidadeDestino.value = \"\";\r\n\t\t\tform.setorComercialOrigemCD.value = \"\";\r\n\t\t form.setorComercialOrigemID.value = \"\";\r\n\t\t\thabilitaSQlS();\r\n\t\t\t\r\n\t\tcase 2: //De setor para baixo\r\n\r\n\t\t form.nomeSetorComercialOrigem.value = \"\";\r\n\t\t form.setorComercialDestinoCD.value = \"\";\r\n\t\t form.setorComercialDestinoID.value = \"\";\t\t \r\n\t\t form.nomeSetorComercialDestino.value = \"\";\r\n\t\t form.quadraOrigemNM.value = \"\";\r\n\t\t form.quadraOrigemID.value = \"\";\r\n///\t\t alert(\"limpar origem 2\");\r\n\t\tcase 3://De quadra pra baixo\r\n\r\n\t\t form.quadraDestinoNM.value = \"\";\r\n\t\t form.quadraDestinoID.value = \"\";\r\n \r\n\t\t form.loteDestino.value = \"\";\r\n\t\t form.loteOrigem.value = \"\";\r\n\t\t \r\n\t\t limparMsgQuadraInexistente();\t\t \r\n\t}\r\n}", "function verifica_tipo(){\n var tipo = $('[name=tipo]').val()\n $('#oculto').css('display', 'none')\n $('#aggbarrio').css('display', 'none')\n $('[name=pais]').attr('disabled', 'disabled')\n $('[name=estado]').attr('disabled', 'disabled')\n $('[name=ciudad]').attr('disabled', 'disabled')\n $('[name=barrio]').attr('disabled', 'disabled')\n var valor = $('[name=\"tipo_ubicacion\"]').val()\n if (valor == 2 || valor == 3 || valor == 4) {\n obtener_paises($('[name=formularioUbicacionesAgregar]'))\n $('[name=pais]').removeAttr('disabled')\n $('[name=estado]').removeAttr('disabled')\n $('[name=ciudad]').removeAttr('disabled')\n $('[name=barrio]').removeAttr('disabled')\n $('[name=pais]').css('display', 'block')\n $('[name=estado]').css('display', 'block')\n $('[name=ciudad]').css('display', 'block')\n $('[name=barrio]').css('display', 'block')\n } else {\n $('[name=formularioUbicacionesAgregar]').find('[name=pais]').attr('disabled', 'disabled')\n $('[name=formularioUbicacionesAgregar]').find('[name=estado]').attr('disabled', 'disabled')\n $('[name=formularioUbicacionesAgregar]').find('[name=ciudad]').attr('disabled', 'disabled')\n $('[name=formularioUbicacionesAgregar]').find('[name=barrio]').attr('disabled', 'disabled')\n $('[name=formularioUbicacionesAgregar]').find('[name=pais]').val(\"\")\n $('[name=formularioUbicacionesAgregar]').find('[name=estado]').val(\"\")\n $('[name=formularioUbicacionesAgregar]').find('[name=ciudad]').val(\"\")\n $('[name=formularioUbicacionesAgregar]').find('[name=barrio]').val(\"\")\n }\n}", "function contruirForm(tipo, accion, id) {\n\n var url_peticion = \"\";\n var nombre_tipo = \"\";\n var titulo;\n switch (tipo) {\n case \"FrutaCosta\":\n titulo = \"Crear Nueva Fruta Costa\";\n if (accion == \"nuevo\") url_peticion = \"/api/fruta/\";\n if (accion == \"editar\") {\n url_peticion = \"/api/fruta/\" + id + \"?_method=PUT\";\n titulo = \"Editar Fruta Costa\";\n }\n break;\n case \"FrutaSierra\":\n titulo = \"Crear Nueva Fruta Sierra\";\n if (accion == \"nuevo\") url_peticion = \"/api/fruta\";\n if (accion == \"editar\") {\n url_peticion = \"/api/fruta/\" + id + \"?_method=PUT\";\n titulo = \"Editar Fruta Sierra\";\n }\n break;\n default:\n // code block\n }\n\n $(\"#divform\").empty();\n $(\"#divform\").append(\"<h2 id='game-page-title'>\" + titulo + \"</h2>\");\n var form = $(\"<form></form>\")\n .attr(\"action\", url_peticion)\n .attr(\"enctype\", \"multipart/form-data\")\n .attr(\"method\", \"POST\");\n\n var labelCategoria = $(\"<label></label>\")\n .attr(\"for\", \"fname\")\n .text(\"Categoría:\");\n\n var labelPregunta = $(\"<label></label>\")\n .attr(\"for\", \"fname\")\n .text(\"Pregunta:\");\n\n var labelNombre = $(\"<label></label>\")\n .attr(\"for\", \"fname\")\n .text(\"Nombre:\");\n var inputNombre = $(\"<input></input>\")\n .attr(\"type\", \"text\")\n .attr(\"id\", \"fname\")\n .attr(\"name\", \"nombre\")\n .attr(\"placeholder\", \"Nombre de \" + nombre_tipo + \"...\")\n .prop('required', true);\n\n var labelValor = $(\"<label></label>\")\n .attr(\"for\", \"fname\")\n .text(\"Valor:\");\n var inputValor = $(\"<input></input>\")\n .attr(\"type\", \"text\")\n .attr(\"id\", \"fname\")\n .attr(\"name\", \"valor\")\n .attr(\"placeholder\", \"Valor de \" + nombre_tipo + \"...\")\n .prop('required', true);\n\n var labelImagen = $(\"<label></label>\")\n .attr(\"for\", \"lname\")\n .text(\"Imagen:\");\n var inputImagen = $(\"<input></input>\")\n .attr(\"type\", \"file\")\n .attr(\"id\", \"fname\")\n .attr(\"name\", \"url\")\n .attr(\"placeholder\", \"Imagen de \" + nombre_tipo + \"...\")\n .prop('required', true);\n\n var submit = $(\"<input></input>\")\n .attr(\"type\", \"submit\")\n .attr(\"value\", \"Guardar\");\n var btnCancel = $(\"<button></button>\")\n .attr(\"id\", \"btnCancel\")\n .attr(\"class\", \"btn btn-default btn-block\")\n .text(\"Cancelar\");\n\n llenarComboCategoria();\n llenarComboPregunta();\n\n form.append(labelCategoria);\n form.append(selectOpction);\n form.append(labelPregunta);\n form.append(selectQuestion);\n form.append(labelNombre);\n form.append(inputNombre);\n form.append(labelValor);\n form.append(inputValor);\n form.append(labelImagen);\n form.append(inputImagen);\n\n var br = $(\"</br>\");\n form.append(br);\n form.append(submit);\n form.append(btnCancel);\n $('#divform').append(form);\n\n //ELIMINAR\n $(\"#btnCancel\").on('click', function (e) {\n $(\"#divform\").empty();\n });\n}", "function obtemJogador(form) {\n\n var jogador = {\n foto: form.foto.value,\n nome: form.nome.value\n }\n\n return jogador;\n}", "function populateJs2Form(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('maeEstatProduFrm.accion'), \n\t\tget('maeEstatProduFrm.origen'));\n\n\n\tset('maeEstatProduFrm.id', jsMaeEstatProduId);\n\tset('maeEstatProduFrm.paisOidPais', [jsMaeEstatProduPaisOidPais]);\n\tset('maeEstatProduFrm.codEstaProd', jsMaeEstatProduCodEstaProd);\n\tif(mode == MMG_MODE_CREATE || mode == MMG_MODE_UPDATE_FORM){\n\t\tunbuildLocalizedString('maeEstatProduFrm', 1, jsMaeEstatProduDescripcion)\n\t\tloadLocalizationWidget('maeEstatProduFrm', 'Descripcion', 1);\n\t}else{\n\t\tset('maeEstatProduFrm.Descripcion', jsMaeEstatProduDescripcion);\t\t\n\t}\n\t\n}", "function LimpiarFormulario(){\n\n if(obtener_valor( 'PLANTILLA' ) == '0'){\n OcultarCampo( 'BUSCARPL', 0 );\n asignar_valor( 'NB_PLANT' , '');\n asignar_valor( 'ID_PLANT' , '');\n asignar_valorM( 'PLANT' , '' , 1 , 1 );\n asignar_valorM( 'PLANT' , '' , 1 , 2 );\n asignar_valorM( 'PLANT' , '' , 1 , 3 );\n asignar_valorM( 'PLANT' , '' , 1 , 7 );\n }else{\n MostrarCampo( 'BUSCARPL', 0 );\n }\n\n return true;\n}", "function populateJs2Form(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('belParamBelceFrm.accion'), \n\t\tget('belParamBelceFrm.origen'));\n\n\n\tset('belParamBelceFrm.id', jsBelParamBelceId);\n\tset('belParamBelceFrm.sbacOidSbac', [jsBelParamBelceSbacOidSbac]);\n\tset('belParamBelceFrm.valDire', jsBelParamBelceValDire);\n\tset('belParamBelceFrm.valTfno', jsBelParamBelceValTfno);\n\tset('belParamBelceFrm.valMontMaxiDife', jsBelParamBelceValMontMaxiDife);\n\tset('belParamBelceFrm.valLimiEfecCaja', jsBelParamBelceValLimiEfecCaja);\n\tset('belParamBelceFrm.numCaja', jsBelParamBelceNumCaja);\n\tset('belParamBelceFrm.valNombLoca', jsBelParamBelceValNombLoca);\n\tset('belParamBelceFrm.valTiempRepo', jsBelParamBelceValTiempRepo);\n\tset('belParamBelceFrm.valFactLoca', jsBelParamBelceValFactLoca);\n\tset('belParamBelceFrm.numMaxiProd', jsBelParamBelceNumMaxiProd);\n\tset('belParamBelceFrm.valAlerStoc', jsBelParamBelceValAlerStoc);\n\tset('belParamBelceFrm.valUsua', jsBelParamBelceValUsua);\n\tset('belParamBelceFrm.clieOidClie', [jsBelParamBelceClieOidClie]);\n\tset('belParamBelceFrm.sociOidSoci', [jsBelParamBelceSociOidSoci]);\n\tset('belParamBelceFrm.ttraOidTipoTran', [jsBelParamBelceTtraOidTipoTran]);\n\tset('belParamBelceFrm.ccbaOidCuenCorrBanc', [jsBelParamBelceCcbaOidCuenCorrBanc]);\n\tset('belParamBelceFrm.tmvcOidCobr', [jsBelParamBelceTmvcOidCobr]);\n\tset('belParamBelceFrm.tmvcOidCier', [jsBelParamBelceTmvcOidCier]);\n\tset('belParamBelceFrm.tmalOidConfStoc', [jsBelParamBelceTmalOidConfStoc]);\n\tset('belParamBelceFrm.tmalOidConfStocTran', [jsBelParamBelceTmalOidConfStocTran]);\n\tset('belParamBelceFrm.tmalOidStocTran', [jsBelParamBelceTmalOidStocTran]);\n\tset('belParamBelceFrm.tmalOidStocDevo', [jsBelParamBelceTmalOidStocDevo]);\n\tset('belParamBelceFrm.tmalOidRegu', [jsBelParamBelceTmalOidRegu]);\n\tset('belParamBelceFrm.tmalOidReguSap', [jsBelParamBelceTmalOidReguSap]);\n\tset('belParamBelceFrm.tmalOidDevoStoc', [jsBelParamBelceTmalOidDevoStoc]);\n\tset('belParamBelceFrm.tmalOidPetiExis', [jsBelParamBelceTmalOidPetiExis]);\n\tset('belParamBelceFrm.paisOidPais', [jsBelParamBelcePaisOidPais]);\n\t\n}", "limpaFormulario(){\n this._inputDataNascimento.value = ''\n this._inputIdade.value = 1;\n this._inputSalario.value = 0;\n this._inputDataNascimento.focus();\n }", "function etapa8() {\n \n //verifica se o usuário já inseriu as formas de pagamento corretamente\n if(valorTotalFestaLocal == 0 && countPrimeiraVezAdd !== 0){\n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"8º Etapa - Horários do Evento\";\n\n document.getElementById('inserirHorarios').style.display = ''; //habilita a etapa 8\n document.getElementById('valoresEformaPagamento').style.display = 'none'; //desabilita a etapa 7\n \n msgTratamentoEtapa7.innerHTML = \"\";\n \n //DEFINI O TEXTO DE CONFIRMAÇÃO DO VALOR A PEGAR COM CONTRATANTE\n \n //apaga o paragrafo do valor a pegar com contratante , pois vai criar outro\n if(criouPegarContratante > 0){\n document.getElementById('pValorPegarContratante').remove();\n }\n criouPegarContratante++;\n \n //recebe o elemento html da ultima etapa (confirmação) e salva em uma variavel \n var confirmacaoInfValoresFinais = document.querySelector(\"#valoresFinalInf\");\n \n //cria os elementos <h6> para todos os valores\n var paragrafoValorPegarContratante = document.createElement(\"h5\");\n\n //define o atributo\n paragrafoValorPegarContratante.class = \"card-title\"; \n paragrafoValorPegarContratante.id = \"pValorPegarContratante\"; \n \n //define o texto\n paragrafoValorPegarContratante.textContent = \"Receber com contrante: R$\"+valorPegarContratante; \n \n //coloca os <p> criados dentro do elemento html da etapa de confirmação\n confirmacaoInfValoresFinais.appendChild(paragrafoValorPegarContratante);\n \n //DEFINI O VALOR DO INPUT DO PEGAR COM CONTRATANTE\n document.getElementById('valorReceberContratante').value = valorPegarContratante;\n \n }else{\n msgTratamentoEtapa7.textContent = \"Não foi possível seguir para a 8º Etapa! Para seguir o valor total adicionado deve ser igual ao Valor Total. =)\"\n }\n \n }", "function agregaform(datos){\n \n d=datos.split('||');\n $('#codigou').val(d[0]);\n $('#nombreu').val(d[1]);\n}", "function preciomoneda()\n{\n var selecvalue = tipo_registro.options[tipo_registro.selectedIndex].value;\n //var selectext = catalogo.options[catalogo.selectedIndex].text;\n if (selecvalue=='Intercambio' || selecvalue=='Venta') {\n var base_url= 'http://localhost/sistema_monedas/';\n $.ajax({\n url: base_url + \"collectionm/form_moneda/\",\n type:\"POST\",\n beforeSend: function() {\n $('#gif_carga').html(\"<center><img src='\"+base_url+\"/public/images/loader.gif' /></center>\");\n },\n success:function(resp){\n //$(\"#input_creado\").append(resp);\n $(\"#precio_moneda\").html(resp);\n //alert(resp);\n },\n error:function(){\n $('#gif_carga').html(\"\");\n $('#precio_moneda').html(\"<center><h4 style='color:red;'>ERROR EN EL SERVIDOR.POR FAVOR ENVIE UN MENSAJE AL ADMINISTRADOR</h4></center>\");\n }\n\n });\n\n $(\"#foto_frente\").prop('required',true);\n $(\"#foto_detras\").prop('required',true);\n\n }else{\n $('#precio_moneda').html(\"\");\n $(\"#foto_frente\").prop('required',false);\n $(\"#foto_detras\").prop('required',false);\n }\n \n}", "function setEnlace() {\n if (comprobarFormulario()) {\n $('<form>')\n .attr('class', 'pre-form')\n .append(createInput(INTIT, 'text', 'Titulo'))\n .append(createSelect(INTILE, TILE, 'Tipo de letra'))\n .append(createInput(INCOTIT, 'color', 'Color del titulo'))\n .append(createInput(INCONT, 'text', 'Contenido'))\n .append(inputBotones(click))\n .appendTo('body');\n }\n\n /**\n * Funcion que realiza la craeción del alert.\n * @param {Event} e Evento que ha disparado esta accion.\n */\n function click(e) {\n e.preventDefault();\n\n var titulo = $('#'+INTIT).val();\n var contenido = $('#'+INCONT).val();\n\n if (titulo && contenido) {\n divDraggable()\n .append(\n $(`<a>`)\n .attr({\n href: contenido,\n target: '_blank'\n })\n .css({\n color: $('#'+INCOTIT).val(),\n 'font-family': $(`#${INTILE} :selected`).val(),\n })\n .html(titulo)\n )\n .append(botonEliminar())\n .appendTo('.principal');\n\n $(e.target).parents('form').remove();\n } else {\n alert('Rellene el campo de \"Titulo\" o el de \"Contenido\" o pulse \"Cancelar\" para salir.');\n }\n }\n}", "function novo1(formulario) {\n limpaFormulario(formulario);\n desabilitaMenuFormulario();\n $(\"#busca\").html('');\n $(\"#nome\").focus();\n}", "function limpiarFormulario(idForm){\n var form=document.getElementById(idForm);\n if(form!=null){\n for(var i in form.elements){\n\n if(form.elements[i].nodeName == \"TEXTAREA\"){\n form.elements[i].value=\"\"; \n }\n //console.log(form.elements[i].type);\n //console.log(form.elements[i].checked);\n //console.log(form.elements[i].value);\n\n\n switch(form.elements[i].type){\n case \"text\":\n form.elements[i].value=\"\";\n break;\n case \"email\":\n form.elements[i].value=\"\";\n break;\n case \"number\":\n form.elements[i].value=\"\";\n break;\n case \"password\":\n form.elements[i].value=\"\";\n break;\n case \"select-one\":\n form.elements[i].value=\"0\";\n break;\n case \"checkbox\":\n form.elements[i].checked=false;\n break;\n case \"radio\":\n form.elements[i].checked=false;\n break;\n }\n }\n }\n \n console.log(form);\n console.log(idForm);\n \n}", "validarInfo() {\n if (this.erros.length > 0) {\n this.validador.style.display = \"table-row\";\n this.imprimirErros(this.erros);\n } else if ((this.validarRepetido(this.nome, this.peso, this.altura)) == false) {\n this.calculaIMC();\n this.adicionarElementos();\n this.validador.style.display = \"none\";\n this.form.reset();\n }\n }", "function ubahTeks() {\n namaHasil = document.getElementById(\"namaForm\").value;\n roleHasil = document.getElementById(\"roleForm\").value;\n availabilityHasil = document.getElementById(\"availabilityForm\").value;\n usiaHasil = document.getElementById(\"usiaForm\").value;\n lokasiHasil = document.getElementById(\"lokasiForm\").value;\n yearHasil = document.getElementById(\"yearForm\").value;\n emailHasil = document.getElementById(\"emailForm\").value;\n\n document.getElementById(\"nama\").innerHTML = namaHasil;\n document.getElementById(\"role\").innerHTML = roleHasil;\n document.getElementById(\"availability\").innerHTML = availabilityHasil;\n document.getElementById(\"usia\").innerHTML = usiaHasil;\n document.getElementById(\"lokasi\").innerHTML = lokasiHasil;\n document.getElementById(\"year\").innerHTML = yearHasil;\n document.getElementById(\"email\").innerHTML = emailHasil;\n}", "function comprobar(){\r\n\tvar f=formElement;\r\n\t// text\r\n\tfor(pregunta=0;pregunta<2;pregunta++){\r\n\r\n\t\tif (f.elements[pregunta].value==\"\") {\r\n\r\n\t\t\tf.elements[pregunta].focus();\r\n\r\n\t\t\talert(\"Tienes que contestar la pregunta \"+(pregunta +1));\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n //select normal\r\n\tfor(pregunta=2;pregunta<4;pregunta++){\r\n\r\n\t\tif (f.elements[pregunta].selectedIndex==0) {\r\n\r\n\t\t\tf.elements[pregunta].focus();\r\n\r\n\t\t\talert(\"Tienes que contestar toda la pregunta \"+(pregunta +1));\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t//select multiple\r\n\tfor(pregunta=4;pregunta<6;pregunta++){\r\n\t\tvar multipleRespondido=false;\r\n for(i=0;i<(f.elements[pregunta].length);i++){\r\n var opt=f.elements[pregunta].options[i];\r\n if(opt.selected){\r\n multipleRespondido=true;\r\n\t\t\t}\r\n\t\t}\r\n if (!multipleRespondido) {\r\n\t\t\tf.elements[pregunta].focus();\r\n\t\t\talert(\"Tienes que contestar la pregunta \"+(pregunta +1));\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t//Checkbox\r\n for(pregunta=6;pregunta<8;pregunta++){\r\n var checked=false;\r\n var nombre;\r\n if (pregunta==6){\r\n nombre=f.checkbox0;\r\n\t\t\t} else {\r\n\t\t\tnombre=f.checkbox1;\r\n\t\t}\r\n for (i = 0; i < nombre.length; i++) {\r\n if (nombre[i].checked) {\r\n\t\t\t\tchecked=true;\r\n\t\t\t}\r\n\t\t}\r\n if (!checked) {\r\n\t\t\tnombre[0].focus();\r\n\t\t\talert(\"Tienes que contestar la pregunta \"+(pregunta +1));\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t// radio\r\n\tfor(pregunta=8;pregunta<10;pregunta++){\r\n\t\tvar nombreRadio;\r\n if (pregunta==8){\r\n nombreRadio=f.nombre0;\r\n\t\t\t} else {\r\n nombreRadio=f.nombre1;\r\n\t\t}\r\n if (nombreRadio.value==\"\") {\r\n nombreRadio[0].focus();\r\n alert(\"Tienes que contestar la pregunta \"+(pregunta +1));\r\n return false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}", "function ocultarFormaPago() \n{\n\telemento=document.forms[0].CodigoBanco;\n\tif(document.forms[0].FormaPago.value == 1) {\t\t\t\t\t\t\t\t\n\t\telemento.style.display=elemento.style.display == \"none\" ? \"block\" : \"none\";\n\t\tdocument.forms[0].CodigoBanco.value = \"\";\t\t\n\t\tdocument.forms[0].CuentaCheque.readOnly = true;\n\t\tdocument.forms[0].CuentaCheque.value = \"\";\n\t\tdocument.forms[0].NumeroCheque.readOnly = true;\n\t\tdocument.forms[0].NumeroCheque.value = \"\";\n\t\tdocument.forms[0].CedulaCliente.readOnly = false;\n\t\tdocument.forms[0].FormularioPsicotropicos.readOnly = false;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\tdocument.forms[0].OtrosValores.value = 0;\n\t\tdocument.forms[0].Efectivo.value = document.forms[0].TotalPago.value;\t\t\t\t\t\t\t\t\n\t}\n\telse {\n\t\telemento.style.display=elemento.style.display == \"none\" ? \"block\" : \"none\";\n\t\t\n\t\tdocument.forms[0].CuentaCheque.readOnly = false;\n\t\tdocument.forms[0].NumeroCheque.readOnly = false;\n\t\tdocument.forms[0].CedulaCliente.readOnly = true;\t\t\t\t\t\t\n\t\tdocument.forms[0].CedulaCliente.value = \"\";\n\t\tdocument.forms[0].FormularioPsicotropicos.readOnly = true;\t\n\t\tdocument.forms[0].FormularioPsicotropicos.value = \"\";\t\n\t\tdocument.forms[0].OtrosValores.value = document.forms[0].TotalPago.value;\n\t\tdocument.forms[0].Efectivo.value = 0;\n\t}\n\treturn true;\n}", "formularioUno(contPar,formPar,filPar){/* avisoCuatro.css*/\n\t\tlet txt,fil;\n\t\t//contenedor\n\t\tconst contenedor = document.createElement('div');\n\t\tcontenedor.setAttribute('class',contPar[1]);\n\t\tcontenedor.setAttribute('id',contPar[2]);\n\t\t//titulo\n\t\tconst titulo = document.createElement('p');\n\t\ttxt = document.createTextNode(contPar[0]);\n\t\ttitulo.appendChild(txt);\n\t\tcontenedor.appendChild(titulo);\n\t\t// form\n\t\tconst formul = document.createElement('form');\n\t\tformul.setAttribute('class',formPar[0]);\n\t\tformul.setAttribute('id',formPar[1]);\n\t\t//filas\n\t\tfilPar.forEach((item,index) =>{\n\t\t\tfil = document.createElement('div');\n\t\t\tfil.setAttribute('class',formPar[2]);\n\t\t\tfil.setAttribute('id',`${formPar[2]}-${index}`);\n\t\t\titem.forEach(it => {fil.appendChild(it);});\n\t\t\tformul.appendChild(fil);\n\t\t});\n\t\tcontenedor.appendChild(formul);\n\t\treturn contenedor;\n\t}", "function populateForm2Js(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('segPaisViewFrm.accion'), \n\t\tget('segPaisViewFrm.origen'));\n\t\n\tjsSegPaisViewId = get('segPaisViewFrm.id').toString();\n\tjsSegPaisViewCodPais = get('segPaisViewFrm.codPais').toString();\n\tjsSegPaisViewMoneOidMone = get('segPaisViewFrm.moneOidMone')[0];\n\tjsSegPaisViewMoneOidMoneAlt = get('segPaisViewFrm.moneOidMoneAlt')[0];\n\tif(mode == MMG_MODE_CREATE || mode == MMG_MODE_UPDATE_FORM){\n\t\tjsSegPaisViewDescripcion = buildLocalizedString('segPaisViewFrm', 1);\n\t}else{\n\t\tjsSegPaisViewDescripcion = get('segPaisViewFrm.Descripcion');\n\t}\n\tjsSegPaisViewIndInteGis = get('segPaisViewFrm.indInteGis')[0];\n\tjsSegPaisViewValIden = get('segPaisViewFrm.valIden')[0];\n\tjsSegPaisViewIndSaldUnic = get('segPaisViewFrm.indSaldUnic');\n\tjsSegPaisViewValProgEjec = get('segPaisViewFrm.valProgEjec').toString();\n\tjsSegPaisViewValPorcAlar = get('segPaisViewFrm.valPorcAlar').toString();\n\tjsSegPaisViewIndCompAuto = get('segPaisViewFrm.indCompAuto').toString();\n\tjsSegPaisViewNumDiasMora = get('segPaisViewFrm.numDiasMora').toString();\n\tjsSegPaisViewIndTratAcumDesc = get('segPaisViewFrm.indTratAcumDesc');\n\tjsSegPaisViewValTiemRezo = get('segPaisViewFrm.valTiemRezo').toString();\n\tjsSegPaisViewValConfSecuCcc = get('segPaisViewFrm.valConfSecuCcc')[0];\n\tjsSegPaisViewNumDiasFact = get('segPaisViewFrm.numDiasFact').toString();\n\tjsSegPaisViewNumLimiDifePago = get('segPaisViewFrm.numLimiDifePago').toString();\n\tjsSegPaisViewIndEmisVenc = get('segPaisViewFrm.indEmisVenc');\n\tjsSegPaisViewValMaxiDifeAnlsComb = get('segPaisViewFrm.valMaxiDifeAnlsComb').toString();\n\tjsSegPaisViewNumPosiNumeClie = get('segPaisViewFrm.numPosiNumeClie').toString();\n\tjsSegPaisViewValFormFech = get('segPaisViewFrm.valFormFech')[0];\n\tjsSegPaisViewValSepaMile = get('segPaisViewFrm.valSepaMile')[0];\n\tjsSegPaisViewValSepaDeci = get('segPaisViewFrm.valSepaDeci')[0];\n\tjsSegPaisViewNumPeriEgre = get('segPaisViewFrm.numPeriEgre').toString();\n\tjsSegPaisViewNumPeriReti = get('segPaisViewFrm.numPeriReti').toString();\n\tjsSegPaisViewFopaOidFormPago = get('segPaisViewFrm.fopaOidFormPago')[0];\n\tjsSegPaisViewValCompTele = get('segPaisViewFrm.valCompTele').toString();\n\tjsSegPaisViewIndFletZonaUbig = get('segPaisViewFrm.indFletZonaUbig')[0];\n\tjsSegPaisViewValIndiSecuMoni = get('segPaisViewFrm.valIndiSecuMoni');\n\tjsSegPaisViewIndSecu = get('segPaisViewFrm.indSecu')[0];\n\tjsSegPaisViewIndBalaAreaCheq = get('segPaisViewFrm.indBalaAreaCheq')[0];\n\tjsSegPaisViewValUrl = get('segPaisViewFrm.valUrl').toString();\n\t\n}", "function compruebaCodigoEntrega(elementoBusqueda) {\n\t\n\t/*busquedaAutom = true;\n\t\n\tvar valueCampoBusqueda = document.getElementById(elementoBusqueda).value;\n\tvar form = document.forms['MWEBNuevaEntregaForm'];\n\tif (estaVacio (valueCampoBusqueda) ) {\n\t\tdocument.forms['MWEBNuevaEntregaForm'].stockCodigoArticuloPropietario.value=\"\";\n\t\tdocument.forms['MWEBNuevaEntregaForm'].stockCodigoArticulo.value=\"\";\n\t\tdocument.forms['MWEBNuevaEntregaForm'].stockDescripcion.value=\"\";\n\t\tdocument.forms['MWEBNuevaEntregaForm'].stockIdCodigoArticulo.value=\"\";\n\t} else {\n\t\tif (document.forms['MWEBNuevaEntregaForm'].modo.value == '') {\n\t\t\tdocument.forms['MWEBNuevaEntregaForm'].estado.value = 'MODO_ANADIR_ARTICULO';\n\t\t}\n\t\telse {\n\t\t\tdocument.forms['MWEBNuevaEntregaForm'].estado.value = document.forms['MWEBNuevaEntregaForm'].modo.value;\n\t\t}\n\t\n\t\tdocument.forms['MWEBNuevaEntregaForm'].modo.value = 'MODO_BUSCAR_ARTICULO_AUTOMATICO';\n\t\tdocument.forms['MWEBNuevaEntregaForm'].campoBusqueda.value = elementoBusqueda;\n\t\tdocument.forms['MWEBNuevaEntregaForm'].submit();\n\t}*/\n var codSeguimiento = document.getElementById('codSeguimiento').value;\n var comentario = document.getElementById('comentario').value;\n var proveedor = document.getElementById('proveedor').value;\n var usuario = document.getElementById('usuario').value;\n var valueCampoBusqueda = document.getElementById(elementoBusqueda).value;\n if(elementoBusqueda==\"codigoArticulo\")\n {\n document.forms['MWEBNuevaOEForm'].codigoArticulo.value=valueCampoBusqueda;\n }else\n {\n document.forms['MWEBNuevaOEForm'].codigoArticuloPropietario.value=valueCampoBusqueda;\n }\n //datosEnvio=\"articulosServlet.do?\"+elementoBusqueda+\"=\"+valueCampoBusqueda+\"&pagina=\"+pagina+\"&usuario=\"+usuariob+\"&origen=\"+origen;\n //datosEnvio=datosEnvio+\"&codSeguimiento=\"+codSeguimiento+\"&comentario=\"+comentario+\"&proveedor=\"+proveedor;\n \n document.forms['MWEBNuevaOEForm'].accion.value=\"buscar\";\n document.forms['MWEBNuevaOEForm'].codSeguimiento.value=codSeguimiento;\n document.forms['MWEBNuevaOEForm'].comentario.value=comentario;\n document.forms['MWEBNuevaOEForm'].proveedor.value=proveedor;\n document.forms['MWEBNuevaOEForm'].pagina.value=\"irArticuloNEp\";\n document.forms['MWEBNuevaOEForm'].origen.value=\"irArticuloNEp\";\n document.forms['MWEBNuevaOEForm'].usuario.value=usuario;\n document.forms['MWEBNuevaOEForm'].action =\"articulosServlet.do\"; //datosEnvio;\n document.forms['MWEBNuevaOEForm'].submit();\n}", "function tipoatributo()\n{\n var selecvalue = tipo_atributo.options[tipo_atributo.selectedIndex].value;\n //var selectext = catalogo.options[catalogo.selectedIndex].text;\n if (selecvalue=='Especiales') {\n $(\"#boton_tipo_atributo\").show();\n\n /* var base_url= 'http://localhost/sistema_monedas/';\n $.ajax({\n url: base_url + \"collectionm/form_moneda/\",\n type:\"POST\",\n beforeSend: function() {\n $('#gif_carga').html(\"<center><img src='\"+base_url+\"/public/images/loader.gif' /></center>\");\n },\n success:function(resp){\n //$(\"#input_creado\").append(resp);\n $(\"#precio_moneda\").html(resp);\n //alert(resp);\n },\n error:function(){\n $('#gif_carga').html(\"\");\n $('#precio_moneda').html(\"<center><h4 style='color:red;'>ERROR EN EL SERVIDOR.POR FAVOR ENVIE UN MENSAJE AL ADMINISTRADOR</h4></center>\");\n }\n\n });*/\n }else{\n $(\"#boton_tipo_atributo\").hide();\n /* $('#precio_billete').html(\"\");*/\n }\n \n}", "function fanTuriQushish() {\n let form = document.forms['createFanTuriForm'];\n let check = {}\n check.nomi = form[\"nomi\"].value;\n fanTuriService.create(JSON.stringify(check), location.reload(), console.log(\"xato\"));\n}", "function limpa_formulário_cep() {\r\n //LIMPA VALORES DO FORMULÁRIO DE CEP\r\n document.getElementById('rua').value=(\"\");\r\n document.getElementById('bairro').value=(\"\");\r\n document.getElementById('cidade').value=(\"\");\r\n document.getElementById('uf').value=(\"\");\r\n}", "function cambiamenu(){\n\n\t\t\tseleccionado=form1.epsnueva.selectedIndex;\n\t\t\tp = form1.epsnueva[form1.epsnueva.selectedIndex].value;\n \t\tt = form1.epsnueva[form1.epsnueva.selectedIndex].text;\n\t\t\ttextoseleccionado=\"\"+p+\"-\"+t;\n\t\t\tcodigoseleccionado=p;\n\n\t\t\t//alert(\"\"+p+\"-\"+t);\n\t\t\testadoclick=true;\t\t\n}", "function limpiar(){\r\n $('#txtextension1').removeAttr('disabled');\r\n $('#txtextension1').focus();\r\n $('#forms').hide();\r\n $('#tipopuerto').val('-1');\r\n $('#regletas').val('-1');\r\n $('#padre').val('-1');\r\n $('#txtpuerto').val('');\r\n $('#txtconEditar').val('');\r\n $('h5').html('');\r\n }", "function Limpiar() {\n //setName(\"id\", \"\")\n //setName(\"nombre\", \"\")\n //setName(\"descripcion\",\"\")\n\n //var elementos = document.querySelectorAll(\"#frmTipoHabitacion [name]\");\n\n //for (var i = 0; i < elementos.length; i++) {\n // elementos[i].value = \"\";\n //}\n\n //LimpiarDatos(\"frmTipoHabitacion\", [\"id\"]);\n LimpiarDatos(\"frmTipoHabitacion\");\n Correcto(\"Funciono mi alerta\");\n}", "function cambiausuario() {\n var f = document.getElementById(\"editar\");\n if(f.f2nom.value==\"\" || f.f2nick.value==\"\" || f.f2pass.value==\"\" || f.f2mail.value==\"\") {\n alert(\"Deben llenarse todos los campos para proceder\");\n } else {\n var x = new paws();\n x.addVar(\"nombre\",f.f2nom.value);\n x.addVar(\"nick\",f.f2nick.value);\n x.addVar(\"pass\",f.f2pass.value);\n x.addVar(\"email\",f.f2mail.value);\n x.addVar(\"estatus\",f.f2est.selectedIndex);\n x.addVar(\"cliente_id\",f.f2cid.value);\n x.addVar(\"usuario_id\",f.f2usrid.value);\n x.go(\"clientes\",\"editausr\",llenausr);\n }\n}", "function ingresaVehiculo(e) {\n patente = document.querySelector(\"#patente\").value\n tipo = document.querySelector(\"#ftipo\").value\n console.log(patente)\n console.log(tipo)\n form.reset()\n}", "function mostrarform(flag) {\n\tcontains = [];\n\tvar_extras();\n\n\tif (flag) {\n\t\t$('#idcliente').val('Publico General');\n\t\t$(\"#idcliente\").selectpicker('refresh');\n\t\t$(\"#listadoregistros\").hide();\n\t\t$(\"#formularioregistros\").show();\n\t\t$(\"#btnagregar\").hide();\n\t\t$(\"#btnGuardar\").hide();\n\t\t$(\"#btnCancelar\").show();\n\t\t$(\"#btnAgregarArt\").show();\n\t\tdetalles = 0;\n\t} else {\n\t\t$(\"#listadoregistros\").show();\n\t\t$(\"#formularioregistros\").hide();\n\t\t$(\"#btnagregar\").show();\n\t}\n}", "function populateJs2Form(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('eduMatriCursoFrm.accion'), \n\t\tget('eduMatriCursoFrm.origen'));\n\n\n\tset('eduMatriCursoFrm.id', jsEduMatriCursoId);\n\tset('eduMatriCursoFrm.paisOidPais', [jsEduMatriCursoPaisOidPais]);\n\tset('eduMatriCursoFrm.cplcOidCabePlanCurs', [jsEduMatriCursoCplcOidCabePlanCurs]);\n\tset('eduMatriCursoFrm.codCurs', jsEduMatriCursoCodCurs);\n\tset('eduMatriCursoFrm.terrOidTerr', [jsEduMatriCursoTerrOidTerr]);\n\tset('eduMatriCursoFrm.clasOidClas', [jsEduMatriCursoClasOidClas]);\n\tset('eduMatriCursoFrm.frcuOidFrec', [jsEduMatriCursoFrcuOidFrec]);\n\tset('eduMatriCursoFrm.regaOidRega', [jsEduMatriCursoRegaOidRega]);\n\tset('eduMatriCursoFrm.zsgvOidSubgVent', [jsEduMatriCursoZsgvOidSubgVent]);\n\tset('eduMatriCursoFrm.zorgOidRegi', [jsEduMatriCursoZorgOidRegi]);\n\tset('eduMatriCursoFrm.zzonOidZona', [jsEduMatriCursoZzonOidZona]);\n\tset('eduMatriCursoFrm.zsccOidSecc', [jsEduMatriCursoZsccOidSecc]);\n\tset('eduMatriCursoFrm.ztadOidTerrAdmi', [jsEduMatriCursoZtadOidTerrAdmi]);\n\tset('eduMatriCursoFrm.perdOidPeriInicComp', [jsEduMatriCursoPerdOidPeriInicComp]);\n\tset('eduMatriCursoFrm.perdOidPeriFinaComp', [jsEduMatriCursoPerdOidPeriFinaComp]);\n\tset('eduMatriCursoFrm.perdOidPeriInicCons', [jsEduMatriCursoPerdOidPeriInicCons]);\n\tset('eduMatriCursoFrm.perdOidPeriFinaCons', [jsEduMatriCursoPerdOidPeriFinaCons]);\n\tset('eduMatriCursoFrm.perdOidPeriIngr', [jsEduMatriCursoPerdOidPeriIngr]);\n\tset('eduMatriCursoFrm.ticuOidTipoCurs', [jsEduMatriCursoTicuOidTipoCurs]);\n\tset('eduMatriCursoFrm.valPathFich', jsEduMatriCursoValPathFich);\n\tset('eduMatriCursoFrm.valObjeCurs', jsEduMatriCursoValObjeCurs);\n\tset('eduMatriCursoFrm.valContCurs', jsEduMatriCursoValContCurs);\n\tset('eduMatriCursoFrm.valRelaMateCurs', jsEduMatriCursoValRelaMateCurs);\n\tset('eduMatriCursoFrm.valMontVent', jsEduMatriCursoValMontVent);\n\tset('eduMatriCursoFrm.fecDispCurs', jsEduMatriCursoFecDispCurs);\n\tset('eduMatriCursoFrm.fecLanz', jsEduMatriCursoFecLanz);\n\tset('eduMatriCursoFrm.fecFinCurs', jsEduMatriCursoFecFinCurs);\n\tset('eduMatriCursoFrm.fecUltiCurs', jsEduMatriCursoFecUltiCurs);\n\tset('eduMatriCursoFrm.fecConcCurs', jsEduMatriCursoFecConcCurs);\n\tset('eduMatriCursoFrm.fecIngr', jsEduMatriCursoFecIngr);\n\tset('eduMatriCursoFrm.numPart', jsEduMatriCursoNumPart);\n\tset('eduMatriCursoFrm.numOrde', jsEduMatriCursoNumOrde);\n\tset('eduMatriCursoFrm.numCampa', jsEduMatriCursoNumCampa);\n\tset('eduMatriCursoFrm.numUnid', jsEduMatriCursoNumUnid);\n\tset('eduMatriCursoFrm.desCurs', jsEduMatriCursoDesCurs);\n\tset('eduMatriCursoFrm.indAcceDmrt', jsEduMatriCursoIndAcceDmrt);\n\tset('eduMatriCursoFrm.indAcceInfo', jsEduMatriCursoIndAcceInfo);\n\tset('eduMatriCursoFrm.indAlcaGeog', jsEduMatriCursoIndAlcaGeog);\n\tset('eduMatriCursoFrm.indBloqExte', jsEduMatriCursoIndBloqExte);\n\tset('eduMatriCursoFrm.indMomeEntr', jsEduMatriCursoIndMomeEntr);\n\tset('eduMatriCursoFrm.indCondPedi', jsEduMatriCursoIndCondPedi);\n\tset('eduMatriCursoFrm.indCtrlMoro', jsEduMatriCursoIndCtrlMoro);\n\tset('eduMatriCursoFrm.indCtrlFunc', jsEduMatriCursoIndCtrlFunc);\n\tset('eduMatriCursoFrm.clclOidClieClasCapa', [jsEduMatriCursoClclOidClieClasCapa]);\n\n}", "function adaptaFormulario () {\r\n\tvar secProfEl = getFormElementById(\"sectorprofesion_c\");\r\n\tif (! secProfEl) {\r\n\t\tconsole.error(\"No se ha definido el campo Sector Profesional.\");\r\n\t} else {\r\n\t\tvar secProf = secProfEl.options[secProfEl.selectedIndex];\r\n\t\tswitch (secProf.value) {\r\n\t\t\tcase \"otros\": visibilidadOtroSector(true); break;\r\n\t\t\tdefault:\t visibilidadOtroSector(false);\t break;\r\n\t\t}\r\n\t}\r\n}", "function verificarCamposForm(id){\n // se verifican cuantos campos tiene el formulario\n // la ultima posicion corresonde al boton de envío\n for (let i = 0; i < $(id)[0].length - 1; i++) {\n let campo = $(id)[0][i];\n let value = $(campo).val();\n let select = $(campo).attr('id');\n select = '#'+select;\n\n if(value == \"\" || value == null || $(select).hasClass('is-invalid')) {\n return false;\n }\n }\n return true;\n}", "function unicffprocessing() {\n /*Récupération des données*/\n var titre = document.unicfanfictionform.titre.value; //titre de la fanfiction\n var image = document.unicfanfictionform.image.value; //image\n var livre = document.unicfanfictionform.livre.value; //livre d'inspiration\n var auteur = document.unicfanfictionform.auteur.value; //auteur d'inspiration\n var age = document.unicfanfictionform.age.value; //âge minimum\n var fanfic = document.unicfanfictionform.texte.value; //Texte du textarea\n \n /*Traitement des données*/\n var modelefanfictionunique = '{{Fanfiction/Partie Unique\\n|image = '+ image + '\\n |livre = '+ livre + '\\n|titre = '+ titre + '\\n|signature = '+ wgUserName + '\\n|auteur = '+ auteur + '\\n|age = '+ age + '\\n|texte = '+ fanfic + '\\n}}';\n \n /*Envoi des données*/\n postFanfic(livre + ' : ' + titre, modelefanfictionunique, 'Nouvelle Fanfiction');\n}", "function RelGrafico(formulario)\r\n{\r\n\tif (formulario.dtinicial.value == '')\r\n\t{\r\n\r\n\t\talert('O Campo \"Data Inicial\" deve ser preenchido.');\r\n\t\tformulario.dtinicial.focus();\r\n\t\treturn false;\r\n\t}\r\n\tif(!ValidaDt(formulario.name,'dtinicial','Data Inicial')){\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif (formulario.dtfinal.value == '')\r\n\t{\r\n\t\talert('O Campo \"Data Final\" deve ser preenchido.');\r\n\t\tformulario.dtfinal.focus();\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif(!ValidaDt(formulario.name,'dtfinal','Data Final')){\r\n\t\treturn false;\r\n\t}\r\n\r\n\tformulario.action = window.location.href;\r\n\tformulario.submit();\r\n}", "function populateForm2Js(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('cobEtapaDeudaFrm.accion'), \n\t\tget('cobEtapaDeudaFrm.origen'));\n\t\n\tjsCobEtapaDeudaId = get('cobEtapaDeudaFrm.id').toString();\n\tjsCobEtapaDeudaCodEtapDeud = get('cobEtapaDeudaFrm.codEtapDeud').toString();\n\tjsCobEtapaDeudaValDesc = get('cobEtapaDeudaFrm.valDesc').toString();\n\tjsCobEtapaDeudaIndExcl = get('cobEtapaDeudaFrm.indExcl');\n\tjsCobEtapaDeudaValEdadInic = get('cobEtapaDeudaFrm.valEdadInic').toString();\n\tjsCobEtapaDeudaValEdadFina = get('cobEtapaDeudaFrm.valEdadFina').toString();\n\tjsCobEtapaDeudaIndTelf = get('cobEtapaDeudaFrm.indTelf');\n\tjsCobEtapaDeudaImpDesd = get('cobEtapaDeudaFrm.impDesd').toString();\n\tjsCobEtapaDeudaImpHast = get('cobEtapaDeudaFrm.impHast').toString();\n\tjsCobEtapaDeudaNumDiasGracCompPago = get('cobEtapaDeudaFrm.numDiasGracCompPago').toString();\n\tjsCobEtapaDeudaValPorcIncu = get('cobEtapaDeudaFrm.valPorcIncu').toString();\n\tjsCobEtapaDeudaMensOidMens = get('cobEtapaDeudaFrm.mensOidMens')[0];\n\tjsCobEtapaDeudaMelcOidMetoLiquCobr = get('cobEtapaDeudaFrm.melcOidMetoLiquCobr')[0];\n\tjsCobEtapaDeudaTbalOidTipoBala = get('cobEtapaDeudaFrm.tbalOidTipoBala')[0];\n\tjsCobEtapaDeudaGacaOidGuioArguCabe = get('cobEtapaDeudaFrm.gacaOidGuioArguCabe')[0];\n\tjsCobEtapaDeudaPaisOidPais = get('cobEtapaDeudaFrm.paisOidPais')[0];\n\tjsCobEtapaDeudaOredOidEtapDeu1 = get('cobEtapaDeudaFrm.oredOidEtapDeu1')[0];\n\tjsCobEtapaDeudaOredOidEtapDeu2 = get('cobEtapaDeudaFrm.oredOidEtapDeu2')[0];\n\tjsCobEtapaDeudaOredOidEtapDeu3 = get('cobEtapaDeudaFrm.oredOidEtapDeu3')[0];\n\t\n}", "function populateJs2Form(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('calGuiasFrm.accion'), \n\t\tget('calGuiasFrm.origen'));\n\n\n\tset('calGuiasFrm.id', jsCalGuiasId);\n\tset('calGuiasFrm.codGuia', jsCalGuiasCodGuia);\n\tset('calGuiasFrm.dpteOidDepa', [jsCalGuiasDpteOidDepa]);\n\tset('calGuiasFrm.valTitu', jsCalGuiasValTitu);\n\tset('calGuiasFrm.fecInicVali', jsCalGuiasFecInicVali);\n\tset('calGuiasFrm.fecFinVali', jsCalGuiasFecFinVali);\n\tset('calGuiasFrm.valDescGuia', jsCalGuiasValDescGuia);\n\tset('calGuiasFrm.paisOidPais', [jsCalGuiasPaisOidPais]);\n\t\n}", "function obtemPacienteFormulario(form) {\n var paciente = {\n nome: form.nome.value,\n peso: form.peso.value,\n altura: form.altura.value,\n gordura: form.gordura.value,\n imc: calcularImc(form.peso.value, form.altura.value)\n }\n return paciente;\n}", "function LimpiarCampos()\n{\n\t\n\t__('agente_name').value= \"\";\n\t__('agente_venta').value= \"\";\n\t__('user_zona').value = \"\";\n\t__('agente_comision').value= \"\";\n\t__('agente_folio').value = \"\";\n\t__('user').value = \"\";\n\t__('registro').style.display = \"inline\";\n\t__('modifica').style.display = \"none\";\n\t__('elimina').style.display = \"none\";\n\t\n\t\n\t// __('cancelar').style.display = 'none';\n\t// __('imprimir').style.display = 'none';\n}", "function procesarNomina(form) {\r\n\tif (confirm(\"¿Dese generar la nomina para los trabajadores seleccionados?\")) {\r\n\t\tdocument.getElementById(\"bloqueo\").style.display = \"block\";\r\n\t\tdocument.getElementById(\"cargando\").style.display = \"block\";\r\n\t\tvar forganismo = document.getElementById(\"forganismo\").value;\r\n\t\tvar ftiponom = document.getElementById(\"ftiponom\").value;\r\n\t\tvar fperiodo = document.getElementById(\"fperiodo\").value;\r\n\t\tvar ftproceso = document.getElementById(\"ftproceso\").value;\r\n\t\tvar num = 0;\r\n\t\tvar aprobados = \"\";\r\n\t\t\r\n\t\t//\tObtengo los valores de los empleados a procesar...\r\n\t\tfor(i=0; n=form.elements[i]; i++) {\r\n\t\t\tif (n.type==\"checkbox\" && n.name==\"chkAprobados\" && n.checked==true) {\r\n\t\t\t\tnum++;\r\n\t\t\t\tvar valor = n.value.split(\"|:|\");\r\n\t\t\t\tif (num == 1) aprobados = valor[0]; else aprobados += \"|:|\" + valor[0];\r\n\t\t\t} \r\n\t\t}\r\n\t\t\r\n\t\t//\tCREO UN OBJETO AJAX PARA VERIFICAR QUE EL NUEVO REGISTRO NO EXISTA EN LA BASE DE DATOS\r\n\t\tvar ajax=nuevoAjax();\r\n\t\tajax.open(\"POST\", \"fphp_ajax_nomina.php\", true);\r\n\t\tajax.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\r\n\t\tajax.send(\"modulo=EJECUCION-PROCESOS&accion=PROCESAR-NOMINA&aprobados=\"+aprobados+\"&organismo=\"+forganismo+\"&tiponom=\"+ftiponom+\"&periodo=\"+fperiodo+\"&proceso=\"+ftproceso);\r\n\t\tajax.onreadystatechange=function() {\r\n\t\t\tif (ajax.readyState==4)\t{\r\n\t\t\t\tvar resp=ajax.responseText;\r\n\t\t\t\tif (resp.trim() != \"\") alert(resp); else alert(\"¡Se generó el calculo exitosamente!\");\t\t\t\r\n\t\t\t\tdocument.getElementById(\"bloqueo\").style.display = \"none\";\t\t\r\n\t\t\t\tdocument.getElementById(\"cargando\").style.display = \"none\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function accionForm (datos) {\n var id_boton = $(this).attr('id');\n var tabla = $(\"#nom-tabla\").val();\n var nom = encodeURIComponent($(\"#nom\").val());\n var campos = $(\"#campos\").val();\n var requeridos = $(\"#requeridos\").val();\n var camp = campos.split(',');\n var campo_post = \"\";\n if(requeridos.length){\n var req = requeridos.split(',');\n for (var i = 0; i < req.length; i++) {\n var valor_req = $(\"#\"+req[i]).val();\n if(valor_req === ''){\n swal({title: \"Error!\",text: \"Este campo es requerido.\",type: \"error\",confirmButtonText: \"Aceptar\",confirmButtonColor: \"#E25856\"},function(){$(\"#\"+req[i]).focus();});\n return false;\n }\n }\n }\n for(var i = 0; i < camp.length; i++){\n if(i === 0){\n campo_post += camp[i]+\"=\"+$(\"#\"+camp[i]).val();\n }\n else{\n campo_post += \"&\"+camp[i]+\"=\"+$(\"#\"+camp[i]).val();\n }\n }\n // validamos si la tabla es la de banner\n if((tabla === 'rmb_banner') || (tabla === 'rmb_tcont')){\n var datos_form = new FormData($(\"#form_master\")[0]);\n }\n\n switch(id_boton){\n case 'cancel':\n $(\"#col-md-12\").load(\"./lista.php?tabla=\"+tabla+\"&nom=\"+nom);\n return;\n break;\n case 'ingresar':\n if((tabla === 'rmb_banner') || (tabla === 'rmb_tcont')){\n var send_post = datos_form;\n }\n else{\n var send_post = \"ins=1&tabla=\"+tabla+\"&\"+campo_post;\n }\n break;\n case 'actualizar':\n if((tabla === 'rmb_banner') || (tabla === 'rmb_tcont')){\n var send_post = datos_form;\n }\n else{\n var id = $(\"#id\").val();\n var send_post = \"id_upd=\"+id+\"&tabla=\"+tabla+\"&\"+campo_post;\n }\n break;\n }\n //Enviar los datos para ingresar o actualizar\n if((tabla === 'rmb_banner') || (tabla === 'rmb_tcont')){\n $.ajax({\n url:\"./edicion.php\",\n cache:false,\n type:\"POST\",\n contentType:false,\n data:send_post,\n processData:false,\n success: function(datos){\n if(datos !== ''){\n swal({\n title: \"Felicidades!\",\n text: datos,\n type: \"success\",\n confirmButtonText: \"Continuar\",\n confirmButtonColor: \"#94B86E\"\n },\n function() {\n $(\"#col-md-12\").load(\"./lista.php?tabla=\"+tabla+\"&nom=\"+nom);\n });\n }\n else{\n swal({\n title: \"Error!\",\n text: \"No se pudo \"+id_boton+\" el registro\",\n type: \"error\",\n confirmButtonText: \"Aceptar\",\n confirmButtonColor: \"#E25856\"\n },\n function() {\n $(\"#\"+req[i]).focus();\n });\n }\n }\n });\n }\n else{\n $.ajax({\n url:\"./edicion.php\",\n cache:false,\n type:\"POST\",\n data:send_post,\n success: function(datos){\n if(datos !== ''){\n swal({\n title: \"Felicidades!\",\n text: datos,\n type: \"success\",\n confirmButtonText: \"Continuar\",\n confirmButtonColor: \"#94B86E\"\n },\n function() {\n $(\"#col-md-12\").load(\"./lista.php?tabla=\"+tabla+\"&nom=\"+nom);\n });\n }\n else{\n swal({\n title: \"Error!\",\n text: \"No se pudo \"+id_boton+\" el registro\",\n type: \"error\",\n confirmButtonText: \"Aceptar\",\n confirmButtonColor: \"#E25856\"\n },\n function() {\n $(\"#\"+req[i]).focus();\n });\n }\n }\n });\n }\n}", "function realizarFormulario(codFormulario) {\r\n\tswitch (codFormulario) {\r\n\tcase 1: // se escogio el formulario de la ventriculografia\r\n\t\tif (verEstadoCheckbox('ventriculografia_activacion')) {\r\n\t\t\taparecerElemento('informe_ventriculografia');\r\n\t\t\tcarga_logica_informe_ventriculografia();\r\n\t\t} else {\r\n\t\t\treiniciar_Elementos_Formulario_Ventriculografia();\r\n\t\t\tdesaparecerElemento('informe_ventriculografia');\r\n\t\t}\r\n\t\t\r\n\t\t recopilarInformeVentriculografia(); \r\n\t\tbreak;\r\n\r\n\tcase 2: // se escogio el formulario del aortograma\r\n\t\tif (verEstadoCheckbox('aortograma_activacion')) {\r\n\t\t\taparecerElemento('informe_aortograma');\r\n\t\t\tcarga_logica_informe_aortograma();\r\n\r\n\t\t} else {\r\n\t\t\treiniciar_elementos_Formulario_Aortograma();\r\n\t\t\tdesaparecerElemento('informe_aortograma');\r\n\t\t}\r\n\t\trecopilarInformeAortograma(); \r\n\t\tbreak;\r\n\r\n\t\t\r\n\tcase 3:\r\n\t\t\r\n\t\tif (verEstadoCheckbox('bypass_activacion')) {\r\n\t\t\taparecerElemento('informe_bypass');\r\n\t\t\tcarga_logica_informe_bypass();\r\n\r\n\t\t} else {\r\n\t\t\treiniciar_elementos_Formulario_Bypass();\r\n\t\t\tdesaparecerElemento('informe_bypass');\r\n\t\t}\r\n\t\trecopilarInformeBypass(); \r\n\r\n\t\tbreak;\r\n\t\t\r\n\tcase 4: // se escogio el formulario de anatomia coronaria\r\n\t\t\r\n\t//\talert(verEstadoCheckbox('anatomia_coronaria_activacion'));\r\n\t\tif (verEstadoCheckbox('anatomia_coronaria_activacion')) {\r\n\t\t\taparecerElemento('informe_anatomia_coronaria');\r\n\t\t\r\n\t\t\t/*if (tipo_lesiones_arterias_general.length == 0 || arterias_bifurcadas.length == 0 ){\r\n\t\t\t\tconsultarlesionesbifurcaciones();\r\n\t\t\t}*/\r\n\t\t\t//else{\r\n\t\t\t\tcarga_logica_informe_anatomia_coronaria();\r\n\t\t\t\tseleccionAnalisisArteria();\r\n\t\t//\t}\r\n\t\t\r\n\t\t} else {\r\n\t\t\treiniciar_Elementos_Formulario_Anatomia_Coronaria();\r\n\t\t\tdesaparecerElemento('informe_anatomia_coronaria');\r\n\t\t}\r\n\t\trecopilarInformeAnatomiaCoronaria();\r\n\t\tbreak;\r\n\t}\r\n\t ActivacionDesactivacionEnvioInformes();\r\n\r\n\t if(tamanoinfotextbox(\"contenido_informe_ventriculografia\")==0){\r\n\t\t recopilarInformeVentriculografia(); \r\n\t }\r\n\t if(tamanoinfotextbox(\"contenido_informe_aortograma\")==0){\r\n\t\t\trecopilarInformeAortograma(); \r\n\t }\r\n\t \r\n\t if(tamanoinfotextbox(\"contenido_informe_bypass\")==0){\r\n\t\t\trecopilarInformeBypass(); \r\n\t }\r\n\t \r\n\t if(tamanoinfotextbox(\"contenido_informe_analisis_anatomia_coronaria\")==0){\r\n\t \trecopilarInformeAnatomiaCoronaria();\r\n\t }\r\n\t\r\n}", "function actualizar_esquema_comision(){\n\t\tenviarFormulario(\"#form_esquema_comision_actualizar\", 'EsquemaComision/actualizar_esquema_comision', '#cuadro4');\n\t}", "function display_new_avistamiento_form() {\n\n // Get the html form that we will fill\n let add_elements_form = document.getElementById(\"nuevos_avistamientos\");\n\n // Check if the form is empty\n if (add_elements_form.children.length === 0) {\n // if it is empty, we have to add:\n // * html div to put the inputs of each avistamiento\n // * html div to put the inputs of the contacto\n // * the button to send the form\n\n // avistamiento input\n let form_input_div = document.createElement(\"div\");\n // submit button\n let submit_form_div = document.createElement(\"div\");\n let form_error_msgs = document.createElement(\"ul\");\n form_error_msgs.id = \"form_error_messages\";\n let submit_form_button = document.createElement(\"button\");\n submit_form_button.type = \"button\";\n submit_form_button.append(\"Enviar Información de AvistamientoDB\");\n submit_form_button.addEventListener('click', function () {\n if (is_valid_form()) {\n display_modal_confirmation(); // add a confirmation box before submitting\n }\n })\n submit_form_div.append(form_error_msgs, submit_form_button);\n\n // contacto input\n let form_contacto_div = document.createElement(\"div\");\n form_contacto_div.className = \"contacto flex_col\";\n form_contacto_div.append(\"Info de Contacto\");\n let form_contacto_name_div = document.createElement(\"div\");\n let form_contacto_name_label = document.createElement(\"label\");\n form_contacto_name_label.htmlFor = \"nombre\";\n form_contacto_name_label.append(\"Nombre:\");\n let form_contacto_name_input = document.createElement(\"input\");\n form_contacto_name_input.id = \"nombre\";\n form_contacto_name_input.name = \"nombre\";\n form_contacto_name_input.className = \"unchecked_input\";\n form_contacto_name_input.type = \"text\";\n form_contacto_name_input.size = 100;\n form_contacto_name_input.maxLength = 200;\n form_contacto_name_input.required = true;\n form_contacto_name_div.append(form_contacto_name_label, form_contacto_name_input);\n let form_contacto_mail_phone_div = document.createElement(\"div\");\n form_contacto_mail_phone_div.className = \"flex_row\";\n let form_contacto_mail_div = document.createElement(\"div\");\n let form_contacto_mail_label = document.createElement(\"label\");\n form_contacto_mail_label.append(\"Correo:\")\n form_contacto_mail_label.htmlFor = \"email\";\n let form_contacto_mail_input = document.createElement(\"input\");\n form_contacto_mail_input.id = \"email\";\n form_contacto_mail_input.name = \"email\";\n form_contacto_mail_input.className = \"unchecked_input\";\n // form_contacto_mail_input.type = \"email\";\n form_contacto_mail_input.type = \"text\";\n form_contacto_mail_input.size = 100;\n form_contacto_mail_input.required = true;\n form_contacto_mail_div.append(form_contacto_mail_label, form_contacto_mail_input)\n let form_contacto_phone_div = document.createElement(\"div\");\n let form_contacto_phone_label = document.createElement(\"label\");\n form_contacto_phone_label.htmlFor = \"celular\";\n form_contacto_phone_label.append(\"Teléfono\");\n let form_contacto_phone_input = document.createElement(\"input\");\n form_contacto_phone_input.id = \"celular\";\n form_contacto_phone_input.name = \"celular\";\n form_contacto_phone_input.className = \"unchecked_input\";\n // form_contacto_phone_input.type = \"tel\";\n form_contacto_phone_input.type = \"text\";\n form_contacto_phone_input.size = 15;\n form_contacto_phone_div.append(form_contacto_phone_label, form_contacto_phone_input);\n form_contacto_mail_phone_div.append(form_contacto_mail_div, form_contacto_phone_div);\n form_contacto_div.append(form_contacto_name_div, form_contacto_mail_phone_div);\n add_elements_form.append(form_input_div, form_contacto_div, submit_form_div);\n }\n\n // Take the form's div where we'll put the inputs\n let form_main_div = add_elements_form.children[0];\n const i = add_elements_form.children[0].children.length; // get the number of children to calculate html ids\n\n let new_div = document.createElement(\"div\");\n new_div.className = \"avistamiento\";\n new_div.id = \"new_avistamiento\"+i;\n\n let datetime_div = document.createElement(\"div\"); // div with date_time's label and input\n let datetime_label = document.createElement(\"label\");\n datetime_label.htmlFor = \"dia-hora-avistamiento\"+i;\n datetime_label.append(\"Fecha y Hora\");\n let datetime_input = document.createElement(\"input\");\n datetime_input.name = \"dia-hora-avistamiento\";\n datetime_input.id = \"dia-hora-avistamiento\"+i;\n datetime_input.className = \"unchecked_input\";\n // datetime_input.type = \"datetime-local\";\n datetime_input.type = \"text\";\n datetime_input.size = 20;\n datetime_input.placeholder = \"año-mes-dia hora:minuto\";\n let time_now = new Date();\n datetime_input.value =\n time_now.getFullYear() + \"-\"\n + (time_now.getMonth()+1>=10? time_now.getMonth()+1: \"0\"+(time_now.getMonth()+1)) + \"-\"\n + (time_now.getDate()>=10? time_now.getDate(): \"0\"+time_now.getDate()) + \" \"\n + (time_now.getHours()>=10? time_now.getHours(): \"0\"+time_now.getHours()) + \":\"\n + (time_now.getMinutes()>=10? time_now.getMinutes(): \"0\"+time_now.getMinutes());\n datetime_input.required = true;\n datetime_div.append(datetime_label, datetime_input);\n let lugar_div = document.createElement(\"div\"); // row with divs for region, comuna and sector\n lugar_div.className = \"flex_row\";\n let region_div = document.createElement(\"div\"); // div with region's label and select\n region_div.className = \"flex_col\";\n let region_div_label = document.createElement(\"label\");\n region_div_label.htmlFor = \"region\"+i;\n region_div_label.append(\"Region\");\n let region_div_select = document.createElement(\"select\");\n region_div_select.name = \"region\";\n region_div_select.id = \"region\"+i;\n region_div_select.className = \"unchecked_input\";\n region_div_select.required = true;\n // the region options will be generated later\n region_div.append(region_div_label, region_div_select);\n let comuna_div = document.createElement(\"div\"); // div with comuna 's label and select\n comuna_div.className = \"flex_col\";\n let comuna_div_label = document.createElement(\"label\");\n comuna_div_label.htmlFor = \"comuna\" + i;\n comuna_div_label.append(\"Comuna\");\n let comuna_div_select = document.createElement(\"select\");\n comuna_div_select.name = \"comuna\";\n comuna_div_select.id = \"comuna\" + i;\n comuna_div_select.className = \"unchecked_input\";\n comuna_div_select.required = true;\n comuna_div_select.innerHTML = \"<option selected value=''>--Elija una Región--</option>\" // you need a region first\n // as the comuna options depends on the region, they will be generated dynamically\n comuna_div.append(comuna_div_label, comuna_div_select);\n let sector_div = document.createElement(\"div\"); // div with sector's label and input\n sector_div.className = \"flex_col\";\n let sector_div_label = document.createElement(\"label\");\n sector_div_label.htmlFor = \"sector\" + i;\n sector_div_label.append(\"Sector\");\n let sector_div_select = document.createElement(\"input\");\n sector_div_select.name = \"sector\";\n sector_div_select.id = \"sector\" + i;\n sector_div_select.className = \"unchecked_input\";\n sector_div_select.type = \"text\";\n sector_div_select.size = 200;\n sector_div_select.maxLength = 100;\n\n sector_div.append(sector_div_label, sector_div_select);\n lugar_div.append(region_div, comuna_div, sector_div)\n let avistamiento_div = document.createElement(\"div\"); // row with divs for description and photo\n avistamiento_div.className = \"flex_row\";\n let avistamiento_text_div = document.createElement(\"div\"); // column with tipo and estado\n avistamiento_text_div.className = \"flex_col\";\n let avistamiento_text_div_type_label = document.createElement(\"label\");\n avistamiento_text_div_type_label.htmlFor = \"tipo-avistamiento\" + i;\n avistamiento_text_div_type_label.append(\"Tipo\");\n let avistamiento_text_div_type_select = document.createElement(\"select\");\n avistamiento_text_div_type_select.name = \"tipo-avistamiento\";\n avistamiento_text_div_type_select.id = \"tipo-avistamiento\" + i;\n avistamiento_text_div_type_select.className = \"unchecked_input\";\n avistamiento_text_div_type_select.required = true;\n let base_option = document.createElement(\"option\");\n base_option.value = \"\"; base_option.append(\"--Elija un subfilo de artrópodo--\");\n avistamiento_text_div_type_select.append(base_option);\n for (let k = 0; k < arthropod_options.length; k++) {\n let o = document.createElement(\"option\");\n o.value = arthropod_options[k]['value'];\n o.append(arthropod_options[k]['option']);\n avistamiento_text_div_type_select.append(o);\n }\n let avistamiento_text_div_state_label = document.createElement(\"label\");\n avistamiento_text_div_state_label.htmlFor = \"estado-avistamiento\"+i;\n avistamiento_text_div_state_label.append(\"Estado\");\n let avistamiento_text_div_state_select = document.createElement(\"select\");\n avistamiento_text_div_state_select.name = \"estado-avistamiento\";\n avistamiento_text_div_state_select.id = \"estado-avistamiento\"+i;\n avistamiento_text_div_state_select.className = \"unchecked_input\";\n avistamiento_text_div_state_select.required = true;\n avistamiento_text_div_state_select.innerHTML = \"<option value=\\\"\\\">--Elija un estado--</option>\";\n for (let k = 0; k < state_options.length; k++) {\n let o = document.createElement(\"option\");\n o.value = state_options[k][\"value\"];\n o.append(state_options[k][\"option\"]);\n avistamiento_text_div_state_select.append(o);\n }\n avistamiento_text_div.append(\n avistamiento_text_div_type_label, avistamiento_text_div_type_select,\n avistamiento_text_div_state_label, avistamiento_text_div_state_select\n )\n let avistamiento_photo_div = document.createElement(\"div\"); // column with rows of photos photo\n avistamiento_photo_div.className = \"flex_col\";\n let avistamiento_photo_div_text = document.createElement(\"div\");\n avistamiento_photo_div_text.append(\"Foto\");\n let avistamiento_photo_div_div = document.createElement(\"div\"); // row with columns with input and preview\n avistamiento_photo_div_div.className = \"flex_row\";\n avistamiento_photo_div_div.id = \"row_of_photo_divs\"+i;\n add_photo_column_input(avistamiento_photo_div_div, i);\n avistamiento_photo_div.append(avistamiento_photo_div_text, avistamiento_photo_div_div)\n avistamiento_div.append(avistamiento_text_div, avistamiento_photo_div);\n\n new_div.append(datetime_div, lugar_div, avistamiento_div);\n form_main_div.append(new_div);\n\n // now we can generate the region options\n generate_region_options(i);\n\n document.getElementById(\"region\"+i).addEventListener('change', function () {display_comuna_options_k(i);})\n\n if (i > 0) {\n display_comuna_options_k(i); // usually, we would wait until the user to select a region, but it's already preset\n sector_div_select.value = document.getElementById(\"sector0\").value;\n }\n}", "function preencheLoteFinal(loteInicial){\r\n\tvar form = document.ImovelOutrosCriteriosActionForm;\r\n\t\r\n\tform.loteDestino.value = loteInicial.value;\r\n}", "function initFormularioCargaMasivaConfirmacion(){\n\n\t\tvar $mainForm = $('#autogestion-form-confirmar');\n\n\t\tvar tipoIngreso = null;\n\n\t\tinitActions();\n\t\tvalidateMainForm();\n\n\t\tfunction validateMainForm(){\n\n\t\t\tdisableSumbitButton($mainForm, true);\n\n\t\t\telementsForm['validator'] = \n\t\t\t\t$mainForm.validate({\n\t\t\t\t\t rules: {\n\t\t\t\t\t\tarchivo: {\n\t\t\t\t\t\t\trequired : {\n\t\t\t\t\t\t\t\tdepends: function(element) {\n\t\t\t\t\t\t\t\t\tvar motivo = $mainForm.find('.motivo-autogestion:checked').val();\n\n\t\t\t\t \treturn motivo == 'estructura-nueva';\n\t\t\t\t }\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\textension: \"xls\",\n\t\t\t\t\t\t\tfilesize: 10000000\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmotivoAutogestion: {\n\t\t\t\t\t\t\trequired: true\n\t\t\t\t\t\t}\n\t\t\t\t\t },\n\t\t\t\t\t messages: {\n\t\t\t\t\t\t archivo: {\n\t\t\t\t\t\t required: \"Ingresa un archivo de 10 MB máximo.\",\n\t\t\t\t\t\t extension: \"Ingresa un archivo con extensión: .xls\",\n\t\t\t\t\t\t filesize: \"Ingresa un archivo de 10 MB máximo.\"\n\t\t\t\t\t\t },\n\t\t\t\t\t\t motivoAutogestion: {\n\t\t\t\t\t\t required: \"Selecciona un motivo.\",\n\t\t\t\t\t\t }\n\t\t\t\t\t },\n\t\t\t\t\t\terrorClass : \"error-dd error\",\n\t\t\t\t\t\terrorElement : 'div',\n\t\t\t\t\t\terrorPlacement: function(error, element) {\n\t\t\t\t\t\t\tvar elementInput = element[0];\n\t\t\t\t\t\t\tif(element[0]['id']==='archivo'){\n\t\t\t\t\t\t\t\t$('.lineas-archivo .extra-info').hide();\n\t\t\t\t\t\t\t\terror.appendTo( $('.lineas-archivo .add-lines-ge-mod' ));\n\t\t\t\t\t\t\t\telement.parent().addClass('error');\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsuccess: function ($error) {\n\t\t\t\t\t\t\tif($error.length>0 && $('#archivo').val() != ''){\n\t\t\t\t\t\t\t\t$('.lineas-archivo .extra-info').hide();\n\t\t\t\t\t\t\t\t$('.lineas-archivo .file.error' ).removeClass('error');\n\t\t\t\t \t\t\t\t$error.remove();\n\t\t\t\t\t\t\t}\n\t\t\t\t },\n\t\t\t\t highlight : function(element, errorClass){\n\t\t\t\t \tvar $element = $(element);\n\t\t\t\t \tif($element.attr('id')==='archivo' && $element.val() == ''){\n\t\t\t\t \t\t$('.lineas-archivo .extra-info').hide();\n\t\t\t\t\t\t\t\t$element.parent().addClass('error');\n\t\t\t\t \t}\n\t\t\t\t },\n\t\t\t\t submitHandler: function(form) {\n\t\t\t\t\t\t\tif(!elementsForm['sending']){\n\t\t\t\t\t\t\t\tsendFormData(form);\n\t\t\t\t\t \t\t}\n\t\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tcheckGeneralValidForm($mainForm);\n\n\t\t\t\tfunction sendFormData(form){\n\t\t\t\t\telementsForm['sending'] = true;\n\t\t\t\t\t$(form).find('button[type=\"submit\"]').prop('disabled', true);\n\n\t\t\t\t\tvar self = $(form).serialize();\n\n\t\t\t\t\tvar urlPOST = ( $(form).prop('action') == '' ? postURL : $(form).prop('action') ) ;\n\t\t\t\t\t\n\t\t\t\t\t/**Quitar una vez en producción y aqui solo checamos si es una línea en development para mandar a otra liga**/\n\t\t\t\t\tvar sendTo = urlPOST;\n\t\t\t\t\turlPOST = checkDevelopmentPostHTML(urlPOST);\n\n\t\t\t\t\t$.post( urlPOST , self )\n\t\t\t\t\t.done(function( data ) {\n\t\t\t\t\t \tServices.gestionGrupos.cargaMasivaCallSuccess(data, form, sendTo, showInvalidErrorArchivo );\n\t\t\t\t\t\telementsForm['sending'] = false;\n\t\t\t\t\t })\n\t\t\t\t\t.fail(function( jqxhr, textStatus, error ) {\n\t\t\t\t\t \t//Mensaje de error del sistema\n\t\t\t\t\t \tServices.gestionGrupos.cargaMasivaCallFail(error, form);\n\t\t\t\t\t \telementsForm['sending'] = false;\n\t\t\t\t\t});\n\t\t\t\t}\t\n\t\t}\n\n\n\t\tfunction initActions(){\n\n\t\t\t/**\n\t\t\t\tSetea la info del Motivo\n\t\t\t**/\n\t\t\tvar $lastStep = $('.carga-masiva-last-step');\n\t\t\t$('.motivo-autogestion').change(function() {\n\t\t\t\tvar $checkbox = $(this);\n\t\t\t\tif(typeof ingresarLineasComponent != 'undefined')\n\t\t\t\t\tingresarLineasComponent.reset();\n\n\t\t\t\tif($('.motivo-autogestion:checked').length>0){\n\t\t\t\t\tvar current = $checkbox.val(),\n\t\t\t\t\tbtntext = (typeof $checkbox.data('btn') != 'undefined' ? $checkbox.data('btn') : 'Subir archivo');\n\n\t\t\t\t\tif(current=='continuar-con-lineas')\n\t\t\t\t\t\t$lastStep.addClass('revertir-estructura');\n\t\t\t\t\telse\n\t\t\t\t\t\t$lastStep.removeClass('revertir-estructura');\n\n\t\t\t\t\t$('#autogestion-btn').html(btntext);\n\t\t\t\t\t$lastStep.addClass('active');\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t$lastStep.removeClass('active');\n\n\n\n\t\t\t});\n\n\t\t}\n\n\t\tfunction resetMainForm(){\n\n\t\t\t$mainForm.find(\"input[type=text], input[type=email], input[type=password], select\").val(\"\");\n\t\t\t$mainForm.find(\"input[type=checkbox], input[type=radio]\").prop(\"checked\", false);\n\t\t\t$mainForm.find('button[type=\"submit\"]').prop('disabled', true);\n\t\t\t\n\t\t\tif(elementsForm['validator']){\n\t\t\t\telementsForm['validator'].resetForm();\n\t\t\t}\n\t\t}\n\n\t}", "function desafiocarro1(form) {\n resposta=form.resposta.value;\n if(resposta == \"44\") {\n alert(\"Parabens, voce acertou!\");\n carro6();\n }\n else{\n alert(\"Tente novamente!\");\n carro5();\n } \n}", "function form_verif(form, initial_value) { \n \n //\n // V�rifions les choses... \n \n var str = form.texte.value;\n \n if(str == initial_value || str == '') {\n\n aff_menu_div('erreur-comment');\n document.getElementById('erreur-comment').innerHTML = 'Votre message est trop court'; \n \n if(document.getElementById('ok-comment')) caff_menu_div('ok-comment');\n \n return true;\n \n } \n \n caff_menu_div('submit-comment');\n aff_menu_div('loader-comment');\n return false; \n\n }", "function procesoPrecio(){\n\n var getMinimo = minimo.slice(-1);\n var getMaximo = maximo.slice(-1);\n \nif(getMinimo != 0 && getMaximo != 0){\n formdata.append(\"minimo\",getMinimo);\n formdata.append(\"maximo\",getMaximo);\n}\n}", "function agregarFilaDeForm(event) {\r\n event.preventDefault();\r\n let data =\r\n {\r\n \"thing\":\r\n {\r\n \"numCapitulo\": capitulo.value,\r\n \"numTemporada\": temporada.value,\r\n \"titulo\": tituloSerie.value,\r\n \"fechaEmision\": emision.value,\r\n \"sinopsis\": sinop.value,\r\n }\r\n };\r\n\r\n guardarEnServicio(data)\r\n .then(function () {\r\n imprimirTabla();\r\n });\r\n\r\n\r\n}", "function limpiarFormularioPrescripcion(){\n $('.btn_otro_medicamento').val('0');\n $('.btn_otro_medicamento').text('Otro medicamento');\n $('#borderMedicamento').removeAttr('hidden');\n $('#border_otro_medicamento').attr('hidden', true);\n $('#select_medicamento').val(\"0\").trigger('change.select2');\n $('#input_otro_medicamento').val('');\n $('#via').val(\"0\").trigger('change.select2');\n $('#input_dosis').val(\"\");\n $('#select_unidad').val(\"0\").trigger('change.select2');\n $('#frecuencia').val(\"0\");\n $('#aplicacion').val(\"\");\n $('#fechaInicio').val(\"\");\n $('#duracion').val(\"0\");\n $('#fechaFin').val(\"\");\n $('#observacion').val(\"\");\n}", "function editarFormulario(){\n //Trae la grid para poder actualizar al editar\n listadoCamposFormulario = Ext.getCmp('listadoCamposFormulario');\n if (listadoCamposFormulario.getSelectionModel().hasSelection()) {\n var row = listadoCamposFormulario.getSelectionModel().getSelection()[0];\n \n\n encontrado=1;\n if(ventana==null) \n ventana = Ext.create ('App.miVentanaBanco');\n\n // Precarga el nombre e id seleccionados\n Ext.getCmp('nombreBanco').setValue(row.get('nombre'));\n Ext.getCmp('idBanco').setValue(row.get('id'));\n\n\n ventana.show();\n \n }\n }", "function populateForm2Js(){\n\t//Primero determinamos el modo en el que estamos;\n\tvar mode = getMMGMode(get('cobUsuarEtapaCobraDetalFrm.accion'), \n\t\tget('cobUsuarEtapaCobraDetalFrm.origen'));\n\t\n\tjsCobUsuarEtapaCobraDetalId = get('cobUsuarEtapaCobraDetalFrm.id').toString();\n\tjsCobUsuarEtapaCobraDetalUeccOidUsuaEtapCobr = get('cobUsuarEtapaCobraDetalFrm.ueccOidUsuaEtapCobr')[0];\n\tjsCobUsuarEtapaCobraDetalEdtcOidEtapDeudTipoCarg = get('cobUsuarEtapaCobraDetalFrm.edtcOidEtapDeudTipoCarg')[0];\n\tjsCobUsuarEtapaCobraDetalZsgvOidSubgVent = get('cobUsuarEtapaCobraDetalFrm.zsgvOidSubgVent')[0];\n\tjsCobUsuarEtapaCobraDetalZorgOidRegi = get('cobUsuarEtapaCobraDetalFrm.zorgOidRegi')[0];\n\tjsCobUsuarEtapaCobraDetalZzonOidZona = get('cobUsuarEtapaCobraDetalFrm.zzonOidZona')[0];\n\tjsCobUsuarEtapaCobraDetalZsccOidSecc = get('cobUsuarEtapaCobraDetalFrm.zsccOidSecc')[0];\n\tjsCobUsuarEtapaCobraDetalTerrOidTerr = get('cobUsuarEtapaCobraDetalFrm.terrOidTerr')[0];\n\tjsCobUsuarEtapaCobraDetalMelcOidMetoLiquCobr = get('cobUsuarEtapaCobraDetalFrm.melcOidMetoLiquCobr')[0];\n\tjsCobUsuarEtapaCobraDetalEucoOidEstaUsuaEtapCobr = get('cobUsuarEtapaCobraDetalFrm.eucoOidEstaUsuaEtapCobr')[0];\n\tjsCobUsuarEtapaCobraDetalGacaOidGuioArguCabe = get('cobUsuarEtapaCobraDetalFrm.gacaOidGuioArguCabe')[0];\n\tjsCobUsuarEtapaCobraDetalValObse = get('cobUsuarEtapaCobraDetalFrm.valObse').toString();\n\t\n}", "function formProducciones(tipo){\n\t//Selecciona la zona debajo del menu horizontal de edicion y la oculta\n\tvar contenidoCentral = document.getElementById(\"contenidoCentral\");\n\tcontenidoCentral.setAttribute(\"class\",\"d-none\");\n\t//Selecciona la zona para poner los formularios\n\tvar contenidoFormularios = document.getElementById(\"contenidoFormularios\");\n\tcontenidoFormularios.setAttribute(\"class\",\"d-block\");\n\t//QUITA TODO EL CONTENIDO PREVIO POR SI HAY OTROS FORMULARIOS\n\twhile (contenidoFormularios.firstChild) {\n\t\tcontenidoFormularios.removeChild(contenidoFormularios.firstChild);\n\t}\n\t\t\n\tif (tipo == \"add\") {\n\t\tvar formulario = document.createElement(\"form\");\n\t\tformulario.setAttribute(\"name\",\"addProduction\");\n\t\tformulario.setAttribute(\"action\",\"\");\n\t\tformulario.setAttribute(\"onsubmit\",\"validarProducciones(); return false\");\n\t\tformulario.setAttribute(\"method\",\"post\");\n\t\tvar leyenda = document.createElement(\"legend\");\n\t\tleyenda.appendChild(document.createTextNode(\"Añadir produccion\"));\n\t\t//Se añade al contenido\n\t\tformulario.appendChild(leyenda);\n\t\tcontenidoFormularios.appendChild(formulario);\n\t\t//TITULO DE LA PRODUCCION\n\t\tvar grupo1 = document.createElement(\"div\");\n\t\tgrupo1.setAttribute(\"class\",\"form-group\");\n\t\tvar labelTitle = document.createElement(\"label\");\n\t\tlabelTitle.setAttribute(\"for\",\"titulo\");\n\t\tlabelTitle.appendChild(document.createTextNode(\"Titulo de la produccion*\"));\n\t\tvar inputTitle = document.createElement(\"input\");\n\t\tinputTitle.setAttribute(\"type\",\"text\");\n\t\tinputTitle.setAttribute(\"class\",\"form-control\");\n\t\tinputTitle.setAttribute(\"id\",\"titulo\");\n\t\tinputTitle.setAttribute(\"onblur\",\"validarCampoTexto(this)\");\n\t\tinputTitle.setAttribute(\"placeholder\",\"Titulo\");\n\t\tvar malTitle = document.createElement(\"small\");\n\t\tmalTitle.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalTitle.setAttribute(\"id\",\"titleMal\");\n\t\t//Se añade al formulario como hijos\n\t\tgrupo1.appendChild(labelTitle);\n\t\tgrupo1.appendChild(inputTitle);\n\t\tgrupo1.appendChild(malTitle);\n\t\tformulario.appendChild(grupo1);\n\t\t//FECHA DE LA PUBLICACION DE LA PRODUCCION\n\t\tvar grupo2 = document.createElement(\"div\");\n\t\tgrupo2.setAttribute(\"class\",\"form-group\");\n\t\tvar labelDate = document.createElement(\"label\");\n\t\tlabelDate.setAttribute(\"for\",\"publication\");\n\t\tlabelDate.appendChild(document.createTextNode(\"Fecha de publicacion*\"));\n\t\tvar inputDate = document.createElement(\"input\");\n\t\tinputDate.setAttribute(\"type\",\"text\");\n\t\tinputDate.setAttribute(\"class\",\"form-control\");\n\t\tinputDate.setAttribute(\"id\",\"publication\");\n\t\tinputDate.setAttribute(\"onblur\",\"validarCampoFecha(this)\");\n\t\tinputDate.setAttribute(\"placeholder\",\"DD/MM/AAAA\");\n\t\tvar malDate = document.createElement(\"small\");\n\t\tmalDate.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalDate.setAttribute(\"id\",\"dateMal\");\n\t\t//Se añade al formulario como hijos\n\t\tgrupo2.appendChild(labelDate);\n\t\tgrupo2.appendChild(inputDate);\n\t\tgrupo2.appendChild(malDate);\n\t\tformulario.appendChild(grupo2);\n\t\t//NACIONALIDAD DE LA PRODUCCION\n\t\tvar grupo3 = document.createElement(\"div\");\n\t\tgrupo3.setAttribute(\"class\",\"form-group\");\n\t\tvar labelNationality = document.createElement(\"label\");\n\t\tlabelNationality.setAttribute(\"for\",\"nationality\");\n\t\tlabelNationality.appendChild(document.createTextNode(\"Nacionalidad*\"));\n\t\tvar inputNationality = document.createElement(\"input\");\n\t\tinputNationality.setAttribute(\"type\",\"text\");\n\t\tinputNationality.setAttribute(\"class\",\"form-control\");\n\t\tinputNationality.setAttribute(\"onblur\",\"validarCampoTexto(this)\");\n\t\tinputNationality.setAttribute(\"id\",\"nationality\");\n\t\tinputNationality.setAttribute(\"placeholder\",\"Nacionalidad\");\n\t\tvar malNationality = document.createElement(\"small\");\n\t\tmalNationality.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalNationality.setAttribute(\"id\",\"nationalityMal\");\n\t\t//Se añade al formulario como hijos\n\t\tgrupo3.appendChild(labelNationality);\n\t\tgrupo3.appendChild(inputNationality);\n\t\tgrupo3.appendChild(malNationality);\n\t\tformulario.appendChild(grupo3);\n\t\t//SIPNOSIS DE LA PRODUCCION\n\t\tvar grupo4 = document.createElement(\"div\");\n\t\tgrupo4.setAttribute(\"class\",\"form-group\");\n\t\tvar labelSypnosis = document.createElement(\"label\");\n\t\tlabelSypnosis.setAttribute(\"for\",\"synopsis\");\n\t\tlabelSypnosis.appendChild(document.createTextNode(\"Sipnosis*\"));\n\t\tvar inputSypnosis = document.createElement(\"input\");\n\t\tinputSypnosis.setAttribute(\"type\",\"text\");\n\t\tinputSypnosis.setAttribute(\"class\",\"form-control\");\n\t\tinputSypnosis.setAttribute(\"onblur\",\"validarCampoTexto(this)\");\n\t\tinputSypnosis.setAttribute(\"id\",\"synopsis\");\n\t\tinputSypnosis.setAttribute(\"placeholder\",\"Sipnosis\");\n\t\tvar malSypnosis = document.createElement(\"small\");\n\t\tmalSypnosis.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalSypnosis.setAttribute(\"id\",\"synopsisMal\");\n\t\t//Se añade al formulario como hijos\n\t\tgrupo4.appendChild(labelSypnosis);\n\t\tgrupo4.appendChild(inputSypnosis);\n\t\tgrupo4.appendChild(malSypnosis);\n\t\tformulario.appendChild(grupo4);\n\t\t//IMAGEN DE LA PRODUCCION\n\t\tvar grupo5 = document.createElement(\"div\");\n\t\tgrupo5.setAttribute(\"class\",\"form-group\");\n\t\tvar labelPicture = document.createElement(\"label\");\n\t\tlabelPicture.setAttribute(\"for\",\"picture\");\n\t\tlabelPicture.appendChild(document.createTextNode(\"Ruta de la imagen*\"));\n\t\tvar inputPicture = document.createElement(\"input\");\n\t\tinputPicture.setAttribute(\"type\",\"text\");\n\t\tinputPicture.setAttribute(\"class\",\"form-control\");\n\t\tinputPicture.setAttribute(\"id\",\"picture\");\n\t\tinputPicture.setAttribute(\"onblur\",\"validarCampoRutaObligatorio(this)\");\n\t\tinputPicture.setAttribute(\"placeholder\",\"X://xxxxxx/xxxx\");\n\t\tvar malPicture = document.createElement(\"small\");\n\t\tmalPicture.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalPicture.setAttribute(\"id\",\"pictureMal\");\n\t\t//Se añade al formulario como hijos\n\t\tgrupo5.appendChild(labelPicture);\n\t\tgrupo5.appendChild(inputPicture);\n\t\tgrupo5.appendChild(malPicture);\n\t\tformulario.appendChild(grupo5);\n\t\t//SELECT PARA EL TIPO DE PRODUCCION\n\t\tvar grupo6 = document.createElement(\"div\");\n\t\tgrupo6.setAttribute(\"class\",\"form-group\");\n\t\tvar labelTipo = document.createElement(\"label\");\n\t\tlabelTipo.setAttribute(\"for\",\"tipo\");\n\t\tlabelTipo.appendChild(document.createTextNode(\"Tipo de produccion*\"));\n\t\tvar selectTipo = document.createElement(\"select\");\n\t\tselectTipo.setAttribute(\"class\",\"form-control\");\n\t\tselectTipo.setAttribute(\"name\",\"tipo\");\n\t\tselectTipo.setAttribute(\"id\",\"tipo\");\n\t\tselectTipo.setAttribute(\"onblur\",\"validarCampoSelect(this)\");\n\t\tselectTipo.setAttribute(\"onchange\",\"mostrarDIVS()\");\n\t\tvar optionNull = document.createElement(\"option\");\n\t\toptionNull.setAttribute(\"value\",\"0\");\n\t\toptionNull.appendChild(document.createTextNode(\"-- Selecciona tipo --\"));\n\t\tvar optionMovie = document.createElement(\"option\");\n\t\toptionMovie.setAttribute(\"value\",\"Movie\");\n\t\toptionMovie.appendChild(document.createTextNode(\"Pelicula\"));\n\t\tvar optionSerie = document.createElement(\"option\");\n\t\toptionSerie.setAttribute(\"value\",\"Serie\");\n\t\toptionSerie.appendChild(document.createTextNode(\"Serie\"));\n\t\tselectTipo.appendChild(optionNull);\n\t\tselectTipo.appendChild(optionMovie);\n\t\tselectTipo.appendChild(optionSerie);\n\t\t//Se añaden como hijos al formulario\n\t\tgrupo6.appendChild(labelTipo);\n\t\tgrupo6.appendChild(selectTipo);\n\t\tformulario.appendChild(grupo6);\n\t\t//DIV QUE APARECE SI EN EL SELECT SE PONE MOVIE\n\t\tvar divMovie = document.createElement(\"div\");\n\t\tdivMovie.setAttribute(\"class\",\"form-group\");\n\t\tdivMovie.setAttribute(\"id\",\"divMovie\");\n\t\t//RECURSO DE LA PRODUCCION MOVIE\n\t\tvar labelResource = document.createElement(\"label\");\n\t\tlabelResource.setAttribute(\"for\",\"recurso\");\n\t\tlabelResource.appendChild(document.createTextNode(\"Recurso de la produccion\"));\n\t\tvar selectResource = document.createElement(\"select\");\n\t\tselectResource.setAttribute(\"class\",\"form-control mb-2\");\n\t\tselectResource.setAttribute(\"id\",\"recurso\");\n\t\tvar optionResource = document.createElement(\"option\");\n\t\toptionResource.setAttribute(\"value\",\"0\");\n\t\toptionResource.appendChild(document.createTextNode(\"-- SIN RECURSO --\"));\n\t\tselectResource.appendChild(optionResource);\n\t\t//Abre la conexion con la base de datos\n\t\tvar request = indexedDB.open(nombreDB);\n\t\t//Si ha salido bien\n\t\trequest.onsuccess = function(event) {\n\t\t\t//Asigna el resultado a la variable db, que tiene la base de datos \n\t\t\tvar db = event.target.result; \n\t\t\tvar objectStore = db.transaction([\"recursos\"],\"readonly\").objectStore(\"recursos\");\n\t\t\t//Abre un cursor para recorrer todos los objetos de la base de datos \n\t\t\tobjectStore.openCursor().onsuccess = function(event) {\n\t\t\t\tvar recurso = event.target.result;\n\t\t\t\tif (recurso) {\n\t\t\t\t\toptionResource = document.createElement(\"option\");\n\t\t\t\t\toptionResource.setAttribute(\"value\",recurso.value.link);\n\t\t\t\t\toptionResource.appendChild(document.createTextNode(recurso.value.link));\n\t\t\t\t\tselectResource.appendChild(optionResource);\n\t\t\t\t\t//Pasa al siguiente recurso\n\t\t\t\t\trecurso.continue();\n\t\t\t\t}\n\t\t\t};\n\t\t};\t\n\t\tdivMovie.appendChild(labelResource);\n\t\tdivMovie.appendChild(selectResource);\n\t\t//LONGITUD DE LA PRODUCCION MOVIE\n\t\tvar labelCoor = document.createElement(\"label\");\n\t\tlabelCoor.setAttribute(\"for\",\"titulo\");\n\t\tlabelCoor.appendChild(document.createTextNode(\"Coordenadas de la produccion\"));\n\t\tvar inputCoor1 = document.createElement(\"input\");\n\t\tinputCoor1.setAttribute(\"type\",\"text\");\n\t\tinputCoor1.setAttribute(\"class\",\"form-control\");\n\t\tinputCoor1.setAttribute(\"id\",\"longitud\");\n\t\tinputCoor1.setAttribute(\"onblur\",\"validarCampoNumeroOpcional(this)\");\n\t\tinputCoor1.setAttribute(\"placeholder\",\"Longitud\");\n\t\tvar malCoor1 = document.createElement(\"small\");\n\t\tmalCoor1.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalCoor1.setAttribute(\"id\",\"longitudMal\");\n\t\tvar inputCoor2 = document.createElement(\"input\");\n\t\tinputCoor2.setAttribute(\"type\",\"text\");\n\t\tinputCoor2.setAttribute(\"class\",\"form-control\");\n\t\tinputCoor2.setAttribute(\"id\",\"latitud\");\n\t\tinputCoor2.setAttribute(\"onblur\",\"validarCampoNumeroOpcional(this)\");\n\t\tinputCoor2.setAttribute(\"placeholder\",\"Latitud\");\n\t\tvar malCoor2 = document.createElement(\"small\");\n\t\tmalCoor2.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalCoor2.setAttribute(\"id\",\"latitudMal\");\n\t\tdivMovie.appendChild(labelCoor);\n\t\tdivMovie.appendChild(inputCoor1);\n\t\tdivMovie.appendChild(malCoor1);\n\t\tdivMovie.appendChild(inputCoor2);\n\t\tdivMovie.appendChild(malCoor2);\n\t\t//DIRECTOR DE LA PRODUCCION MOVIE\n\t\t//SE CREA EL BUSCADOR \n\t\tvar grupo6 = document.createElement(\"div\");\n\t\tgrupo6.setAttribute(\"class\",\"form-group mt-3\");\n\t\tvar label6 = document.createElement(\"label\");\n\t\tlabel6.setAttribute(\"for\",\"produccionesCat\");\n\t\tlabel6.appendChild(document.createTextNode(\"Asignar director a la nueva produccion*\"));\n\t\tvar divInputBtn = document.createElement(\"div\");\n\t\tdivInputBtn.setAttribute(\"class\",\"input-group\");\n\t\tvar divBtn = document.createElement(\"div\");\n\t\tdivBtn.setAttribute(\"class\",\"input-group-prepend\");\n\t\tvar botonRemoverD = document.createElement(\"button\");\n\t\tbotonRemoverD.setAttribute(\"type\",\"button\");\n\t\tbotonRemoverD.setAttribute(\"class\",\"btn btn-sm btn-outline-secondary\");\n\t\tbotonRemoverD.appendChild(document.createTextNode(\"Remover\"));\n\t\t//añade el evento al hacer click al boton de remover\n\t\tbotonRemoverD.addEventListener(\"click\",function(){\n\t\t\tvar input = document.forms[\"addProduction\"][\"director\"];\n\t\t\t\t//Quita el ultimo elemento del array\n\t\t\t\tarrayDir.pop();\n\t\t\t\tinput.value = arrayDir.toString();\n\t\t\t\t//muestra la tabla\n\t\t\t\tdocument.getElementById(\"divTabla\").style.display = \"block\";\n\n\t\t});\n\t\tvar inputDirector = document.createElement(\"input\");\n\t\tinputDirector.setAttribute(\"class\",\"form-control \");\n\t\tinputDirector.setAttribute(\"type\",\"text\");\n\t\tinputDirector.setAttribute(\"id\",\"director\");\n\t\tinputDirector.readOnly = true;\n\t\tvar malDirector = document.createElement(\"small\");\n\t\tmalDirector.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalDirector.setAttribute(\"id\",\"directorMal\");\n\t\tvar divTablaD = document.createElement(\"div\");\n\t\tdivTablaD.setAttribute(\"id\",\"divTabla\");\n\t\tvar buscadorD = document.createElement(\"input\");\n\t\tbuscadorD.setAttribute(\"class\",\"form-control my-3\");\n\t\tbuscadorD.setAttribute(\"type\",\"text\");\n\t\tbuscadorD.setAttribute(\"id\",\"buscador\");\n\t\tbuscadorD.setAttribute(\"placeholder\",\"Buscar...\");\n\t\t//SE CREA LA TABLA DE LOS DIRECTORES\n\t\tvar tablaD = document.createElement(\"table\");\n\t\ttablaD.setAttribute(\"class\",\"table table-bordered\");\n\t\ttablaD.setAttribute(\"name\",\"tablaDirector\");\n\t\ttablaD.setAttribute(\"id\",\"tablaDirector\");\n\t\tvar theadD = document.createElement(\"thead\");\n\t\tvar trD = document.createElement(\"tr\");\n\t\tvar thVacioD = document.createElement(\"th\");\n\t\tvar ocultarD = document.createElement(\"button\");\n\t\tocultarD.setAttribute(\"type\",\"button\");\n\t\tocultarD.setAttribute(\"class\",\"btn btn-secondary\");\n\t\tocultarD.appendChild(document.createTextNode(\"Mostrar/Ocultar\"));\n\t\tocultarD.addEventListener(\"click\", function(){\n\t\t\tvar cont = document.getElementById(\"tablaDirectores\");\n\t\t\tif(cont.style.display==\"table-row-group\"){\n\t\t\t\tcont.style.display = \"none\";\n\t\t\t}else{\n\t\t\t\tcont.style.display = \"table-row-group\";\n\t\t\t}\n\t\t});\n\t\tthVacioD.appendChild(ocultarD);\n\t\tvar thNombreD = document.createElement(\"th\");\n\t\tthNombreD.appendChild(document.createTextNode(\"Nombre completo\"));\n\t\tvar tbodyD = document.createElement(\"tbody\");\n\t\ttbodyD.setAttribute(\"id\",\"tablaDirectores\");\n\t\t//Abre la conexion con la base de datos\n\t\tvar request2 = indexedDB.open(nombreDB);\n\t\t//Si ha salido bien\n\t\trequest2.onsuccess = function(event) {\n\t\t\t//Asigna el resultado a la variable db, que tiene la base de datos \n\t\t\tvar db2 = event.target.result; \n\t\t\tvar objectStore2 = db2.transaction([\"directores\"],\"readonly\").objectStore(\"directores\");\n\t\t\t//Abre un cursor para recorrer todos los objetos de la base de datos \n\t\t\tobjectStore2.openCursor().onsuccess = function(event) {\n\t\t\t\tvar director = event.target.result;\n\t\t\t\tif (director) {\n\t\t\t\t\tvar trDirD = document.createElement(\"tr\");\n\t\t\t\t\tvar tdAddD = document.createElement(\"td\");\n\t\t\t\t\tvar addD = document.createElement(\"button\");\n\t\t\t\t\taddD.setAttribute(\"type\",\"button\");\n\t\t\t\t\taddD.setAttribute(\"class\",\"btn btn-danger\");\n\t\t\t\t\tif (director.value.lastName2 == null) {\n\t\t\t\t\t\tdirector.value.lastName2 = \" \";\n\t\t\t\t\t}\n\t\t\t\t\taddD.setAttribute(\"value\",director.value.name+\" \"+director.value.lastName1+\" \"+director.value.lastName2);\n\t\t\t\t\taddD.appendChild(document.createTextNode(\"Añadir\"));\n\t\t\t\t\tvar tdNombreD = document.createElement(\"td\");\n\t\t\t\t\ttdNombreD.appendChild(document.createTextNode(director.value.name+\" \"+director.value.lastName1+\" \"+director.value.lastName2));\n\t\t\t\t\ttdNombreD.setAttribute(\"class\",\"col-8\");\n\t\t\t\t\ttdAddD.appendChild(addD);\n\t\t\t\t\ttrDirD.appendChild(tdAddD);\n\t\t\t\t\ttrDirD.appendChild(tdNombreD);\n\t\t\t\t\ttbodyD.appendChild(trDirD);\n\t\t\t\t\t//Añade una funcion a cada boton de añadir\n\t\t\t\t\taddD.addEventListener(\"click\", function(){\n\t\t\t\t\t\tvar input = document.forms[\"addProduction\"][\"director\"];\n\t\t\t\t\t\t//Añade al array el nomnbre de boton\n\t\t\t\t\t\tarrayDir.push(this.value);\n\t\t\t\t\t\tinput.value = arrayDir.toString();\n\t\t\t\t\t\t//oculta la tabla\n\t\t\t\t\t\tdocument.getElementById(\"divTabla\").style.display = \"none\";\n\t\t\t\t\t});\n\t\t\t\t\t//Pasa al siguiente director\n\t\t\t\t\tdirector.continue();\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t\t//Añade los eventos de la tabla\n\t\t$(document).ready(function(){\n\t\t\t$(\"#buscador\").on(\"keyup\", function() {\n\t\t\t var value = $(this).val().toLowerCase();\n\t\t\t $(\"#tablaDirectores tr\").filter(function() {\n\t\t\t\t$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)\n\t\t\t });\n\t\t\t});\n\t\t});\n\t\tgrupo6.appendChild(label6);\n\t\tdivInputBtn.appendChild(divBtn);\n\t\tdivBtn.appendChild(botonRemoverD);\n\t\tdivInputBtn.appendChild(inputDirector);\n\t\tdivInputBtn.appendChild(malDirector);\n\t\tgrupo6.appendChild(divInputBtn);\n\t\tdivTablaD.appendChild(buscadorD);\n\t\tdivTablaD.appendChild(tablaD);\n\t\tgrupo6.appendChild(divTablaD);\n\t\ttablaD.appendChild(theadD);\n\t\ttablaD.appendChild(tbodyD);\n\t\ttheadD.appendChild(trD);\n\t\ttrD.appendChild(thVacioD);\n\t\ttrD.appendChild(thNombreD);\n\t\tdivMovie.appendChild(grupo6);\n\t\tformulario.appendChild(divMovie);\n\t\t//DIV QUE APARECE SI EN EL SELECT SE PONE SERIE\n\t\tvar divSerie = document.createElement(\"div\");\n\t\tdivSerie.setAttribute(\"class\",\"form-group\");\n\t\tdivSerie.setAttribute(\"id\",\"divSerie\");\n\t\t//TEMPORADA DE LA PRODUCCION SERIE\n\t\tvar labelSeason = document.createElement(\"label\");\n\t\tlabelSeason.setAttribute(\"for\",\"recurso\");\n\t\tlabelSeason.appendChild(document.createTextNode(\"Temporada de la produccion\"));\n\t\tvar selectSeason = document.createElement(\"select\");\n\t\tselectSeason.setAttribute(\"class\",\"form-control\");\n\t\tselectSeason.setAttribute(\"id\",\"temporada\");\n\t\tvar optionSeason = document.createElement(\"option\");\n\t\toptionSeason.setAttribute(\"value\",\"0\");\n\t\toptionSeason.appendChild(document.createTextNode(\"-- SIN TEMPORADA --\"));\n\t\tselectSeason.appendChild(optionSeason);\t\n\t\tfor (let index = 0; index < arraySeason.length; index++) {\n\t\t\toptionSeason = document.createElement(\"option\");\n\t\t\toptionSeason.setAttribute(\"value\",arraySeason[index].title);\n\t\t\toptionSeason.appendChild(document.createTextNode(arraySeason[index].title));\n\t\t\tselectSeason.appendChild(optionSeason);\t\n\t\t}//Fin del for\t\n\t\t//Se añaden como hijos al formulario\n\t\tdivSerie.appendChild(labelSeason);\n\t\tdivSerie.appendChild(selectSeason);\n\t\tformulario.appendChild(divSerie);\n\t\t//REPARTO DE LA PRODUCCION\n\t\t//SE CREA EL BUSCADOR \n\t\tvar grupo7 = document.createElement(\"div\");\n\t\tgrupo7.setAttribute(\"class\",\"form-group\");\n\t\tvar label7 = document.createElement(\"label\");\n\t\tlabel7.setAttribute(\"for\",\"reparto\");\n\t\tlabel7.appendChild(document.createTextNode(\"Reparto de la produccion\"));\n\t\t//Div vacio en el que se añaden los actores en los que se pulsa\n\t\tvar divReparto = document.createElement(\"div\");\n\t\tdivReparto.setAttribute(\"class\",\"form-group\");\n\t\tdivReparto.setAttribute(\"id\",\"divReparto\");\n\t\tvar buscadorReparto = document.createElement(\"input\");\n\t\tbuscadorReparto.setAttribute(\"class\",\"form-control my-3\");\n\t\tbuscadorReparto.setAttribute(\"type\",\"text\");\n\t\tbuscadorReparto.setAttribute(\"id\",\"buscadorReparto\");\n\t\tbuscadorReparto.setAttribute(\"placeholder\",\"Buscar...\");\n\t\t//SE CREA LA TABLA DE LOS ACTORES\n\t\tvar tablaR = document.createElement(\"table\");\n\t\ttablaR.setAttribute(\"class\",\"table table-bordered\");\n\t\ttablaR.setAttribute(\"name\",\"reparto\");\n\t\ttablaR.setAttribute(\"id\",\"reparto\");\n\t\tvar theadR = document.createElement(\"thead\");\n\t\tvar trR = document.createElement(\"tr\");\n\t\tvar thVacioR = document.createElement(\"th\");\n\t\tvar ocultarR = document.createElement(\"button\");\n\t\tocultarR.setAttribute(\"type\",\"button\");\n\t\tocultarR.setAttribute(\"class\",\"btn btn-secondary\");\n\t\tocultarR.appendChild(document.createTextNode(\"Mostrar/Ocultar\"));\n\t\tocultarR.addEventListener(\"click\", function(){\n\t\t\tvar cont = document.getElementById(\"tablaReparto\");\n\t\t\tif(cont.style.display==\"table-row-group\"){\n\t\t\t\tcont.style.display = \"none\";\n\t\t\t}else{\n\t\t\t\tcont.style.display = \"table-row-group\";\n\t\t\t}\n\t\t});\n\t\tthVacioR.appendChild(ocultarR);\n\t\tvar thNombreR = document.createElement(\"th\");\n\t\tthNombreR.appendChild(document.createTextNode(\"Nombre\"));\n\t\tvar tbodyR = document.createElement(\"tbody\");\n\t\ttbodyR.setAttribute(\"id\",\"tablaReparto\");\n\t\t//Contador para llevar la cuenta de los divs creados\n\t\tvar contador = 0;\n\t\t//Abre la conexion con la base de datos\n\t\tvar request3 = indexedDB.open(nombreDB);\n\t\t//Si ha salido bien\n\t\trequest3.onsuccess = function(event) {\n\t\t\t//Asigna el resultado a la variable db, que tiene la base de datos \n\t\t\tvar db3 = event.target.result; \n\t\t\tvar objectStore3 = db3.transaction([\"actores\"],\"readonly\").objectStore(\"actores\");\n\t\t\t//Abre un cursor para recorrer todos los objetos de la base de datos \n\t\t\tobjectStore3.openCursor().onsuccess = function(event) {\n\t\t\t\tvar actor = event.target.result;\n\t\t\t\tif (actor) {\n\t\t\t\t\tvar trCatR = document.createElement(\"tr\");\n\t\t\t\t\tvar tdAddR = document.createElement(\"td\");\n\t\t\t\t\tvar addR = document.createElement(\"button\");\n\t\t\t\t\taddR.setAttribute(\"type\",\"button\");\n\t\t\t\t\taddR.setAttribute(\"class\",\"btn btn-danger\");\n\t\t\t\t\tif (actor.value.lastName2 == null) {\n\t\t\t\t\t\tactor.value.lastName2 = \" \";\n\t\t\t\t\t}\n\t\t\t\t\taddR.setAttribute(\"value\",actor.value.name+\" \"+actor.value.lastName1+\" \"+actor.value.lastName2);\n\t\t\t\t\taddR.appendChild(document.createTextNode(\"Añadir\"));\n\t\t\t\t\tvar tdActorR = document.createElement(\"td\");\n\t\t\t\t\ttdActorR.appendChild(document.createTextNode(actor.value.name+\" \"+actor.value.lastName1+\" \"+actor.value.lastName2));\n\t\t\t\t\ttdActorR.setAttribute(\"class\",\"col-8\");\n\t\t\t\t\ttdAddR.appendChild(addR);\n\t\t\t\t\ttrCatR.appendChild(tdAddR);\n\t\t\t\t\ttrCatR.appendChild(tdActorR);\n\t\t\t\t\ttbodyR.appendChild(trCatR);\n\t\t\t\t\t//Añade una funcion a cada boton de añadir\n\t\t\t\t\taddR.addEventListener(\"click\", function(){\n\t\t\t\t\t\t//Añade al array el nombre de boton\n\t\t\t\t\t\tarrayReparto.push(this.value);\n\t\t\t\t\t\t//llama a la funcion de añadir divActor\n\t\t\t\t\t\taddReparto(this.value,contador);\n\t\t\t\t\t\tcontador++;\n\t\t\t\t\t});\n\n\t\t\t\t\t//Pasa al siguiente actor\n\t\t\t\t\tactor.continue();\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t\t//Añade eventos al hacer click sobre los botones del formulario creado\n\t\t$(document).ready(function(){\n\t\t\t$(\"#buscadorReparto\").on(\"keyup\", function() {\n\t\t\tvar value = $(this).val().toLowerCase();\n\t\t\t$(\"#tablaReparto tr\").filter(function() {\n\t\t\t\t$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)\n\t\t\t});\n\t\t\t});\n\t\t});\n\t\tgrupo7.appendChild(label7);\n\t\tgrupo7.appendChild(divReparto);\n\t\tgrupo7.appendChild(buscadorReparto);\n\t\tgrupo7.appendChild(tablaR);\n\t\ttablaR.appendChild(theadR);\n\t\ttablaR.appendChild(tbodyR);\n\t\ttheadR.appendChild(trR);\n\t\ttrR.appendChild(thVacioR);\n\t\ttrR.appendChild(thNombreR);\n\t\tformulario.appendChild(grupo7);\n\t\t//CATEGORIAS DE LA PRODUCCION\n\t\t//SE CREA EL BUSCADOR \n\t\tvar grupo8 = document.createElement(\"div\");\n\t\tgrupo8.setAttribute(\"class\",\"form-group\");\n\t\tvar label8 = document.createElement(\"label\");\n\t\tlabel8.setAttribute(\"for\",\"categorias\");\n\t\tlabel8.appendChild(document.createTextNode(\"Asignar categorias a la produccion\"));\n\t\tvar divInputBtn = document.createElement(\"div\");\n\t\tdivInputBtn.setAttribute(\"class\",\"input-group\");\n\t\tvar divBtn = document.createElement(\"div\");\n\t\tdivBtn.setAttribute(\"class\",\"input-group-prepend\");\n\t\tvar botonRemoverC = document.createElement(\"button\");\n\t\tbotonRemoverC.setAttribute(\"type\",\"button\");\n\t\tbotonRemoverC.setAttribute(\"class\",\"btn btn-sm btn-outline-secondary\");\n\t\tbotonRemoverC.appendChild(document.createTextNode(\"Remover\"));\n\t\t//añade el evento al hacer click al boton de remover\n\t\tbotonRemoverC.addEventListener(\"click\",function(){\n\t\t\tvar input = document.forms[\"addProduction\"][\"categorias\"];\n\t\t\t\t//Quita el ultimo elemento del array\n\t\t\t\tarrayCategorias.pop();\n\t\t\t\tinput.value = arrayCategorias.toString();\n\n\t\t});\n\t\tvar cat = document.createElement(\"input\");\n\t\tcat.setAttribute(\"class\",\"form-control \");\n\t\tcat.setAttribute(\"type\",\"text\");\n\t\tcat.setAttribute(\"id\",\"categorias\");\n\t\tcat.readOnly = true;\n\t\tvar malCat = document.createElement(\"small\");\n\t\tmalCat.setAttribute(\"class\",\"form-text text-muted\");\n\t\tmalCat.setAttribute(\"id\",\"catMal\");\n\t\tvar buscadorC = document.createElement(\"input\");\n\t\tbuscadorC.setAttribute(\"class\",\"form-control my-3\");\n\t\tbuscadorC.setAttribute(\"type\",\"text\");\n\t\tbuscadorC.setAttribute(\"id\",\"buscadorCategorias\");\n\t\tbuscadorC.setAttribute(\"placeholder\",\"Buscar...\");\n\t\t//SE CREA LA TABLA DE LAS CATEGORIAS\n\t\tvar tablaC = document.createElement(\"table\");\n\t\ttablaC.setAttribute(\"class\",\"table table-bordered\");\n\t\ttablaC.setAttribute(\"name\",\"categoria\");\n\t\ttablaC.setAttribute(\"id\",\"categoria\");\n\t\tvar theadC = document.createElement(\"thead\");\n\t\tvar trC = document.createElement(\"tr\");\n\t\tvar thVacioC = document.createElement(\"th\");\n\t\tvar ocultarC = document.createElement(\"button\");\n\t\tocultarC.setAttribute(\"type\",\"button\");\n\t\tocultarC.setAttribute(\"class\",\"btn btn-secondary\");\n\t\tocultarC.appendChild(document.createTextNode(\"Mostrar/Ocultar\"));\n\t\tocultarC.addEventListener(\"click\", function(){\n\t\t\tvar cont = document.getElementById(\"tablaCategorias\");\n\t\t\tif(cont.style.display==\"table-row-group\"){\n\t\t\t\tcont.style.display = \"none\";\n\t\t\t}else{\n\t\t\t\tcont.style.display = \"table-row-group\";\n\t\t\t}\n\t\t});\n\t\tthVacioC.appendChild(ocultarC);\n\t\tvar thNombreC = document.createElement(\"th\");\n\t\tthNombreC.appendChild(document.createTextNode(\"Nombre\"));\n\t\tvar tbodyC = document.createElement(\"tbody\");\n\t\ttbodyC.setAttribute(\"id\",\"tablaCategorias\");\n\t\t//Abre la conexion con la base de datos\n\t\tvar request4 = indexedDB.open(nombreDB);\n\t\t//Si ha salido bien\n\t\trequest4.onsuccess = function(event) {\n\t\t\t//Asigna el resultado a la variable db, que tiene la base de datos \n\t\t\tvar db4 = event.target.result; \n\t\t\tvar objectStore4 = db4.transaction([\"categorias\"],\"readonly\").objectStore(\"categorias\");\n\t\t\t//Abre un cursor para recorrer todos los objetos de la base de datos \n\t\t\tobjectStore4.openCursor().onsuccess = function(event) {\n\t\t\t\tvar categoria = event.target.result;\n\t\t\t\tif (categoria) {\n\t\t\t\t\tvar trCatC = document.createElement(\"tr\");\n\t\t\t\t\tvar tdAddC = document.createElement(\"td\");\n\t\t\t\t\tvar addC = document.createElement(\"button\");\n\t\t\t\t\taddC.setAttribute(\"type\",\"button\");\n\t\t\t\t\taddC.setAttribute(\"class\",\"btn btn-danger\");\n\t\t\t\t\taddC.setAttribute(\"value\",categoria.value.name);\n\t\t\t\t\taddC.appendChild(document.createTextNode(\"Añadir\"));\n\t\t\t\t\tvar tdTituloC = document.createElement(\"td\");\n\t\t\t\t\ttdTituloC.appendChild(document.createTextNode(categoria.value.name));\n\t\t\t\t\ttdTituloC.setAttribute(\"class\",\"col-8\");\n\t\t\t\t\ttdAddC.appendChild(addC);\n\t\t\t\t\ttrCatC.appendChild(tdAddC);\n\t\t\t\t\ttrCatC.appendChild(tdTituloC);\n\t\t\t\t\ttbodyC.appendChild(trCatC);\n\t\t\t\t\t//Añade una funcion a cada boton de añadir\n\t\t\t\t\taddC.addEventListener(\"click\", function(){\n\t\t\t\t\t\tvar input = document.forms[\"addProduction\"][\"categorias\"];\n\t\t\t\t\t\t//Añade al array el nomnbre de boton\n\t\t\t\t\t\tarrayCategorias.push(this.value);\n\t\t\t\t\t\tinput.value = arrayCategorias.toString();\n\t\t\t\t\t});\n\n\t\t\t\t\t//Pasa al siguiente categoria\n\t\t\t\t\tcategoria.continue();\n\t\t\t\t}\n\t\t\t};\n\t\t};\n\t\t//Añade eventos al hacer click sobre los botones del formulario creado\n\t\t$(document).ready(function(){\n\t\t\t$(\"#buscadorCategorias\").on(\"keyup\", function() {\n\t\t\t var value = $(this).val().toLowerCase();\n\t\t\t $(\"#tablaCategorias tr\").filter(function() {\n\t\t\t\t$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)\n\t\t\t });\n\t\t\t});\n\t\t});\n\t\tgrupo8.appendChild(label8);\n\t\tdivInputBtn.appendChild(divBtn);\n\t\tdivBtn.appendChild(botonRemoverC);\n\t\tdivInputBtn.appendChild(cat);\n\t\tdivInputBtn.appendChild(malCat);\n\t\tgrupo8.appendChild(divInputBtn);\n\t\tgrupo8.appendChild(buscadorC);\n\t\tgrupo8.appendChild(tablaC);\n\t\ttablaC.appendChild(theadC);\n\t\ttablaC.appendChild(tbodyC);\n\t\ttheadC.appendChild(trC);\n\t\ttrC.appendChild(thVacioC);\n\t\ttrC.appendChild(thNombreC);\n\t\tformulario.appendChild(grupo8);\n\t\t//BOTONES DEL FORMULARIO\n\t\tvar grupoBtn = document.createElement(\"div\");\n\t\tgrupoBtn.setAttribute(\"class\",\"form-group d-flex justify-content-around\");\n\t\tvar aceptar = document.createElement(\"button\");\n\t\taceptar.setAttribute(\"type\",\"submit\");\n\t\taceptar.setAttribute(\"class\",\"btn btn-primary \");\n\t\taceptar.appendChild(document.createTextNode(\"Guardar\"));\n\t\tvar cancelar = document.createElement(\"button\");\n\t\tcancelar.setAttribute(\"type\",\"button\");\n\t\tcancelar.setAttribute(\"class\",\"btn btn-primary\");\n\t\tcancelar.appendChild(document.createTextNode(\"Cancelar\"));\n\t\t//Añade eventos al hacer click sobre los botones del formulario creado\n\t\tcancelar.addEventListener(\"click\", showHomePage);\n\t\tcancelar.addEventListener(\"click\", function(){\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontenidoCentral.setAttribute(\"class\",\"d-block\");\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontenidoFormularios.setAttribute(\"class\",\"d-none\");\n\t\t\t\t\t\t\t\t\t\t\t\t\t//Se limpia los arrays array\n\t\t\t\t\t\t\t\t\t\t\t\t\twhile(arrayProducciones.length != 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tarrayProducciones.shift();\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\twhile(arrayDir.length != 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tarrayDir.shift();\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\twhile(arrayCategorias.length != 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tarrayCategorias.shift();\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\twhile(arrayReparto.length != 0){\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tarrayReparto.shift();\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t//Se añade al formulario como hijos\n\t\tgrupoBtn.appendChild(aceptar);\n\t\tgrupoBtn.appendChild(cancelar);\n\t\tformulario.appendChild(grupoBtn);\n\t\t/* FIN DEL FORMULARIO DE AÑADIR PRODUCCION */\n\t}else if (tipo == \"delete\") {\n\t\tvar formulario = document.createElement(\"form\");\n\t\tformulario.setAttribute(\"name\",\"deleteProduction\");\n\t\tformulario.setAttribute(\"action\",\"\");\n\t\tformulario.setAttribute(\"onsubmit\",\"return false\");\n\t\tformulario.setAttribute(\"method\",\"post\");\n\t\tvar leyenda = document.createElement(\"legend\");\n\t\tvar grupo = document.createElement(\"div\");\n\t\tgrupo.setAttribute(\"class\",\"form-group\");\n\t\tleyenda.appendChild(document.createTextNode(\"Eliminar produccion\"));\n\t\t//SE CREA EL BUSCADOR \n\t\tvar buscador = document.createElement(\"input\");\n\t\tbuscador.setAttribute(\"class\",\"form-control mb-3\");\n\t\tbuscador.setAttribute(\"type\",\"text\");\n\t\tbuscador.setAttribute(\"id\",\"buscador\");\n\t\tbuscador.setAttribute(\"placeholder\",\"Buscar...\");\n\t\t//SE CREA LA TABLA DE LAS PRODUCCIONES\n\t\tvar tabla = document.createElement(\"table\");\n\t\ttabla.setAttribute(\"class\",\"table table-bordered\");\n\t\ttabla.setAttribute(\"name\",\"produccion\");\n\t\ttabla.setAttribute(\"id\",\"produccion\");\n\t\tvar thead = document.createElement(\"thead\");\n\t\tvar tr = document.createElement(\"tr\");\n\t\tvar thVacio = document.createElement(\"th\");\n\t\tvar ocultar = document.createElement(\"button\");\n\t\tocultar.setAttribute(\"type\",\"button\");\n\t\tocultar.setAttribute(\"class\",\"btn btn-secondary\");\n\t\tocultar.appendChild(document.createTextNode(\"Mostrar/Ocultar\"));\n\t\tocultar.addEventListener(\"click\", function(){\n\t\t\tvar cont = document.getElementById(\"tablaProducciones\");\n\t\t\tif(cont.style.display==\"table-row-group\"){\n\t\t\t\tcont.style.display = \"none\";\n\t\t\t}else{\n\t\t\t\tcont.style.display = \"table-row-group\";\n\t\t\t}\n\t\t});\n\t\tthVacio.appendChild(ocultar);\n\t\tvar thTitulo = document.createElement(\"th\");\n\t\tthTitulo.appendChild(document.createTextNode(\"Titulo\"));\n\t\tvar thTipo = document.createElement(\"th\");\n\t\tthTipo.appendChild(document.createTextNode(\"Tipo\"));\n\t\tvar tbody = document.createElement(\"tbody\");\n\t\ttbody.setAttribute(\"id\",\"tablaProducciones\");\n\t\t//Abre la conexion con la base de datos\n\t\tvar request = indexedDB.open(nombreDB);\n\t\t//Si ha salido bien\n\t\trequest.onsuccess = function(event) {\n\t\t\t//Asigna el resultado a la variable db, que tiene la base de datos \n\t\t\tvar db = event.target.result; \n\t\t\tvar objectStore = db.transaction([\"producciones\"],\"readonly\").objectStore(\"producciones\");\n\t\t\t//Abre un cursor para recorrer todos los objetos de la base de datos \n\t\t\tobjectStore.openCursor().onsuccess = function(event) {\n\t\t\t\tvar produccion = event.target.result;\n\t\t\t\t//Si el cursor devuelve un valor \n\t\t\t\tif (produccion) {\n\t\t\t\t\tvar trPro = document.createElement(\"tr\");\n\t\t\t\t\tvar tdEliminar = document.createElement(\"td\");\n\t\t\t\t\tvar eliminar = document.createElement(\"button\");\n\t\t\t\t\teliminar.setAttribute(\"type\",\"button\");\n\t\t\t\t\teliminar.setAttribute(\"class\",\"btn btn-danger\");\n\t\t\t\t\teliminar.setAttribute(\"value\",produccion.value.title);\n\t\t\t\t\teliminar.appendChild(document.createTextNode(\"Eliminar\"));\n\t\t\t\t\teliminar.addEventListener(\"click\", deleteProduction);\n\t\t\t\t\tvar tdTitulo = document.createElement(\"td\");\n\t\t\t\t\ttdTitulo.appendChild(document.createTextNode(produccion.value.title));\n\t\t\t\t\tvar tdTipo = document.createElement(\"td\");\n\t\t\t\t\tvar nomTipo = \"\";\n\t\t\t\t\tif (produccion.value.tipo == \"Movie\") {\n\t\t\t\t\t\tnomTipo = \"Pelicula\";\n\t\t\t\t\t}else{\n\t\t\t\t\t\tnomTipo = \"Serie\";\n\t\t\t\t\t}\n\t\t\t\t\ttdTipo.appendChild(document.createTextNode(nomTipo));\n\t\t\t\t\ttdEliminar.appendChild(eliminar);\n\t\t\t\t\ttrPro.appendChild(tdEliminar);\n\t\t\t\t\ttrPro.appendChild(tdTitulo);\n\t\t\t\t\ttrPro.appendChild(tdTipo);\n\t\t\t\t\ttbody.appendChild(trPro);\n\t\t\t\t\t//Pasa a la siguiente produccion\n\t\t\t\t\tproduccion.continue();\n\t\t\t\t}//Fin del if\n\t\t\t};//Fin de objectStore.openCursor().onsuccess\n\t\t};//Fin de request.onsuccess\n\t\tvar grupoBtn = document.createElement(\"div\");\n\t\tgrupoBtn.setAttribute(\"class\",\"form-group d-flex justify-content-around\");\n\t\tvar cancelar = document.createElement(\"button\");\n\t\tcancelar.setAttribute(\"type\",\"button\");\n\t\tcancelar.setAttribute(\"class\",\"btn btn-primary\");\n\t\tcancelar.appendChild(document.createTextNode(\"Cancelar\"));\n\t\t//Añade eventos al hacer click sobre los botones del formulario creado y el buscador\n\t\t$(document).ready(function(){\n\t\t\t$(\"#buscador\").on(\"keyup\", function() {\n\t\t\t var value = $(this).val().toLowerCase();\n\t\t\t $(\"#tablaProducciones tr\").filter(function() {\n\t\t\t\t$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)\n\t\t\t });\n\t\t\t});\n\t\t});\n\t\tcancelar.addEventListener(\"click\", showHomePage);\n\t\tcancelar.addEventListener(\"click\", function(){\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontenidoCentral.setAttribute(\"class\",\"d-block\");\n\t\t\t\t\t\t\t\t\t\t\t\t\tcontenidoFormularios.setAttribute(\"class\",\"d-none\");\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\n\t\t//se crea el formulario de borrado\n\t\tformulario.appendChild(leyenda);\n\t\tgrupo.appendChild(buscador);\n\t\tgrupo.appendChild(tabla);\n\t\tformulario.appendChild(grupo);\n\t\ttabla.appendChild(thead);\n\t\ttabla.appendChild(tbody);\n\t\tthead.appendChild(tr);\n\t\ttr.appendChild(thVacio);\n\t\ttr.appendChild(thTitulo);\n\t\ttr.appendChild(thTipo);\n\t\tgrupoBtn.appendChild(cancelar);\n\t\tformulario.appendChild(grupoBtn);\n\t\tcontenidoFormularios.appendChild(formulario);\n\t\t/* FIN DEL FORMULARIO DE ELIMINAR PRODUCCION */\n\t}//Fin de los if\n}//Fin de formProducciones", "function AgregarUsuario(admin)\n{ \n var form;\n form='<div class=\"EntraDatos\">';\n form+='<table>';\n form+='<thead>';\n form+='<tr><th colspan=\"2\">'; \n form+='Nuevo Usuario'; \n form+='</th></tr>'; \n form+='</thead>'; \n form+='<tbody>';\n form+='<tr>';\n form+='<td width=\"50%\">'; \n form+='<label>Cédula de Identidad:</label>';\n form+='<input type=\"text\" id=\"CI\" class=\"Editable\" tabindex=\"1000\" title=\"Introduzca el Número de Cédula\"/>';\n form+='<input type=\"button\" onclick=\"javascript:BuscarUsuario()\" tabindex=\"1001\" title=\"Buscar\" value=\"Buscar\"/>';\n form+='</td>';\n form+='<td>';\n form+='<label>Correo Electrónico:</label>';\n form+='<input type=\"text\" class=\"Campos\" id=\"Correo\" title=\"Correo Electrónico\" readonly=\"readonly\"/>';\n form+='</td>';\n form+='</tr>';\n form+='<tr>';\n form+='<td>';\n form+='<label>Nombre:</label>';\n form+='<input type=\"text\" class=\"Campos\" id=\"Nombre\" title=\"Nombre\" readonly=\"readonly\"/>';\n form+='</td>';\n form+='<td>';\n form+='<label>Apellido:</label>';\n form+='<input type=\"text\" class=\"Campos\" id=\"Apellido\" title=\"Apellido\" readonly=\"readonly\"/>';\n form+='</td>';\n form+='</tr>'; \n form+='<tr>';\n form+='<td colspan=\"2\">';\n form+='<input type=\"hidden\" id=\"id_unidad\" />'; \n form+='<label>Unidad Administrativa:</label>';\n form+='<center><input type=\"text\" class=\"Campos Editable\" id=\"Unidad\" title=\"Unidad Administrativa\" tabindex=\"1002\"/></center>';\n form+='</td>'; \n form+='</tr>';\n form+='<tr>';\n form+='<td>';\n form+='<label>Nivel de Usuario:</label>';\n form+='<select class=\"Campos Editable\" id=\"Nivel\" title=\"Seleccione el Nivel del Usuario\" tabindex=\"1003\">';\n form+='<option selected=\"selected\" value=\"0\">[Seleccione]</option>';\n form+='</select>';\n form+='</td>';\n form+='<td>';\n if (admin==1)\n {\n form+='<label>Rol de Usuario:</label>';\n form+='<div class=\"ToggleBoton\" onclick=\"javascript:ToggleBotonAdmin()\" title=\"Haga clic para cambiar\">';\n form+='<img id=\"imgAdmin\" src=\"imagenes/user16.png\"/>';\n form+='</div>';\n form+='<span id=\"spanAdmin\">&nbsp;Usuario Normal</span>'; \n }\n form+='<input type=\"hidden\" id=\"hideAdmin\" value=\"f\" />'; \n form+='</td>';\n form+='</tr>'; \n form+='</tbody>';\n \n form+='<tfoot>';\n form+='<tr><td colspan=\"2\">';\n form+='<div class=\"BotonIco\" onclick=\"javascript:GuardarUsuario()\" title=\"Guardar Usuario\">';\n form+='<img src=\"imagenes/guardar32.png\"/>&nbsp;'; \n form+='Guardar';\n form+= '</div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';\n form+='<div class=\"BotonIco\" onclick=\"javascript:CancelarModal()\" title=\"Cancelar\">';\n form+='<img src=\"imagenes/cancel.png\"/>&nbsp;';\n form+='Cancelar';\n form+= '</div>';\n form+='</td></tr>';\n form+='</tfoot>';\n form+='</table>'; \n form+='</div>';\n $('#VentanaModal').html(form);\n $('#VentanaModal').show(); \n $('#CI').focus();\n \n selector_autocompletar(); \n}", "function agregaformEve(datos){\n //console.log(\"datos: \"+datos);\n d=datos.split('||');\n \n //document.getElementById(\"codigo_af_aceptar1\").value=d[0];\n $('#idEveE').val(d[0]);\n $('#nombreEveE').val(d[1]);\n $('#personalEveE').val(d[2]);\n}", "function inicializarCampos() {\r\n document.querySelector('#tipo').value = vehiculos[0].tipo;\r\n document.querySelector('#marca').value = vehiculos[0].marca;\r\n document.querySelector('#modelo').value = vehiculos[0].modelo;\r\n document.querySelector('#patente').value = vehiculos[0].patente;\r\n document.querySelector('#anio').value = vehiculos[0].anio;\r\n document.querySelector('#precio').value = vehiculos[0].precio;\r\n if (document.querySelector('#tipo').value == \"auto\") {\r\n document.querySelector('#capacidadBaul').value = vehiculos[0].capacidadBaul;\r\n }\r\n else if (document.querySelector('#tipo').value == \"camioneta\") {\r\n document.querySelector('#capacidadCarga').value = vehiculos[0].capacidadCarga;\r\n }\r\n}", "function limpiar_campos(){\r\n\r\n\t//NOMBRE\r\n\tdocument.getElementById(\"txt_nombre\").value = \"\";\r\n\t$(\"#div_nombre\").attr(\"class\",\"form-group\");\r\n\t$(\"#span_nombre\").hide();\r\n\t\r\n\t//EMAIL\r\n\tdocument.getElementById(\"txt_email\").value = \"\";\r\n\t$(\"#div_email\").attr(\"class\",\"form-group\");\r\n\t$(\"#span_email\").hide();\r\n\r\n\t//TELEFONO\r\n\tdocument.getElementById(\"txt_telefono\").value = \"\";\r\n\t$(\"#div_telefono\").attr(\"class\",\"form-group\");\r\n\t$(\"#span_telefono\").hide();\r\n\r\n //TIENE HIJOS?\r\n tiene_hijos[0].checked=true;\r\n\r\n //ESTADO CIVIL\r\n document.getElementById(\"cbx_estadocivil\").value=\"SOLTERO\";\r\n\r\n //INTERESES\r\n document.getElementById(\"cbx_libros\").checked =false;\r\n document.getElementById(\"cbx_musica\").checked =false;\r\n document.getElementById(\"cbx_deportes\").checked =false;\r\n document.getElementById(\"cbx_otros\").checked =false;\r\n $(\"#div_intereses\").attr(\"class\",\"form-group\");\r\n $(\"#span_intereses\").hide();;\r\n}", "function viderFormulaire() {\n //Enlever les messages à l'écran\n $('#manitouAlertes').html('').hide();\n $('.manitouHighlight').removeClass('manitouHighlight');\n $('.manitouErreur').remove();\n\n //Vider les champs\n $('#manitouSimplicite input:not([type=submit],[type=checkbox]), #manitouSimplicite select').val('');\n $('#manitouNomFichier').html('');\n\n //Décocher les cases à cocher\n $('#manitouSimplicite input[type=checkbox]').prop('checked', false);\n\n //Remettre des valeurs par défaut\n $('#langueCorrespondance').val(langue);\n $('#manitouPreferences tbody tr').remove();\n ajouterPreference();\n $('#manitouLieuxPreferes tbody tr').remove();\n ajouterLieuTravail();\n\n fichierSelectionne = false;\n }", "function limpiarFormulario(frm) {\n frm.reset();\n document.getElementById(\"btnEliminar\").classList.add(\"hidden\");\n document.getElementById(\"btnSubmit\").textContent = \"Guardar Automovil\";\n document\n .getElementById(\"btnSubmit\")\n .classList.replace(\"btn-secondary\", \"btn-primary\");\n\n document.forms[0].id.value = \"\";\n}" ]
[ "0.68715876", "0.68280387", "0.67812854", "0.675915", "0.67059207", "0.6691888", "0.6675431", "0.66635", "0.66505617", "0.6627156", "0.6611526", "0.6602542", "0.66023296", "0.6599742", "0.65895236", "0.65596557", "0.65596557", "0.6550468", "0.65349567", "0.65242827", "0.6523904", "0.65100473", "0.64974344", "0.64876866", "0.6485508", "0.6482174", "0.6479336", "0.6476887", "0.6473828", "0.6466853", "0.6445485", "0.64444333", "0.6435395", "0.643501", "0.64259267", "0.6416057", "0.6411412", "0.64090526", "0.6404622", "0.639817", "0.63961464", "0.6389344", "0.63855565", "0.63631463", "0.6346133", "0.63434976", "0.63419574", "0.6337311", "0.6334603", "0.63137734", "0.6313425", "0.6309528", "0.63082826", "0.6306291", "0.6305472", "0.62952006", "0.62915766", "0.6285293", "0.6279047", "0.6274278", "0.6274212", "0.6270584", "0.6267355", "0.62668705", "0.62668115", "0.6263842", "0.62579495", "0.6254667", "0.6249833", "0.624309", "0.62386316", "0.6237822", "0.6237287", "0.6236661", "0.6231246", "0.6229203", "0.6214081", "0.6213913", "0.62132746", "0.6212305", "0.6212284", "0.6209955", "0.62094957", "0.6207816", "0.6205495", "0.6200353", "0.61999196", "0.61962116", "0.6181635", "0.61802346", "0.6173188", "0.61718464", "0.61682856", "0.6166785", "0.61612463", "0.61578923", "0.61564296", "0.6151564", "0.6146618", "0.61458886", "0.6144523" ]
0.0
-1
TODO add custom fields for profiler messages
function Profiler(logger, name, level) { this.logger = logger; this.name = name; this.times = 0; this.diff = 0; this.paused = true; this.level = level || 'debug'; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function _timeProfile(message) {\n if (config.show_performance)\n elapsed_time(message);\n}", "messages() {\n const messages = super.messages();\n messages[ACTIVE].push({\n level: INFO,\n code: \"hermit.scanning\",\n text: \"Scan Hermit QR code now.\",\n });\n return messages;\n }", "getStatistics() {\n return {\n averageRTTms: this.rpcProxy.getAverageRttMs(),\n sentMessages: this.id - INITIAL_ID,\n failedMessages: this.rpcProxy.errorCounter,\n };\n }", "function showProfileMessage(message, secondMessage = '') {\n console.log(message, this.name, secondMessage);\n}", "getReportFetchMessage() {\n if (this.state.loading) {\n return 'Fetching Testplan report...';\n } else if (this.state.error !== null){\n return `Error fetching Testplan report. (${this.state.error.message})`;\n } else {\n return 'Waiting to fetch Testplan report...';\n }\n }", "getUsageStats() {\n return `Buffer: ${bytes(this.recentBuffer.length)}, lrErrors: ${this.lrErrors}`;\n }", "displayInfo() {\n\t\t\tlet info = super.displayInfo() + ', разработчики: ' + this.getDevelopers() ;\n\t\t\tconsole.log( info );\n\t\t\treturn info\n\t\t\t}", "traceInfo(message, object) {\n if (this.traceLevel >= 1) {\n let stack = ` len(stack)=${this.stack.length} `;\n if (this.traceLevel >= 3) {\n stack = this.stack.map(n => n.v);\n }\n let registers = `(x:${this.x},y:${this.y})`;\n console.log(registers, stack, message, object);\n }\n }", "function statistics() {\n\t/*var time = Date.now() - startTime - pauseTime;\n\t\tvar seconds = (time / 1000 % 60).toFixed(2);\n\t\tvar minutes = ~~(time / 60000);\n\t\tstatsTime.innerHTML = (minutes < 10 ? '0' : '') + minutes +\n\t(seconds < 10 ? ':0' : ':') + seconds;*/\n}", "function genBasicCallInfo(call_id, total_time, segment_id) {\r\n return \"Call_id: \" + call_id \r\n + \"<br> total time: \" + total_time \r\n + \"<br> Segment: \" + segment_id;\r\n}", "getReport()\r\n\t{\r\n\t\tlet report = '';\r\n\r\n\t\tmembers.forEach( (member, duration) => s += member.username + '\\t\\t' + duration + ' seconds\\n' );\r\n\t\treturn report;\r\n\t}", "function Profiler({ metadata, phases, ...props }) {\n function reportProfile(\n id,\n phase,\n actualDuration,\n baseDuration,\n startTime,\n commitTime,\n interactions\n ) {\n if (!phases || phases.includes(phase)) {\n queue.push({\n metadata,\n id,\n phase,\n actualDuration,\n baseDuration,\n startTime,\n commitTime,\n interactions,\n });\n }\n }\n\n return <React.Profiler onRender={reportProfile} {...props} />;\n}", "function updateMessage(){\n $scope.message = $scope.timer.timerText + \" \";\n if($scope.timer.type === 'currency') {\n $scope.message += $filter('currency')($scope.timer.currencyAmount * $scope.val / 100 / 100, '$');\n } else if($scope.timer.type === 'percent'){\n $scope.message += Math.round($scope.val) + '%';\n } else {\n $scope.message += ($scope.time * 1000).toString().toHHMMSS();\n }\n }", "function stamp(message) {\n if (window.name.includes('performance')) {\n // eslint-disable-next-line no-console\n console.log(`${new Date() - performance.timing.navigationStart}:${message}`);\n }\n}", "profilerData() {\n return {\n type: this.relation.type,\n model: this.relation.model.name,\n throughModel: this.relation.throughModel().name,\n relatedModel: this.relation.relatedModel().name,\n };\n }", "function showProfile (name, catchPhrase, location) {\n\tconsole.log(`PROFILE:\\n Name: ${name}\\n Catchphrase: ${catchPhrase}\\n Location: ${location}`);\n}", "applyAudit() {\n super.applyAudit();\n this.log.debug('This is only another custom messagem from your custom server :)');\n }", "function PROFILERTRACE(msg) {\n if (gDebugTrace)\n PROFILERLOG(msg);\n}", "function statistics() {\n var time = Date.now() - startTime - pauseTime;\n var seconds = (time / 1000 % 60).toFixed(2);\n var minutes = ~~(time / 60000);\n statsTime.innerHTML = (minutes < 10 ? '0' : '') + minutes +\n (seconds < 10 ? ':0' : ':') + seconds;\n}", "handleStatsComplete(msg){\n\tif(msg.workerRequestToken !== this.state.workerRequestToken){return;}\n\tthis.props.setPlotUIState({\n\t stats_obj: {$set: msg.stats_obj}\n\t});\n }", "function getSummonerStatsSummary(){\n\n}", "function Camera_GetCurrentHintMessages()\n{\n\t//default result: fail\n\tvar strMessage = \"\";\n\t//request camera data\n\tthis.CameraData = new CameraData_CameraData();\n\t//fake the camera parameters\n\tthis.CameraData.Parameters.bShowErrorLaser = false;\n\tthis.CameraData.Parameters.bShowErrorOverlay = false;\n\tthis.CameraData.Parameters.bShowInfoLaser = false;\n\tthis.CameraData.Parameters.bShowInfoOverlay = false;\n\tthis.CameraData.Parameters.bShowMouseOverLaser = false;\n\tthis.CameraData.Parameters.bShowMouseOverOverlay = false;\n\tthis.CameraData.Parameters.bShowDataLaser = true;\n\tthis.CameraData.Parameters.bShowDataOverlay = false;\n\tthis.CameraData.Parameters.bShowActionLaser = true;\n\tthis.CameraData.Parameters.bShowActionOverlay = false;\n\t//create a hints command\n\tvar hintsCmd = new CameraCommand_Hints(this);\n\t//initialise it\n\thintsCmd.Initialise();\n\t//loop through the list of items\n\tfor (var i = 0, c = hintsCmd.ListItems.length; i < c; i++)\n\t{\n\t\t//valid?\n\t\tif (hintsCmd.ListItems[i].TutorialMessage)\n\t\t{\n\t\t\t//needs separator?\n\t\t\tif (strMessage.length > 0)\n\t\t\t{\n\t\t\t\t//add separator\n\t\t\t\tstrMessage += \"<p/>\";\n\t\t\t}\n\t\t\t//add the message\n\t\t\tstrMessage += hintsCmd.ListItems[i].TutorialMessage.HTMLContent;\n\t\t}\n\t}\n\t//return the result\n\treturn strMessage;\n}", "function infoText(name, limit_value, beforeSum, afterSum) {\n\t\tlet message = '<div class=\"col-md-3 col-sm-6 col-12\" style=\"float: left; text-align: left;\">'+name+'</div><div class=\"col-md-3 col-sm-6 col-12\" style=\"float: left; text-align: left;\">Limit: '+limit_value+'</div><div class=\"col-md-3 col-sm-6 col-12\" style=\"float: left; text-align: left;\"> Miesiąc: '+beforeSum+'</div><div class=\"col-md-3 col-sm-6 col-12\" style=\"float: left; text-align: left;\"> Łącznie: '+afterSum+'</div>';\n\t\treturn message;\n\t}", "getStorageDetailsMessage_() {\n if (this.entry.isPresentInAccount() && this.entry.isPresentOnDevice()) {\n return this.i18n('passwordStoredInAccountAndOnDevice');\n }\n return this.entry.isPresentInAccount() ?\n this.i18n('passwordStoredInAccount') :\n this.i18n('passwordStoredOnDevice');\n }", "report() {\n const measureKeys = Object.keys(this.measures)\n\n measureKeys.forEach(key => {\n const m = this.measures[key]\n\n this.logMeasure(key, m)\n })\n }", "function PagerMessage(pagerModule) {\n this.pagerModule = pagerModule;\n }", "constructor() {\n this._stats = null;\n this.id = '__Profiler__';\n this._showFPS = false;\n this._rootNode = null;\n this._device = null;\n this._canvas = null;\n this._ctx = null;\n this._texture = null;\n this._region = new GFXBufferTextureCopy();\n this._canvasArr = [];\n this._regionArr = [this._region];\n this.digitsData = null;\n this.pass = null;\n this._canvasDone = false;\n this._statsDone = false;\n this._inited = false;\n this._lineHeight = _constants.textureHeight / (Object.keys(_profileInfo).length + 1);\n this._wordHeight = 0;\n this._eachNumWidth = 0;\n this._totalLines = 0;\n this.lastTime = 0;\n\n {\n this._canvas = document.createElement('canvas');\n this._ctx = this._canvas.getContext('2d');\n\n this._canvasArr.push(this._canvas);\n }\n }", "function adb_send_start_profiling_fn(data, next_call) {\n if (data.process_info.error) {\n var err = data.process_info ? data.process_info.error : \"null process_info\";\n data.progress_callback({progress: 0, action: \"Error getting process info: \" + err});\n return;\n }\n\n return data.process_info.startProfilingCmd;\n}", "function showProfile(name, catchphrase, location) {\n\tconsole.log(`PROFILE:\\nName: ${name}\\nCatchphrase: ${catchphrase}\\nLocation: ${location}`);\n}", "get uploadingMsg() {\n return `Bezig met het opladen van ${this.fileQueue.files.length} bestand(en). (${this.fileQueue.progress}%)`;\n }", "function processCollector() {\r\n\r\n var valiation;\r\n\r\n if (procOperations < 0) {\r\n helperPreMiddlewares.sendRespOfIssue(req, res, 400, 'user profile');\r\n next();\r\n return;\r\n }\r\n\r\n if (procOperations === 0x07) {\r\n valiation = iWAUser.validateObject(uProfile);\r\n\r\n if (valiation !== true) {\r\n // Some attribute value is wrong\r\n helperPreMiddlewares.traceErrors(req,\r\n new iWAErrors.HttpRequest('Controller: user # Pre-middleware: parseProfileData | ' +\r\n 'Some of the sent user\\'s profile field, has a wrong type or value. Validations ' +\r\n 'details: ' + valiation));\r\n helperPreMiddlewares.sendRespOfIssue(req, res, 400, 'user profile');\r\n return;\r\n\r\n } else {\r\n // We don't need update req.processed.userProfile, because we got the reference and we've changed\r\n // the proper object instance\r\n next();\r\n }\r\n }\r\n }", "function setDefault(statMsg) {\n console.log(JSON.stringify(statMsg)); \n}", "showMessages () {\n this.messages.forEach((message) => {\n console.log(`${messageStyles[message.getType()]} ${message.getType()}: ${message.getText()}`)\n })\n }", "generateDetailedMessage(status, headers, payload, requestData) {\n let shortenedPayload;\n const payloadContentType = (0, _getHeader.default)(headers, 'Content-Type') || 'Empty Content-Type';\n if (payloadContentType.toLowerCase() === 'text/html' && payload.length > 250) {\n shortenedPayload = '[Omitted Lengthy HTML]';\n } else {\n shortenedPayload = JSON.stringify(payload);\n }\n const requestDescription = `${requestData.type} ${requestData.url}`;\n const payloadDescription = `Payload (${payloadContentType})`;\n return [`Ember AJAX Request ${requestDescription} returned a ${status}`, payloadDescription, shortenedPayload].join('\\n');\n }", "function initProfiler(name, flags) {\n if (flags === void 0) { flags = 0; }\n checkInit();\n var profiler = profilerInstances[name];\n if (profiler === void 0) {\n profilerInstances[name] = profiler = new ProfilerDetails(name, \"ms\", flags);\n container.appendChild(profiler.widget.element);\n }\n}", "printMemberProps(){\n console.log(`${this.name} plays ${this.instrument} in the Dum Dum Girls Band`);\n }", "function profileInfo(object) {\n \n \n // return the message, use the function we created capitalizeWord and pass object.name as par\n // ans add 'is a' function capitalizeWord(object.species);\n return capitalizeWord(object.name) + ' ' + 'is a' + ' ' + capitalizeWord(object.species);\n}", "function stageMessage(msg){\n stagedMessages.push(msg);\n}", "function printInfo(profileName, badgeCount, firstPointCount, secondPointCount) {\n var infoMessage = profileName + ' has ' + badgeCount + ' Treehouse badges, ' + firstPointCount + ' JavaScript points, & ' + secondPointCount + ' Ruby points!';\n console.log(infoMessage);\n}", "_logString () {\n return logItemHelper('YMap', this, `mapSize:${this._map.size}`)\n }", "function ProfileData() {\r\n}", "get messagesPerSecond() {\n return this.getNumberAttribute('messages_per_second');\n }", "toString(): string {\n const message = this.url != null ? this.url.url : \"\";\n return `${this.total} | ${this.progress} :: retrieving: ${message}`;\n }", "function runningStatStr(stat) {\n\t return `Last: ${stat.last.toFixed(2)}ms | ` +\n\t `Avg: ${stat.mean.toFixed(2)}ms | ` +\n\t `Avg${stat.maxBufferSize}: ${stat.bufferMean.toFixed(2)}ms`;\n\t}", "function createMeasurementMsg(){\n var msg = {\n type: \"measurement\",\n timestamp: Date.now(),\n value: distribution(mean,range),\n unit: \"kg\"\n };\n console.log(msg.value);\n //filestream.write(msg.value.toString()+\";\")\n return JSON.stringify(msg);\n}", "getMessage() {\n return this.name + \" must be less than \" + this.max + \". You entered \" + this.field; \n }", "displayInfo() {\n\t\t\tlet info = super.displayInfo() + ', менеджер: ' + this.manager.name ;\n\t\t\tconsole.log( info );\n\t\t\treturn info\n\t\t\t}", "injectPerForumStats(chart) {\n waitFor(\n () => {\n let now = Date.now();\n if (now - this.lastProfile.timestamp < 15 * 1000)\n return Promise.resolve(this.lastProfile);\n return Promise.reject(new Error(\n 'Didn\\'t receive profile information (for per-profile stats)'));\n },\n {\n interval: 500,\n timeout: 15 * 1000,\n })\n .then(profile => {\n new PerForumStatsSection(\n chart?.parentNode, profile.body, this.displayLanguage,\n /* isCommunityConsole = */ true);\n })\n .catch(err => {\n console.error(\n 'extraInfo: error while preparing to inject per-forum stats: ',\n err);\n });\n }", "static messageDataSaved() {\n const lastUpdated = this.getLastUpdated();\n if (lastUpdated) {dataSavedMessage.textContent += ' on ' + lastUpdated;}\n dataSavedMessage.style.display = 'block';\n }", "function profileInfo(object) {\nreturn capitalizeWord(object.name) + ' is a ' + capitalizeWord(object.species);\n}", "get message() {\n\t\t\tif (this._memoMessage !== undefined) {\n\t\t\t\treturn this._memoMessage;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t___R$$priv$project$rome$$internal$diagnostics$error$wrappers_ts$insideDiagnosticsErrorSerial\n\t\t\t) {\n\t\t\t\treturn [\n\t\t\t\t\t\"Possible DiagnosticsError message serialization infinite loop\",\n\t\t\t\t\t\"Diagnostic messages:\",\n\t\t\t\t\tthis.diagnostics.map((diag) =>\n\t\t\t\t\t\t\"- \" +\n\t\t\t\t\t\t___R$project$rome$$internal$markup$escape_ts$readMarkup(\n\t\t\t\t\t\t\tdiag.description.message,\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t].join(\"\\n\");\n\t\t\t}\n\n\t\t\tlet message = this._message === undefined ? \"\" : this._message + \"\\n\";\n\t\t\t___R$$priv$project$rome$$internal$diagnostics$error$wrappers_ts$insideDiagnosticsErrorSerial = true;\n\n\t\t\tconst reporter = new ___R$project$rome$$internal$cli$reporter$Reporter_ts$default(\n\t\t\t\t\"DiagnosticsErrorMessage\",\n\t\t\t);\n\t\t\tconst stream = reporter.attachCaptureStream(\"none\", {columns: undefined});\n\t\t\tconst printer = new ___R$project$rome$$internal$cli$diagnostics$DiagnosticsPrinter_ts$default({\n\t\t\t\treporter,\n\t\t\t\tprocessor: new ___R$project$rome$$internal$diagnostics$DiagnosticsProcessor_ts$default(),\n\t\t\t\twrapErrors: true,\n\t\t\t});\n\t\t\tfor (const diag of this.diagnostics) {\n\t\t\t\tprinter.printDiagnostic(diag, reporter, false);\n\t\t\t}\n\t\t\treporter.resources.release();\n\t\t\tmessage += stream.read();\n\t\t\t___R$$priv$project$rome$$internal$diagnostics$error$wrappers_ts$insideDiagnosticsErrorSerial = false;\n\n\t\t\tthis._memoMessage = message;\n\t\t\treturn message;\n\t\t}", "get profile() {\n\t\treturn this.__profile;\n\t}", "get profile() {\n\t\treturn this.__profile;\n\t}", "function traceMessage (event) {\n\t\t_logger.log(_prefix, 'trace event message: ' + event.data.message);\n\t\tif (_pageNotificationCallback) {\n\t\t\t_pageNotificationCallback('message', event.data.message);\n\t\t}\n\t}", "function resMessages() {\r\n return {\r\n transactionDeclined: 'Transaction declined',\r\n somethingWrong: 'COMMON.SOMETHING_WRONG',\r\n invalidInput: 'COMMON.INVALID_DETAILS',\r\n mendatory: 'COMMON.MANDATORY_DETAILS',\r\n unauthorized: 'COMMON.UNAUTHORIZED',\r\n emailFromReq: 'COMMON.EMAIL_FROM_REQ',\r\n emailToReq: 'COMMON.EMAIL_TO_REQ',\r\n emailSubjectReq: 'COMMON.EMAIL_SUBJECT_REQ',\r\n emailMessageReq: 'COMMON.EMAIL_MESSAG_EREQ',\r\n selectOnlyOne: 'COMMON.SELECT_AT_LEAST_ONE',\r\n selectAtLeastOne: 'COMMON.SELECT_AT_LEAST_ONE',\r\n picReq: 'COMMON.PIC_REQ',\r\n picInvalid: 'COMMON.PIC_INVALID',\r\n val_PicReq: 'COMMON.VALIDATION.1102',\r\n val_PicInvalid: 'COMMON.VALIDATION.1103',\r\n val_PicDuplicate: 'COMMON.VALIDATION.1110',\r\n val_SelectCompany: 'COMMON.VALIDATION.1104'\r\n };\r\n}", "toString() {\n return `${this.name}: \"${this.message}\"`;\n }", "function printDetailsModified() {\n\treturn `${this.name} (${this.type}) - ${this.age}`;\n}", "[LOAD_PROFILE_INFO](context, payload) {\n context.commit(GET_PROFILE_INFO, payload); \n }", "function printMemberProps(member){\n console.log(`${member.name} plays ${member.instrument} in the Dum Dum Girls Band`);\n}", "toString() {\n return `${this.name}: ${this.message}`;\n }", "function profileInfo (obj) {\n\n \n return capitalizeWord(obj.name) + ' is a ' + capitalizeWord(obj.species);\n \n}", "function PerformanceReporter() {\n }", "toLog(){return{total:this.total,progress:this.progress,url:this.url==null?\"\":this.url.url}}", "function getMessage() {\n\n}", "function updateMessages(){getCurrentDisplayValue().then(function(msg){ctrl.messages=[getCountMessage(),msg];});}", "function EZtrace()\t\t\t\n\t{\nif (true) return;\t\t\n\t\tif (this instanceof arguments.callee)\n\t\t{\t\t\t\t\t\t\t\t\n\t\t\tthis._pageName = '';\n\t\t\tthis._messages = [];\n\t\t\tthis._traceUpdates = null;\t\t\t\t//updated by EZ.trace()\n\t\t\tthis._displayerUpdates = null;\t\t\t//updated by EZtrace.html\n\t\t\treturn;\n\t\t}\n\t\treturn _addMessage.apply(EZ.trace, [].slice.call(arguments));\n\t}", "log(message) {\r\n this.messageService.add(`操作信息: ${message}`);\r\n }", "function msg(ctr,rec){\r\n return\"<div class='tooltipcontent'><li><span>Country : \"+ctr+\"</span></li><li><span>Records : \"+rec+\"</span></li></div>\";\r\n }", "function $__jsx_profiler() {\n}", "function profile(request, response){\r\n //prints message to the console\r\n console.log(\"user requested 'profile'\");\r\n}", "generateMessage (callback) {\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'get',\n\t\t\t\tpath: this.path,\n\t\t\t\ttestTracking: true,\n\t\t\t\treallyTrack: true,\n\t\t\t\trequestOptions: {\n\t\t\t\t\tnoJsonInResponse: true,\n\t\t\t\t\texpectRedirect: true\n\t\t\t\t}\n\t\t\t},\n\t\t\tcallback\n\t\t);\n\t}", "function createMessage(message, vm, parent) {\n if (parent) {\n vm = {\n _isVue: true,\n $parent: parent,\n $options: vm\n };\n }\n\n if (vm) {\n // Only show each message once per instance\n vm.$_alreadyWarned = vm.$_alreadyWarned || [];\n if (vm.$_alreadyWarned.includes(message)) return;\n vm.$_alreadyWarned.push(message);\n }\n\n return `[Vuetify] ${message}` + (vm ? generateComponentTrace(vm) : '');\n}", "report(label = \"params\") {\n const { showDeleted, showHidden, filterText } = this;\n const dString = showDeleted ? \"showDeleted\" : \"\";\n const hString = showHidden ? \"showHidden\" : \"\";\n\n console.groupCollapsed(label, `(${dString} ${hString}`);\n console.log(\"showDeleted\", showDeleted);\n console.log(\"showHidden\", showHidden);\n console.log(\"filterText\", filterText);\n console.groupEnd();\n }", "_updateMessage() {\n this.clear();\n this.push(this._PACKAGE_PREFIX +\n utils_1.number2HexString(this._opts.type) +\n utils_1.boolean2HexString(this._opts.showTime) +\n utils_1.boolean2HexString(this._opts.showWeather) +\n utils_1.boolean2HexString(this._opts.showTemp) +\n utils_1.boolean2HexString(this._opts.showCalendar) +\n utils_1.color2HexString(this._color));\n }", "function Profile() {\n\t}", "static printMessage(message) {\r\n let timedMessage = `[${new Date().toLocaleTimeString()}]: ${message}`;\r\n console.log(HookManager.cleanString(timedMessage));\r\n }", "function profileInfo(object) {\nlet string = `${capitalizeWord(object.name)} is a ${capitalizeWord(object.species)}`;\nreturn string;\n}", "report() {\n console.log(this.name + \" is a \" + this.type + \" type and has \" + this.energy + \" energy.\");\n }", "function teamDetailsForUser(msg, done) {\n const userId = getUserId(msg);\n const snippets = robot.brain.get(userId);\n if (!Array.isArray(snippets)) {\n return provideUsername(msg, done);\n }\n\n msg.send(`Details:\\n${snippets.map(snippet => ` - ${snippet}`).join('\\n')}`, done);\n }", "showStats(){\n console.log(\"Name:\", this.name, \"\\nStrength:\", this.strength, \"\\nSpeed:\", this.speed, \"\\nHealth:\", this.health);\n }", "getRunningProfilingData() {\n\t\t\treturn this.profiling;\n\t\t}", "function testGetWarning() {\n let vIds = messages.reduce((a, c) => {\n a.add(c.visitor.id);\n return a;\n }, new Set());\n let v = pickVisitor([...vIds]);\n let x = {\n sentTime: new Date().toISOString(),\n visitor: v,\n warning: getWarning(v),\n };\n console.log(JSON.stringify(x, null, '\\t'));\n console.log();\n}", "log(message) {\n this.messageService.add(`HeroService: ${message}`);\n }", "compute(correlationId, message, logLevel) {\n\n let ts = moment().tz('Europe/Rome').format('YYYY-MM-DD HH:mm:ss.SSS');\n\n if (logLevel == 'info') console.info('[' + ts + '] - [' + correlationId + '] - [' + this.apiName + '] - ' + message);\n else if (logLevel == 'error') console.error('[' + ts + '] - [' + correlationId + '] - [' + this.apiName + '] - ' + message);\n else if (logLevel == 'warn') console.warn('[' + ts + '] - [' + correlationId + '] - [' + this.apiName + '] - ' + message);\n\n }", "getMessageInfo () {\n const displayedValue = this.internalStore.select ('value').get ('value');\n const message = this.internalStore.select ('value').get ('info');\n if (message !== displayedValue) {\n return message;\n } else {\n return null;\n }\n }", "function RainbowProfileReport() {\r\n}", "static get properties() {\n return {\n message: { type: String },\n };\n }", "constructor() {\n super('feedback', [], {\n usage: '<message>',\n middleware: [\n 'throttle.user:1,5'\n ]\n });\n }", "function generalCallback(msg) {\n let date = new Date(msg.date * 1000);\n let hours = date.getHours();\n let minutes = \"0\" + date.getMinutes();\n let seconds = \"0\" + date.getSeconds();\n let formattedTime = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()} ${hours}:${minutes.substr(-2)}:${seconds.substr(-2)}`;\n console.log(`[${formattedTime}] Message (${msg.message_id}) received from @${msg.from.username} (${msg.from.id})`);\n}", "toString() { \n return `[Message; Text: ${this.text}; GUID: ${this.guid}]`;\n }", "getProgressMessage(label){\n\t\treturn this.config[label].progressMessage;\n\t}", "getInfo() {\n return `${super.getInfo()} Their average students grade is ${this.getAverageGrades()}`\n \n }", "annotate(message: string, data: Object) {\n this.message = message;\n this.data = assign(this.data, data);\n }", "function logstat(statistic) {\n let txt='';\n Log(\"Шел год \" + generation,\"gen\"); // \"Generation \"\n txt+=statTxt(`На планете всего было существ`,`начало`, allCreatures.length,statistic.female,statistic.male);\n if (allCreatures.length>0) txt+=`Из них: `\n txt+=statTxt(`Деревянн`,``,statistic.wood,statistic.woodFem,statistic.woodMale);\n txt+=statTxt(`Стальн`,``,statistic.steel,statistic.steelFem,statistic.steelMale);\n txt+=statTxt(`Духовн`,``,statistic.spirit,statistic.spiritFem,statistic.spiritMale);\n if ((statistic.water>statistic.waterIce&&statistic.waterIce>0)||\n (statistic.water>statistic.waterLiquid&&statistic.waterLiquid>0)||\n (statistic.water>statistic.waterSream&&statistic.waterSream>0)) \n {txt+=statTxt(`Водян`,``,statistic.water,statistic.waterFem,statistic.waterMale); txt+` А из водяных существ:`}\n else if (statistic.water>0) {txt+=`Водно-`}\n txt+=statTxt(`Ледян`,``,statistic.waterIce,statistic.waterIceFem,statistic.waterIceMale);\n txt+=statTxt(`Жидк`,``,statistic.waterLiquid,statistic.waterLiquidFem,statistic.waterLiquidMale);\n txt+=statTxt(`Парообразн`,``,statistic.waterSream,statistic.waterSreamFem,statistic.waterSreamMale);\n Log(txt,\"stat\"); \n/* `All-${allCreatures.length} f-${statistic.female}/m-${statistic.male}\nWood-${statistic.wood} f-${statistic.woodFem}/m-${statistic.woodMale}\nSteel-${statistic.steel} f-${statistic.steelFem}/m-${statistic.steelMale}\nSpirit-${statistic.spirit} f-${statistic.spiritFem}/m-${statistic.spiritMale}\nWater-${statistic.water} f-${statistic.waterFem}/m-${statistic.waterMale}\nIce water-${statistic.waterIce} f-${statistic.waterIceFem}/m-${statistic.waterIceMale}\nLiquid water-${statistic.waterLiquid} f-${statistic.waterLiquidFem}/m-${statistic.waterLiquidMale}\nWaterSream-${statistic.waterSream} f-${statistic.waterSreamFem}/m-${statistic.waterSreamMale}\n`*/\n}", "function userInfoStartWizardConversation(id) {\n userInfoMap[id].conversationTiming.push({start: +new Date(), end: undefined});\n}", "function createMessage(message, vm, parent) {\n // if (Vuetify.config.silent) return\n if (parent) {\n vm = {\n _isVue: true,\n $parent: parent,\n $options: vm\n };\n }\n\n if (vm) {\n // Only show each message once per instance\n vm.$_alreadyWarned = vm.$_alreadyWarned || [];\n if (vm.$_alreadyWarned.includes(message)) return;\n vm.$_alreadyWarned.push(message);\n }\n\n return \"[Vuetify] \".concat(message) + (vm ? generateComponentTrace(vm) : '');\n}", "function my_title_format (window) {\n return '{'+get_current_profile()+'} '+window.buffers.current.description;\n}", "function Statistics() {\n var labelSent = $('#label-sent');\n var labelReceived = $('#label-received');\n var labelElapsed = $('#label-elapsed');\n return function(sent, received, elapsed) {\n labelSent.textContent = sent;\n labelReceived.textContent = received;\n if (elapsed != undefined) {\n labelElapsed.textContent = elapsed;\n }\n }\n }", "function incomingMessage(param) {\r\n\tif (tabs.items.getCount() > 0)\r\n \tcurrentTab = tabs.getActiveTab();\r\n\r\n\tvar startDetails = new Object();\r\n\tstartDetails.userName = param.sender;\r\n delete startDetails;\r\n addMessage(param.sender, param.message, param.sender);\r\n \r\n if (currentTab.id != param.sender) { \r\n \tvar tab = findTab(param.sender);\r\n \tflashTabWithNewMessage(tab,getBgColorUponNewMessage(),getFlashNumOfTimesUponNewMessage());\r\n } \r\n \r\n notifyToolbar(); \r\n}", "generateMessage (callback) {\n\t\t// create a channel or direct stream, this should send a message to the users that they've been\n\t\t// added to the stream, but not to the current user, who is not being added to the stream\n\t\tthis.streamFactory.createRandomStream(\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tthis.message = { stream: response.stream };\n\t\t\t\tcallback();\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: this.type,\n\t\t\t\ttoken: this.users[1].accessToken,\t\n\t\t\t\tteamId: this.team.id,\n\t\t\t\tmemberIds: [this.users[2].user.id]\t\n\t\t\t}\n\t\t);\n\t}" ]
[ "0.6386364", "0.6029055", "0.5931499", "0.5689865", "0.55454767", "0.54338276", "0.5401419", "0.53847295", "0.5377581", "0.5339478", "0.53226006", "0.5314411", "0.5300518", "0.52959704", "0.5281602", "0.5262394", "0.5237166", "0.52005845", "0.51949733", "0.5188414", "0.51831526", "0.5166315", "0.516563", "0.5162395", "0.5159165", "0.5142671", "0.5140172", "0.51283115", "0.511496", "0.5106093", "0.50937515", "0.50850534", "0.5082674", "0.50670224", "0.50504637", "0.5038532", "0.5026852", "0.5024366", "0.50139004", "0.4990685", "0.498245", "0.49735495", "0.49521047", "0.49309993", "0.492787", "0.4927099", "0.49228948", "0.4910162", "0.49090508", "0.4907236", "0.4905702", "0.4902066", "0.4902066", "0.49005446", "0.4895859", "0.48815992", "0.48813882", "0.488011", "0.4873462", "0.48681968", "0.48627353", "0.4861335", "0.48575255", "0.4853475", "0.4852326", "0.48512703", "0.48501828", "0.48476774", "0.4844248", "0.48440945", "0.4842431", "0.48422527", "0.48307145", "0.48254246", "0.4823297", "0.48220247", "0.4820939", "0.48152688", "0.48146173", "0.4802522", "0.4801241", "0.4800199", "0.4798613", "0.4796432", "0.47875223", "0.47872627", "0.4786486", "0.47863546", "0.47829425", "0.47781995", "0.47781387", "0.47738048", "0.4773206", "0.4763849", "0.47610202", "0.47605187", "0.47460553", "0.47457105", "0.4743009", "0.47390318" ]
0.5274832
15
Store user details in session storage. Session storage was used to store the user details so as to simulate a typical user login scenario. The user details would be cleared once the browser window is closed.
function saveToSessionStorage() { const passwordValue = password.value; // Get the password input value const usernameValue = username.value; // Get the username input value // The user object holds the username and password let user = { username: usernameValue, password: passwordValue, }; // Store the user object in session storage. // Also store a boolean variable that identifies if the user is // logged in. sessionStorage.setItem("user", JSON.stringify(user)); sessionStorage.setItem("isValidUser", JSON.stringify(true)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static storeUser(user) {\n localStorage.setItem('userInfo', user);\n }", "function storeUserData () {\n\t\tvar key,\n\t\tstorageData = {};\n\n\t\t// Loop thru user object and encode each name/value.\n\t\tfor (key in user) {\n\t\t\tif (user.hasOwnProperty(key)) {\n\t\t\t\tstorageData[(encryption.encode(key))] = encryption.encode(user[key]);\n\t\t\t}\n\t\t}\n\n\t\tIBM.common.util.storage.setItem(storage.key, storageData, 3600 * 24 * (user.information_level === \"basic\" ? storage.expireDaysBasic : storage.expireDaysDetailed));\n\t}", "function setUserDetailsInLocalStorage(user) {\n localStorage.setItem(\"userDetails\", JSON.stringify(user));\n}", "_addSessionToStorage() {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(this._session));\n }", "static saveSession() {\n if (typeof window === 'undefined') return\n window.sessionStorage.idCacheByUserId = JSON.stringify(idCacheByUserId)\n window.sessionStorage.itemCacheByUserId = JSON.stringify(itemCacheByUserId)\n window.sessionStorage.userCache = JSON.stringify(userCache)\n }", "function saveUserData() {\n localStorage.setItem('locallyStored', JSON.stringify(userData))\n}", "function saveSession(session) {\n $window.sessionStorage['user'] = JSON.stringify(session);\n }", "function setSessionStorage(email, accessToken, idToken, displayName, profilePicture, userUid)\n{\n sessionStorage.setItem('display_name_firebase', displayName);\n sessionStorage.setItem('profile_picture_firebase', profilePicture);\n sessionStorage.setItem('email_firebase', email);\n sessionStorage.setItem('access_token_firebase', accessToken);\n sessionStorage.setItem('id_token_firebase', idToken);\n sessionStorage.setItem('uid_firebase', userUid);\n}", "function saveSession(data) {\n localStorage.setItem('username', data.username);\n localStorage.setItem('id', data._id);\n localStorage.setItem('authtoken', data._kmd.authtoken);\n userLoggedIn();\n }", "function saveSession(data) {\n localStorage.setItem('username', data.username);\n localStorage.setItem('id', data._id);\n localStorage.setItem('authtoken', data._kmd.authtoken);\n userLoggedIn();\n }", "function saveUserData(userData) {\n localStorage.setItem('username', userData.username);\n localStorage.setItem('accessToken', userData.accessToken);\n localStorage.setItem('id', userData.id);\n username = userData.username;\n accessToken = userData.accessToken;\n }", "function storeSession (data) {\n const now = new Date()\n const expirationDate = new Date(now.getTime() + data.expiresIn * 1000)\n localStorage.setItem('expirationDate', expirationDate)\n localStorage.setItem('expiresIn', data.expiresIn * 1000)\n localStorage.setItem('token', data.idToken)\n localStorage.setItem('userId', data.localId)\n localStorage.setItem('refreshToken', data.refreshToken)\n}", "function storeLoginDetails({ username, session }) {\n Cookies.set(\"username\", username);\n Cookies.set(\"session\", session);\n}", "static saveUserInfo(userData) {\n localStorage.setItem('uid', userData.uid);\n localStorage.setItem('name', userData.name);\n }", "function saveUserCredentialsInLocalStorage() {\n console.debug('saveUserCredentialsInLocalStorage');\n if (currentUser) {\n localStorage.setItem('token', currentUser.loginToken);\n localStorage.setItem('username', currentUser.username);\n }\n}", "function saveUserCredentialsInLocalStorage() {\n console.debug(\"saveUserCredentialsInLocalStorage\");\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n}", "function storesessiondata(){\n\tvar storagedata=JSON.stringify(sessiondata);\n\twindow.localStorage.setItem(cookiename, storagedata);\n}", "static storeUserInfo(userInfo) {\n localStorage.setItem(this.KEY_USER_INFO, JSON.stringify(userInfo));\n }", "async writeToStorage() {\r\n const fetchedInfo = {\r\n fetchedUsername: this.state.fetchedUsername,\r\n fetchedPassword: this.state.fetchedPassword,\r\n };\r\n\r\n //Save the user info\r\n localStorage.setItem(\"fetchedInfo\", JSON.stringify(fetchedInfo));\r\n }", "function saveAuthData() {\n // Skip if the local storage is not available.\n if (!utils.storageAvailable('localStorage')) {\n return;\n }\n\n // Create the data object.\n var data = {\n authUserID: authUserID\n };\n\n // Save to the local storage.\n localStorage.setItem(authDataID, JSON.stringify(data));\n }", "function storeCredentials () {\n var storage = window.localStorage;\n\n //Get Info\n username = document.getElementById(\"username\").value;\n password = document.getElementById(\"password\").value;\n\n //Store Info\n storage.setItem(\"username\", username);\n storage.setItem(\"password\", password);\n\n //Hide Login\n hideLogin();\n}", "getSessionStorageUser() {\n return JSON.parse(sessionStorage.getItem('user'))\n }", "saveSession(userInfo) {\r\n localStorage.setItem('Admin', userInfo.Admin)\r\n let userAuth = userInfo._kmd.authtoken\r\n localStorage.setItem('authToken', userAuth)\r\n let userId = userInfo._id\r\n localStorage.setItem('userId', userId)\r\n let username = userInfo.username\r\n localStorage.setItem('username', username)\r\n\r\n observer.onSessionUpdate()\r\n }", "function saveUserDetails() {\n var user = {\n 'first': $('#user_event_first_name').val(),\n 'last': $('#user_event_last_name').val(),\n 'email': $('#user_event_user_email').val()\n };\n localStorage.setItem('wceUser', JSON.stringify(user));\n}", "async function storageUser(data){\n await AsyncStorage.setItem('Auth_user', JSON.stringify(data));\n }", "function storeuName() {\n sessionStorage.uName = document.getElementById(\"uName\").value;\n}", "function putValueOnSession(key, value){\n\tif (hasStorage()) {\n\t\tsessionStorage.setItem(window.xuser.id + '|' + key, stringify(value));\n\t}\n}", "persist() {\n localStorage.setItem(\n STORAGE_KEY + \"/\" + this.user.getId(),\n JSON.stringify(this.data)\n );\n }", "saveToSessionStorage() {\n Object.keys(this).forEach(key =>\n sessionStorage.setItem(key, JSON.stringify(this[key]))\n );\n setTimeout(() => sessionStorage.clear(), 200000);\n }", "function saveInSessionStorage(key, value) {\n if (typeof(Storage) !== \"undefined\") {\n sessionStorage.setItem(key, JSON.stringify(value))\n } else {\n console.log(\"Sorry! No Web Storage support..\");\n }\n}", "function saveUserInfo(userInfo) {\r\n\t \tself._userInfo = userInfo;\r\n\t \tlocalStorage.setItem('user', JSON.stringify(userInfo));\r\n\t }", "function addStorage(employeeDetails) {\n localStorage.setItem(\"userDetails\", JSON.stringify(employeeDetails));\n}", "function saveSession(){\n sessionStorage.setItem('timers', JSON.stringify(Timers));\n sessionStorage.setItem('settings', JSON.stringify(settingsDefaults));\n}", "function setUserLocalStorage(username, email) {\n localStorage.setItem(\"username\", username);\n localStorage.setItem(\"email\", email);\n}", "clearUserFromStorage() {\n this.getSession().forget(this.sessionKeyName);\n this.clearRememberMeCookie();\n }", "function storeUsers() {\n localStorage.setItem(\"users\", JSON.stringify(users));\n}", "function storeUsers() {\n localStorage.setItem(\"users\", JSON.stringify(users));\n}", "setUserLS(userName) {\n localStorage.setItem('logedUser', userName);\n }", "function deleteUserDataFromSessionStorage() {\n localStorage.removeItem('userData');\n}", "function saveToLocalStorage() { \n\t\n\t\t\t\t\tvar lscount = localStorage.length; \n\t\t\t\t\tvar Userstring=User.toJSONString();\n\t\t\t\t\t\t\tlocalStorage.setItem(\"User_\" + lscount, Userstring); \n\t\t\n}", "saveSessionStorage(sessionStorageID, setValue){\n window.sessionStorage.setItem(sessionStorageID, setValue);\n }", "function saveAuthToken(username, token) {\n\tsessionStorage.setItem(\"username\", username);\n\tsessionStorage.setItem(\"authToken\", token);\n}", "function saveUserProfile(userProfile) {\r\n\t \tself._userProfile = userProfile;\r\n\t \tlocalStorage.setItem('userProfile', JSON.stringify(userProfile));\r\n\t }", "function storeForm() {\n\t\t\n\t\t$( \".sessioninput\" ).each(function( index ) {\n\t\t\t\n\t\t\twindow.localStorage.setItem($(this).attr(\"name\"), $(this).val());\n\t\t\t\n\t\t});\n\t\t\n\t\t\n\t\tstartSession()\n\t}", "function SaveUserInfo()\r\n{\r\n\tdoc=window.content.document;\r\n\tdoc=XPCNativeWrapper.unwrap(doc);\r\n\tuser_name=doc.getElementById(\"user-name\").getAttribute(\"value\");\r\n\tsession_key=doc.getElementById(\"session-key\").getAttribute(\"value\");\r\n\tglobalStorage['ytfm.ashishdubey.info'].setItem(\"user\",user_name);\t\r\n\tglobalStorage['ytfm.ashishdubey.info'].setItem(\"key\",session_key);\r\n\tLoadUserInfo();\r\n}", "getUserData() {\n return JSON.parse(localStorage.getItem(SIMPLEID_USER_SESSION));\n }", "function saveCredentials() {\n\tvar username = document.getElementById(\"username\").value;\n\tvar password = document.getElementById(\"password\").value;\n\tvar creds = {\n\t\t\tuser: username,\n\t\t\tpass: password\n\t};\n\tvar store = JSON.stringify(creds);\n\tlocalStorage.setItem(\"AtmosphereLogin\", store);\n}", "function saveSessionValue(key, value){\n\tif(typeof(Storage) !== 'undefined') {\n\t\tlocalStorage.setItem(key, value);\n \t//window.localStorage.setItem(key, value);\n }\n}", "storeSession(pathname, nextSessionData) {\n // We use pathname instead of key because the key is unique in the history.\n var sessionData = JSON.parse(sessionStorage.getItem(pathname));\n // Update the session data with the changes.\n sessionStorage.setItem(pathname, JSON.stringify(Object.assign({}, sessionData, nextSessionData)));\n }", "function ContextStorage() {\n\t\tvar store = $.telligent.evolution.user.accessing.isSystemAccount\n\t\t\t? global.sessionStorage\n\t\t\t: global.localStorage;\n\t\tstore = global.sessionStorage;\n\n\t\tfunction addUserToKey(key) {\n\t\t\treturn $.telligent.evolution.user.accessing.id + ':' + key;\n\t\t}\n\n\t\treturn {\n\t\t\tget: function(key) {\n return JSON.parse(store.getItem(addUserToKey(key)));\n\t\t\t},\n\t\t\tset: function(key, data) {\n store.setItem(addUserToKey(key), JSON.stringify(data));\n\t\t\t},\n\t\t\tremove: function(key) {\n store.removeItem(addUserToKey(key));\n\t\t\t}\n\t\t};\n\t}", "function saveUsers(){\n $(\"#create-account\").css(\"display\",\"none\");\n var str = JSON.stringify(users);\n console.log(str);\n localStorage.setItem(\"users\", str);\n}", "function saveUsers(){\n $(\"#create-account\").css(\"display\",\"none\");\n var str = JSON.stringify(users);\n console.log(str);\n localStorage.setItem(\"users\", str);\n}", "function populateStorage () {\n localStorage.setItem('prop1', 'red')\n localStorage.setItem('prop2', 'blue')\n localStorage.setItem('prop3', 'magenta')\n\n sessionStorage.setItem('prop4', 'cyan')\n sessionStorage.setItem('prop5', 'yellow')\n sessionStorage.setItem('prop6', 'black')\n }", "function clearUserData()\n {\n userData = userDataDefault;\n window.localStorage.setItem(localStorageName, JSON.stringify(userData));\n }", "function saveStats(){\n sessionStorage.setItem('stats', JSON.stringify(stats));\n sessionStorage.setItem('statsinfo', JSON.stringify(statsinfo));\n}", "function setsaveInfoLocalStorage(userInfo){\n localStorage.setItem('userInfo',JSON.stringify(userInfo));\n}", "function storeLocal() {\n const jsonUserData = JSON.stringify(userData);\n localStorage.setItem('fullname', jsonUserData);\n}", "function currentUser (){\n return JSON.parse(window.sessionStorage.getItem(\"user_info\"));\n}", "function saveProfileInformation(){\n\tvar name = document.getElementById(\"profileName\").value;\n\tvar age = document.getElementById(\"userAge\").value;\n\tvar phoneNumber = document.getElementById(\"userPhone\").value;\n\tvar mailId = document.getElementById(\"userMail\").value;\n\tvar address = document.getElementById(\"userAddress\").value;\n\tvar profileImg = document.getElementById(\"userImg\").value;\n\tvalidateUserProfile(name, age, phoneNumber, mailId, address, profileImg);\n\tif (profileDataValid) {\n\t\tvar user = new User(name, age, phoneNumber, mailId, address, profileImg);\n\t\tlocalStorage.setItem(\"profileData\", JSON.stringify(user));\n\t}\n\telse{\n\t\talert(\"Error saving Data\");\n\t}\n}", "setSession(value){\n localStorage.setItem(this.SESSION, value);\n }", "function getUser() {\n if (promisedUser.data.success) {\n $scope.user = promisedUser.data.user;\n $window.sessionStorage.setItem('currentUser', JSON.stringify($scope.user));\n }\n }", "function saveUsers(detailsStr) {\n var usersJSON = JSON.stringify(detailsStr);\n localStorage.setItem(LS_MEME_USER, usersJSON);\n}", "function setUserData(name, value) {\n if (window.localStorage) { // eslint-disable-line\n window.localStorage.setItem(name, value) // eslint-disable-line\n } else {\n Cookies.set(name, value, { expires: 7 })\n }\n}", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function syncCurrentUserToLocalStorage() {\n if (currentUser) {\n localStorage.setItem(\"token\", currentUser.loginToken);\n localStorage.setItem(\"username\", currentUser.username);\n }\n }", "function saveinStorage() {\n\tsessionStorage.setItem('idList', JSON.stringify(idList));\n\tsessionStorage.setItem('currentL', currentL);\n\tsessionStorage.setItem('currentR', currentR);\n\tsessionStorage.setItem('left', left);\n\tsessionStorage.setItem('right', right);\n\tsessionStorage.setItem('tempArr', JSON.stringify(tempArr));\n\tsessionStorage.setItem('position', position);\n}", "saveSession () {\n this.storage.touch()\n }", "function _save(key, value) {\n $window.sessionStorage.setItem(key, value);\n }", "function saveSessionStorage(data) {\n sessionStorage.setItem(\"songID\", data);\n }", "function setStorage() \r\n\t{\r\n if (typeof(Storage) !== \"undefined\")\r\n\t\t{\r\n if (remember)\r\n\t\t\t{\r\n localStorage.setItem(\"member\", 'true');\r\n if (publicAddr)\r\n localStorage.setItem(\"address\", publicAddr);\r\n } else\r\n\t\t\t{\r\n localStorage.removeItem('member');\r\n localStorage.removeItem('address');\r\n }\r\n } \r\n }", "function rememberUser() {\r\n\tif(localStorage.remember) {\r\n\t\tgetId('name').value = localStorage.name;\r\n\t\tgetId('email').value = localStorage.email;\r\n\t\tgetId('phone').value = localStorage.phone;\r\n\t\tgetId('address').value = localStorage.address;\r\n\t\tgetId('remember').checked = localStorage.remember;\r\n\t}\r\n}", "function save() {\n localStorage.setItem(\"user\", JSON.stringify(user));\n localStorage.setItem(\"score\", JSON.stringify(score));\n}", "function storeUserInfoInDatabase (response) {\n const auth0Id = response.data.sub // .sub is short for 'subject' on Auth0\n const db = req.app.get('db')\n return db.read_user(auth0Id).then(users => {\n if (users.length) {\n const user = users[0]\n req.session.user = user // Using sessions with Auth0\n res.redirect('/profile')\n } else {\n const createUserData = [\n auth0Id,\n response.data.email,\n response.data.name,\n response.data.picture\n ]\n return db.create_user(createUserData).then(newUsers => {\n const user = newUsers[0]\n req.session.user = user // Here is session again\n res.redirect('/profile')\n })\n }\n })\n }", "sessionCLose() {\n localStorage.removeItem(\"user\");\n }", "function retrieveProfileInfo() {\n return JSON.parse(sessionStorage.getItem(\"user\"));\n}", "function saveUserData() {\n var saveData = readValuesFromPage();\n\n EcwidApp.setAppStorage(saveData.private, function (savedData) {\n console.log('Private preferences saved!');\n });\n\n EcwidApp.setAppPublicConfig(saveData.public, function (savedData) {\n console.log('Public preferences saved!');\n })\n}", "_cacheSession() {\n if (this._conn.authenticated) {\n if (this._conn.jid && this.rid && this.sid) {\n sessionStorage.setItem(\n 'strophe-bosh-session',\n JSON.stringify({\n 'jid': this._conn.jid,\n 'rid': this.rid,\n 'sid': this.sid,\n })\n );\n }\n } else {\n sessionStorage.removeItem('strophe-bosh-session');\n }\n }", "function createSessionStorage() {\r\n // Get previous session storage\r\n var cartContents = JSON.parse(sessionStorage.getItem('cart-contents'));\r\n\r\n // Create empty array if storage is empty\r\n if (cartContents == null) {\r\n cartContents = []\r\n sessionStorage.setItem('cart-contents', JSON.stringify(cartContents));\r\n }\r\n}", "function setUser(user) {\n\t\t\tlocalStorage.addLocal('user', user);\n\t\t}", "function loginUserData(data) {\n var flag = \"active\";\n sessionStorage.setItem(\"LoginJson\", flag);\n sessionStorage.setItem(\"FullName\", data.fname + \" \" + data.mname);//for fname\n sessionStorage.setItem(\"MiddleName\", data.mname);//for mname\n sessionStorage.setItem(\"LastName\", data.lname);//for lname\n sessionStorage.setItem(\"LoginId\", data.loginid);//for loginid\n sessionStorage.setItem(\"CurrentUserId\", data._id.$oid); //for Current User \n sessionStorage.setItem(\"OrgId\", data.orgid);\n// sessionStorage.setItem(\"Privileges\", privileges);\n sessionStorage.setItem(\"RoleNames\", data.roles);\n sessionStorage.setItem(\"UserType\", data.type);\n getOrgName();\n}", "function setSessionData(key, data) {\n if (Modernizr.sessionstorage) {\n sessionStorage.setItem(key, JSON.stringify(data));\n }\n }", "function storeState() {\n\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data));\n }", "function writeUser() {\n\n const user = JSON.parse(localStorage.getItem('person'));\n const sessionClients = JSON.parse(sessionStorage.getItem('usersClients'));\n const sessionReps = JSON.parse(sessionStorage.getItem('usersReps'));\n\n window.allClients = [];\n window.allReps = [];\n\n if (sessionClients) {\n\n $.each(sessionClients, function (index, client) {\n // add new form data to an existing client\n window.allClients.push(client);\n });\n\n } else { // no client data in session so get it from the user \n $.each(user.clients, function (index, client) {\n\n window.allClients.push(client);\n\n });\n }\n\n if (sessionReps) {\n\n $.each(sessionReps, function (index, rep) {\n // add new form data to an existing rep\n window.allReps.push(rep);\n });\n\n } else { // no rep data in session so get it from the user \n $.each(user.reps, function (index, rep) {\n\n window.allReps.push(rep);\n\n });\n }\n\n\n sessionStorage.setItem('usersClients', JSON.stringify(window.allClients));\n // sessionStorage.setItem('usersMultipleClients', JSON.stringify(window.allClients));\n\n sessionStorage.setItem('usersReps', JSON.stringify(window.allReps));\n\n var firstTimeUser = true;\n if (sessionStorage.getItem('sessionGuid')) {\n firstTimeUser = false;\n }\n\n // count number of clients \n var sessionClientSubmitted = false;\n var sessionRepSubmitted = false;\n\n\n\n if ((window.allClients.length > 0) && (window.allReps.length > 0)) {\n // console.log(' both');\n localStorage.setItem('repFlow', 'both');\n $('.pt-switch-account').show();\n\n if (user.clients) {\n sessionClientSubmitted = true;\n }\n\n } else if (window.allClients.length > 0) {\n localStorage.setItem('repFlow', 'representing');\n if (user.clients) {\n sessionClientSubmitted = true;\n }\n } else if (window.allReps.length > 0) {\n localStorage.setItem('repFlow', 'represented');\n if (user.reps) {\n sessionRepSubmitted = true;\n }\n }\n\n // if (sessionReps) {\n // localStorage.setItem('repFlow', 'representing');\n // if (sessionReps.rep[0].submittedApplication == \"true\") {\n // localStorage.setItem('repFlow', 'representing');\n // var sessionRepSubmitted = true;\n // user.reps.push(sessionReps.rep[0]);\n // }\n\n // if (sessionReps.rep[0].role == \"Cease\") {\n // user.numberOfReps = 0\n // user.reps.length = 0;\n // sessionRepSubmitted = false;\n // localStorage.setItem('repFlow', 'none');\n // sessionStorage.removeItem('usersReps');\n // if (!window.location.hash) {\n // window.location = window.location + '#rep-list';\n // window.location.reload();\n // }\n // }\n\n // }\n\n\n // set\n if ((user.clients.length > 0) || (sessionClientSubmitted === true)) {\n\n if (user.clients.length > 0) {\n user.numberOfClients = user.clients.length;\n } else {\n user.numberOfClients = window.allClients.length;\n }\n\n } else if (user.clients.length < 1) {\n user.numberOfClients = 0;\n }\n\n if ((user.reps.length > 0) || (sessionRepSubmitted === true)) {\n\n if (user.reps.length > 0) {\n user.numberOfReps = user.reps.length;\n } else {\n user.numberOfReps = window.allReps.length;\n }\n } else if (user.reps.length < 1) {\n user.numberOfReps = 0;\n // localStorage.setItem('repFlow', 'newbie');\n }\n\n if (user.claims) {\n user.numberOfClaims = user.claims.length;\n } else {\n user.numberOfClaims = 0;\n }\n\n\n // show hide the switch account buttons\n\n // console.log('sessionClientSubmitted -> ' + sessionClientSubmitted);\n // console.log('window.allClients.length -> ' + window.allClients.length);\n if ((sessionRepSubmitted === true) && (sessionClientSubmitted === true)) {\n localStorage.setItem('repFlow', 'both');\n $('.pt-switch-account').show();\n firstTimeUser = false;\n } else if ((sessionRepSubmitted === true) || (user.numberOfReps > 0)) {\n // localStorage.setItem('repFlow', 'represented');\n firstTimeUser = false;\n } else if ((sessionClientSubmitted === true) || (window.allClients.length > 0)) {\n // localStorage.setItem('repFlow', 'representing');\n $('.pt-switch-account').show();\n firstTimeUser = false;\n } else {\n $('.pt-switch-account').hide();\n // alert('hiding');\n }\n\n if (firstTimeUser) {\n localStorage.setItem('repFlow', 'newbie');\n }\n\n var practitioners = \"\";\n\n $.ajax({\n url: '/docs/data/medical-practitioner.json',\n type: 'GET',\n dataType: 'json',\n async: false\n })\n .done((data) => {\n practitioners = `<ul>`;\n $.each(data.practitioners, (index, pract) => {\n if (user.practitioners.includes(pract._id)) {\n practitioners += `<li>${pract.nameFull}</li>`;\n }\n });\n practitioners += `</ul>`;\n });\n\n\n var userHtml = '';\n var start = '<div class=\"pt-flex-grid\"><div class=\"pt-col\">';\n var end = '</div></div>'\n userHtml += start + 'Name </div><div class=\"pt-col\">' + user.nameFull + end;\n userHtml += start + 'Age </div><div class=\"pt-col\">' + getAge(user.dob) + end;\n userHtml += start + 'Is a veteran </div><div class=\"pt-col\">' + user.veteran + end;\n userHtml += start + 'Practitioners </div><div class=\"pt-col\">' + practitioners + end;\n userHtml += start + 'Currently Serving </div><div class=\"pt-col\">' + user.isCurrentlyServing + end;\n userHtml += start + 'Clients </div><div class=\"pt-col\">' + user.numberOfClients + end;\n userHtml += start + 'Reps </div><div class=\"pt-col\">' + user.numberOfReps + end;\n userHtml += start + 'Last payment </div><div class=\"pt-col\">' + user.lastPayment + end;\n userHtml += start + 'Claims </div><div class=\"pt-col\">' + user.numberOfClaims + end;\n userHtml += start + 'Story </div><div class=\"pt-col\">' + user.story + end;\n\n user.picture = '<img class=\"pt-image-circle\" src=\"' + user.picture + '\">';\n\n\n $('#userContainerId').html(userHtml);\n $('.pt-current-user-name-picture').html(user.picture);\n $('.pt-current-user-name-first').html(user.name.first);\n $('.pt-current-user-name-full').html(user.nameFull);\n $('.pt-current-user-last-payment').html(user.lastPayment);\n $('.pt-current-user-number-of-claims').html(user.numberOfClaims);\n\n\n}", "function saveUserData() {\n\tupdateSnakeStorage();\n\tsetLocalStorageItem(\"Snake\", SNAKE_STORAGE);\n}", "function storedata(username, jwt) {\r\n if(typeof(Storage) !== \"undefined\") {\r\n if (localStorage.jwt && localStorage.username) {\r\n localStorage.username =username;\r\n localStorage.jwt =jwt;\r\n // alert('done')\r\n } else {\r\n localStorage.username =username;\r\n localStorage.jwt =jwt;\r\n // alert('done add')\r\n }\r\n } else {\r\n alert(\"Sorry, your browser does not support web storage...\");\r\n }\r\n }", "loginSuccess(response) {\r\n console.log('connected')\r\n sessionStorage.setItem('userDetails', JSON.stringify({ username: response.profileObj.name, imageUrl: response.profileObj.imageUrl}));\r\n this.setState({\r\n loggedIN: true\r\n })\r\n }", "function save(storage, name, value) {\n try {\n var key = propsPrefix + name;\n if (value == null) value = '';\n storage[key] = value;\n } catch(err) {\n console.log('Cannot access local/session storage:', err);\n }\n }", "function session()\n{\nif (!localStorage.adminUser)\n{\n//default to empty array\nlocalStorage.adminUser = JSON.stringify([]);\n}\nreturn JSON.parse(localStorage.adminUser);\n}", "function save_data() {\r\n\tsessionStorage.setItem('pieces', JSON.stringify(Data.pieces))\r\n\tsessionStorage.setItem('stamps', JSON.stringify(Data.stamps))\r\n\tsessionStorage.setItem('categories', JSON.stringify(Data.categories))\r\n\tsessionStorage.setItem('tuto', JSON.stringify(Data.tuto))\r\n}", "function saveUser(user) {\n var users = JSON.parse(localStorage.getItem(\"users\"));\n if (!users) {\n var users = [];\n users.push(user);\n } else {\n users.push(user);\n }\n localStorage.setItem(\"users\", JSON.stringify(users));\n\n window.parent.postMessage(\"message\", \"*\");\n}", "function save(storage, name, value) {\n try {\n var key = propsPrefix + name;\n if (value == null) value = '';\n storage[key] = value;\n } catch (err) {\n console.log('Cannot access local/session storage:', err);\n }\n }", "function save(storage, name, value) {\n try {\n var key = propsPrefix + name;\n if (value == null) value = '';\n storage[key] = value;\n } catch (err) {\n console.log('Cannot access local/session storage:', err);\n }\n }", "function save(storage, name, value) {\n try {\n var key = propsPrefix + name;\n if (value == null) value = '';\n storage[key] = value;\n } catch (err) {\n console.log('Cannot access local/session storage:', err);\n }\n }", "function save(storage, name, value) {\n try {\n var key = propsPrefix + name;\n if (value == null) value = '';\n storage[key] = value;\n } catch (err) {\n console.log('Cannot access local/session storage:', err);\n }\n }", "function save(storage, name, value) {\n try {\n var key = propsPrefix + name;\n if (value == null) value = '';\n storage[key] = value;\n } catch (err) {\n console.log('Cannot access local/session storage:', err);\n }\n }", "function save(storage, name, value) {\n try {\n var key = propsPrefix + name;\n if (value == null) value = '';\n storage[key] = value;\n } catch (err) {\n console.log('Cannot access local/session storage:', err);\n }\n }" ]
[ "0.7763968", "0.74131286", "0.7411828", "0.73758596", "0.73696715", "0.7363886", "0.7301787", "0.72977257", "0.72938496", "0.72938496", "0.7250397", "0.7158515", "0.71335274", "0.70816964", "0.7065029", "0.70576197", "0.70398957", "0.7039261", "0.7002955", "0.6996285", "0.6979792", "0.69754887", "0.6961601", "0.69414836", "0.687441", "0.68444335", "0.6843998", "0.6821751", "0.6767256", "0.6766395", "0.6760481", "0.6755973", "0.67411745", "0.6737227", "0.6711227", "0.67014694", "0.67014694", "0.667865", "0.6675556", "0.6673795", "0.66584975", "0.6634995", "0.6626363", "0.662178", "0.6594822", "0.6594763", "0.6579641", "0.6569437", "0.6565011", "0.6552626", "0.6547849", "0.6547849", "0.6542266", "0.6524794", "0.6521409", "0.6508452", "0.6507888", "0.6506649", "0.6503141", "0.64932996", "0.6486303", "0.6459599", "0.64568883", "0.645311", "0.645311", "0.645311", "0.645311", "0.645311", "0.645311", "0.6448433", "0.6442166", "0.6442104", "0.64382046", "0.6431581", "0.64185244", "0.6415051", "0.64106005", "0.6405441", "0.6402181", "0.6385864", "0.6385379", "0.63797075", "0.6378002", "0.637559", "0.63694805", "0.63645333", "0.6348614", "0.6348485", "0.63399005", "0.63262624", "0.6322914", "0.63204396", "0.6313543", "0.63107103", "0.6310083", "0.6310083", "0.6310083", "0.6310083", "0.6310083", "0.6310083" ]
0.7963589
0
array PUSH and SHIFTTTTTTTT
function nextInline (arr, numko) { arr.push(numko); return arr.shift(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function ShiftArrayValsLeft(arr){\n}", "function shift(arr){\n console.log(arr.shift())\n console.log(arr)\n}", "function shiftLeft(arr){\n arr.push(arr.shift(0));\n return arr;\n}", "function task14_16_13(){\n var arr = [];\n arr.unshift(\"keyboard\");\n arr.unshift(\"mouse\");\n arr.unshift(\"printer\");\n arr.unshift(\"monitor\");\n document.write(\" TOTAL \");\n document.write(\"<br>\");\n document.write(\"Array : \" + arr);\n\n document.write(\"<br>\");\n document.write(\" Removal \");\n document.write(\"<br>\");\n document.write(\"Array : \" + arr);\n document.write(\"<br>\");\n arr.shift(\"keyboard\");\n document.write(\"Array : \" + arr);\n document.write(\"<br>\");\n arr.shift(\"mouse\");\n document.write(\"Array : \" + arr);\n document.write(\"<br>\");\n arr.shift(\"printer\");\n document.write(\"Array : \" + arr);\n document.write(\"<br>\");\n arr.shift(\"monitor\");\n document.write(\"<br>\");\n}", "function myUnshift(arr, newVal) {\n let newArr = [newVal];\n for (let i = 0; i < arr.length; i++) {\n newArr.push(arr[i]);\n }\n return newArr;\n}", "function shift() {\n myArray.shift();\n showAray();\n}", "function myUnshift(arr, newVal) {\n return [newVal, ...arr];\n}", "function unshift(arr, val) {\n var i;\n for (i = arr.length - 1; i >= 0; i--) {\n arr[i + 1] = arr[i];\n }\n arr[0] = val;\n return arr.length;\n}", "function popShift(arr) {\n let popped = arr.pop(); // Change this line\n let shifted = arr.shift(); // Change this line\n return [shifted, popped];\n}", "function shift(arr) {\n var shifted = splice(arr, 0, 1);\n return {\n array: shifted.array,\n val: arr[0]\n };\n}", "function popShift(arr) {\r\n let popped = arr.pop(); // Change this line\r\n let shifted = arr.shift(); // Change this line\r\n return [shifted, popped];\r\n}", "function applyShift(array) {\n\t// create a shifted variable\n\tlet shifted;\n\t// assign it to an expression removing the first element from the array\n\tshifted = array.shift();\n\t// return the shifted variable\n\treturn shifted;\n}", "function popShift(arr) {\n let popped = arr.pop(); // change this line\n let shifted = arr.shift();// change this line\n return [shifted, popped];\n}", "function arrShift(arr) {\n var newArray = [];\n for (var i = 1; i <= arr.length; i++) {\n if (i <= arr.length - 1) {\n newArray.push(arr[i]);\n } else if (i = arr.length) {\n newArray.push(0);\n }\n\n }\n var arr = newArray;\n return arr;\n\n}", "static cycle(arr, shift) {\n var tReturn = arr.slice(0);\n for (var tI = 0; tI < shift; tI++) {\n var tmp = tReturn.shift();\n tReturn.push(tmp);\n }\n return tReturn;\n }", "function shift(arr, datum) {\n var ret = arr[0];\n for (var i = 1; i < arr.length; i++) {\n arr[i-1] = arr[i];\n }\n arr[arr.length - 1] = datum;\n return ret;\n }", "function shiftLeft(arr) {\n var temp = 0;\n\n for (i = 0; i < arr.length; i++) {\n temp = arr[i + 1];\n arr[i] = temp\n\n }\n\n arr.pop()\n arr.push(0)\n return arr\n}", "function unshift(arr){\n console.log(arr.unshift('bananana','pansies'))\n console.log(arr)\n}", "function shift(array) {\n var newLen = array.length - 1;\n var value = array[0];\n\n for (var i = 0; i < array.length; i++) {\n array[i] = array[i + 1];\n }\n\n array.length = newLen;\n return value;\n}", "function shiftValues(arrX) {\r\n var length = arrX.length\r\n for (var i = 0; i < length - 1; i++) {\r\n arrX[i] = arrX[i + 1];\r\n }\r\n arrX[arrX.length - 1] = 0\r\n console.log(\"\\n\\nShift Array Values: [1, 2, 3]\")\r\n console.log(arrX)\r\n}", "immutablePush(array, newItem){\n return [ ...array, newItem ]; \n }", "function shift(array) {\n return [array[0], array.splice(0, 1)][0];\n}", "function shift(arr) {\n var firstElement = arr[0];\n var i;\n for (i = 1; i < arr.length; i++) {\n arr[i - 1] = arr[i];\n }\n arr.length = arr.length - 1;\n return firstElement;\n}", "unshift() {\n _checkManualPopulation(this, arguments);\n\n let values = [].map.call(arguments, this._cast, this);\n values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);\n [].unshift.apply(this, values);\n this._registerAtomic('$set', this);\n this._markModified();\n return this.length;\n }", "unshift() {\n _checkManualPopulation(this, arguments);\n\n let values = [].map.call(arguments, this._cast, this);\n values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);\n [].unshift.apply(this, values);\n this._registerAtomic('$set', this);\n this._markModified();\n return this.length;\n }", "rotateArr(arr, shift) {\n return _.flatten([arr.slice(-shift), arr.slice(0, -shift)], true);\n }", "function WithoutShift(arr){\n for(var i = 0; i < arr.length -1; i++){\n arr[i] = arr[i + 1];\n }\n arr[arr.length - 1] = 0\n console.log(arr);\n}", "function shift(arr) {\r\n let result;\r\n\r\n if (arr.length !== 0) {\r\n result = arr.splice(0, 1).pop();\r\n }\r\n\r\n return result;\r\n}", "function unshift(arr) {\n var items = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n items[_i - 1] = arguments[_i];\n }\n arr = arr.concat(flatten(items));\n return {\n array: arr,\n val: arr.length\n };\n}", "function mov(ori, des) { \n des.push(ori.pop()); \n}", "function shiftArray(a)\n {\n let tmp = a[0];\n\n for (let j = 1; j < a.length; j++)\n {\n a[a.length-1] = a[j]\n a[j] = tmp;\n tmp = a[a.length-1];\n }\n\n return a;\n }", "function shiftArr(arrayObj) {\n if (Array.isArray(arrayObj) && (arrayObj.length == 4)) {\n for (var i = 0; i < 3; i++) {\n for (var j = 0; j < 7; j++) {\n for (var k = 0; k < 48; k++) {\n arrayObj[i][j][k] = arrayObj[i + 1][j][k];\n }\n }\n }\n }\n\n}", "function shift(array, k){\n let tempOne = 0;\n let tempTwo = 0;\n for(let i = 0; i < 1; i++){\n if(array.length < 2){\n return false;\n }\n tempOne = array[0]; // 0 = 1\n array[0] = array[array.length - 1]; // 1 = 4\n array[array.length - 1] = tempOne; \n }\n return array;\n}", "function leftShiftOne(arr)\n{\n\tvar tmp = arr[0];\n\tfor (var i = 1; i < arr.length; i++)\n\t{\n\t\tarr[i - 1] = arr[i];\n\t}\n\tarr[arr.length - 1] = tmp;\n}", "function shiftToLeft(arr) {\n for ( let i = 0; i < arr.length-1; i++) {\n arr[i] = arr[i+1];\n }\n arr.pop();\n // console.log(arr);\n return arr;\n}", "function shiftToLeft(arr) {\n for ( let i = 0; i < arr.length-1; i++) {\n arr[i] = arr[i+1];\n }\n arr.pop();\n // console.log(arr);\n return arr;\n}", "shift() {\n const ret = [].shift.call(this);\n this._registerAtomic('$set', this);\n this._markModified();\n return ret;\n }", "shift() {\n const ret = [].shift.call(this);\n this._registerAtomic('$set', this);\n this._markModified();\n return ret;\n }", "function shiftArrayValues(arr){\n for (let i=1;i<arr.length;i++){\n arr[i-1] = arr[i];\n }\n arr[arr.length-1] = 0;\n return arr;\n}", "function pushFront(arr, val){\n for (var i = arr.length; i > 0; i --){\n console.log(i+\" arr[\"+arr[i]+\"]\");\n arr[i] = arr[i -1];\n }\n arr[0] = val;\n return arr;\n}", "function popShift(arr) {\n let popped = arr.pop();\n let shifted = arr.shift();\n return [shifted, popped];\n}", "function unshift(array, value) {\n for (var i = array.length; i > 0; i--) {\n array[i] = array[i - 1];\n }\n\n array[0] = value;\n return array.length;\n}", "function myArrayFunction(arr) {\n var myNewPets = [...arr];\n myNewPets.push(\"Bird\", \"Fish\");\n myNewPets.pop(\"Fish\");\n myNewPets.shift(\"Dog\");\n myNewPets.unshift(\"Lion\");\n console.log(myNewPets);\n}", "function PushFront(arr, val){\n arr.push(1);\n for(var i = arr.length - 1; i > 0; i--){\n arr[i] = arr[i -1];\n }\n arr[0] = val;\n }", "function unshift(array, value) {\n for (var i = array.length; i >= 0; i--) {\n array[i] = array[i -1];\n }\n\n array[0] = value;\n return array.length;\n}", "function rotateLeft(array){\n var x = array.shift()\n array.push(x)\n console.log(array)\n}", "function pushFront(arr, val) {\n\n }", "function steamrollArray(arr) {\n var newArr = [];\n // var arrCopy = [...arr];\n var arrLength = arr.length;\n var n = 0;\n while (arr.length > 0) {\n var val = arr.shift();\n if (Array.isArray(val)) { \n arr = val.concat(arr);\n } else {\n newArr.push(val);\n }\n }\n console.log(newArr);\n return newArr;\n }", "shift() {\n if (this.isEmpty()) {\n console.warn(`Cannot do operation shift on empty list`);\n return;\n }\n\n let temp = this.arr[0];\n\n shiftLeft(this, 0);\n\n --this.lastIndex;\n\n shrinkIfSparse(this);\n\n return temp;\n }", "function PushFrontOne(arr, val){\n for(var i = arr.length - 1; i >= 0; i--){\n arr[i + 1] = arr[i]\n }\n arr[0] = val;\n console.log(arr);\n}", "function r(){for(this.shift=[\"\\n\"],this.step=\" \",maxdeep=100,ix=0,ix=0;ix<maxdeep;ix++)this.shift.push(this.shift[ix]+this.step)}", "function testArrayPush(arr) {\n arr.push(100);\n console.log(arr);\n}", "function Array_push()\n\t{\n\t\tvar i = 0;\n\t\tif( this instanceof Array )\n\t\t{\n\t\t\ti = this.length;\n\t\t\t\n\t\t\t// Preallocation of array\n\t\t\tif( arguments.length > 0 )\n\t\t\t\tthis[arguments.length + this.length - 1] = null;\n\t\t\t\n\t\t\tfor( ; i < this.length; ++i )\n\t\t\t\tthis[i] = arguments[i - this.length + arguments.length];\n\t\t}\t\t\n\t\treturn i;\n\t}", "function shiftToLeft(arr, ind){\n if(arr.length >= 3 && arr[ind+1] && arr[ind+2]){\n var temp1 = arr[ind+1];\n var temp2 = arr[ind+2];\n arr[ind+2] = arr[ind];\n arr[ind+1] = temp2;\n arr[ind] = temp1;\n return arr;\n }else{\n console.log(\"out of bounds\");\n }\n}", "function a(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "unshift(...items) {\n const newThis = [...items, ...this];\n const newLength = newThis.length;\n for (let i = 0; i < newLength; i++) {\n if (i < this.length) {\n this[i] = newThis[i];\n }\n else {\n this.push(newThis[i]);\n }\n }\n return newLength;\n }", "push(val) {\n\n\n }", "function push(val) {\n stack[++topp] = val;\n \n}", "function shift(ary) {\n if (ary === []) { return }\n else {\n return ary.splice(0, 1)[0]\n }\n}", "function pushFront(arr,val){\n for(var i = arr.length - 1; i >= 0; i++){\n arr[i + 1] = arr[i]\n }\n arr[0] = val\n console.log(arr)\n}", "function shiftArrayValsLeft(arr){\n for(var i = 1; i < arr.length; i++){\n arr[i - 1] = arr[i]\n }\n arr[arr.length - 1] = 0\n return arr\n}", "function push(arr, newItem){\n[arr.length] = newItem;\n console.log(arr)\n}", "function push(array) {\n var lastIndex = array.length -1;\n \n for (var i = 1; i < arguments.length; i++) {\n array[lastIndex + i] = arguments[i];\n }\n\n return array.length\n}", "function shiftValues(arr) {\n for ( let i = 0 ; i < arr.length ; i++) {\n console.log('index is ', i);\n if ( i === 0 ) {\n }\n else if ( i === arr.length-1 ) {\n console.log('index is ', i)\n arr[arr.length-1] = 0;\n } \n else {\n arr[i-1] = arr[i]\n }\n }\n console.log(arr);\n}", "function steamrollArray(arr) {\n \n var output = [],\n iteration = 1;\n \n // iterate as long as arr has length\n while (arr.length > 0) {\n \n console.log('--------- Loop ' + iteration + ' ---------');\n console.log(' Input: ', arr);\n \n // capture 1st element of innput array\n var elem = arr.shift();\n console.log(' Shifting: ', elem);\n console.log(' Leftovers: ', arr);\n \n if (Array.isArray(elem)) {\n // elem = array, reassign arr, adding \n arr = elem.concat(arr);\n } else {\n // elem != array, push elem to output\n output.push(elem);\n }\n \n console.log(' New array: ', arr);\n console.log('Output arr: ', output);\n \n // increment iteration - only used for console output\n iteration += 1;\n \n }\n \n return output;\n \n}", "function cyclicShiftLeft(theArray, positions) {\r\n var temp = theArray.slice(0, positions);\r\n theArray = theArray.slice(positions).concat(temp);\r\n return theArray;\r\n}", "function push(array) {\n return [array.length, array.push(...Object.values(arguments).slice(1))][0];\n}", "function e(t,i){for(;i+1<t.length;i++)t[i]=t[i+1];t.pop()}", "function pushFront(arr, val){\n for(var i = arr.length-1; i >= 0; i--){\n arr[i+1] = arr[i];\n }\n arr[0] = val;\n return arr;\n}", "_emitArray(arr) {\n for (let i = arr.length - 1; i >= 0; i--) {\n this.emitPush(arr[i]);\n }\n return this.emitPush(arr.length).emit(OpCode.PACK);\n }", "function shiftIt(nums){\n\tlet y = 0;\n\n\tfor ( let i = 0 ; i < nums.length ; i ++ ){\n\t\n\t\tif( nums[i] !== 0 ){\n\t\t\t\tlet temp = nums[i]\n\t\t\t\tnums[i] = nums[y]\n\t\t\t\tnums[y] = temp;\n\t\t\t\ty++;\n\t\t\t}\n\t\t}\n\t}", "function elementshift(pmsg,i)\n{\n var tempindex = pmsg.indexOf(errormsg[i]);\n \n for(var count=tempindex;count<pcont;count++)\n { \n pmsg[count]=pmsg[count+1]; \n } \n pmsg[pcont]=errormsg[i]; \n return pmsg;\n}", "function copyAndPush(arr, obj) {\n var result = arr.slice();\n result.push(obj);\n return result;\n}", "push (obj, getterSetter = this.sharedGetterSetter) {\n if (this.length === this.size) this.extendArrays(this.deltaSize)\n getterSetter.ix = this.length++\n for (const key in obj) getterSetter[key] = obj[key]\n }", "function panggilShift() {\n var kota = ['bandung','garut','jakarta','cirebon','jogja']\n //console.log(kota);\n console.log('-------------');\n var yangDihapus = []\n for (var i = 0; i < 3; i++) {\n k = kota.shift()\n yangDihapus.push(k)\n console.log(k);\n }\n console.log('ini yg di hapus bray====', yangDihapus);\n\n return kota\n}", "push(...vs) {\n vs.forEach(v => { this.store[this.length] = v; this.length += 1; });\n }", "push(value) {\n this.data.unshift(value);\n }", "dequeue() {\r\n this.Array.shift();\r\n}", "shift() {\n let ret = this[0];\n for (let i = 0; i < __classPrivateFieldGet(this, _length); ++i)\n this[i] = this[i + 1];\n delete this[__classPrivateFieldSet(this, _length, +__classPrivateFieldGet(this, _length) - 1)];\n return ret;\n }", "function shiftArrayValsLeft(arr) {\n for (var ix = 1; ix < arr.length; ix++) {\n arr[ix -1] = arr[ix];\n }\n arr.length--;\n return arr;\n}", "function rltshift () {\n}", "function applyPush(array, element) {\n\t// add the element to the back of the array\n\tarray.push(element);\n\t// return the array\n\treturn array;\n}", "unshift(item) {\n for (let i = this.length; i > 0; i--) {\n this.data[i] = this.data[i - 1];\n }\n this.data[0] = item;\n this.length++;\n return this.data;\n }", "shiftItems(index) {\n for (let i = index; i < this.length - 1; i++) {\n this.data[i] = this.data[i + 1];\n }\n delete this.data[this.length - 1];\n this.length--;\n }", "function copyMachine(arr, num) {\n let newArr = [];\n while (num >= 1) {\n // Only change code below this line\nnewArr.push([...arr]);\n // Only change code above this line\n num--;\n }\n return newArr;\n}", "function a(e,t){var n=i.length?i.pop():[],a=o.length?o.pop():[],s=r(e,t,n,a);return n.length=0,a.length=0,i.push(n),o.push(a),s}", "function shiftArrayValsLeft(arr) {\n for (var ix = 1; ix < arr.length; ix++) {\n arr[ix -1] = arr[ix];\n }\n arr[arr.length - 1] = 0;\n return arr;\n}", "function applyUnshift(array, element) {\n\t// add the element to the front of the array\n\tarray.unshift(element);\n\t// return the array\n\treturn array;\n}", "function rotate(arr, shiftBy){\n add_index = arr.length;\n for (i=0; i < arr.length; i++){\n if(i !== shiftBy+1){\n arr[add_index] = arr[i];\n add_index = add_index + 1;\n }\n else{\n break;\n }\n }\n for(j = 0; j < shiftBy+1; j ++){\n arr.shift();\n }\n return arr;\n}", "push(...values) {\n return stack.push(...values);\n }", "push(...rest) {\n return this.splice(this.length, 0, ...rest);\n }", "function mixedNumbers(arr) {\r\n // Only change code below this line\r\n arr.unshift('I', 2,'three')\r\n arr.push(7, 'VIII', 9)\r\n // Only change code above this line\r\n return arr;\r\n}", "function pushFront(arr,val){\n for (var index = arr.length; index >= 0; index--){\n var currentValue = arr[index-1];\n arr[index] = currentValue;\n }\n arr[0] = val;\n return arr;\n}", "function mixedNumbers(arr) {\n // change code below this line\narr.unshift('I', 2, 'three');\narr.push(7, 'VIII', 9);\n // change code above this line\n return arr;\n}", "function push(e) {\n topp++;\n stackarr[topp] = e;\n}", "shift(_this) {\n _this.array[0] && _this.array[0].dom && _this.alertBoxElement.removeChild(_this.array[0].dom);\n _this.array.length && _this.array.shift();\n }", "function pushFront(arr, new_val){\n arr.push(new_val) \n for (var i = 0; i < arr.length-1; i++){\n var temp = arr[i];\n arr[i] = arr[arr.length-1]\n arr[arr.length-1] = temp\n }\n}", "shift(delta) { start+=delta }", "shift(delta) { start+=delta }", "shift() {\n return this.splice(0, 1)[0];\n }", "function mixedNumbers(arr) {\n // Only change code below this line\narr.unshift('I', 2, 'three');\narr.push(7, 'VIII', 9);\n // Only change code above this line\n return arr;\n}" ]
[ "0.71770066", "0.69691795", "0.69443846", "0.68355906", "0.6772296", "0.6729929", "0.6707596", "0.66854024", "0.6674943", "0.6667162", "0.66634804", "0.6663368", "0.6655321", "0.66288793", "0.6624209", "0.6587704", "0.6564944", "0.6561068", "0.65374446", "0.6514341", "0.6500662", "0.64893144", "0.6437611", "0.6397326", "0.6397326", "0.638325", "0.6383174", "0.6366911", "0.63545203", "0.63408095", "0.63337785", "0.63288987", "0.6326518", "0.63117254", "0.6281116", "0.6281116", "0.62633264", "0.62633264", "0.6250789", "0.6240277", "0.6237248", "0.62207913", "0.6213222", "0.6212739", "0.61884016", "0.6187994", "0.6171702", "0.6146524", "0.61367667", "0.6124496", "0.6117953", "0.6101488", "0.6085061", "0.60794914", "0.6075513", "0.6068235", "0.606644", "0.6059618", "0.6053172", "0.6053079", "0.6051574", "0.6049767", "0.6036927", "0.6034826", "0.60334283", "0.6024614", "0.6017739", "0.6012439", "0.6012391", "0.6006429", "0.5985435", "0.59813863", "0.5966262", "0.5962826", "0.596023", "0.5959608", "0.5959578", "0.59587616", "0.5958067", "0.59546", "0.5935079", "0.59349716", "0.59314674", "0.5927021", "0.5922246", "0.5921402", "0.59213084", "0.5921053", "0.5917784", "0.59142804", "0.5913584", "0.5910494", "0.5908276", "0.59079635", "0.5905518", "0.59054834", "0.5904343", "0.5887689", "0.5887689", "0.58874375", "0.587808" ]
0.0
-1
aug 4 math undefined
function abTest(a, b) { if (a > 0 || b > 0) { return undefined; } else { console.log("not undefined"); } return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function MathUtils() {}", "function math(m, b){\n return (-1 * b)/m\n}", "get std_eqn() {\n if (this.type == 0) {\n // parabola\n if (this.o == 0)\n return \"$$(y\"+ (this.k > 0 ? \"-\" : \"+\")+ Math.abs(this.k) +\")^2 = \" + this.lr + \"(x\" + (this.h > 0 ? \"-\" : \"+\") + Math.abs(this.h) + \")$$\"\n else\n return \"$$(x\"+ (this.h > 0 ? \"-\" : \"+\")+ Math.abs(this.h) +\")^2 = \" + this.lr + \"(y\" + (this.k > 0 ? \"-\" : \"+\") + Math.abs(this.k) +\")$$\"\n } else if (this.type == 1) {\n return \"$$\\\\dfrac{(x\"+ (this.h > 0 ? \"-\" : \"+\") + Math.abs(this.h) + \")^2}{\"+this.a+\"^2} + \\\\dfrac{(y\"+(this.k > 0 ? \"-\" : \"+\")+Math.abs(this.k)+\")^2}{\"+this.b+\"^2} = 1$$\"\n } else {\n if (this.o == 0)\n return\"$$\\\\dfrac{(x\"+ (this.h > 0 ? \"-\" : \"+\") + Math.abs(this.h) + \")^2}{\"+this.a+\"^2} - \\\\dfrac{(y\"+(this.k > 0 ? \"-\" : \"+\")+Math.abs(this.k)+\")^2}{\"+this.b+\"^2} = 1$$\"\n else\n return \"$$\\\\dfrac{(y\"+ (this.k > 0 ? \"-\" : \"+\") + Math.abs(this.k) + \")^2}{\"+this.a+\"^2} - \\\\dfrac{(x\"+(this.h > 0 ? \"-\" : \"+\")+Math.abs(this.h)+\")^2}{\"+this.b+\"^2} = 1$$\"\n }\n }", "get y() { return init.h - inProptn(1, 7) * 1.5; }", "function math1 (value) {\r\n\treturn (value * 1.5) - 1;\r\n}", "function Calculation() {\n }", "function e(t,n){0}", "function e(t,n){0}", "function gradenumeric() {\n //var fasit = qobj.fasit;\n // for numeric the fasit is a template like this\n // 33.13:0.5 the answer is 33.13 +- 0.5\n // 32.0..33.5 the answer must be in the interval [32.0,33.5]\n // TODO a..b is the same as rng:a,b -- should we drop one of them?\n // nor:m,s the answer x is scored as e^-((1/(2) * ((x-m)/s)^2\n // sym:exp the answer x is scored as pycas(x - exp) == 0\n // eva:exp|a|b the answer x is scored as eval(x) == exp\n // zro:exp|a the answer x is correct if |exp(x)| < a\n // reg:r the answer x is scored as regular exp match for x,r\n // lis:a:A,b:B,c the answer x is scored as x == one of a,b,c - score is given by :A or 1\n var cor = ff;\n switch (swi) {\n case 'nor:':\n var norm = tch.split(',');\n var med = +norm[0];\n var std = +norm[1];\n var ex = ((uanum - med)/std);\n var sco = Math.pow(2.712818284,-(0.5*ex*ex));\n if (sco > 0.05) {\n ucorr += sco;\n feedb = Math.floor((1-sco)*10);\n } else {\n uerr++;\n }\n cor = med;\n break;\n case 'rng:': // [[rng:10,20]]\n var lims = tch.split(',');\n var lo = +lims[0];\n var hi = +lims[1];\n if (uanum >= lo && uanum <= hi) {\n ucorr += 1;\n feedb = 1;\n } else {\n uerr++;\n }\n cor = lo;\n break;\n case 'sym:':\n simple = false; // callback done after sympy is finished\n // fixup for 3x => 3*x etc\n var completed = { comp:0, lock:0 };\n if (uatxt == undefined || uatxt == '') {\n callback(score,'no input',completed,ua,1);\n } else {\n var elem = tch.split('|');\n var target = elem[0];\n var differ = elem[1]; // optional text that useranswer must NOT EQUAL\n // for symbolic equality - dont accept original equation\n // or new eq that is longer (not simpler)\n if (differ && (differ == uatxt || differ.length < uatxt.length) ) {\n callback(score,'sicut prius',completed,ua,1);\n } else {\n var ufu = sympify(target); // fasit\n cor = ufu;\n var fafu = sympify(uatxt); // user response\n var diffu = sympify(differ); // if testing equality - must be as short or shorter than this\n var intro = '# coding=utf-8\\n'\n + 'from sympy import *\\n';\n var text = 'x,y,z,a,b,c,d,e,f,u,v,w = symbols(\"x,y,z,a,b,c,d,e,f,u,v,w\")\\n'\n + 'a1=sympify(\"'+ufu+'\")\\n'\n + 'b1=sympify(\"'+fafu+'\")\\n'\n + 'c1=a1-b1\\n'\n + 'print simplify(c1)\\n';\n var score = 0;\n console.log(intro+text);\n fs.writeFile(\"/tmp/symp\"+now, intro+text, function (err) {\n if (err) { callback(score,'error1',completed,ua,1); throw err; }\n try {\n var child = exec(\"/usr/bin/python /tmp/symp\"+now, function(error,stdout,stderr) {\n fs.unlink('/tmp/symp'+now);\n //console.log(\"err=\",stderr,\"out=\",stdout,\"SOO\");\n if (error) {\n console.log(error,stderr);\n callback(score,'error2',completed,ua,1);\n } else {\n if (stdout && stdout != '') {\n //console.log(stdout);\n var feedb = stdout;\n var eta = +stdout.trim();\n if (_.isFinite(eta) && eta == 0 || Math.abs(eta) < 0.001 ) {\n score = 1\n if (differ) {\n // we are testing for simplification\n // minimum assumed to be ufu, diffu.length is original length (unsimplified)\n var span = diffu.length - ufu.length; // max shortening possible\n var dif = fafu.length - ufu.length; // how much shorter\n if (span > 0) {\n score = Math.max(0,Math.min(1,1-dif/span));\n // relative score depending on how many chars\n // you have shortened the eq - span assumed to be max\n feedb = (score > 0.8) ? 'Good answer' : (score > 0.5) ? 'Nearly' : 'Not quite';\n }\n } else {\n feedb = 'Correct answer';\n }\n } else {\n feedb = 'Incorrect answer';\n score = 0;\n }\n var cutcost = (attnum > 2) ? Math.min(1,cost*attnum*2) : cost*attnum;\n var adjust = score * (1 - cutcost - hintcost*hintcount);\n //console.log(qgrade,adjust,attnum,cost);\n score = aquest.points * Math.max(0,adjust);\n }\n //console.log(\"CAME SO FAR SYMBOLIC PYTHON \",eta,score,stdout,stderr,error);\n callback(score,feedb,completed,ua,1);\n }\n });\n } catch(err) {\n callback(score,'error3',completed,ua,1);\n }\n });\n }\n }\n break;\n case 'zro:':\n // zro:exp|a the answer x is correct if |exp(x)| < a\n var elem = tch.split('|');\n var exp = elem[0];\n var tol = elem[1] || 0.001 ;\n var sco = 0;\n exp = normalizeFunction(exp,0,ua);\n var num = +uatxt;\n if (uatxt != undefined && uatxt != '' && uatxt != '&nbsp;&nbsp;&nbsp;&nbsp;') {\n // user supplied root checked\n console.log(\"Checking if root:\",uatxt,exp);\n var bad = false;\n try {\n var fu1 = new Function(\"x\",' with(Math) { return ' +exp+'; }' );\n var f1 = Math.abs(fu1(num));\n console.log(\"Evalueated to \",f1,tol)\n if (f1 <= tol) {\n sco = 1;\n feedb = '1'; // mark as correct\n } else {\n bad = true;\n }\n }\n catch (err) {\n console.log(\"EVAL fu \",err);\n bad = true;\n }\n if (bad) {\n uerr++;\n } else {\n ucorr += sco;\n }\n }\n cor = 'NaN';\n break;\n case 'eva:':\n // eva:exp|a|b the answer x is scored as eval(x) == exp\n // the user answer must NOT EQUAL a,\n // Quiz: multiply (x+6) by 2, do not accept 2*(x+2)\n // eva:2x+12|2(x+6)\n // the answer should be as short as b (punished for extra chars - up to a.length)\n // simplify (2+4)*(7-5)\n // eva:12|(2+4)*(7-5)|12\n // so the constraints are : evaluate as 12, not eq \"(2+4)*(7-5)\" , as short as 12\n // partial score if between \"12\" and \"(2+4)*(7-5)\" in length\n var elem = tch.split('|');\n var exp = elem[0];\n var differ = elem[1]; // optional text that useranswer must NOT EQUAL\n var simply = elem[2]; // optional text that useranswer should match in length\n var lolim = -5;\n var hilim = 5;\n var sco = 0;\n exp = normalizeFunction(exp,0,ua);\n cor = exp;\n var ufu = normalizeFunction(uatxt,0);\n var udiff =normalizeFunction(differ,0);\n //console.log(exp,lolim,hilim,ufu);\n if (differ && (differ === uatxt || udiff === ufu) ) {\n uerr++;\n console.log(\"sicut prius\");\n } else if (exp === ufu) {\n ucorr++; // they are exactly equal\n feedb = '1'; // mark as correct\n //console.log(\"exact\");\n } else {\n //console.log(\"EVA:\",exp,ufu);\n if (uatxt != undefined && uatxt != '' && uatxt != '&nbsp;&nbsp;&nbsp;&nbsp;') {\n // user supplied function numericly tested against fasit\n // for x values lolim .. hilim , 20 steps\n var dx = (+hilim - +lolim) / 20;\n var bad = false;\n try {\n //return 'with(Math) { return ' + fu + '; }';\n var fu1 = new Function(\"x\",' with(Math) { return ' +exp+'; }' );\n var fu2 = new Function(\"x\",' with(Math) { return ' +ufu+'; }' );\n var reltol,f1,f2;\n for (var pi=0,xi = lolim; pi < 20; xi += dx, pi++) {\n //console.log(\"testing with \",xi);\n f1 = fu1(xi);\n f2 = fu2(xi);\n if (!isFinite(f1) && !isFinite(f2)) {\n reltol = 0;\n //console.log(\"NaN/inf\",xi,reltol);\n } else {\n reltol = f1 ? Math.abs(f1-f2)/Math.abs(f1) : Math.abs(f1-f2);\n }\n //console.log(xi,f1,f2,reltol);\n if (reltol > 0.005) {\n bad = true;\n break;\n }\n sco += reltol;\n }\n }\n catch (err) {\n console.log(\"EVAL fu \",err);\n bad = true;\n }\n if (bad) {\n uerr++;\n } else {\n if (simply) {\n // we are testing for simplification\n // minimum assumed to be simply.length, differ.length is original length (unsimplified)\n var span = differ.length - simply.length; // max shortening possible\n var dif = Math.min(span,Math.max(0,differ.length - ufu.length)); // how much shorter\n if (span > 0) {\n sco = 1 - Math.max(0,Math.min(1,dif/span));\n // relative score depending on how many chars\n // you have shortened the eq - span assumed to be max\n }\n }\n ucorr += 1 - sco;\n feedb = '1'; // mark as correct\n }\n }\n }\n break;\n case 'reg:':\n try {\n tch = tch.trim();\n var myreg = new RegExp('('+tch+')',\"gi\");\n var isgood = false;\n uatxt.replace(myreg,function (m,ch) {\n //console.log(\"REG:\",uatxt,tch,m,ch);\n isgood = (m == uatxt);\n });\n if ( isgood) {\n ucorr++; // good match for regular expression\n feedb = '1'; // mark as correct\n } else if (uatxt != undefined && uatxt != '' && uatxt != '&nbsp;&nbsp;&nbsp;&nbsp;') {\n uerr++;\n }\n }\n catch (err) {\n console.log(\"BAD REG EXP\",tch);\n if (uatxt != undefined && uatxt != '' && uatxt != '&nbsp;&nbsp;&nbsp;&nbsp;') {\n uerr++;\n }\n }\n cor = 'NaN';\n break;\n case 'lis:':\n var goodies = tch.split(',');\n if (goodies.indexOf(uatxt) > -1) {\n ucorr++;\n feedb = '1'; // mark as correct\n } else if (uatxt != undefined && uatxt != '' && uatxt != '&nbsp;&nbsp;&nbsp;&nbsp;') {\n uerr++;\n }\n cor = goodies[0];\n break;\n default:\n var num,tol,cor;\n cor = ff;\n //console.log(\"trying numeric\",ff,uatxt );\n if (ff == num) feedb = 1;\n if ( ff.indexOf(':') > 0) {\n // we have a fasit like [[23.3:0.5]]\n var elm = ff.split(':');\n num = +elm[0];\n tol = +elm[1];\n cor = num;\n //console.log(\"NUM:TOL\",ff,num,tol,uanum);\n } else if ( ff.indexOf('..') > 0) {\n // we have a fasit like [[23.0..23.5]]\n var elm = ff.split('..');\n var lo = +elm[0];\n var hi = +elm[1];\n tol = (hi - lo) / 2;\n num = lo + tol;\n cor = num;\n //console.log(\"LO..HI\",ff,lo,hi,num,tol,uanum);\n } else {\n num = +ff; tol = 0.0001;\n }\n if ( ff == 'any' || ff == 'anytext' || Math.abs(num - uanum) <= tol) {\n ucorr++;\n feedb = '1'; // mark as correct\n } else if (uatxt != undefined && uatxt != '' && uatxt != '&nbsp;&nbsp;&nbsp;&nbsp;') {\n uerr++;\n }\n break;\n }\n return cor;\n }", "function e( g , nu )\n {\n\n return ( 2.0 * g * (1.0 + nu) );\n\n }", "exponent() { return new Decimal(((Array.isArray(tmp.ma.mastered))?tmp.ma.mastered.includes(this.layer):false)?1.07:1.1) }", "wu_c(){\n return (1.2*(this.DL+this.SDL) + 1.6*this.LL)*(this.Sj/12)\n }", "function mathematicsFunction (a,b) {\n var plus = a + b;\n return plus;\n}", "Ec(){\r\n return 57*Math.pow(this.fc,0.5)\r\n }", "exponent() { return new Decimal(((Array.isArray(tmp.ma.mastered))?tmp.ma.mastered.includes(this.layer):false)?.008:.0075) }", "exponent() { return new Decimal(((Array.isArray(tmp.ma.mastered))?tmp.ma.mastered.includes(this.layer):false)?1.4:1.85) }", "function Vypiscislo(x)\n{\n return +x-3\n}", "function ex1(){\n return 12+20\n }", "function mathFunctions() {\n console.log(\"Math.PI : \" + Math.PI);\n console.log(\"Math.LOG10E : \" + Math.LOG10E);\n console.log(\"Math.abs(-10) : \" + Math.abs(-10));\n console.log(\"Math.floor(1.99) : \" + Math.floor(1.99));\n console.log(\"Math.ceil(1.01) : \" + Math.ceil(1.01));\n console.log(\"Math.random() : \" + Math.random());\n}", "function mathFunctions() {\n console.log(\"Math.PI : \" + Math.PI);\n console.log(\"Math.LOG10E : \" + Math.LOG10E);\n console.log(\"Math.abs(-10) : \" + Math.abs(-10));\n console.log(\"Math.floor(1.99) : \" + Math.floor(1.99));\n console.log(\"Math.ceil(1.01) : \" + Math.ceil(1.01));\n console.log(\"Math.random() : \" + Math.random());\n}", "exponent() { return ((Array.isArray(tmp.ma.mastered))?tmp.ma.mastered.includes(this.layer):false)?new Decimal(1.4):new Decimal(1.85) }", "function MathRecognitionData() {\n }", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function n(t,e){0}", "function zero(){ return 0;}", "function Math() {\r\n// EventEmitter.call(this);\r\n}", "function mi(t,e){0}", "exponent() { return new Decimal(((Array.isArray(tmp.ma.mastered))?tmp.ma.mastered.includes(this.layer):false)?.2:.125) }", "exponent() { return new Decimal(((Array.isArray(tmp.ma.mastered))?tmp.ma.mastered.includes(this.layer):false)?.025:.02) }" ]
[ "0.71944296", "0.61095524", "0.6037894", "0.5964743", "0.59325355", "0.5914474", "0.5911294", "0.5911294", "0.5867642", "0.58452725", "0.58244795", "0.5816817", "0.5805406", "0.58046377", "0.5800606", "0.579539", "0.5756804", "0.573758", "0.5716843", "0.5716843", "0.569654", "0.5685487", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56817156", "0.56805575", "0.56755984", "0.5675058", "0.56740254", "0.5670811" ]
0.0
-1
Change progress bar action
function setProgressBar(curStep){ var percent = parseFloat(100 / steps) * curStep; percent = percent.toFixed(); $(".progress-bar") .css("width",percent+"%") .html(percent+"%"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function progressBar(action) {\n if(action == 1){\n\t element.setAttribute('max', numberOfQuestions); \n }\n else if(action == 2){\n element.setAttribute('value', questionIndexTracker);\n }\n else{\n Console.log(\"Error in progress bar selection 1 == set, 2 == record\")\n }\n}", "function updateProgress (){\n\tprogress.value += 30;\n}", "function updateProgressBar() {\n pbValue+=10;\n $('.progress-bar').css('width', pbValue+'%').attr('aria-valuenow', pbValue);\n $('.progress-bar').text(pbValue + \"%\");\n }", "function changeProgress(current, next, action) {\n //changing title\n $(\"#test_head_container span\").text(next);\n var progress, width, id;\n progress = document.getElementById(\"progress\");\n width = current * 34;\n if (action === \"next\") {\n //calling increase to change progress bar\n id = setInterval(increase, 20);\n } else {\n //calling decrease to change progress bar\n id = setInterval(decrease, 20);\n }\n //increasing progress bar\n function increase() {\n if (width >= next * 34) {\n clearInterval(id);\n } else {\n width += 1;\n progress.value = width;\n }\n }\n //decreasing progress bar\n function decrease() {\n if (width <= next * 34) {\n clearInterval(id);\n } else {\n width -= 1;\n progress.value = width;\n }\n }\n}", "function set_progress(percent)\n{\n\tconsole.log(\"XDDD\");\n\tdocument.getElementById(\"bar\").style.width=percent+\"%\";\n}", "function updateBar(){\n var bar = $('#progress');\n\tif (variables.progress < 100){\n\t\tvariables.progress += 5;\n\t\tbar.width(variables.progress + '%');\n\t} else {\n\t\tvariables.progress = 0;\n\t\tvariables.videos += 1;\n\t\tbar.width(\"0%\");\n\t\tclearKeys();\n\t\tloadRound();\n\t}\n}", "function progress(newWidth){\n\t$(\"#PBar\").css({width: newWidth + \"%\"});\n\t$(\"#PBar\").val(newWidth + \"%\");\n}", "function SetProgress(bar, value){\n\n // temporarily animate the bar\n bar.classList.add(\"progress-bar-animated\");\n\n // set the bar's new value\n bar.style.width = value+\"%\";\n bar.setAttribute(\"aria-valuenow\", value);\n bar.innerText = value + \"%\";\n\n // stop the animation after a pause\n setTimeout( () => {\n bar.classList.remove(\"progress-bar-animated\");\n }, 2000);\n}", "onprogress() {}", "function setProgress(percent) {\n $('#progressBar .progress-bar').css({width: percent + '%'});\n $('#percent').text(percent + '%');\n}", "_setProgress(v) {\n\t\tconst w = PROGRESSBAR_WIDTH * v;\n\t\tthis._fg.tilePositionX = w;\n\t\tthis._fg.width = PROGRESSBAR_WIDTH- w;\n\t}", "function updateProgress() {\n $(\"#progressBar\").css(\"width\", _progress + \"%\");\n }", "_progress() {\n\tconst currentProgress = this.state.current * ( 100 / this.state.questionsCount );\n this.progress.style.width = currentProgress + '%';\n\n\t// update the progressbar's aria-valuenow attribute\n this.progress.setAttribute('aria-valuenow', currentProgress);\n }", "function progressBarFull() {\n\t$(\"#progress-bar-yellow\").css(\"width\",\"100%\");\n\tprogressBarPoint = 100;\n}", "function changeProgressBar(bar, healthPercent) {\n bar.setAttribute(\"style\", \"width: \" + healthPercent + \"%\");\n if (healthPercent <= 50 && healthPercent >= 15) {\n bar.className += \" health-warning\";\n } else if (healthPercent <= 15) {\n bar.className += \" health-danger\";\n }\n}", "setProgress (value) {\n\n this.progressBar.style.width\n = (value || 0) +'%';\n }", "function moveProgressBar() {\n\n\tvar status = document.querySelector('#status');\n\ttime = 0;\n\n\tprogress = setInterval(green, 20);\n\n\tfunction green() {\n\t\tif (time >= 100) {\n\t\t\tclearInterval(progress);\n\t\t\texitGame();\n\t\t} else if (score >= 10) {\n\t\t\ttime +=1;\n\t\t} else {\n\t\t\ttime +=0.5;\n\t\t} status.style.width = time + \"%\";\n\t}\n}", "_updateProgressBar() {\n if (this.props.samplingState === 'timeout') {\n this.StatusAction.configure({\n progressbar: false,\n animation: false,\n trickle: false\n });\n return;\n }\n if (this.props.samplingState === 'error') {\n this.StatusAction.hide();\n }\n const progress = this.props.samplingProgress;\n // initial schema phase, cannot measure progress, enable trickling\n if (this.props.samplingProgress === -1) {\n this.trickleStop = null;\n this.StatusAction.configure({\n visible: true,\n progressbar: true,\n animation: true,\n trickle: true,\n subview: StatusSubview\n });\n } else if (progress >= 0 && progress < 100 && progress % 5 === 1) {\n if (this.trickleStop === null) {\n // remember where trickling stopped to calculate remaining progress\n const StatusStore = app.appRegistry.getStore('Status.Store');\n this.trickleStop = StatusStore.state.progress;\n }\n const newProgress = Math.ceil(this.trickleStop + (100 - this.trickleStop) / 100 * progress);\n this.StatusAction.configure({\n visible: true,\n trickle: false,\n animation: true,\n progressbar: true,\n subview: StatusSubview,\n progress: newProgress\n });\n } else if (progress === 100) {\n this.StatusAction.done();\n }\n }", "launchprogressbar() {\n\t\tlet percent = this.progressbar.attr(\"data-percent\"); // récupère le data 100% de l\"élément\n this.progressbar.animate( {\n \twidth: percent // on passe de 0% à 100%\n },this.timeout, \"linear\", () => {\n \tthis.progressbar.css(\"width\", 0); // une fois l'animation complète, on revient à 0\n });\n }", "function updateProgressBar(){\n // Update the value of our progress bar accordingly.\n $('#progress-bar').val((player.getCurrentTime() / player.getDuration()) * 100);\n }", "function setProgress(id, progress) {\n if (progress !== -1) {\n $('#progress-in-' + id).width(progress + '%');\n } else {\n $('#progress-out-' + id).remove();\n }\n }", "updateProgress() {\n this._Onprogress(this.state.CSVProgress * 100);\n }", "function setProgress(value) {\n\tdocument.getElementById(\"progressbar\").setAttribute(\"aria-valuenow\",value);\n\tdocument.getElementById(\"progressbar\").setAttribute(\"style\",\"width: \" +value+ \"%\");\t\n\tdocument.getElementById(\"progressbar\").innerHTML = (value+ \"%\"); \n}", "function changeProgressBar() {\n song.currentTime = progressBar.value;\n}", "function setProgressBar(curStep){\n var percent = parseFloat(50 / steps) * curStep;\n percent = percent.toFixed();\n $(\".barrapedido1\")\n .css(\"width\",percent+\"%\")\n .html(percent+\"%\"); \n }", "static finish() {\n this.progress = 100;\n setTimeout(() => {\n this.bar.style.width = `${this.progress}%`;\n }, 100);\n setTimeout(() => {\n this.parent.style.height = '0px';\n }, 1000);\n }", "function updateProgressBar(progress) {\n\n if (!progress) {\n progress = 0;\n }\n\n // get progress bar\n var progress_div = document.getElementById(\"training-progress\");\n\n if (!progress_div) {\n console.warn(\"Missing progress-bar element!\");\n return;\n }\n\n // update progress bar status\n var progress_str = String(progress) + \"%\";\n progress_div.style.width = progress_str;\n //progress_div.setAttribute(\"aria-valuenow\", String(progress));\n progress_div.innerHTML = progress_str;\n\n if (progress >= 100) {\n progress_div.classList.add(\"progress-bar-success\");\n progress_div.classList.add(\"progress-bar-striped\");\n }\n else {\n progress_div.setAttribute(\"class\", \"progress-bar\");\n }\n}", "updateProgressBar(percentage) {\n let $progressBar = document.getElementById(\"progress-bar\");\n this.progressBarObj.value = Math.min(\n 100,\n this.progressBarObj.value + percentage\n );\n $progressBar.style.width = this.progressBarObj.value + \"%\";\n $progressBar.valuenow = this.progressBarObj.value;\n $progressBar.innerText = this.progressBarObj.value + \"%\";\n }", "function updateProgress (event) {\r\n var elem = document.getElementById(\"bar\"); \r\n var width = 0;\r\n if (event.lengthComputable) {\r\n var percentComplete = event.loaded / event.total;\r\n width = parseInt(100 * percentComplete);\r\n elem.style.width = Math.max(4, width) + '%'; \r\n elem.innerHTML = '&nbsp;' + Math.max(1, width) + '%';\r\n } else {\r\n\t\t\t// Unable to compute progress information since the total size is unknown\r\n console.log(\"no progress indication available\");\r\n } // end if else length\r\n } // end function updateProgress (event) ", "function updateEditProgress (progress) {\n var total = progress.total\n var quorum = 0\n var missing = 0\n document.getElementById('prog').title = progress.collected +\n ' updated out of ' + total + ' members.'\n document.getElementById('prog-collected').style.width = quorum + '%'\n // document.getElementById('prog-collected').class = \"progress-bar-success\"\n document.getElementById('prog-collected').classList.remove('progress-bar-warning')\n document.getElementById('prog-collected').classList.add('progress-bar-success')\n // prog-missing now means \"extra votes after quorum has been reached.\"\n document.getElementById('prog-missing').style.width = -missing + '%'\n document.getElementById('prog-missing').class = 'progress-bar'\n document.getElementById('prog-missing').classList.add('progress-bar')\n document.getElementById('prog-missing').classList.remove('progress-bar-warning')\n // document.getElementById('prog-missing').classList.add('progress-bar-success')\n document.getElementById('prog-missing').classList.remove('progress-bar-striped')\n}", "function updateProgressBar(){\n // Update the value of our progress bar accordingly.\n $('#progress-bar').val((r.getCurrentTime() / r.getDuration()) * 100);\n}", "increaseProgressBar() {\n this.width += 100 / this.nbSecond * this.intervalTime / 1000; // calcul de la vitesse d'incrémentation en fonction du nombre de secondes total attendu\n $('#progress-bar').width(`${this.width}%`); // définition de la width\n if (this.width >= 100) {\n this.stopTimer(false);\n }\n this.timeSpent += this.intervalTime;\n }", "function updateProgressbarDisplay() {\n if (progressBarProgressionElement) {\n updateStep(progressBarProgressionElement)\n updateCounter()\n }\n }", "function updateProgress(value) {\n var progressBarStep = value*stepSize;\n $(\"#progress\").css(\"width\", progressBarStep + \"%\");\n $(\"#progress\").attr(\"aria-valuenow\", progressBarStep);\n $(\"#progress-current\").html(value);\n}", "function setProgressBar(curStep){\n var percent = parseFloat(100 / steps) * curStep;\n percent = percent.toFixed();\n $(\".progress-bar-1\")\n .css(\"width\",percent+\"%\")\n .html(percent+\"%\"); \n }", "function updateProgress(oEvent){}", "function setProgress(e) {\n const newTime = e.offsetX / progressRange.offsetWidth;\n elements.progressBar.style.width = `${newTime * 100}%`;\n elements.video.currentTime = newTime * video.duration;\n}", "function setProgress(currstep) {\n var percent = parseFloat(100 / widget.length) * currstep;\n percent = percent.toFixed();\n $(\".progress-bar\").css(\"width\", percent + \"%\").html(percent + \"%\");\n }", "function usar_update_progress_bar( percentage, speed ) {\n\t\tif ( typeof speed == 'undefined' ) {\n\t\t\tspeed = 150;\n\t\t}\n\t\t$( '.usar-progress' ).animate({\n\t\t\twidth: percentage\n\t\t}, speed );\n\t}", "function updateProgressBar(progress){\r\n //console.log(\"updateProgressBar:\"+progress);\r\n var jsProgress=$('.progress-bar');\r\n if(progress==null){\r\n jsProgress.attr('aria-valuetransitiongoal', parseInt(jsProgress.attr('aria-valuemax'))).progressbar();\r\n }\r\n else{\r\n if(parseInt(progress)>parseInt(jsProgress.attr('aria-valuemax'))){\r\n jsProgress.attr('aria-valuetransitiongoal', parseInt(jsProgress.attr('aria-valuemax'))).progressbar();\r\n }\r\n jsProgress.attr('aria-valuetransitiongoal', parseInt(progress+\"\")).progressbar();\r\n }\r\n}", "function setProgressBar(percent, e, num) {\n percentNum = (percent / 5) * 100;\n percent = percentNum.toString() + \"%\";\n $(\"#progressBar\" + num).css(\"width\", percent);\n }", "function updateProgress(percentage){\n\tvar elem = document.getElementById('progress-bar');\n\tvar width = 1;\n\t\n\twidth = percentage;\n\tif(width > 1) width = 1;\n\telem.style.width = percentage*100 + '%';\n\n\t\n}", "function setProgressBar(curStep){\n var percent = parseFloat(50 / steps) * curStep;\n percent = percent.toFixed();\n $(\".barrafinal\")\n .css(\"width\",percent+\"%\")\n .html(percent+\"%\"); \n }", "onProgress(percentage, count) {}", "function s2cProgress() {\n\t$('#s2cbar').css(\"width\", function() {\n\t\treturn $(this).attr(\"aria-valuenow\") + \"%\";\n\t});\n}", "function c2sProgress() {\n\t$('#c2sbar').css(\"width\", function() {\n\t\treturn $(this).attr(\"aria-valuenow\") + \"%\";\n\t});\n}", "function setProgressBar() {\n monthlyProgress = daysMetGoal/daysInMonth;\n monthlyProgress = Math.round(monthlyProgress * 100, 0);\n var barLength = 1;\n if(statIndex == 1){\n if(monthlyProgress > 0){\n\t\tbarLength = monthlyProgress * .9; //divide by 9/10 since the progress bar is only 90 pixels wide\n\t}\n \tstatDisplay.setCursor(90, 55);\n\tstatDisplay.writeString(font, 1, '| ' + monthlyProgress + '%', 1, true);\n }\n else if (statIndex == 0){\n\tif(progress > 0) {\n\t\tbarLength = progress * .9;\n\t}\n\tstatDisplay.setCursor(90, 55);\n \tstatDisplay.writeString(font, 1, '| ' + progress + '%', 1, true);\n }\n barLength = Math.round(barLength);\n if(barLength > 90){ //if over 90 pixels, max out at 90 to prevent overwriting pixels\n barLength = 90;\n }\n statDisplay.setCursor(1,1);\n statDisplay.drawLine(1, 55, barLength, 55, 1);\n statDisplay.drawLine(1, 56, barLength, 56, 1);\n statDisplay.drawLine(1, 57, barLength, 57, 1);\n statDisplay.drawLine(1, 58, barLength, 58, 1);\n statDisplay.drawLine(1, 59, barLength, 59, 1);\n statDisplay.drawLine(1, 60, barLength, 60, 1);\n statDisplay.drawLine(1, 61, barLength, 61, 1);\n}", "function callbackProgress( progress, result ) {\n\treturn;\n\tvar bar = 250;\n\tif ( progress.total ){\n\t\tbar = Math.floor( bar * progress.loaded / progress.total );\n\t}\n\tvar curBarWidth = document.getElementById( \"bar\" ).style.width;\n\tdocument.getElementById( \"bar\" ).style.width = bar + \"px\";\n}", "function progressBar(elem) {\n $elem = elem;\n //build progress bar elements\n buildProgressBar();\n //start counting\n start();\n }", "function progressBar( elem ) {\n jQueryelem = elem;\n // build progress bar elements\n buildProgressBar();\n // start counting\n start();\n }", "function progressBar(elem) {\n $elem = elem;\n // build progress bar elements\n buildProgressBar();\n // start counting\n start();\n }", "function ui_multi_update_file_progress(id, percent, color, active)\n{\n color = (typeof color === 'undefined' ? false : color);\n active = (typeof active === 'undefined' ? true : active);\n\n var bar = $('#uploaderFile' + id).find('div.progress-bar');\n\n bar.width(percent + '%').attr('aria-valuenow', percent);\n bar.toggleClass('progress-bar-striped progress-bar-animated', active);\n\n if (percent === 0){\n bar.html('');\n } else {\n bar.html(percent + '%');\n }\n\n if (color !== false){\n bar.removeClass('bg-success bg-info bg-warning bg-danger');\n bar.addClass('bg-' + color);\n }\n}", "function progressBar(elem){\n $elem = elem;\n //build progress bar elements\n buildProgressBar();\n //start counting\n start();\n }", "function update_progress() {\n let tot = open + closed;\n\n $(\"#progress_open\").css(\"width\", (open * 100 / tot) + \"%\");\n $(\"#progress_close\").css(\"width\", (closed * 100 / tot) + \"%\");\n}", "function updateProgress() {\n var progress = 0,\n currentValue = $scope.curVal,\n maxValue = $scope.maxVal,\n // recompute overall progress bar width inside the handler to adapt to viewport changes\n progressBarWidth = progressBarBkgdElement.prop('clientWidth');\n\n if ($scope.maxVal) {\n // determine the current progress marker's width in pixels\n progress = Math.min(currentValue, maxValue) / maxValue * progressBarWidth;\n }\n\n // set the marker's width\n progressBarMarkerElement.css('width', progress + 'px');\n }", "function _updateProgressBar(oldReferenceLayer){oldReferenceLayer.querySelector(\".introjs-progress .introjs-progressbar\").style.cssText=\"width:\".concat(_getProgress.call(this),\"%;\");oldReferenceLayer.querySelector(\".introjs-progress .introjs-progressbar\").setAttribute(\"aria-valuenow\",_getProgress.call(this));}", "function progress(step, nbSteps, stepLabel) {\n var percent = (step/(nbSteps+1))*100;\n $(\"#progress .progress-bar\").attr('aria-valuenow', step).attr('aria-valuemax', nbSteps+1).attr('style','width:'+percent.toFixed(2)+'%').find(\"span\").html(step + \"/\" + nbSteps);\n $(\"#progressStep\").html(stepLabel);\n}", "function progressBar(elem){\r\n $elem = elem;\r\n //build progress bar elements\r\n buildProgressBar();\r\n //start counting\r\n start();\r\n }", "function changeProgressBar(qCount) {\n\n progress.innerHTML = \"Question \" + (qCount+1) + \" of 10\";\n tracker = id(\"num\" + (qCount+1));\n tracker.style.backgroundColor = \"orange\";\n\n}", "function setProgress(e) {\n // get width of progress bar\n const width = this.getBoundingClientRect().width\n // console.log(width)\n\n // get mouse click position in progress bar\n const clickX = e.offsetX\n // console.log(clickX)\n\n // get duration of song\n const duration = audioSong.duration\n\n // set currentTime to mouse click position divided by total width of progress bar, and multiplied by duration of song\n audioSong.currentTime = (clickX / width) * duration\n}", "_setProgress(e) {\n const newTime = e.offsetX / this.progressRange.offsetWidth;\n this.progressBar.style.width = `${newTime * 100}%`;\n video.currentTime = newTime * video.duration;\n }", "function progressBar(elem){\n $elem = elem;\n //build progress bar elements\n buildProgressBar();\n //start counting\n start();\n }", "function progressBar(elem){\n $elem = elem;\n //build progress bar elements\n buildProgressBar();\n //start counting\n start();\n }", "function progressBar(elem){\n $elem = elem;\n //build progress bar elements\n buildProgressBar();\n //start counting\n start();\n }", "function progressBar(elem){\n $elem = elem;\n //build progress bar elements\n buildProgressBar();\n //start counting\n start();\n }", "function _toggleProgress(ctrl, on) {\n\t\tvar indicator = _selector('progress', ctrl).toggleClass(CLASS_HIDDEN, !on);\n\t\twindow.clearInterval(indicator.data(BOXPLUS));\n\t\tif (on) {\n\t\t\tindicator.data(BOXPLUS, window.setInterval(function () {\n\t\t\t\tindicator.css('background-position', progress = (progress - 32) % 384); // 384px = 12 states * 32px width\n\t\t\t}, 150));\n\t\t}\n\t}", "function $updateProgressBar(percent, complete){\r\n\tconsole.log(\"Recalculating progress bar - \" + percent + \"% initial data returned\");\r\n\tif (percent < 100) {\r\n\t\t\t$(\".meter > span\").each(function() {\r\n\t\t\t$(this).css('width', percent + \"%\");\r\n\t\t\t$(this).removeClass().addClass('orange');\r\n\t\t});\t\t\r\n\t}\t\r\n\tif (complete){\r\n\t\t$(\".meter > span\").each(function() {\r\n\t\t \t$(this).removeClass().addClass('green').css('width', '100%');\r\n\t\t});\t\t\t\r\n\t}\r\n}", "function progress() {\n $(\"#progressbar\").slider('value', Math.floor((100 / audio.duration) * audio.currentTime));\n $(\"#duration\").text(getTime(audio.currentTime) + \" / \" + getTime(audio.duration));\n }", "function animateBar() {\n let i = 0;\n document.querySelector(\".progress-bar\").innerHTML = i + \"%\";\n let animation = setInterval(function () {\n i = i + 1;\n if (i <= 100) {\n document.querySelector(\".progress-bar\").style.width = i + \"%\";\n document.querySelector(\".progress-bar\").innerHTML = i + \"%\";\n } else {\n clearInterval(animation);\n }\n }, 20);\n}", "updateProgressBar() {\n let revealRange = 103 - 24; //See css comment (progressBox). \n let revealPercent = this.points / this.pointsNeeded; //Current percent of points needed.\n this.baseProgressMargin = -24; //Margin value: Progress box hides bar.\n this.progressMargin = this.baseProgressMargin - revealPercent * revealRange; //New margin value\n document.getElementById(\"progress\").style.marginTop = this.progressMargin + \"vh\"; //Reveal percent of glowing border as level progress indicator.\n }", "function updateProgressBar(){ \r\n\tdocument.getElementById('progress').style.width = [count+1]/30*100+'%'; \r\n}", "function setUploadProgress(progress) {\n console.log(\"Upload-progress: \" + progress);\n var newWidth = progress + \"%\";\n console.log(\"Neue Breite concat: \" + newWidth);\n progressBar.css('width', newWidth);\n console.log(\"Neue Breite: \" + $(progressBar).width());\n }", "function updateProgress(){\n const computedPercentage = Math.round(attendanceRecords.length / traineeIds.length * 100);\n $(\"#progressbar\").children().attr(\"aria-valuenow\", computedPercentage).css(\"width\", computedPercentage + \"%\").text(computedPercentage + \"% Complete\");\n}", "function setProgressBar(e){\n const width = this.clientWidth;\n const clickX = e.offsetX;\n const {duration} = music;\n music.currentTime = (clickX / width)* duration;\n}", "function updateprogress() {\n\tvar actvdot = $('.stepdot.active');\n\tactvdot.addClass('done').removeClass('active').next().next().addClass('active');\n}", "function updateProgress(percentage) {\n document.getElementById(\"pbar_innerdiv\").style.width = percentage + \"%\";\n}", "function updateProgress (evt) {\n\n if (evt.lengthComputable) {\n var percentComplete = Math.floor((evt.loaded / evt.total) * 100),\n percentIntegrated = (percentComplete / 100) * options.width;\n\n // Display progress status\n if(options.progress != false) {\n $(options.progress).text(percentComplete); \n }\n\n // Convert 'percentComplete' to preloader element's width\n $(options.gazer).stop(true).animate({\n width: percentIntegrated\n }, function() {\n options.done.call();\n });\n\n } else {\n // when good men do nothing \n }\n }", "function updateProgress() {\n\t var percentage = (progressBar.hideEta - new Date().getTime()) / progressBar.maxHideTime * 100;\n\t progressElement.style.width = percentage + '%';\n\t }", "function updateProgressBar(){\n progressBarTimer += 5; // percentage\n \n var progressString = String(progressBarTimer) + \"%\";\n $(\"#progressBar\").css( \"width\", progressString);\n if (progressBarTimer === 100) {\n //stop timer\n clearInterval( localInterval);\n $(\"#progressBar\").css( \"width\", \"0%\");\n }\n}", "function updateProgressById(id, percent) {\n\t$(\"#\"+id+ \" .bar\").width(percent + \"%\");\n}", "function handleProgress(e){\n if(e.lengthComputable){\n var percent = e.loaded / e.total * 100;\n $('.progress-bar').attr({value:e.loaded,max:e.total});\n $('.progress-bar').css('width', percent + '%');\n }\n }", "function startBar() {\n if (i == 0) {\n i = 1;\n width = 0;\n var id = setInterval(tick, 10);\n\n // 1 tick function of progress bar 1 tick = 100ms and\n function tick() {\n if (width >= 100 ) {\n clearInterval(id);\n i = 0;\n checkEndGame();\n } else {\n adjustWidth();\n }\n\n // adjust width of progress bar and % displayed each tick\n function adjustWidth() {\n width += 0.0166666666666667;\n bar.style.width = width + \"%\";\n bar.innerHTML = width.toFixed(1) + \"%\";\n\n // set width value to a var\n barWidth = width;\n }\n\n }\n }\n }", "function updateProgressBar(width) {\n document.documentElement.style.setProperty('--progressbar-width', `${width}%`);\n}", "function setProgress(ev) {\n const totalWidth = this.clientWidth;\n const clickWidth = ev.offsetX;\n const clickWidthRatio = clickWidth / totalWidth;\n disc.currentTime = clickWidthRatio * disc.duration;\n}", "function setProgress(container, progress){\n var bar = new ProgressBar.SemiCircle(container, {\n strokeWidth: 6,\n color: '#fff',\n trailColor: '#e0e0e0',\n trailWidth: 1,\n easing: 'easeInOut',\n duration: 1400,\n svgStyle: null,\n text: {\n value: '',\n alignToBottom: false\n },\n from: {color: '#fff'},\n to: {color:'#fff'},\n // Set default step function for all animate calls\n step: (state, bar) => {\n bar.path.setAttribute('stroke', state.color);\n var value = Math.round(bar.value() * 100);\n if (value === 0) {\n bar.setText('0%');\n } else {\n bar.setText(value+\"%\");\n }\n bar.text.style.color = state.color;\n }\n });\n bar.text.style.fontFamily = '\"Roboto\", Helvetica, sans-serif';\n bar.text.style.fontSize = '2rem';\n\n bar.animate(progress); // Number from 0.0 to 1.0\n }", "function updateProgressBarLoadingCore() {\n var loading = 0, loaded = 0;\n loading += view.getModel().getResourceManager().getLoadingCount();\n loaded += view.getModel().getResourceManager().getLoadedCount();\n // Progress %\n status.setProgress(Math.floor(100 * (loaded || 0) / ((loading || 0) + (loaded || 1))) / 100);\n }", "function renderProgress(val, perc, message) {\n\t\tbar.style.width = perc + \"%\";\n\n renderMessage(message);\n\t}", "function updateProgress() {\n \"use strict\";\n //Gestion progress bar\n $('#quiz-progress').css('width', function () {\n var current = $('#question-number').text(), total = $('#question-total').val();\n return ((current / total) * 100).toString() + \"%\";\n });\n}", "function updateProgress ( current, total ){\n $(\".progress .currentProgress\").css('width', ((current - 1) / total) * 100 +'%');\n $(\".progress .progresstext\").html('Frage '+ current + ' von ' + (total))\n }", "function updateProgress(){\n $('.progress-bar').append('<li class=\"single-bar glow\"></li>');\n}", "function addProgress() {\n var progressValue = (100 * parseFloat($('#progressBarOne').css('width')) / parseFloat($('#progressBarOne').parent().css('width'))) + '%';\n var progressValueNum = parseFloat(progressValue);\n if (progressValueNum < 99) {\n var finalValue = (progressValueNum + 16.6);\n $('#progressBarOne').css('width', finalValue + \"%\");\n $(\"#progressBarOne\").text(finalValue.toFixed(0) + \"%\");\n\n }\n else {\n $('#progressBarOne').css('width', \"100%\");\n $(\"#progressBarOne\").text(\"100%\");\n\n }\n\n if (finalValue >= 95) {\n $('#progressBarOne').css('background-color', '#56a773')\n }\n}", "_updateProgress() {\n super._updateProgress();\n\n const that = this;\n\n //Label for Percentages\n if (that.showProgressValue) {\n const percentage = parseInt(that._percentageValue * 100);\n\n that.$.label.innerHTML = that.formatFunction ? that.formatFunction(percentage) : percentage + '%';\n }\n else {\n that.$.label.innerHTML = '';\n }\n\n if (that.value === null || that.indeterminate) {\n that.$value.addClass('jqx-value-animation');\n }\n else {\n that.$value.removeClass('jqx-value-animation');\n }\n\n that.$.value.style.transform = that.orientation === 'horizontal' ? 'scaleX(' + that._percentageValue + ')' : 'scaleY(' + that._percentageValue + ')';\n }", "function setProgress2(index) {\r\n\t\tconst calc = ((index + 1) / ($slider2.slick('getSlick').slideCount)) * 100;\r\n\r\n\t\t$progressBar2\r\n\t\t\t.css('background-size', `${calc}% 100%`)\r\n\t\t\t.attr('aria-valuenow', calc);\r\n\t}", "function metaProgress() {\n\t$('#metabar').css(\"width\", function() {\n\t\treturn $(this).attr(\"aria-valuenow\") + \"%\";\n\t});\n}", "function progress(number) {\n var node = $(\"#fileUploadProgress\");\n node.text(number + \" %\");\n node.attr(\"aria-valuenow\", number);\n node.attr(\"style\", \"width:\" + number + \"%\");\n}", "function updatePbar(pbtgt,pbval) {\r\n\t$(function() {\r\n\t\t$( \"#\"+pbtgt ).progressbar({\r\n\t\t\tvalue: pbval\r\n\t\t });\r\n\t});\r\n}", "function updateProgressBar (chosenHP, val, maxVal) {\n var addStr = \" progress-bar progress-bar-striped progress-bar-animated \"\n var percentage = Math.floor((val/maxVal)*100) \n if(percentage > 50) {\n $(\"#\"+ chosenHP).removeClass( \"bg-danger\" )\n $(\"#\"+ chosenHP).removeClass( \"bg-warning\" )\n $(\"#\"+ chosenHP).attr(\"class\", addStr + \"bg-success\")\n }\n if(percentage <= 50 && percentage >25){\n $(\"#\"+ chosenHP).removeClass( \"bg-success\" )\n $(\"#\"+ chosenHP).attr(\"class\", addStr + \"bg-warning\")\n }\n else if(percentage <= 25) {\n $(\"#\"+ chosenHP).removeClass( \"bg-warning\" )\n $(\"#\"+ chosenHP).attr(\"class\", addStr + \"bg-danger\")\n }\n\n $(\"#\"+ chosenHP).attr(\"style\", \"width: \" + percentage + \"%; height:25px\")\n\n}", "function updateProgress() {\n let progressLabel = ui.Label({\n value: 'Scanning image collections ' + processedCount + ' of ' + collectionCount,\n style: {fontWeight: 'bold', fontSize: '12px', margin: '10px 5px'}\n });\n\n progressPanel.clear();\n progressPanel.add(progressLabel)\n }", "function updateProgress() {\n // To Update Progress Circle\n circles.forEach((circle, index) => {\n if (index < currentActive) {\n circle.classList.add(\"active\");\n } else {\n circle.classList.remove(\"active\");\n }\n });\n\n // To Update Progress Line\n const actives = document.querySelectorAll(\".active\");\n\n progress.style.width =\n ((actives.length - 1) / (circles.length - 1)) * 100 + \"%\";\n\n if (currentActive === 1) {\n prev.disabled = true;\n } else if (currentActive === circles.length) {\n next.disabled = true;\n } else {\n prev.disabled = false;\n next.disabled = false;\n }\n}", "function animate() {\n setTimeout(function () {\n progress += increment;\n if(progress < maxprogress) {\n $progressBar.attr('value', progress);\n animate();\n } else {\n // $progressBar.css('display', 'inline');\n\n }\n }, timeout);\n}" ]
[ "0.74477345", "0.72282267", "0.72270733", "0.7165991", "0.714557", "0.7068672", "0.70466894", "0.70089096", "0.70082325", "0.70082086", "0.6989072", "0.69709826", "0.6960757", "0.68830436", "0.6854484", "0.6828043", "0.67773724", "0.6769633", "0.67674536", "0.67616606", "0.6760407", "0.6757348", "0.6752998", "0.67489463", "0.674608", "0.67275083", "0.6720097", "0.67002517", "0.66931117", "0.66907775", "0.6679057", "0.6675559", "0.6675473", "0.66750157", "0.66560894", "0.6652206", "0.66436815", "0.6634396", "0.66305226", "0.66251504", "0.6623315", "0.6622357", "0.66118425", "0.6579608", "0.65788347", "0.656592", "0.6558878", "0.6556107", "0.65558857", "0.6554346", "0.6534369", "0.65323985", "0.65310884", "0.6529722", "0.6524482", "0.6522134", "0.6520552", "0.6504627", "0.65007204", "0.6496557", "0.64962304", "0.6487953", "0.6487953", "0.6487953", "0.6487953", "0.64750344", "0.64587414", "0.6455928", "0.6452554", "0.6439606", "0.6439102", "0.6431771", "0.6429622", "0.6423254", "0.6415412", "0.6406409", "0.6405299", "0.6397254", "0.6395726", "0.6395126", "0.6386932", "0.6379614", "0.6373689", "0.6363113", "0.63599485", "0.63534117", "0.634371", "0.63424814", "0.63392615", "0.6336424", "0.6335768", "0.6334857", "0.6334344", "0.6334204", "0.63314104", "0.63296473", "0.63190407", "0.6317654", "0.62953305", "0.6286957" ]
0.67241746
26
set with drawing.activate() drawing data constructor
function Drawing(){ this.header={ $INSBASE:{x:0,y:0,z:0}, $EXTMIN:{x:0,y:0,z:0}, $EXTMAX:{x:10,y:10,z:0} }; this.tables={ linetype:{ Continuous:{ name: "Continuous", description: "Solid line", patternLength: 0 }, HIDDEN2: { name: "HIDDEN2", description: "Hidden (.5x) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _", pattern:[0.125, -0.0625], patternLength: 0.1875 } }, layer:{ handle: "2", ownerHandle: "0", layers: { "0":{Name:"0", Visible:true, color:16711680}, "A-WALL":{Name:"0", Visible:true, color:16711680} } } }; this.blocks={}; this.entities=[ line.create(this) //new line.Line(this) ]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "configureStartingData() {\n // We don't use a singleton because defaults could change between calls.\n new DrawingDefaultsConfig(this, this._last_tool).render(true);\n }", "function draw(){\n\t\t// Needed to comply with Tool Delegate design pattern\n\t}", "function newDrawing(data) {\n fill(0,255,0);\n ellipse(data.x, data.y, 80, 80);\n}", "function newDrawing(data){\n noFill();\n\n for (var i = 0; i < 200; i += 20) {\n stroke (250);\n bezier(data.x-(i/2.0), data.y, 410, 20, 440, 300, 240-(i/16.0), 300+(i/8.0));\n } \n}", "setXY(x,y)\n {\n this.x = x;\n this.y = y;\n this.drawx = x;\n this.drawy = y;\n\n this.vis = {\n\t\tdx : 0,\n\t\tdy : 0,\n\t\tx : this.x,\n\t\ty : this.y\n\t\t};\n\n }", "constructor() {\n super();\n this.draw();\n }", "function newDrawing(data){\n noStroke();\n fill(255,0,100); \n ellipse(data.x, data.y, 60, 60);\n\n}", "updateGraphicsData() {\n // override\n }", "function activateDraw() {\r\n measureConfig.isActive = true;\r\n measureButton.classList.toggle(\"esri-draw-button-selected\");\r\n\r\n // clear previously used line features\r\n clearPolyline();\r\n measureConfig.finsishedFeature = null;\r\n view.popup.close();\r\n\r\n // on each pointer-down event, a vertex is added to the line\r\n // allowing the user to draw a new line segment in continuation\r\n // of the activeFeature\r\n pointerDownListener = view.on(\"pointer-down\", addPoint);\r\n\r\n // on each pointer-move event, the last segment of the line\r\n // is updated so that the final vertex is the location\r\n // of the pointer or mouse\r\n pointerMoveListener = view.on(\"pointer-move\", function(event) {\r\n updateLastVertex(event);\r\n // measure the polyline on each pointer-move event\r\n if (measureConfig.activeFeature) {\r\n measurePolyline(measureConfig.activeFeature.geometry);\r\n }\r\n });\r\n\r\n // finishes drawing the line (and measurement) and\r\n // drawing is deactivated on the view\r\n doubleClickListener = view.on(\"double-click\", function(event) {\r\n // stops the default double-click behavior in the view\r\n event.stopPropagation();\r\n // stores the final densified version of the polyline\r\n finishDrawing(event);\r\n // measures the final polyline\r\n measurePolyline(measureConfig.finsishedFeature.geometry);\r\n });\r\n }", "startDraw(){\n if(!this.drawing) {\n this.drawing = true;\n this.then = Date.now();\n this.draw();\n }\n }", "initBeforeStroke(param) {\n\t\tsuper.initBeforeStroke(param);\n\t\t//LOGGING&&console.log(this.brush);\n\t\t// pre-render the brushtip data\n\t\tthis.lastCircleFromPrevStroke=null;\n\t}", "function activate() {\n populationApp.toolbar.activate(Draw.FREEHAND_POLYGON);\n\n displayOutput(i18n.t(that.ns + \":na\"));\n }", "function startDrawing(event) {\n isDrawing = true;\n [lastX, lastY] = [event.offsetX, event.offsetY];\n}", "draw() {\n\n // only display the dirt if it is visible... \n if (this.visible){\n\n ctxDATA.fillStyle = this.color; \n ctxDATA.fillRect(this.x, this.y, this.w, this.h);\n \n // end of visibility check \n }\n\n // end of the draw method for the Dirt \n }", "function draw() {\n cenas[cenaAtual].draw();\n}", "startDrawingTool () {\n this.startedDrawing = true\n this.drawingManager.setMap(this.map)\n this.drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON)\n }", "function start_drawing() {\n $('#normal_ear').lazylinepainter( \n {\n \"svgData\": pathObj,\n \"strokeWidth\": 2,\n \"strokeColor\": \"#7f857f\"\n }).lazylinepainter('paint'); \n }", "begin() {\n this.ctx.beginPath();\n this.ctx.moveTo(this.position[0], this.position[1]);\n }", "function TransparencyData(alphaPen,alphaBrush,blendMode){this.alphaPen=alphaPen;this.alphaBrush=alphaBrush;this.blendMode=blendMode;}", "draw(){\n this.ctx.strokeStyle = this.getStrokeColor();\n this.ctx.lineWidth = 2;\n this.ctx.beginPath()\n this.ctx.moveTo(this.prevx, this.prevy);\n this.ctx.lineTo(this.x, this.y)\n this.ctx.stroke()\n this.ctx.fill();\n }", "function dnObj() {\n\t\t\t\tvar selectOb = canvas.getActiveObject();\n\t\t\t\tcanvas.sendBackwards(selectOb).renderAll();\n\n\t\t}", "startDrawing() {\n var canvas = this.context.getContext(\"2d\");\n canvas.save();\n this.updateAnimation = true;\n var infographic = this;\n window.requestAnimationFrame(function () { infographic.drawLoading(); });\n }", "beginPath() {\n this.justBegun = true;\n this.context.beginPath();\n }", "function drawOnDemand(){\n\n\n}", "function bringdnObj() {\n\t\t\tvar selectOb = canvas.getActiveObject();\n\t\t\tcanvas.sendToBack(selectOb).renderAll();\n\n\t\t}", "startDrawingShapeMode() {\n if (this.getCurrentState() !== states.SHAPE) {\n this._state = states.SHAPE;\n this._getModule(modules.SHAPE).startDrawingMode();\n }\n }", "function bringupObj() {\n\t\t\tvar selectOb = canvas.getActiveObject();\n\t\t\tcanvas.bringToFront(selectOb).renderAll();\t\n\t\t}", "function activateArrowDrawing() {\n // TODO diagram: reset selected arrows and selected devices, enable arrow active mode and add active class to arrow button in sidebar\n arrowButton.addClass('active');\n drawingMode = true;\n //unselect arrows and devices\n\n }", "function upObj() {\n\t\t\tvar selectOb = canvas.getActiveObject();\n\t\t\tcanvas.bringForward(selectOb).renderAll();\t\n\t\t}", "function setPoints() {\n\n if (isDragging) return;\n\n isDrawing = true;\n\n var plod = d3.mouse(this);\n linePoint1 = {\n x: plod[0],\n y: plod[1]\n };\n\n polyPoints.push(plod);\n\n var circlePoint = gContainer.append(\"circle\")\n .attr(\"cx\", linePoint1.x)\n .attr(\"cy\", linePoint1.y)\n .attr(\"r\", 4)\n .attr(\"start-point\", true)\n .classed(\"handle\", true)\n .style(\"cursor\", \"pointer\");\n\n\n // on setting points if mousedown on a handle\n if (d3.event.target.hasAttribute(\"handle\")) {\n completePolygon()\n }\n\n }", "_draw() {\n\n }", "draw() {}", "draw() {}", "draw() {}", "draw() {}", "start() {\n this.preDragFill = this.attr(\"fill\");\n this.ox = this.attr(\"cx\");\n this.oy = this.attr(\"cy\");\n this.attr({ fill: config.draggingCircleColor });\n }", "createDrawing (payload) {\n console.debug('MIXIN', payload)\n var color = '#77d2ff'\n var opacidad = 0.3\n var editable = true\n var tipo\n\n this.map.SetControlDrawingVisible(false)\n\n if (payload.tipo === 'radial') {\n // if (payload.seccion === 'PuntoInteres') {\n // this.seccionDrawing = 'PuntoInteres'\n // } else {\n // this.seccionDrawing = null\n tipo = 'circle'\n this.map.DrawingMap(tipo, payload.radio)\n // }\n }\n if (payload.tipo === 'poligonal') {\n tipo = 'polygon'\n this.map.DrawingMap(tipo)\n }\n if (payload.tipo === 'marker') {\n tipo = 'marker'\n this.rutaOrigen = {}\n this.rutaDestino = {}\n this.ContRutas = 0\n this.map.DrawingMap(tipo)\n }\n }", "activate()\n\t{\n\t\tconsole.log(\"LineTool.activate\")\n\t\teditor.view.container.dom.style.cursor=\"crosshair\"\n\t\tthis.mouseIp=new InputPoint()\n\t\tthis.firstIp= new InputPoint();\n\t}", "activate() {\n\t\tthis.active = true;\n\t\tthis.duration = this.savedDuration;\n\t\tif (this.partial) {\n\t\t\tthis.cycle = Math.ceil((1/this.density));\n\t\t}\n\t\telse {\n\t\t\tthis.cycle = 1;\n\t\t}\n\t\tthis.counter = 0;\n\t}", "draw() { }", "draw() { }", "draw() { }", "draw(){\r\n ctx.beginPath();\r\n ctx.rect(this.x, this.y, this.width, this.height);\r\n //console.log(this.x)\r\n ctx.fillStyle = D_color;\r\n ctx.fill();\r\n ctx.closePath();\r\n }", "init() {\n this.x = 200;\n this.y = 410; \n }", "draw () { //change name to generate?? also need to redo\n return null;\n }", "render(){\n this.canvas_data.set(this.data);\n this.context.putImageData(this.canvas_imageData, 0, 0);\n }", "function updateDraw(){\r\n //ToDo\r\n }", "function _onOpen() {\n\tdraw();\n}", "function _onOpen() {\n\tdraw();\n}", "constructor (color) {\n this.color = color\n this.shouldDraw = true\n }", "constructor() {\n this.canvas = document.getElementById(\"canvas\");\n this.ctx = this.canvas.getContext(\"2d\");\n this.bounds = this.canvas.getBoundingClientRect();\n this.color = COLORS.red;\n this.tool = TOOLS.pen;\n\n // tool customization\n this.pencilWidth = 10;\n this.eraserWidth = 10;\n this.shapeWidth = 10;\n this.fontSize = 16;\n this.fontFamily = \"Arial\";\n\n this.drawing = false;\n\n // store the mouse coordinates\n this.currentPosition = {\n x: 0,\n y: 0,\n };\n this.startPosition = {\n x: 0,\n y: 0,\n };\n\n this.savedCanvas;\n this.savedActions = [];\n\n this.draw = this.draw.bind(this);\n this.startDrawing = this.startDrawing.bind(this);\n this.stopDrawing = this.stopDrawing.bind(this);\n this.onMouseMove = this.onMouseMove.bind(this);\n this.showTextInput = this.showTextInput.bind(this);\n this.addText = this.addText.bind(this);\n this.init = this.init.bind(this);\n }", "startDrawing() {\n\n this.clearCanvas();\n //use because funtions was lost in methods\n var that = this;\n //event of mous click\n this.canvas.addEventListener(\"mousedown\", function(e) {\n //show confirmation button after first click\n document.getElementById(\"station-confirmer-btn\").style.display = \"initial\";\n document.getElementById(\"canvas\").style.borderColor = \"#5CB85C\";\n //switch on\n that.test = true;\n //begin of drawing\n that.context.beginPath();\n that.context.moveTo(e.offsetX, e.offsetY);\n //get the movement of mouse\n that.canvas.addEventListener(\"mousemove\", function(event) {\n //condition to check switch\n if (that.test === true) {\n var x = event.offsetX;\n var y = event.offsetY;\n //draw line to every next point od movement\n that.context.lineTo(x, y);\n that.context.stroke();\n }\n });\n });\n //mouse up event\n this.canvas.addEventListener(\"mouseup\", function() {\n //switch of\n that.test = false;\n });\n }", "draw() {\n if (this._selected) {\n this.selectedDraw();\n }\n if (this._hovered) {\n this.hoveredDraw();\n }\n if (!this._hovered && !this._selected) {\n this.normalDraw();\n }\n this.isHovered();\n this.isClicked();\n }", "constructor(activeAlpha, activeBeta, activeSample, activeDraw, linePlot, histChart, ecdfChart) {\r\n this.activeAlpha = activeAlpha;\r\n this.activeBeta = activeBeta;\r\n this.activeSample = activeSample;\r\n this.activeDraw = activeDraw;\r\n this.linePlot = linePlot;\r\n this.histChart = histChart;\r\n this.ecdfChart = ecdfChart;\r\n this.sampleData = [];\r\n this.mu = null;\r\n this.sigma = null;\r\n this.drawSliders();\r\n }", "canvasDraw() {\n let prev = this.p0;\n for (const point of this.points) {\n Point.drawLine(prev, point, false, this.isSelected, this.color);\n prev = point;\n }\n Point.drawLine(prev, this.p3);\n Point.drawLine(this.p0, this.p1, true);\n Point.drawLine(this.p2, this.p3, true);\n this.p0.draw();\n this.p1.draw();\n this.p2.draw();\n this.p3.draw();\n }", "function init() {\n clearCanvas()\n drawBackgroundColor()\n drawOrigin()\n }", "function drawCustom(data) {\n\n var dataBinding = dataContainer.selectAll(\"custom.rect\")\n .data(data);\n\n dataBinding\n .attr(\"fillStyle\", function(d) {return z(d.z)});\n \n dataBinding.enter()\n .append(\"custom\")\n .classed(\"rect\", true)\n .attr(\"x\", function(d) {return x(d.x)})\n .attr(\"y\", function(d, i) {return y(d.y)})\n .attr(\"width\", y.rangeBand())\n .attr(\"height\", x.rangeBand())\n .attr(\"fillStyle\", function(d) {return z(d.z)})\n .attr(\"strokeStyle\", \"white\")\n .attr(\"lineWidth\", strokeWidth)\n \n drawCanvas();\n \n }", "function changeDrawingColor(e) {\n fCanvas.freeDrawingBrush.color = e.target.value;\n}", "function startDrawing(x,y){\n // console.log(e);\n isDrawing = true;\n startX = x;\n startY = y;\n}", "drawCurrentState(){\n reset();\n drawPolygonLines(this.hull, \"red\"); \n drawLine(this.currentVertex, this.nextVertex, \"green\");\n drawLine(this.currentVertex,this.points[this.index]);\n for(let i=0;i<this.points.length;i++){\n this.points[i].draw();\n }\n\n for(let i=0;i<this.hull.length;i++){\n this.hull[i].draw(5,\"red\");\n }\n }", "function draw() {}", "function draw() {}", "function setBrush(){\n\tbrush = new Array(state.length);\n\t\n\tfor(var x = 0; x < brush.length; x++){\n\t\tbrush[x] = state[x].slice();\n\t}\n}", "click() {\n this.reset();\n this.draw();\n }", "draw() {\n\n this.drawInteractionArea();\n\n //somewhat depreciated - we only really draw the curve interaction but this isnt hurting anyone\n if(lineInteraction)\n this.drawLine();\n else\n this.drawCurve();\n\n this.drawWatch(); \n\n }", "function draw(patt) {\n\n $canvas.drawRect({\n layer: true,\n fillStyle: patt,\n x: x,\n y: y,\n width: width,\n height: height\n });\n }", "draw() {\n }", "function init(x, y, width, height, data) {\n return COG.extend({\n x: x,\n y: y,\n width: width,\n height: height\n }, data);\n }", "initializeState() {\n super.initializeState();\n const defaultWidth = 30;\n const defaultHeight = 50;\n const attrs = this.state.attributes;\n attrs.x1 = -defaultWidth / 2;\n attrs.y1 = -defaultHeight / 2;\n attrs.x2 = +defaultWidth / 2;\n attrs.y2 = +defaultHeight / 2;\n attrs.cx = 0;\n attrs.cy = 0;\n attrs.width = defaultWidth;\n attrs.height = defaultHeight;\n attrs.stroke = null;\n attrs.fill = { r: 200, g: 200, b: 200 };\n attrs.strokeWidth = 1;\n attrs.opacity = 1;\n attrs.visible = true;\n }", "function brushstart(p) {\n\t\t\t\t\t\tif (brush.data !== p) {\n\t\t\t\t\t\t\tcell.call(brush.clear());\n\t\t\t\t\t\t\tbrush.x(x[p.x]).y(y[p.y]).data = p;\n\t\t\t\t\t\t}\n\t\t\t\t\t}", "function setFuncDrawing() {\n\tcanvas.removeEventListener(\"mousedown\", currentFunc);\n\tcurrentFunc = startDrawing;\n\tcanvas.addEventListener(\"mousedown\", currentFunc);\n}", "set data ({x, y}){\n this._x = x\n this._y = y\n }", "function startPressPen(event) {\n isDrawning = true\n\n // start draw here, go make some dots\n draw(event)\n }", "draw(){\n canCon.beginPath();\n canCon.rect(this.x, this.y, this.width, this.height);\n canCon.fillStyle = 'blue';\n canCon.fill();\n}", "function brushstart(p) {\n if (brushCell !== this) {\n d3.select(brushCell).call(brush.move, null);\n brushCell = this;\n x.domain(Features[p.x]);\n y.domain(Features[p.y]);\n }\n }", "draw() {\n this.state.ctx.beginPath();\n this.state.ctx.moveTo(this.state.prevX, this.state.prevY);\n this.state.ctx.lineTo(this.state.currX, this.state.currY);\n this.state.ctx.strokeStyle = this.state.x;\n this.state.ctx.lineWidth = this.state.y;\n this.state.ctx.stroke();\n this.setState({ctx: this.state.ctx});\n }", "startDraw() {\n\t\tif (this.cursorVisible != false) {\n\t\t\tthis.write(\"\\x1B[?25l\");\n\t\t\tthis.cursorVisible = false;\n\t\t}\n\t\tthis.write(\"\\x1B7\"); //save cursor pos\n\t}", "function init() {\r\n Draw() ;\r\n}", "setDrawState(drawState) {\n this._drawState = drawState;\n }", "function brushstart(p) {\n if (brushCell !== this) {\n d3.select(brushCell).call(brush.clear());\n x.domain(domainByTrait[p.x]);\n y.domain(domainByTrait[p.y]);\n brushCell = this;\n }\n }", "inActive() {\n this.text.style.fill = \"black\";\n }", "fill() {\n this.movePen(this.bpenx, this.bpeny);\n this.context.fill.apply(this.context, arguments);\n }", "draw() {\n if (this.isFilled) {\n this.fill();\n } else {\n this.outline();\n }\n }", "function SetShape(obj) {\n var drawingshape;\n drawingshape = { type: \"Basic\", shape: obj };\n node = {\n shape: drawingshape\n };\n diagramInstance.drawingObject = node;\n enableTool();\n}", "show(){\n fill(0)\n stroke(255)\n circle(this.x,this.y,this.d)\n }", "constructor(x,y,setColor,width,height, enumer){ //might add a param for text\n super(x,y);\n this.col = setColor;\n this.w = width;\n this.h = height;\n this.enumerator = enumer;\n }", "setData(o) {\n this.dom = o;\n this.dom.leading = new SVGNumber_SVGNumber(o.leading || 1.3);\n return this;\n }", "draw(){\n noStroke();\n if(this.getHover() || this.getSelected()){\n fill(BLUE_5); //needs a constant\n }\n else{\n fill(this.col);\n }\n \n push();\n beginShape(); //CCW\n vertex(this.getX() - (this.w)/2.0, this.getY() + (this.h)/2.0); //top left\n vertex(this.getX() - (this.w)/2.0, this.getY() - (this.h)/2.0);\n vertex(this.getX() + (this.w)/2.0, this.getY() - (this.h)/2.0);\n vertex(this.getX() + (this.w)/2.0, this.getY() + (this.h)/2.0);\n\n endShape(CLOSE);\n pop();\n }", "draw() {\n\n }", "function draw() {\n /*\n * Court dropdown + button\n */\n controls.Court.select(\"select\")\n .on(\"change\", function() {\n d3.select(this.parentNode).select(\"input\")\n .node()\n .value = this.value\n ;\n run_query({ key: \"Court\", value: this.value });\n })\n ;\n controls.Court.select(\"select\").selectAll(\"option\")\n .data(pivots.Court)\n .enter().append(\"option\")\n .text(identival)\n .attr(\"value\", identikey)\n ;\n /*\n * Phase button + dropdown combo\n */\n dom.select(\"#chooser-Phase\")\n .call(controls.Phase)\n ;\n controls.Phase.choices(pivots.Phase).callback(run_query);\n /*\n * State button + dropdown combo\n */\n d3.select(\"#chooser-State\") // different parent <div>\n .call(controls.State.callback(run_query))\n ;\n /*\n * Reset button\n */\n controls.reset = dom.select(\".reset-button button\")\n .on(\"click\", function() {\n controls.Court.select(\"select\").selectAll(\"option\")\n .property(\"selected\", function(d, i) { return !i; })\n ;\n controls.Court.select(\"select\").each(function(d, i) {\n d3.select(this).on(\"change\").apply(this, [d, i]);\n })\n ;\n controls.Court.node().click();\n controls.Phase.reset();\n controls.State.reset();\n })\n ;\n }", "draw() {\n var p = window.p;\n\n let col= this.col ? this.p.color(this.col.r, this.col.g , this.col.b) : this.p.color(255,255,255);\n\n //we draw line\n this.p.stroke(col); //it's for campability with old clients\n this.p.strokeWeight(this.sw);\n this.p.line(this.a.x, this.a.y, this.b.x, this.b.y);\n\n }", "draw(x, y) {\n var added = x + \",\" + y;\n\n //Sonst Endlosschleife mit Aufruf aus onResize\n if (!this.resizing) {\n this.pairs.push({ x: x, y: y });\n }\n\n var currAtt = this.poly.getAttribute(\"points\");\n if (currAtt === null) {\n currAtt = added;\n } else {\n currAtt += \"\\n\" + added;\n }\n this.poly.setAttribute(\"points\", currAtt);\n }", "_drawFocus()\n\t{\n\t\t\n\t}", "function draw(){\n\t\tif (newFurniture != undefined) newFurniture.draw();\n\t}", "function freeDraw() {\n mainDiagram.toolManager.panningTool.isEnabled = false;\n // create drawing tool for mainDiagram, defined in FreehandDrawingTool.js\n var tool = new FreehandDrawingTool();\n // provide the default JavaScript object for a new polygon in the model\n tool.archetypePartData =\n { stroke: \"black\", strokeWidth: 5, category: \"FreehandDrawing\", key: uuidv4() };\n // install as last mouse-move-tool\n mainDiagram.toolManager.mouseMoveTools.add(tool);\n globalState.tool = tool;\n this.onclick = cancelFreeDraw;\n document.getElementById(\"freedraw\").innerHTML = '<img id=\"freedraw_img\" width=\"20\" height=\"20\" style=\"margin:2px\"/>' + \" 完成\"\n document.getElementById(\"freedraw_img\").src = APPLICATION_ROOT + \"Content/done.png\";\n\n}", "function brushstart(p) {\n if (brushCell !== this) {\n d3.select(brushCell).call(brush.clear());\n x.domain(domainByTrait[p.x]);\n y.domain(domainByTrait[p.y]);\n brushCell = this;\n }\n }", "draw(context) {\n //TO-DO\n }", "function butColor(object,color){\n if(String(color)!=\"undefined\"&&String(color)!=\"NaN\")\n if(color[0]>0)\n {\n object.onDraw = fillRect; \n object.fillBrush= object.graphics.newBrush( object.graphics.BrushType.SOLID_COLOR, color );\n object.visible=0;\n object.visible=1;\n }\n\nfunction fillRect(){ \n with( this ) {\ntry{ \n graphics.drawOSControl();\n graphics.rectPath(0,0,size[0]-2,size[1]-2);\n graphics.fillPath(fillBrush);\n }\n catch(err){}\n }\n } \n }", "function brushstart(p) {\n\t\t\tif (brushCell !== this) {\t\t\n\t\t\t\td3.select(brushCell).call(brush.clear());\t\t\n\t\t\t\tx.domain(domainByVarName[p.x]);\t\t\n\t\t\t\ty.domain(domainByVarName[p.y]);\t\t\n\t\t\t\tbrushCell = this;\t\t\n\t\t\t}\t\t\n\t\t}", "draw(){\n }" ]
[ "0.65772414", "0.6383411", "0.6240913", "0.60735613", "0.60711265", "0.6063453", "0.6028304", "0.6022559", "0.60153395", "0.5989123", "0.59854096", "0.59819174", "0.5849899", "0.58492386", "0.58143526", "0.5800647", "0.5796674", "0.577526", "0.5752931", "0.5751492", "0.5743334", "0.5727159", "0.5719997", "0.57048917", "0.56916064", "0.5672497", "0.5670006", "0.5664917", "0.5662193", "0.5659567", "0.5659109", "0.565473", "0.565473", "0.565473", "0.565473", "0.56280607", "0.5627894", "0.562038", "0.5616094", "0.5608824", "0.5608824", "0.5608824", "0.5606999", "0.55999887", "0.5599208", "0.5597897", "0.55876786", "0.5585011", "0.5585011", "0.5581302", "0.5579097", "0.5578198", "0.5565841", "0.5562077", "0.5554892", "0.5542504", "0.55344874", "0.5529426", "0.55267274", "0.55231005", "0.5516355", "0.5516355", "0.551417", "0.55121595", "0.5511947", "0.55118823", "0.5508794", "0.5503014", "0.5500124", "0.549637", "0.5493637", "0.5492095", "0.5484801", "0.5476808", "0.5467445", "0.5460141", "0.54573965", "0.5455948", "0.5450079", "0.5449846", "0.54442364", "0.54337955", "0.5431574", "0.5422033", "0.54193264", "0.5417632", "0.5413699", "0.5412258", "0.540911", "0.54070365", "0.5406246", "0.5406098", "0.5404751", "0.53999734", "0.5399242", "0.5394526", "0.5389556", "0.5386548", "0.5386141", "0.53803664" ]
0.5827011
14
Login the test user
function loginUser(authenticate, done) { request(app) .post('/authenticate') .send({ email: '[email protected]', password: 'whatWhat' }) .expect(200) .end(onResponse); function onResponse(error, res) { authenticate.token = res.body.token; done(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function login() {\n User.login(self.user, handleLogin);\n }", "login(user) {\n return this.perform('post', '/login', user);\n }", "async loginUser() {\n await this.userName.sendKeys(browser.params.loginData.login.login_set_1.username);\n await this.password.sendKeys(browser.params.loginData.login.login_set_1.password);\n await this.loginButton.click();\n }", "function login() {}", "async login() {}", "async login() {\n const user = await userFactory();\n const { session, sig } = sessionFactory(user);\n\n // set up a cookie in the Chromium instance\n await this.page.setCookie({ name: 'session', value: session });\n await this.page.setCookie({ name: 'session.sig', value: sig });\n // refresh the page, simulate logging in\n // we land on the blog page after logging in\n // http:// needed for travis\n await this.page.goto('http://localhost:3000/blogs');\n // otherwise the test will fail becaause it goes very quickly\n await this.page.waitFor('a[href=\"/auth/logout\"]');\n }", "function testLogin() {\n\tif (!loginHash || !loginSalt) { // This shouldn't be called without login hash and/or salt\n\t\tauthenticationTitle.html(\"Something happened\");\n\t\tthrow \"The account storage container for this user has not been set up\";\n\t}\n\n\tif (os.hash(passwordInputBox.val() + loginSalt + \"\") + \"\" === loginHash + \"\") { // Compute hash from password + salt, compare to stored hash\n\t\tlockScreen.addClass(\"lockscreenopened hidden\"); // Hide lockscreen\n\t\tinitialiseShellUX(); // Initialise rest of the shell\n\n\t\tpasswordInputBox.val(\"\"); // Clear password box as a basic security precaution\n\n\t\twallpaper.on(\"mousedown\", function(){ // If you click wallpaper, every window will unfocus\n\t\t\tunfocusWindows();\n\t\t});\n\t} else {\n\t\tauthenticationTitle.html(\"Incorrect Password\"); // Incorrect password!!\n\t\tauthenticationTitle.delay(1500).html(\"Hey, User!\"); // Reset this\n\t}\n}", "async login(testController, username, password) {\n await this.isDisplayed(testController);\n await testController.typeText('#login-form-email', username);\n await testController.typeText('#login-form-password', password);\n await testController.click('#login-form-submit');\n await navBar.isLoggedIn(testController, username);\n }", "function doLogin(userName, password){\n\n}", "function userLogin() {\n /**-----------------------------------------------------------------------*/\n /** Get the user's name and password as entered into the login form: */\n /**-----------------------------------------------------------------------*/\n var name = document.querySelector('[name=\"username\"]').value;\n var password = document.querySelector('[name=\"password\"]').value;\n\n /**-----------------------------------------------------------------------*/\n /** Check if the user is authorized to use the application: */\n /**-----------------------------------------------------------------------*/\n authenticateUser(name, password, userIsAuthorised);\n}", "function login() {\n // We give username and password to log the user in\n // In case there is something wrong with the credentials\n // we use the setError to display it\n // If the user logs in successfully then the loginCallback is called.\n setLoading(true);\n databaseLogin(username, password, loginCallback, showError);\n }", "login(login) {\n return apiClient.post('users/login', login)\n }", "async login() {\n const I = this;\n I.amOnPage('/');\n I.fillField('input[type=\"email\"]', '[email protected]');\n I.fillField('input[type=\"password\"]', 'Heslo123');\n I.click(locate('button').withText('Prihlásiť sa'));\n }", "function performLogin(cy){\ncy.get(usernameTxtField).type('jp')\ncy.get(passwordTxtFIeld).type('1010')\ncy.get(submitButtonLogin).click()\n}", "function login() {\n var userName = document.getElementById(\"username\");\n var password = document.getElementById(\"password\");\n\n var logonForm = document.getElementById(\"logonForm\");\n logonForm.setAttribute(\"class\", \"hiddenPage\");\n\n request.userName = userName.value;\n\n // the password has not been protected / encyrpted - please change if required.\n request.password = password.value;\n\n // retry the call to the Epicor API\n makeServiceRequest();\n }", "function login(context) {\n const username = context.params.username;\n const password = context.params.password;\n\n userModel.login(username, password)\n .then(function (res) {\n userModel.saveSession(res);\n handler.showInfo(`Login successful.`);\n context.redirect('#/home/meme');\n }).catch((err) => {\n handler.handleError(err);\n $('input[name=\"username\"]').val('');\n $('input[name=\"password\"]').val('');\n });\n }", "function login() {\n var loggedIn = auth.login();\n fakeWindow.sendMessage({\n type: 'authorization_response',\n code: 'acode',\n state: 'notrandom',\n });\n return loggedIn;\n }", "function localLogin() {\n Message.loading();\n User.login({}, LoginModel.form).$promise\n .then(function(userWrapper) {\n Message.hide();\n console.log(\"---------- userWrapper ----------\");\n console.log(userWrapper);\n AppStorage.user = userWrapper.user;\n AppStorage.token = userWrapper.token;\n AppStorage.isFirstTime = false;\n U.goToState('Main.MainTab.PostList.PostListRecent', null, 'forward');\n })\n .catch(function(err) {\n console.log(\"---------- err ----------\");\n console.log(err);\n if (err.status === 403) {\n return Message.alert('로그인 알림', '비밀번호/이메일이 틀렸습니다. 다시 입력해주세요');\n } else {\n return Message.alert();\n }\n });\n }", "function loginClick() {\n\t username = $(\"#userName\").val();\n\t password = $(\"#password\").val();\n\t getRememberMestatus();\n\t var params = {\"username\":username,\"password\":password};\n\t var callerId = \"login\";\n\t var url = \"/logon\";\n\t reqManager.sendPost(callerId, url, params, loginSuccessHandler, loginErrorHandler, null);\n\t}", "loginBasic() {\n this.open();\n this.login('[email protected]', 'PotterMalfoy22');\n this.clickLoginButton();\n }", "async login(){\n\t\tconst page = await this.goToNewPage('http://www.espn.com/login');\n\t\tawait page.waitForSelector(\"iframe\");\n\n\t\t//Gets the iframe for the login page\n\t\tconst elementHandle = await page.$('div#disneyid-wrapper iframe');\n\t\tconst frame = await elementHandle.contentFrame();\n\n\t\t//Selects the username field and types the username \n\t\tawait frame.waitForSelector('[ng-model=\"vm.username\"]', {visible: true})\n\t\tconst username = await frame.$('[ng-model=\"vm.username\"]');\n\t\tawait username.type(this.email);\n\n\t\t//Selects the password field and tyes the password\n\t\tawait frame.waitForSelector('[ng-model=\"vm.password\"]', {visible: true})\n\t\tconst password = await frame.$('[ng-model=\"vm.password\"]');\n\t\tawait password.type(this.password);\n\n\t\t//Selects the log in button and clicks it\n\t\tawait frame.waitForSelector('[aria-label=\"Log In\"]', {visible: true})\n\t\tconst loginButton = await frame.$('[aria-label=\"Log In\"]');\n\t\tawait loginButton.click();\n\t\treturn true;\n\t}", "async doLogin () {\n\t\tthis.responseData = await new LoginHelper({\n\t\t\trequest: this,\n\t\t\tuser: this.user,\n\t\t\tloginType: this.loginType\n\t\t}).login();\n\t}", "async login() {\n const user = await userFactory();\n const { session, sig } = sessionFactory(user);\n \n await this.page.setCookie({ name: 'session', value: session });\n await this.page.setCookie({ name: 'session.sig', value: sig });\n await this.page.goto('localhost:3000/blogs'); // refresh page after set cookie session\n await this.page.waitFor('a[href=\"/auth/logout\"]');\n }", "function login(user, pass, callback) {\n\tsendRequest({ request: 'login', username: user, password: pass }, callback);\n}", "function login() {\n var loginWin = createLoginWin();\n loginWin.open();\n }", "async login() {\n await auth0.loginWithPopup();\n this.user = await auth0.getUser();\n if(this.user) _isLoggedIn = true;\n }", "login (username, password) {\n this.inputUsername.setValue(username);\n this.inputPassword.setValue(password);\n this.btnSubmit.click(); \n const homepage= $('#inventory_container');\n expect(homepage).toBeDisplayed();\n \n \n }", "async doLogin () {\n\t\tthis.responseData = await new LoginHelper({\n\t\t\trequest: this,\n\t\t\tuser: this.user,\n\t\t\tloginType: this.loginType,\n\t\t\tdontSetFirstSession: this.signupToken.provider && !this.signupToken.teamId,\n\t\t\tnrAccountId: this.request.body.nrAccountId\n\t\t}).login();\n\t\tthis.responseData.signupStatus = this.signupToken.signupStatus;\n\t\tthis.responseData.provider = this.signupToken.provider;\n\t\tthis.responseData.providerAccess = this.signupToken.providerAccess;\n\t\tthis.responseData.teamId = this.signupToken.teamId;\n\t}", "async login(username, password) {\n await (await this.btnPageSys).click();\n await (await this.btnLogSys).click();\n await (await this.btnLogAccount).click();\n await (await this.roleUser).selectByAttribute(\"value\", \"svcq\");;\n await (await this.inputUsername).setValue(username);\n await (await this.inputPassword).setValue(password);\n await (await this.btnSubmit).click();\n }", "login (userField, passField)\n {\n this.loginLogic(document.getElementById(userField).value, document.getElementById(passField).value);\n }", "function login() {\n var user = null;\n command_line.prompt('login:');\n // don't stor logins in history\n if (settings.history) {\n command_line.history().disable();\n }\n command_line.commands(function(command) {\n try {\n echo_command(command);\n if (!user) {\n user = command;\n command_line.prompt('password:');\n command_line.mask(true);\n } else {\n command_line.mask(false);\n self.pause();\n if (typeof settings.login != 'function') {\n throw \"Value of login property must be a function\";\n }\n settings.login(user, command, function(user_data) {\n if (user_data) {\n var name = settings.name;\n name = (name ? '_' + name : '');\n $.Storage.set('token' + name, user_data);\n $.Storage.set('login' + name, user);\n //restore commands and run interpreter\n command_line.commands(commands);\n // move this to one function init.\n initialize();\n } else {\n self.error('Wrong password try again');\n command_line.prompt('login:');\n user = null;\n }\n self.resume();\n if (settings.history) {\n command_line.history().enable();\n }\n });\n }\n } catch (e) {\n display_exception(e, 'LOGIN', self);\n throw e;\n }\n });\n }", "function login(){\n browser.maximizeWindow()\n browser.url('https://stage.pasv.us/user/login')\n $('[name=\"email\"]').setValue('[email protected]')\n $('[name=\"password\"]').setValue('lutka')\n $('[type=\"submit\"]').click()\n}", "async function testLogin1() {\n try {\n driver.get(url + \"login\");\n\n driver.findElement(By.id(\"normal_login_email\")).sendKeys(\"[email protected]\");\n driver.findElement(By.id(\"normal_login_password\")).sendKeys(\"abc888888888\");\n\n driver.findElement(By.className(\"login-form-button\")).click();\n } catch (err) {\n console.error(\"Something went wrong!\\n\", err.stack, \"\\n\");\n }\n}", "login_as(email, password) {\n this.open()\n var EmailField = browser.element(by.id('edit-name'));\n var PassField = browser.element(by.id('edit-pass'));\n var SubmitButton = browser.element(by.id('edit-submit'));\n EmailField.sendKeys(email); \n PassField.sendKeys(password);\n SubmitButton.click();\n browser.wait(EC.urlContains('/users'), 10000); // added an explicit wait as site much slow \n }", "function logIn() {\n\tvar user = $(\"#user\").val(); // Username\n\tvar pass = $(\"#pass\").val(); // Password\n\tconsole.log(user, pass);\n\thttpPostRequest(\n\t\t'/api-login/login',\n\t\t{user: user, pass: pass},\n\t\t'Login WRONG',\n\t\t(response) => {\n\t\t\t$(\"#name-user\").text(user);\n\t\t\t$(\"#not-logged\").hide();\n\t\t\t$(\"#logged\").show();\n\t\t\t// Random nickName and session\n\t\t\t$(\"#sessionName\").val(\"Session \" + Math.floor(Math.random() * 10));\n\t\t\t$(\"#nickName\").val(\"Participant \" + Math.floor(Math.random() * 100));\n\t\t}\n\t);\n}", "function u_login(ctx, email, password, uh, permanent) {\n ctx.result = u_login2;\n ctx.permanent = permanent;\n api_getsid(ctx, email, prepare_key_pw(password), uh);\n}", "function checkUserLogin() {\n if (!user) {\n loginWithRedirect()\n } else {\n getUserTeam();\n }\n }", "function login(context) {\n const username = this.params.username;\n const password = this.params.password;\n\n userModel.login(username, password)\n .then(function (res) {\n userModel.saveSession(res);\n handler.showInfo(`Successfully logged in!`);\n viewController.allListings(context);\n }).catch((err) => {\n handler.handleError(err);\n $('input[name=\"username\"]').val('');\n $('input[name=\"password\"]').val('');\n });\n }", "function dummyLogin() {\n// loginAs( dummyFilters );\n loginAs(memberSearchFilters);\n }", "login (username, password) {\n this.loginUsername.setValue(username);\n this.loginPassword.setValue(password);\n this.loginBtn.click();\n }", "function login () {\n vm.isloading= true;\n authUser.loginApi(vm.credential);\n }", "async login({name = '', pass = ''} = {}) {\n await this.enterUserName(name);\n await this.enterPassword(pass);\n return this.clickLoginButton();\n }", "login (username, password) {\n this.inputUsername.setValue(username);\n this.inputPassword.setValue(password);\n this.btnSubmit.click();\n }", "function loginUser( e, t ) {\n e.preventDefault();\n\n var username = t.find(\"#login-username\").value,\n password = t.find(\"#login-password\").value;\n\n Meteor.loginWithPassword( username, password, function( err ) {\n if( err )\n FlashMessages.sendError(\"Could not log you in, details: \" + err.toString() );\n var user = Meteor.user();\n try {\n if( user.profile.admin ) {\n // NOP\n }\n } catch ( e ) {\n FlashMessages.sendError(\"You need to be a superuser to login.\");\n }\n });\n}", "function main() {\r\n // user.userLogin(\"[email protected]\", \"sporks\");\r\n}", "function login() {\n\t\tclearPage();\n\t\twindow.CLASH.user.id = 0;\n\t\tlet loginForm = document.querySelector('#login');\n\t\tlet loginbtn = loginForm.querySelector('#loginBtn');\n\t\tlet password = loginForm.querySelector('#passwd');\n\t\tpassword.innerHTML = '';\n\t\tloginForm.classList.remove('h-login');\n\t\tloginbtn.classList.add('h-login');\n\t}", "function api_login(user, pass){\n\t\tif(!isBlank(main_data.login.un) && !isBlank(main_data.login.pass)){\n\t\t\tvar myJSON = {\"_object\":\"auth\",\"_action\":\"login\",\"_source\":main_data.login.method,\"email\":main_data.login.un,\"password\":main_data.login.pass};\n\t\t\tapi_get(myJSON,api_login_callback);\n\t\t}\n\t}", "login (userRole) {\n this.inputEmail.setValue(userRole.email);\n this.inputPassword.setValue(userRole.password);\n this.btnSubmit.waitForDisplayed({timeout: 2000} );\n this.btnSubmit.click();\n }", "function login(){\n dispatch(findUser(document.getElementById('email').value,document.getElementById('password').value));\n }", "function loginUser(username, password) {\n $.post(\"api/user/login\", {\n username: username,\n password: password\n })\n .then(function() {\n console.log(\"Success!\")\n })\n .catch(function(err) {\n console.log(err);\n });\n }", "async function testLogin2() {\n try {\n driver.get(url + \"login\");\n\n driver\n .findElement(By.id(\"normal_login_email\"))\n .sendKeys(\"[email protected]\");\n driver.findElement(By.id(\"normal_login_password\")).sendKeys(\"abc888\");\n\n driver.findElement(By.className(\"login-form-button\")).click();\n } catch (err) {\n console.error(\"Something went wrong!\\n\", err.stack, \"\\n\");\n }\n}", "orderAccess() {\n loginPage.open();\n loginPage.username.setValue('[email protected]');\n loginPage.password.setValue('pepito');\n loginPage.submit();\n }", "function loginUserCallback() {\n loginUser();\n }", "async function login() {\n let form = $('#formLogin');\n let username = form.find('input[name=\"username\"]').val();\n let password = form.find('input[name=\"passwd\"]').val();\n\n try {\n let response = await requester.post('user', 'login', 'basic', { username, password });\n saveSession(response);\n showView('viewAds');\n showInfo('Successfully logged in!');\n } catch (e) {\n handleError(e);\n }\n }", "function loginUser(user, response)\n\t{\n\t\tclient.get(\"username:\" + user.username, function(err, id) {\n\t\t\tif (err != null)\n\t\t\t{\n\t\t\t\tconsole.log(err);\n\t\t\t\thandleReply(buildResponse(500, null, \"err\"), response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (id == null)\n\t\t\t{\n\t\t\t\thandleReply(buildResponse(401, null, \"Username not found\"), response);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclient.hget(\"user_id:\" + id, \"password\", function(err, reply){\n\t\t\t\tif (user.password != reply)\n\t\t\t\t{\n\t\t\t\t\thandleReply(buildResponse(401, null, \"Password doesn't match records\"), response);\n\t\t\t\t\tconsole.log(\"Pw: \" + reply);\n\t\t\t\t\tconsole.log(\"Actual pw: \" + user.password);\n\t\t\t\t}\n\t\t\t\tvar auth = Math.random().toString(36).slice(2);\n\t\t\t\tclient.set(\"auth:\" + auth, id, function(err){ if (err) console.log(err); });\n\t\t\t\tclient.hset(\"user_id:\" + id, \"api_key\", auth);\n\t\t\t\tclient.hset(\"user_id:\" + id, \"api_date\", new Date());\n\t\t\t\thandleReply(buildResponse(200, {\"auth\" : auth}, null), response);\n\t\t\t});\n\t\t});\n\n\t}", "function doLogin(username, password, callback) {\n\tmagic(\n\t\t\t\"GetUserAuthentication\",\n\t\t\tusername,\n\t\t\tappname,\n\t\t\t\"\",\n\t\t\ttoken,\n\t\t\tpassword,\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\n\t\t\tfunction(res) {\n\t\t\t\tif (res.status == \"error\") {\n\t\t\t\t\tconsole.log(\"error logging in: \" + res.data);\n\n\t\t\t\t\tcallback(\"error\");\n\n\t\t\t\t} else {\n\t\t\t\t\tvar data = JSON.parse(res[\"data\"]);\n\n\t\t\t\t\tvar validUser = data[0][\"getuserauthenticationinfo\"][0][\"ValidUser\"];\n\t\t\t\t\tif (validUser.indexOf(\"YES\") != -1) {\n\t\t\t\t\t\twindow.ehrUsername = username;\n\t\t\t\t\t\twindow.ehrPassword = password;\n\n\t\t\t\t\t\tcallback(\"success\");\n\n\t\t\t\t\t} else\n\t\t\t\t\t\tcallback(\"invalid\");\n\t\t\t\t}\n\t\t\t});\n}", "async function login() {\n let form = $('#formLogin');\n let username = form.find('input[name=\"username\"]').val();\n let password = form.find('input[name=\"passwd\"]').val();\n\n try {\n let response = await requester.post('user', 'login', 'basic', {username, password});\n saveSession(response);\n showView('viewAds');\n showInfo('Successfully logged in!');\n } catch (e) {\n handleError(e);\n }\n }", "async function login(data) {\n const e = new FormError();\n\n // Attempt to find the user based on the username\n const user = await User.findOne({\n where: { user_login: data.username },\n });\n\n // If we don't have a valid user, throw.\n if (!user) {\n e.set('username', 'An account with that username does not exist.');\n }\n\n e.throwIf();\n\n const checkCapabilities = await Usermeta.findOne({\n attributes: ['umeta_id'],\n where: {\n user_id: user.id,\n meta_key: `${prefix}capabilities`,\n meta_value: {\n [Op.like]: '%contributor%',\n },\n },\n });\n\n if (!checkCapabilities) {\n e.set('username', 'An account with that username does not exist.');\n }\n\n e.throwIf();\n\n // Check that the passwords match\n if (!await checkPassword(data.password, user.user_pass)) {\n e.set('password', 'Your password is incorrect.');\n }\n\n e.throwIf();\n\n return user;\n }", "async handleLogin () {\n\t\tconst { email, password, teamId } = this.request.body;\n\t\tthis.user = await new LoginCore({\n\t\t\trequest: this\n\t\t}).login(email, password, teamId);\n\t}", "function login(){\n\t\tvar user = document.getElementById(\"username\").value;\n\t\tvar pass = document.getElementById(\"passBox\").value;\n\t\tvar remember = document.getElementById(\"rememberme\").checked;\n\t\t\n\t\t//for testing, send to http://webster.cs.washington.edu/params.php\n\t\t//post to login-submit.php\n\t\tpost_to_url(\"login-submit.php\", \n\t\t\t{\"user\":user,\"pass\":pass,\"remember\":remember});\n\t}", "function login(){\n\t\tvar user = document.getElementById(\"username\").value;\n\t\tvar pass = document.getElementById(\"passBox\").value;\n\t\tvar remember = document.getElementById(\"rememberme\").checked;\n\t\t\n\t\t//for testing, send to http://webster.cs.washington.edu/params.php\n\t\t//post to login-submit.php\n\t\tpost_to_url(\"login-submit.php\", \n\t\t\t{\"user\":user,\"pass\":pass,\"remember\":remember});\n\t}", "function loginUser () {\n const username = document.getElementById(\"email\").value\n const password = document.getElementById(\"password\").value\n const userUrl = urlBase + 'user/' + username\n console.log(userUrl)\n const user = {\n 'username': username,\n 'password': password,\n }\n loginUrl = urlBase + 'user/login'\n generalPost(loginUrl, user)\n \n \n}", "async doLogin () {\n\t\tconst loginHelper = new LoginHelper({\n\t\t\trequest: this.request,\n\t\t\tuser: this.user,\n\t\t\tloginType: this.loginType\n\t\t});\n\t\tif (this.notTrueLogin) {\n\t\t\tawait loginHelper.allowLogin();\n\t\t} \n\t\telse {\n\t\t\tthis.responseData = await loginHelper.login();\n\t\t}\n\t}", "function watchDemoBtn() {\n $('#demo-login').click(event => {\n const userData = {\n username: 'demouser1124',\n password: 'demopassword1124'\n };\n\n HTTP.loginUser({\n userData,\n onSuccess: res => {\n const authUser = res.user;\n authUser.jwtToken = res.jwtToken;\n CACHE.saveAuthenticatedUser(authUser);\n window.open('/user/hub.html', '_self');\n },\n onError: err => {\n $('#error-message').html(`\n <p>Your username and/or password were incorrect.</p>\n `);\n }\n });\n })\n}", "async login() {\n\t\t// Authentication is saved in cookie jar\n\t\tconst form = new FormData();\n\n\t\tform.append('email', this.email);\n\t\tform.append('password', this.password);\n\n\t\tconst result = await this.client.post('data/validate-login', {\n\t\t\tbody: form\n\t\t}).json();\n\n\t\tthis.signedUserId = result.signed_user_id;\n\t\tthis.uid = result.user_id;\n\n\t\tthis._setupWebSocket();\n\t}", "function userLogin(user) {\n loginStateChange(user);\n console.log(user.id);\n}", "function login(username, password) {\n let endpoint = \"/Users/login\";\n let payload = {\n \"username\":username,\n \"password\":password,\n };\n let headers = {\"Content-Type\":\"application/x-www-form-urlencoded\"};\n console.log(\"before send\");\n sendRequest(method, endpoint, headers, payload, loginCallback); // From CRUD.js\n return true;\n}", "async function doLogin() {\n\n const {password,passwordField,uri,username,usernameField} = _cfg.providerSite.loginForm\n\n await siteScraper.doLoginWithCookies({\n log,\n loginFormUri: uri,\n loggedInCookieNames: _cfg.providerSite.loggedInCookieNames,\n password,\n passwordField,\n username,\n usernameField,\n requester: ePayWindowRequest\n })\n}", "function login(email, password) {\n cy.get('input.email')\n .type(email)\n .should('have.value', email)\n cy.get('input.password')\n .type(password)\n .type('{enter}')\n cy.contains(email)\n cy.contains('Dashboard')\n cy.contains('Login to Wordsmith')\n .should('not.exist')\n}", "function login() {\n \tUserService.login(vm.user.username, vm.user.password)\n .then(function(response){\n if(response.data) {\n $rootScope.currentUser = response.data;\n $location.url(\"/profile\");\n }\n });\n }", "loginWithPassword(password) {\n this.open();\n this.login('[email protected]', password);\n }", "function login() {\n\n\t\t// Check for arguments. The first argument, could be a callback\n\t\t// Because some actions need login first\n\t\tvar args = slice.call(arguments, 0), callback = args.shift();\n\n\t\t// Handle the response of login\n\t\tfunction handleLogin(response) {\n\t\t\t// error handling\n\t\t\tif (response && response.error) {\n\t\t\t\tconsole.log('Error on UserModule', 'Can\\'t login', response);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// if there's any callback there, just call him\n\t\t\tif (typeof callback === 'function') { callback(args); }\n\t\t}\n\n\t\t// Login with facebook\n\t\tFB.login(handleLogin, { scope: u.SCOPE });\n\n\t}", "function login() {\n Auth.login(authCtrl.user).then(function(){\n $state.go('home');\n });\n }", "userLogin(loginData) {\n\n var user = this.app.User();\n var loginRequest = user.login(loginData.email, loginData.password);\n return this.makePromise(loginRequest);\n }", "function loginUser(email, password) {\n $.post('/api/login', {\n email,\n password,\n })\n .then(() => {\n window.location.replace('/members');\n // If there's an error, log the error\n })\n .catch(handleLoginErr);\n }", "initLogin() {\n this.send({\n id: 10000,\n magic: '0x1234',\n method: 'global.login',\n params: {\n clientType: '',\n ipAddr: '(null)',\n loginType: 'Direct',\n password: '',\n userName: this.dahua_username,\n },\n session: 0,\n });\n }", "function login(error, data) {\n if(error) { console.log(error) }\n console.log(\"in loggingin.js: login()\")\n return db.checkLogin(data.username, data.password)\n}", "function doLogin() {\n vm.processing = true;\n\n // clear the error\n vm.error = '';\n\n Auth\n .login(vm.loginData.username, vm.loginData.password)\n .success(function(data) {\n vm.processing = false;\n\n // if a user successfully logs in, redirect to users page\n if (data.success) {\n $location.path('/users');\n } else {\n vm.error = data.message;\n }\n });\n }", "function retrieveLogin(email, password) {\n $.post(\"/api/login\",\n { email, password }\n ).then(function (res) {\n console.log(res)\n // USER LOGIN SUCCESSFUL\n if (res.success === true) {\n window.localStorage.setItem(\"user_id\", res.user.id);\n window.location.href = \"/inventory\"\n }\n // USER LOGIN FAILED\n else {\n // display login error message\n $(\"#invalidLogin\").append(\"<b>INVALID LOGIN</b>\");\n }\n });\n }", "login(email, password) {\n return __awaiter(this, void 0, void 0, function* () {\n let response = yield request({\n method: 'post',\n json: true,\n uri: `${this.EFoodAPIOrigin}/api/v1/user/login`,\n body: { email, password }\n });\n if (response.status == 'ok') {\n this.store.sessionId = response.data.session_id;\n this.store.user = trimName(response.data.user);\n }\n return response.status == 'ok';\n });\n }", "loginIntoAdminBackend() {\n cy.goToPage(this.AdminUrl);\n cy.loginIntoAccount('input[name=email]', 'input[name=passwd]', 'admin');\n }", "function loginUser(ev) {\n ev.preventDefault();\n let inputUsername = $('#loginUsername');\n let inputPassword = $('#loginPasswd');\n\n let usernameVal = inputUsername.val();\n let passwdVal = inputPassword.val();\n\n auth.login(usernameVal, passwdVal)\n .then((userInfo) => {\n saveSession(userInfo);\n inputUsername.val('');\n inputPassword.val('');\n showInfo('Login successful.');\n }).catch(handleError);\n }", "doLogin() {\n //abort in case of validation errors\n if (this.user.UserID === '' ||\n this.user.Password === '' || \n this.user.UserID === null || \n this.user.Password === null ) { return; }\n var self = this;\n\n //update with user credentials\n angular.extend(this.credentials, this.user);\n\n //call webapi to login the user\n var onLoginSuccess = function onLoginSuccessCallback() {\n var handlePostlogin = self.auth.handlePostLogin;\n return function (data) {\n handlePostlogin.apply(self.auth, arguments)\n };\n };\n\n this.auth\n .login(this.credentials)\n .then(onLoginSuccess());\n }", "function loginUser(password)\n{\n\tvar transaction = pimsDB.transaction(\"users\");\n\tvar objectStore = transaction.objectStore(\"users\");\n\tvar request = objectStore.get(password);\n\trequest.onsuccess = function(e)\n\t{\n\t\tif (e.target.result == null)\n\t\t{\n\t\t\t$(\"#login_password\").val(\"\");\n\t\t\tshowUserMessage(\"INVALID PASSWORD\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tuserInitials = e.target.result.initials;\n\t\t\thideUserMessage();\n\t\t\t$(\"#login_password\").css(\"display\", \"none\");\n\t\t\tinitMenu();\n\t\t}\n\t};\t\n}", "function loginUser(e, data) {\n\t//Disable page refresh with preventDefault\n\t//preventDefault does have some weird behaviors\n\t//so it make cause some UI problems later\n\t//to avoid, use a div instead of a button or input\n\t//and do not submit\n\te.preventDefault();\n\n\t//map values to variables\n\tlet login = data.login[0];\n\tlet email = data.email;\n\tlet password = data.password;\n\n\t//call the graphQL endpoint with the given variables, since its an outside API call its a promise\n\tlogin({ variables: { email: email.value, password: password.value } })\n\t\t.then((res) => {\n\t\t\t//default prompt should display an error\n\t\t\tvar prompt = { title: 'Failed to Login', type: 'error' };\n\t\t\t//if logged in return true from the GRAPHQL API then change prompt\n\t\t\tif (res.data.login) {\n\t\t\t\tprompt = { title: 'Welcome back ' + res.data.login.email + '!', type: 'success' };\n\t\t\t}\n\n\t\t\t//function that calls UI component\n\t\t\tsweatAlert(prompt);\n\t\t})\n\t\t.catch((err) => {\n\t\t\t//This logs the error onto the console\n\t\t\tconsole.error(err + ' => LoginIn View : FAILED AT loginUser');\n\t\t\t//Displays error to user\n\t\t\tsweatAlert({ title: 'Internal Server Error', type: 'error' });\n\t\t});\n}", "function doLogin() {\n console.log('Doing login', vm.loginData);\n\n // Simulate a login delay. Remove this and replace with your login\n // code if using a login system\n $timeout(delayLoad, 1000);\n\n /**\n * Closes the modal\n */\n function delayLoad() {\n vm.closeLogin();\n }\n }", "async function login() {\n let user = Moralis.User.current();\n if (!user) {\n user = await Moralis.authenticate();\n }\n console.log(\"logged in user:\", user);\n}", "static async login(data) {\n return App.make('Auth').login(data);\n }", "function login(username, password, success, failure) {\n if (username === 'admin' && password === 'admin') {\n success('Login success')\n } else {\n failure('Login failed')\n }\n}", "function loginUser(email, password) {\n $.post(\"/api/login\", {\n email: email,\n password: password\n }).then(() => {\n window.location.replace(\"/search\");\n // If there's an error, log the error\n }, handleLoginErr({ responseJSON: \"Invalid email/password combination\" }));\n }", "function loginUser(email, password) {\n\t\t// POST call to login route\n\t\t$.post(\"/api/login\", {\n\t\t\temail: email,\n\t\t\tpassword: password,\n\t\t})\n\t\t\t// Redirect to entry page\n\t\t\t.then(function() {\n\t\t\t\twindow.location.replace(\"/moods-entry\");\n\t\t\t})\n\t\t\t// Handle errors\n\t\t\t.catch(function(err) {\n\t\t\t\tthrow err;\n\t\t\t});\n\t}", "function login(callback) {\n request\n .get(config.host+root+'/getUserInfo')\n .set('x-dev-token', config.token)\n .end(handler(function(resp){\n if( !resp.error ) {\n config.user = resp;\n }\n\n callback(resp);\n }));\n}", "function logEditorIn(login, password, doOnSuccess, doOnFailure){\n\tmakeJsonRequest('atomics/log_editor_in.php', 'l=' + login + '&p=' + password, {\n\t\tsuccess: function(response){\n\t\t\tswitch(response.status){\n\t\t\t\tcase 'success' :\n\t\t\t\t\tdoOnSuccess(response.editor_name)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'failure' :\n\t\t\t\t\tif(doOnFailure){\n\t\t\t\t\t\tdoOnFailure()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t})\n}", "function login(user, password) {\n if (user === \"userName\" && password === \"password1\") {\n return \"Logged in with regular callback\";\n } else {\n return \"wrong credentials\";\n }\n}", "async function logAuserIn() {\n let userService = new UserService(process.env.MICRO_API_TOKEN);\n let rsp = await userService.login({\n email: \"[email protected]\",\n password: \"mySecretPass123\",\n });\n console.log(rsp);\n}", "function login(user, callback) {\n queryFactory.query('POST', \"user/auth\", {}, user).then(function (response) {\n if (response.data.status === \"success\") {\n saveSession(response.data);\n callback(response.data)\n\n }\n else if (response.data.status === \"error\"){\n callback(response.data);\n }\n\n }, function (err) {\n callback(err)\n });\n }", "static loginUser(email: string, password: string): Promise<*> {\n const url = LoginServerUrls.login();\n return LoginServerRequests.request(url, null, null, email, password);\n }", "login (user) {\n return API.User.Login(user)\n .then(response => {\n this.setSession(response)\n return 'success'\n })\n .catch(error => {\n AppSignal.sendError(error)\n throw error\n })\n }", "function loginUser(email, password) {\n $.post(\"/api/login\", {\n email: email,\n password: password\n })\n .then(() => {\n window.location.replace(\"/members\");\n // If there's an error, log the error\n })\n }", "function logInAnotherUser() {\n window.localStorage.removeItem(\"loggedBlogger\")\n let user2 = {\n name: \"Kerho Ukkonen\",\n username: \"keukkone\",\n password: \"gekko96\",\n }\n cy.request(\"POST\", \"http://localhost:3001/api/users/\", user2)\n\n cy.request(\"POST\", \"http://localhost:3001/api/login\", {\n username: user.username,\n password: user.password,\n }).then((response) => {\n localStorage.setItem(\"loggedBlogger\", JSON.stringify(response.body))\n cy.visit(\"http://localhost:3000\")\n })\n }", "login(user = \"anonymous\", password = \"guest\") {\n this.ftp.log(`Login security: ${(0, netUtils_1.describeTLS)(this.ftp.socket)}`);\n return this.ftp.handle(\"USER \" + user, (res, task) => {\n if (res instanceof Error) {\n task.reject(res);\n }\n else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) { // User logged in proceed OR Command superfluous\n task.resolve(res);\n }\n else if (res.code === 331) { // User name okay, need password\n this.ftp.send(\"PASS \" + password);\n }\n else { // Also report error on 332 (Need account)\n task.reject(new FtpContext_1.FTPError(res));\n }\n });\n }" ]
[ "0.7651535", "0.7440154", "0.7367435", "0.7206985", "0.71536726", "0.71252376", "0.7107737", "0.7081823", "0.6984199", "0.69768536", "0.69349104", "0.69219434", "0.6918515", "0.6914208", "0.68136704", "0.68124044", "0.6802883", "0.6800781", "0.68003964", "0.6782678", "0.6764182", "0.6751715", "0.6732662", "0.67046434", "0.6681424", "0.6674526", "0.66630673", "0.66413635", "0.6640947", "0.66398036", "0.6636431", "0.66318005", "0.66283673", "0.6615948", "0.66134125", "0.66079473", "0.6607253", "0.6603653", "0.65981364", "0.6598002", "0.6573136", "0.6572471", "0.6568017", "0.655816", "0.6543208", "0.6541605", "0.6540845", "0.6534647", "0.65339816", "0.6531557", "0.6521775", "0.6520795", "0.6508311", "0.6501057", "0.64992654", "0.6496468", "0.6496013", "0.64915943", "0.648977", "0.6489475", "0.6489475", "0.6473362", "0.6471462", "0.64687234", "0.6465955", "0.6457391", "0.64552414", "0.6445329", "0.64383835", "0.64321226", "0.64319885", "0.6430311", "0.64178914", "0.6413801", "0.6395055", "0.63842154", "0.6379469", "0.63784087", "0.63726324", "0.6371245", "0.63693476", "0.6368589", "0.636066", "0.6359449", "0.6351716", "0.63460827", "0.6346017", "0.6341205", "0.63411826", "0.6334076", "0.6313998", "0.6313455", "0.63108647", "0.6310347", "0.63055235", "0.6303252", "0.6295972", "0.6294962", "0.62931496", "0.6293105", "0.62880814" ]
0.0
-1
TEST SUITE TEST 1
function test1() { const actual = myAtoi('42'); const expected = 42; if (actual === expected) { return '✔'; } return 'X'; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function testRun()\r\n{\r\n}", "run_test() { start_tests(); }", "function runTests() {\n\ttestBeepBoop();\n\ttestGetDigits();\n}", "function generateTest() {\n // TODO\n}", "function testMain() {\n var mode = 'test';\n main(mode);\n}", "function ct_test() {\n return ok;\n}", "function test() {\n console.log('Beginning test process!'.blue);\n projects.action = 'test';\n github.getCredentials()\n .catch(janitor.error('Failure getting credentials'.red))\n .then(greenlight.getGradable)\n .catch(janitor.error('Failure getting sessions'.red))\n .then(sessions.selectSession)\n .catch(janitor.error('Failure selecting session'.red))\n .then(projects.selectProject)\n .catch(janitor.error('Failure selecting project'.red))\n .then(grabTests)\n .catch(janitor.error('Failure grabbing tests'.red))\n .then(runTests)\n .catch(janitor.error('Failure running tests'.red))\n .then(displayResults)\n .catch(janitor.error('Failure displaying results'.red))\n .then(() => console.log('Successfully concluded test.'.blue))\n .catch((err) => { console.error(err); });\n}", "function test() {\n runTests0();\n runTests1(); \n return true;\n}", "function testAllTests() {\n testExtremal();\n testDifference();\n testSpearman();\n testSerial()\n}", "async generateTests()\n {\n this.description = 'Basic Tests:';\n\n this.addTest(new Test('This is an example test. The first parameter is a description.', DescriptionTest));\n }", "function test(test) {\n var attrs = {\n classname: test.parent.fullTitle()\n , name: test.title\n , time: test.duration / 1000\n };\n\n if ('failed' == test.state) {\n var err = test.err;\n attrs.message = escape(err.message);\n console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));\n } else if (test.pending) {\n console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));\n } else {\n console.log(tag('testcase', attrs, true) );\n }\n}", "function runTest() {\n Logger.log(\"This is the newest test\");\n}", "_passed(test) {\n console.log(\"Test has Passed\");\n const sessionId = this._getSessionId();\n this._updateBuild(sessionId, { 'status': 'passed', 'name': test.title });\n }", "function startAllTests(){ \n testGetObjectFromArrays();\n testNormalizeHeader();\n testFillInTemplateFromObject();\n testIsCellEmpty();\n testIsAlnum();\n testIsDigit();\n}", "function run(){\n\n\tdescribe(\"XML Tester\", function(){\n\t\t\n\t\t//gameName = process.env.npm_config_gamename;\n\t\t//console.log(\"Testing \" + gameName);\n\t\t\n\t\t//findXML();\n\t\t//parseXML();\n\t\t//loadGame();\n\t\t//StartMultiGameTest();\n\t});\n}", "function runTest() {\n return exports.handler(test_input3, test_context, function(err, result) {\n if (err) console.error(err);\n else console.log(result);\n });\n}", "function test() {\n console.log(\"tested!\");\n}", "function testFunction() {\nconsole.log('you passed the test');\n}", "function AssertTests() {\n}", "function test() {\n console.log('TEST SUITE');\n for(let i=0; i < testFuncs.length; i++) {\n let test = testFuncs[i];\n try {\n test();\n console.log('(' + i + ')' + test.name + ': PASS')\n } catch(e) {\n console.log('(' + i + ')' + test.name + ': FAIL');\n console.log(e);\n }\n }\n}", "enterTest(ctx) {\n\t}", "function start_test(scope){\n\tif(current_test==0){\n\t\tmachine_stage.getChildByName(\"test_1\").text = kplus_test_values[current_test_beaker_number-6]\t+\" ppm\";\n\t\tchangeFlame(1);\n\t}\n\telse{\n\t\tmachine_stage.getChildByName(\"test_1\").text = naplus_test_values[current_test_beaker_number-6]\t+\" ppm\";\n\t\tchangeFlame(0);\n\t}\n}", "function run_test() {\n do_calendar_startup(run_next_test);\n}", "function testInstaller(test){\n if (true){\n return '>'+test; \n }\n}", "async function basicTesting() {\n console.log(chalk.white(\"INITIALIZING BASIC TESTING\"));\n await testAvailableBooks();\n await testTicker(\"btc_mxn\");\n await testGetTrades(\"btc_mxn\");\n await testOrders(\"eth_mxn\", \"buy\", \"1.0\", \"market\");\n await testOrders(\"eth_mxn\", \"sell\", \"1.0\", \"market\");\n await testWithdrawals(\"btc\", \"0.001\", \"15YB8xZ4GhHCHRZXvgmSFAzEiDosbkDyoo\");\n await testBalances();\n}", "function test_candu_collection_tab() {}", "function beforeTest()\n{\n\tconsole.log(\"'beforeTest' executed\");\n}", "test() {\n return true\n }", "function setUp() {\n}", "function testServer(test) { //{{{\n test.done();\n }", "testArtists() {\n this.artistTest.startAllTests();\n }", "onTestPass(test) {\n this._passes++;\n this._out.push(test.title + ': pass');\n let status_id = this.qaTouch.statusConfig('Passed');\n let caseIds = this.qaTouch.TitleToCaseIds(test.title);\n if (caseIds.length > 0) {\n let results = caseIds.map(caseId => {\n return {\n case_id: caseId,\n status_id: status_id,\n };\n });\n this._results.push(...results);\n }\n }", "function indexTests() {\n let startTestNum = startGameTests(); //testing the startGame function\n let callUnoTestNum = callUnoTests(); //testing the callUno function\n let cheatTestNum = cheatTests();\n console.log(\"\\n$ * * * * All tests for index.js * * * *\");\n console.log(\n \"$ Total tests for start() - 3. Passed: \" +\n startTestNum +\n \". Failed: \" +\n (3 - startTestNum)\n );\n console.log(\n \"$ Total tests for callUno() - 2. Passed: \" +\n callUnoTestNum +\n \". Failed: \" +\n (2 - callUnoTestNum)\n );\n console.log(\n \"$ Total tests for all cheats - 4. Passed: \" +\n cheatTestNum +\n \". Failed: \" +\n (4 - cheatTestNum)\n );\n console.log(\"\\n$ * * * * End tests for index.js * * * *\");\n return startTestNum + callUnoTestNum + cheatTestNum;\n}", "function getTestsCount (){ return this.testsCount }", "function testClient(test) { //{{{\n test.done();\n }", "function _testRunnerMain() {\n _doSetup();\n\n // if there's no _runTest, assume we need to test the parser. Pass Processing env.\n if (this._testWrapper)\n this._testWrapper(this._pctx);\n else\n _checkParser();\n\n if (this._finished)\n this._finished();\n\n print('TEST-SUMMARY: ' + _passCount + '/' + _failCount);\n}", "function run_all_tests(){\n\t$(\"#tests_list .section_title\").each(function(num,obj){\n\t\ttype=obj.id.substr(8);\n\t\trun_tests(type);\n\t});\n}", "function TEST_TITLE() {\n var ownName = arguments.callee.caller.toString();\n // Trim off \"function \".\n ownName = ownName.substr('function '.length);\n // Trim off everything after the function name.\n ownName = ownName.substr(0, ownName.indexOf('('));\n LOG('========================================');\n LOG('Running test: ' + ownName);\n LOG('');\n numErrors_ = 0;\n}", "async function main() {\n const g_tests = async (flag) => {\n let test_base;\n let prefix = '';\n switch (flag) {\n case 'm':\n test_base = test_base_general;\n prefix = 'test_';\n break;\n case 'a':\n test_base = test_base_audio;\n prefix = 'test_';\n break;\n case 's':\n case 'c':\n test_base = test_base_toc;\n break;\n }\n ;\n const retval = await get_tests(`${test_base}/index.json`, prefix);\n return retval;\n };\n const preamble_run_test = async (name) => {\n if (name[0] === 'm' || name[0] === 'a' || name[0] === 's' || name[0] === 'c') {\n const tests = await g_tests(name[0]);\n run_test(tests[name].url);\n }\n else {\n throw new Error('Abnormal test id...');\n }\n };\n try {\n if (process.argv && process.argv.length > 2) {\n if (process.argv[2] === '-sm' || process.argv[2] === '-sa') {\n const label = process.argv[2][2];\n const tests = await g_tests(label);\n const scores = generate_scores(tests);\n console.log(JSON.stringify(scores, null, 4));\n }\n else if (process.argv[2] === '-l') {\n // run a local test that is not registered in the official test suite\n run_test(process.argv[3]);\n }\n else {\n preamble_run_test(process.argv[2]);\n }\n }\n else {\n preamble_run_test('m4.01');\n }\n }\n catch (e) {\n console.log(`Something went very wrong: ${e.message}`);\n process.exit(1);\n }\n}", "function logtest(name) {\n log.info(\"----------\");\n log.info((testnum++)+\". \"+name);\n}", "async test() {\n /**\n * @summary 测试数据库连接\n * @description 测试swagger\n * @router post /home/test\n * @request body test 配置请求携带参数\n * @Request header string token eg:write your params at here\n * @response 200 JsonResult 操作结果\n */\n const { ctx } = this;\n ctx.body = await this.service.home.test();\n }", "function testAll() {\n testAssert()\n testRemainder()\n testConversions()\n}", "function test(msg, run){\n\t\t\tTimer.start(msg);\n\t\t\tvar activeTest = {\n\t\t\t\tname: msg\n\t\t\t};\n\t\t\tactiveSuite.tests.push(activeTest);\n\t\t\ttry {\n\t\t\t\trun();\n\t\t\t\tactiveSuite.passedTestsCount++;\n\t\t\t\tactiveTest.duration = Timer.stop(msg);\n\t\t\t} catch(e) {\n\t\t\t\tactiveTest.duration = Timer.stop(msg);\n\t\t\t\tactiveTest.error = true;\n\t\t\t\tactiveSuite.error = true;\n\t\t\t\tactiveSuite.failedTestsCount++;\n\t\t\t\tif(e.name == \"AssertionError\"){\n\t\t\t\t\tactiveTest.message = e.message;\n\t\t\t\t\tactiveTest.actual = \"\" + e.actual;\n\t\t\t\t\tactiveTest.expected = \"\" + e.expected;\n\t\t\t\t} else {\n\t\t\t\t\tactiveTest.message = \"Error: \" + e;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function RunTests() {\n var storeIds = [175, 42, 0, 9];\n var transactionIds = [9675, 23, 123, 7];\n\n storeIds.forEach(function(storeId) {\n transactionIds.forEach(function(transactionId) {\n var shortCode = generateShortCode(storeId, transactionId);\n var decodeResult = decodeShortCode(shortCode);\n $(\"#test-results\").append(\n \"<div>\" + storeId + \" - \" + transactionId + \": \" + shortCode + \"</div>\"\n );\n AddTestResult(\"Length <= 9\", shortCode.length <= 9);\n AddTestResult(\"Is String\", typeof shortCode === \"string\");\n AddTestResult(\"Is Today\", IsToday(decodeResult.shopDate));\n AddTestResult(\"StoreId\", storeId === decodeResult.storeId);\n AddTestResult(\"TransId\", transactionId === decodeResult.transactionId);\n });\n });\n}", "function countTestCases()/* : Number*/\n {\n return 1;\n }", "function Test() {\n\tallReset();\n\tTest = new classTest();\n\tpost(\"start\", \"\\n\");\n\tdisplayAll(); \t\n\t}", "function Test() {\n\tallReset();\n\tTest = new classTest();\n\tpost(\"start\", \"\\n\");\n\tdisplayAll(); \t\n\t}", "function test1(arg1) {\n console.log(\"test1: \" + arg1);\n }", "testAlbums() {\n this.albumTest.startAllTests();\n }", "function run_tests(type){\n\t$(\"#tests_\"+type+\"s tr\").each(function(num,obj){\n\t\tid=obj.id.substr(5);\n\t\tname = $(\"#\"+obj.id+\" .test_name\").html();\n\t\tname = name.substr(0,name.length);\n\t\trun_test(id,type,name);\n\t});\n}", "function test() {\n return 1;\n }", "enterAnd_test(ctx) {\n\t}", "function PerformanceTestCase() {\n}", "function fullTest(Srl){\n\tGen = Srl.Generative;\n\tAlgo = Srl.Algorithmic;\n\tMod = Srl.Transform;\n\tRand = Srl.Stochastic;\n\tStat = Srl.Statistic;\n\tTL = Srl.Translate;\n\tUtil = Srl.Utility;\n\n\t// testSerial();\n\ttestGenerative();\n\ttestAlgorithmic();\n\ttestStochastic();\n\ttestTransform();\n\ttestStatistic();\n\ttestTranslate();\n\ttestUtility();\n}", "function runTests(e, p) {\n console.log(\"Check requested\")\n\n // Create Notification object (which is just a Job to update GH using the Checks API)\n var note = new Notification(`tests`, e, p);\n note.conclusion = \"\";\n note.title = \"Run Tests\";\n note.summary = \"Running the test targets for \" + e.revision.commit;\n note.text = \"This test will ensure build, linting and tests all pass.\"\n\n // Send notification, then run, then send pass/fail notification\n return notificationWrap(build(e, p), note)\n}", "function RunTests() {\n\n var storeIds = [175, 42, 0, 9]\n var transactionIds = [9675, 23, 123, 7]\n\n storeIds.forEach(function (storeId) {\n transactionIds.forEach(function (transactionId) {\n var shortCode = generateShortCode(storeId, transactionId);\n var decodeResult = decodeShortCode(shortCode);\n $(\"#test-results\").append(\"<div>\" + storeId + \" - \" + transactionId + \": \" + shortCode + \"</div>\");\n AddTestResult(\"Length <= 9\", shortCode.length <= 9);\n AddTestResult(\"Is String\", (typeof shortCode === 'string'));\n AddTestResult(\"Is Today\", IsToday(decodeResult.shopDate));\n AddTestResult(\"StoreId\", storeId === decodeResult.storeId);\n AddTestResult(\"TransId\", transactionId === decodeResult.transactionId);\n })\n })\n}", "function _runTest (index, basename, html) {\n const tests = [\n // preamble page\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // tests titlePage option\n _testToc(root, basename, 'Welcome');\n t.is(root.find('#_footnoteref_3').length, 1);\n t.is(root.find('#_footnotedef_3').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // part I\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Part I');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap 1\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '1. First Chapter');\n t.is(root.find('#_footnoteref_4').length, 1);\n t.is(root.find('#_footnotedef_4').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // chap 2\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2. Second Chapter');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec1\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.1. Chap2. First Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.2. Chap2. Second Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-1 (depth:3)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.2.1. Chap2. Sec 2-1');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-1-1 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-1-1');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-1-2 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-1-2');\n t.is(root.find('#_footnoteref_4').length, 1);\n t.is(root.find('#_footnotedef_4').length, 1);\n t.is(root.find('a.footnote').length, 2); // multiply referred in Sec 2-1-2\n t.is(root.find('div.footnote').length, 1);\n },\n // chap2 sec2-2 (depth:3)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.2.2. Chap2. Sec 2-2');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-2-1 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-2-1');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-2-2 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-2-2');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-2-3 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-2-3<sup class=\"footnote\">[1]</sup>');\n t.is(root.find('#_footnoteref_1').length, 1);\n t.is(root.find('#_footnotedef_1').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // chap2 sec2-3 (depth:3)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.2.3. Chap2. Sec 2-3');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec3 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.3. Chap2. Third Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // part II\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Part II');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap 3 (depth:1)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3. Third Chapter<sup class=\"footnote\">[2]</sup>');\n t.is(root.find('#_footnoteref_2').length, 1);\n t.is(root.find('#_footnotedef_2').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // chap3 sec1 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3.1. Chap3. First Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap3 sec2 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3.2. Chap3. Second Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap3 sec3 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3.3. Chap3. Third Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n ];\n if (tests[index])\n tests[index](basename, html);\n }", "enterTestlist1(ctx) {\n\t}", "function standAloneTest()\n{\n $(\"#qunit\").css({display: \"block\"})\n\n gbmLggDzSpecificTests();\n\n} // standAloneTest", "function run_tests(showbanner)\n{\n\tDEBUG = true;\n\tlog.redirect(log.CONSOLE);\n\tlog.init();\n\t\n\tvar rootcon = new Console();\n\tneuro_addKeyPressListener(rootcon.keyListener);\n\tneuro_addKeyUpListener(rootcon.keyUpListener);\n\tneuro_addKeyDownListener(rootcon.keyDownListener);\n\t\n\tlog.info(\"JU Test thinks you are running: \" + SysBrowser.getGuessDisplay());\n\t//log.info(new SysBrowser().report(true));\n\t\n\tif(showbanner)\n\t\tju_show_banner();\n\t\n\tresultsdiv = document.getElementById(\"testresults\");\n\t\n\t//for(i in this)\n\tfor(i in Tests)\n\t{\n\t\t//if it looks like a test function\n\t\tvar arry = i.toString().match(/^test_/);\n\t\tif(arry != null && arry.length > 0)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\teval( \"ju_test_results.put('\"+i+\"',eval(Tests.\" + i+\"()))\" );\n\t\t\t}\n\t\t\tcatch(e)\n\t\t\t{\n\t\t\t\tju_test_results.put(i, JUAssert.fail() );\n\t\t\t\tlog.error(e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tju_display_results();\n}", "function afterTest()\n{\n\tconsole.log(\"'afterTest' executed\");\n}", "function run_selectedTests() {\r\n\tadd_UnSelectedTestsToShould_ignore();\r\n\tvar suite = framework.createTestSuite(framework.testcaseArray[\"suiteName\"]);\r\n\tfor (var tc in framework.testcaseArray) {\r\n\t\tsuite.add(framework.testcaseArray[tc]);\r\n\t}\r\n\tframework.runSuite(suite);\r\n\t//enable the four display button\r\n\tdocument.getElementById('btnXML').style.display = 'inline';\r\n\tdocument.getElementById('btnTAP').style.display = 'inline';\r\n\tdocument.getElementById('btnJUnitXML').style.display = 'inline';\r\n\tdocument.getElementById('btnJSON').style.display = 'inline';\r\n\tdocument.getElementById('btnSendReport').style.display = 'inline';\r\n}", "function TestMethods() {}", "enterTestlist(ctx) {\n\t}", "function testAddSuccess() {\r\n assertEquals(2, add(1,1));\r\n}", "function test() {\n waitForExplicitFinish();\n\n getParentProcessActors(testTarget);\n}", "function retrieveUnitTests()\n{\n // get the manifest and status filter\n var manifest = getTestSuiteManifest();\n var status = getUnitTestStatusFilter();\n\n // note the test cases are loading\n document.getElementById('unit-tests').innerHTML = \"<span style=\\\"font-size: 150%; font-weight: bold; color: #f00\\\">Test Cases are Loading...</span>\";\n\n // send the HTTP request to the crazy ivan web service\n sendRequest('retrieve-tests?manifest=' + manifest +\n '&status=' + status, displayUnitTests)\n}", "function generateTestCaseCallback(Y) {\r\n var testCases = new Array();\r\n var Assert = Y.Assert;\r\n\t\t\r\n testCases[0] = new Y.Test.Case({\r\n name: \"blackberry.invoke for Task\",\r\n\t\t\t\r\n\t\t\tsetUp : function () {\r\n\t\t\t\t//Order is a stack, last object will appear first in DOM\r\n\t\t\t\tframework.setupFailButton();\r\n\t\t\t\tframework.setupPassButton();\r\n\t\t\t\tframework.setupInstructions();\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\ttearDown : function () {\r\n\t\t\t\tframework.tearDownFailButton();\r\n\t\t\t\tframework.tearDownPassButton();\r\n\t\t\t\tframework.tearDownInstructions();\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.invoke.TaskArguments should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.invoke.TaskArguments);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.invoke.TaskArguments.VIEW_NEW should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.invoke.TaskArguments.VIEW_NEW);\r\n\t\t\t\tAssert.areSame(0, blackberry.invoke.TaskArguments.VIEW_NEW);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.invoke.TaskArguments.VIEW_EDIT should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.invoke.TaskArguments.VIEW_EDIT);\r\n\t\t\t\tAssert.areSame(1, blackberry.invoke.TaskArguments.VIEW_EDIT);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//Invoke Task with TaskArguments with no parameters defined\r\n\t\t\t\"MANUAL 1 should invoke Task with empty TaskArguments\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Result should be Task application opening up\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to invoke task and passing empty TaskArguments\");\r\n\t\t\t\tvar args = new blackberry.invoke.TaskArguments();\r\n blackberry.invoke.invoke(blackberry.invoke.APP_TASKS, args);\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//Invoke Task with TaskArgument-VIEW_NEW-Summary\r\n\t\t\t\"MANUAL 2 should invoke Task with TaskArguments with VIEW_NEW and Summary\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Result should be Task application opening up\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to invoke task and passing TaskArguments with VIEW_NEW\");\r\n\t\t\t\tvar task = new blackberry.pim.Task();\r\n\t\t\t\ttask.summary = 'Summary and New';\r\n\t\t\t\tvar args = new blackberry.invoke.TaskArguments(task);\r\n\t\t\t\targs.view = 0;\r\n blackberry.invoke.invoke(blackberry.invoke.APP_TASKS, args);\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//Invoke Task with TaskArgument-VIEW_EDIT-Summary\r\n\t\t\t\"MANUAL 3 should invoke Task with TaskArguments with VIEW_EDIT and Summary\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Result should be Task application opening up\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to invoke task and passing TaskArguments with VIEW_EDIT\");\r\n\t\t\t\tvar task = new blackberry.pim.Task();\r\n\t\t\t\ttask.summary = 'Summary and Edit';\r\n\t\t\t\ttask.save();\r\n\t\t\t\tvar args = new blackberry.invoke.TaskArguments(task);\r\n\t\t\t\targs.view = 1;\r\n blackberry.invoke.invoke(blackberry.invoke.APP_TASKS, args);\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\r\n });\r\n\t\t\r\n return testCases;\r\n }", "async function runTests () {\n\tawait countSimpleFamilies()\n\tawait simpleExample()\n\tawait countSimpleFamilies()\n}", "function onRunTestClicked(e) {\n e.preventDefault();\n executableModuleMessageChannel.send('ui_backend', {'command': 'run_test'});\n}", "function test_service_bundle_vms() {}", "function unit() {\n // Add more tests here.\n return linkUnit();\n}", "function _runTest (index, basename, html) {\n const tests = [\n // preamble page\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Titlepage');\n t.is(root.find('#_footnoteref_3').length, 1);\n t.is(root.find('#_footnotedef_3').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // part I\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Part I');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap 1\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '1. First Chapter');\n t.is(root.find('#_footnoteref_4').length, 1);\n t.is(root.find('#_footnotedef_4').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // chap 2\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2. Second Chapter');\n t.is(root.find('#_footnoteref_1').length, 1);\n t.is(root.find('#_footnotedef_1').length, 1);\n t.is(root.find('#_footnoteref_4').length, 1);\n t.is(root.find('#_footnotedef_4').length, 1);\n t.is(root.find('a.footnote').length, 3); // multiply referred in Sec 2-1-2\n t.is(root.find('div.footnote').length, 2);\n },\n // part II\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Part II');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap 3\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3. Third Chapter<sup class=\"footnote\">[2]</sup>');\n t.is(root.find('#_footnoteref_2').length, 1);\n t.is(root.find('#_footnotedef_2').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n ];\n if (tests[index])\n tests[index](basename, html);\n }", "function RUN_ALL_TESTS() {\n console.log('> itShouldSaveSingleProperty');\n saveSingleProperty();\n console.log('> itShouldSaveMultipleProperties');\n saveMultipleProperties();\n console.log('> itShouldReadSingleProperty');\n readSingleProperty();\n console.log('> itShouldReadAllProperties');\n readAllProperties();\n // The tests below are successful if they run without any extra output\n console.log('> itShouldUpdateProperty');\n updateProperty();\n console.log('> itShouldDeleteSingleProperty');\n deleteSingleProperty();\n console.log('> itShouldDeleteAllUserProperties');\n deleteAllUserProperties();\n}", "function test01(){\n console.log(\"Test 01: Game is Initiallized: \");\n if(game)\n console.log(\"Passed.\");\n else\n console.log(\"failed.\");\n}", "function runTest(test) {\n debug(\"parsing test\");\n var testConfig = jf.readFileSync(process.env.SUITE_CONFIG);\n var wptLoc = testConfig.wptServer\n ? testConfig.wptServer\n : \"https://www.webpagetest.org\";\n\n var wpt = new WebPageTest(wptLoc, testConfig.wptApiKey),\n options = {\n pollResults: 5, //poll every 5 seconds\n timeout: 600, //wait for 10 minutes\n video: true, //this enables the filmstrip\n location: test.location,\n firstViewOnly: test.firstViewOnly, //refresh view?\n requests: false, //do not capture the details of every request\n lighthouse: true\n };\n\n wptScript = wpt.scriptToString(test.script);\n\n debug(\n \"starting test on script \" + wptScript + \" in location \" + test.location\n );\n\n wpt.runTest(wptScript, options, function(err, results) {\n if (err) {\n return console.error([err, { url: test.url, options: options }]);\n }\n dataStore.saveDatapoint(test, results);\n });\n}", "function test(testName, callback) {\n \tif (focused$1) {\n \t\treturn;\n \t}\n\n \tvar newTest = new Test({\n \t\ttestName: testName,\n \t\tcallback: callback\n \t});\n\n \tnewTest.queue();\n }", "function testSwitcher(count) {\r\n if (count < selectedTestList.length) {\r\n try {\r\n eval(selectedTestList[count] + \"()\");\r\n } catch(err) {\r\n console.log(\"Error while eval function \" + selectedTestList[count], err);\r\n }\r\n } else {\r\n done();\r\n }\r\n}", "function okTest1() {\n assert(true, \"assert true\")\n}", "async runTest() {}", "function setUp()/* : void*/\n {\n }", "function TestRoot() {}", "function checkUnitTest(num, html_url, sparql_url, expected_result)\n{\n var rdfaExtractorUrl = getRdfaExtractorUrl();\n var sparqlEngineUrl = getSparqlEngineUrl();\n \n document.getElementById('unit-test-status-' + num).innerHTML =\n \"CHECKING...\";\n sendRequest('check-test?id=' + num +\n '&source=' + html_url +\n '&sparql=' + sparql_url +\n '&expected-result=' + expected_result +\n '&rdfa-extractor=' + escape(rdfaExtractorUrl) +\n '&sparql-engine=' + escape(sparqlEngineUrl),\n displayUnitTestResult, num)\n}", "function runTest(callback) {\n currentIncrement = testsToRun[0];\n odfeRunner.setTestIncrement(currentIncrement);\n odfeRunner.setDocsBaseDir(testClassesDirectory);\n\tcurrentTest = currentIncrement.test;\n console.log(\"\\nRun test \" + currentTest);\n\tfs.copy(srcDir + currentTest, trgDir + currentTest, function (err) {\n\t\tif (err) {\n\t\t\tcallback(err);\n\t\t} else {\n\t\t\tconsole.log(\"To Run Moved \" + srcDir + currentTest + \" to \" + trgDir + currentTest);\n\t\t\ttestsToRun.shift();\n async.series([\n cover,\n parseCoverage,\n odfe,\n deleteTrgTest,\n deleteTrgTestFromTarget\n ], function (err) {\n console.log(\"Run test done for \" + currentTest);\n callback();\n });\n\t\t}\n\t});\n}", "function runTest(test) {\n test.testOptions.screenCapture = './accessability-test/output/' + test.name +'.png'\n var options = { \n ...test.testOptions, \n standard: 'Section508'}; //standard: 'Section508'}; standard: 'WCAG2AAA'; \"WCAG2A\"; WCAG2AA}; \n pa11y(test.url, options).then((results) => {\n results.screenGrab = test.name + '.png';\n var htmlResults = accReporter.process(results, test.url, true);\n fs.writeFile('accessability-test/output/'+ test.name + '.html', htmlResults, function(err) {})\n }).catch((err) => {\n console.log(err);\n });\n}", "function build_tests() {\r\n\t\tvar tests = new Collection(), version = \"Mon Dec 19 11:24:51 2011\";\r\n\r\n\t\t// check for existense of framework 2 files\r\n\t\tvar framework_file = test_presence.create_sub({\r\n\t\t\tid: \"framework-found\",\r\n\t\t\tname: \"The bm-framework.js file should be in the file manager\",\r\n\t\t\tdesc: \"The JavaScript framework 2.0 requires that the file bm-framework.js be loaded into the javascript folder in the file manager. You can get this file from the JavaScript Starter Kit. If this test is not passing, check that the sitename you entered on this page is correct, and also check the name of the case-sensitive 'javascript' folder.\",\r\n\t\t\tregex: /bootstrap/,\r\n\t\t\ttest_url: function() { return \"/bmfsweb/\"+templates.sitename+\"/image/javascript/bm-framework.js?break-cache\" },\r\n\t\t\tfix_url: function() { return \"/admin/filemanager/list_files.jsp\"; }\r\n\t\t});\r\n\t\ttests.add(framework_file);\r\n\r\n\t\ttests.add(\r\n\t\t\tframework_file.create_sub({\r\n\t\t\t\tid: \"framework-version\",\r\n\t\t\t\tregex: \"@version \"+version,\r\n\t\t\t\tname: \"bm-framework version (found in the comment at the top) should match \" + version,\r\n\t\t\t\tdesc: \"This test checks the time stamp on the version tag of the framework, and compares it to the latest release.<br/><br/>If this test raises a warning, confirm the @version stamp at the top of bm-framework is AFTER \" + version+\". <br/><br/>If the framework is out of date, download the latest version through the link at the top of the page.\",\r\n\t\t\t\twait_for: tests.find_by_ids(\"framework-found\")\r\n\t\t\t})\r\n\t\t);\r\n\r\n\t\ttests.add(\r\n\t\t\ttest_presence.create_sub({\r\n\t\t\t\tid: \"text-found\",\r\n\t\t\t\tname: \"The text.js file should be in the file manager\",\r\n\t\t\t\tdesc: \"The JavaScript framework 2.0 requires that the file text.js be loaded into the javascript folder in the file manager. You can get this file from the JavaScript Starter Kit. If this test is not passing, check that the sitename you entered on this page is correct, and also check the name of the case-sensitive 'javascript' folder.\",\r\n\t\t\t\tregex: /.*/,\r\n\t\t\t\ttest_url: function() { return \"/bmfsweb/\"+templates.sitename+\"/image/javascript/text.js?breach-cache\";},\r\n\t\t\t\tfix_url: function() { return \"/admin/filemanager/list_files.jsp\";}\r\n\t\t\t})\r\n\t\t);\r\n\r\n\r\n\t\t// defaults to the header/footer test - very straightforward\r\n\t\ttests.add(clone(test_absence));\r\n\r\n\t\ttests.add(\r\n\t\t\ttest_presence.create_sub({\r\n\t\t\t\tid: \"header-added\",\r\n\t\t\t\tname: \"Header/Footer should have a reference to bm-framework.js\",\r\n\t\t\t\tdesc: \"The framework 2.0 requires a script tag with reference to bm-framework.js: <br/> <code>&lt;script type='text/javascript' src='$BASE_PATH$/javascript/bm-framework.js' &gt;&lt;/script&gt;</code>\",\r\n\t\t\t\tregex: /bm-framework.js/\r\n\t\t\t})\r\n\t\t);\t\t\r\n\t\t\r\n\t\ttests.add(\r\n\t\t\ttest_absence.create_sub({\r\n\t\t\t\tid: \"nerfed\",\r\n\t\t\t\twarning_passes: false,\r\n\t\t\t\tname: \"The allplugins-require.js file should be replaced by the new version\",\r\n\t\t\t\tdesc: \"In 1.0, the file javascript/allplugins-require.js was the core of the framework. By replacing it with a dummy file, we are effectively disabling the old framework, without creating 404 errors on the server.<br/> If this test is failing, it means that we have detected the previous file in place.<br/> If you get a warning, it may mean that the file doesn't exist. This can be okay - just make sure that you remove all references to it in other places.\",\r\n\t\t\t\tregex: /define/,\r\n\t\t\t\ttest_url: function() { return \"/bmfsweb/\"+templates.sitename+\"/image/javascript/allplugins-require.js?break-cache\";},\r\n\t\t\t\tfix_url: function() { return \"/admin/filemanager/list_files.jsp\";}\r\n\t\t\t})\r\n\t\t);\r\n\r\n\t\t// homepage test - check the alt js for references\r\n\t\ttests.add(\r\n\t\t\ttest_absence.create_sub({\r\n\t\t\t\tid: \"homepage-remove\",\r\n\t\t\t\tname: \"The Home Page Alt JS file shouldn't have any references to allplugins-require.js (make sure you clear the cache)\",\r\n\t\t\t\tdesc: \"The references to allplugins-require.js need to be removed from the home page alternate JS file. This test fails when that old code is detected, and will show a warning if it can't find the file. In case of failure you can remove the entire function 'include_homepage_js', which is how the old code was loaded on the home page. As part of the upgrade, you will also be replacing this Alt JS file with a new piece of code. If you do remove this code, make sure that 'homepage' is marked as active in bm-framework.js.\",\r\n\t\t\t\twarning_passes: false,\r\n\t\t\t\ttest_url:function() { return \"/bmfsweb/\"+templates.sitename+\"/homepage/js/\"+templates.sitename+\"_Hp_Alt.js\";},\r\n\t\t\t\tfix_url:function() { return \"/admin/homepage/define_xsl_template.jsp\";}\r\n\t\t\t})\r\n\t\t);\r\n\r\n\t\t// homepage test - check the alt js for references\r\n\t\ttests.add(\r\n\t\t\ttest_presence.create_sub({\r\n\t\t\t\tid: \"homepage-param\",\r\n\t\t\t\tname: \"The Home Page Alt JS file should have a reference to bm-framework.js\",\r\n\t\t\t\tdesc: \"The JavaScript framework 2.0 uses an (optional) parameter to assist in identifying the home page. This file can be found in the JavaScript Start Kit; it is basically: <code>window['framework/homepage']=true</code>. If this test fails, it means that it found the Alt JS file, but no reference to the new code. A warning means it can't find the file.\",\r\n\t\t\t\twarning_passes: false,\r\n\t\t\t\tregex: /framework\\/homepage/,\r\n\t\t\t\twait_for: tests.find_by_ids(\"homepage-remove\"),\r\n\t\t\t\ttest_url:function() { return \"/bmfsweb/\"+templates.sitename+\"/homepage/js/\"+templates.sitename+\"_Hp_Alt.js\";},\r\n\t\t\t\tfix_url:function() { return \"/admin/homepage/define_xsl_template.jsp\";}\r\n\t\t\t})\r\n\t\t);\r\n\r\n\r\n\t\t// homepage test - check the homepage directly\r\n\t\ttests.add(\r\n\t\t\ttest_absence.create_sub({\r\n\t\t\t\tid: \"homepagedirect\",\r\n\t\t\t\tname: \"The Home Page shouldn't have any references to allplugins-require (will fail for comments)\",\r\n\t\t\t\tdesc: \"The home page may have some references to the old framework, that are outside of the alt js file. This could be from a customized Homepage XSL file, or more likely from a custom home page. If this test fails you will have to manually search for and remove these references.\",\r\n\t\t\t\twait_for: tests.find_by_ids(\"header\"),\r\n\t\t\t\ttest_url:function() { return \"/commerce/display_company_profile.jsp\";},\r\n\t\t\t\tfix_url:function() { return \"/commerce/display_company_profile.jsp\";},\r\n\t\t\t\twarning_passes: false\r\n\t\t\t})\r\n\t\t);\r\n\r\n\t\t// this one we need a refernce to later, so breaking the pattern a bit\r\n\t\tvar globalscript_test = test_absence.create_sub({\r\n\t\t\tid: \"gss-allplugin\",\r\n\t\t\tname: \"Global Script Search shouldn't have any matches for allplugins-require (will fail for comments)\",\r\n\t\t\tdesc: \"We are running a global script search for the term 'allplugins-require'. The test will fail if it finds any results. This can be used to identify any BML that is referencing the old framework directly. All these references should be removed. This will NOT show references from default values on config attributes. This will most likely only find one reference - in our BML Util Library 'require_javascript.'\",\r\n\t\t\twait_for: tests.find_by_ids(\"homepage-remove\", \"header\"),\r\n\t\t\ttest_url: function() { return \"/admin/scripts/search_script.jsp?formaction=searchBmScript&search_string=allplugins-require\";},\r\n\t\t\tfix_url:function() { return this.test_url(); },\r\n\t\t\tget_text: function() {\r\n\t\t\t\tvar defer = jq$.Deferred(), me = this;\r\n\t\t\t\tjq$.get(me.test_url(), {}, function(data) { \r\n\t\t\t\t\t//get rid of the first two... we put it there!\r\n\t\t\t\t\tdata = data.replace(me.regex, \"\");\r\n\t\t\t\t\tdata = data.replace(me.regex, \"\");\r\n\t\t\t\t\tdefer.resolve(data);\r\n\t\t\t\t});\r\n\r\n\t\t\t\treturn defer.promise();\r\n\t\t\t}\r\n\t\t});\r\n\t\ttests.add(globalscript_test);\r\n\r\n\t\t// global script test - for bml-util lib\r\n\r\n\t\ttests.add(\r\n\t\t\tglobalscript_test.create_sub({\r\n\t\t\t\tid: \"gss-bml\",\r\n\t\t\t\tname: \"Global Script Search shouldn't have any matches for require_javascript\",\r\n\t\t\t\tdesc: \"We are running a global script search for the term 'require_javascript'. The test will fail if it finds any results. This can be used to identify any BML that is referencing the now obsolete library that we used to load JavaScript in the Framework v1. These references should be removed, and the corresponding section activated in bm-framework.js.\",\r\n\t\t\t\twait_for: tests.find_by_ids(\"gss-allplugin\"),\r\n\t\t\t\tregex: /require_javascript/,\r\n\t\t\t\ttest_url: function() { return \"/admin/scripts/search_script.jsp?formaction=searchBmScript&search_string=require_javascript\";},\r\n\t\t\t\tfix_url: function() { return this.test_url();}\r\n\t\t\t})\r\n\t\t);\r\n\r\n\t\ttests.add(\r\n\t\t\ttest_absence.create_sub({\r\n\t\t\t\tid: \"start-configs\",\r\n\t\t\t\tname: \"Run this test again manually to begin the configuration tests.\",\r\n\t\t\t\tdesc: \"This test will run and fail the first time - you must manually run it in order to begin the configuration tests, which can be time intensive.\",\r\n\t\t\t\ttimes: 0,\r\n\t\t\t\trun: function() {\r\n\t\t\t\t\tif(this.times === 0) {\r\n\t\t\t\t\t\tthis.times += 1;\r\n\t\t\t\t\t\tthis.on_fail();\r\n\t\t\t\t\t\tthis.render();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.on_pass();\r\n\t\t\t\t\t\tthis.render();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t);\r\n\r\n\t\t// crawl the homepage, create a test for each configurator\r\n\t\ttests.add(\r\n\t\t\ttest_absence.create_sub({\r\n\t\t\t\tid: \"crawl\",\r\n\t\t\t\tname: \"Test configuration using homepage punchins... \",\r\n\t\t\t\tdesc: \"This test will crawl the home page for punchin urls, and then spin up a test for each one it finds. This is so that we can quickly crawl the configurators directly on the buyside, and identify which ones reference allplugins-require. Please note that this will only visit the first page of each configurator; it's possible that we will miss some references if they are buried deep within a configurator.\",\r\n\t\t\t\twait_for: tests.find_by_ids(\"homepage-remove\", \"header\", \"gss-allplugin\", \"gss-bml\", \"start-configs\"),\r\n\t\t\t\tregex: /require_javascript/,\r\n\t\t\t\ttest_url:function() { return \"/commerce/display_company_profile.jsp\";},\r\n\t\t\t\tfix_url:function() { return \"/commerce/display_company_profile.jsp\";},\r\n\t\t\t\t// this test spawns additional tests\r\n\t\t\t\trun: function() {\r\n\t\t\t\t\tvar me = this,\r\n\t\t\t\t\tdefer = jq$.Deferred(),\r\n\t\t\t\t\thome_str = jq$.ajax({\r\n\t\t\t\t\t\turl: me.test_url()\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tme.is_running = true;\r\n\t\t\t\t\thome_str.then(function(data) {\r\n\t\t\t\t\t\t// matches url for configurator punchins\r\n\t\t\t\t\t\tvar matches = data.match(/<a[^>]*?href=\"\\/commerce\\/new_equipment\\/.*?<\\/a>/g),\r\n\t\t\t\t\t\t\tcount = 0;\r\n\r\n\t\t\t\t\t\t_(matches).each(function(val) {\r\n\t\t\t\t\t\t\tvar label = val.match(/(>)(.*)(<)/)[2],\r\n\t\t\t\t\t\t\t\turl = val.match(/(\")(\\/commerce.*)(\")/)[2],\r\n\t\t\t\t\t\t\t\tid = eventify(\"bmjs-config-id-\" + count++),\r\n\t\t\t\t\t\t\t\ttest,\r\n\t\t\t\t\t\t\t\tdefer = jq$.Deferred(),\r\n\t\t\t\t\t\t\t\tdescription = \"This will scrape the first page of the configurator for references to allplugins-require, and fail if it finds any. This test was dynamically generated by scraping the home page for punchin URLs. If this test fails remove the references, then make sure config is active in the bm-framework.js file.\";\r\n\r\n\t\t\t\t\t\t\turl = url.replace(/&amp;/g, \"&\");\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\ttest = test_absence.create_sub({\r\n\t\t\t\t\t\t\t\tid: id,\r\n\t\t\t\t\t\t\t\tname: label + \" shouldn't have any references to allplugins-require.\",\r\n\t\t\t\t\t\t\t\tdesc: description,\r\n\t\t\t\t\t\t\t\ttest_url: function() { return url;},\r\n\t\t\t\t\t\t\t\tfix_url: function() { return url;},\r\n\t\t\t\t\t\t\t\twarning_passes: false\r\n\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\ttest.begin();\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\tme.on_pass();\r\n\t\t\t\t\t\tme.render();\r\n\t\t\t\t\t});\r\n\t\t\t\t\tme.render();\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t);\r\n\r\n\t\twindow.tests = tests;\r\n\t\treturn tests;\r\n\t}", "enterOr_test(ctx) {\n\t}", "function myTestName() {\n var testName = \"My Test Name\";\n logStart(testName);\n try {\n target.captureScreenWithName(\"screen name\");\n logMessage(\"1. First Step.\");\n \n // add steps here\n \n target.captureScreenWithName(\"Reading List\");\n logPass(testName);\n }\n catch(exception) {\n logMessage(\"TEST FAILED - \" + exception);\n logMessage(\"Logging Element Tree\");\n app.logElementTree();\n logFail(testName);\n }\n}", "function testCreate(){\n // debugger\n var notelist = new NoteList()\n var note = notelist.create(\"Go shopping\")\n testisNote(note)\n testDisplayNote()\n }", "function ClassTests()\n{\n}", "function GetTestability(){}", "beforeRun() {}", "function test_utilization_host() {}", "function _testSuiteInit() {\n return ImptTestHelper.runCommand(`impt project create --product ${PRODUCT_NAME} --create-product --name ${DG_NAME} --descr \"${DG_DESCR}\" ${outputMode}`, (commandOut) => {\n ImptTestHelper.emptyCheck(commandOut);\n });\n }", "function Test(suite, name, func) {\n this.suite = suite;\n this.name = name;\n this.func = func;\n this.title = name.replace(/^test/, '').replace(/([A-Z])/g, ' $1');\n\n this.failures = [];\n this.status = stati.notrun;\n this.checks = 0;\n}", "function test(bool) {\n if (!bool) {\n alert(\"Failed test. See console logs for error messages.\")\n console.error(\"Failed test '\" + TC_NAME +\"' in \" + TEST_FILENAME)\n console.log(\"Test case:\")\n console.dir(TC)\n console.log(\"Result:\")\n console.dir(RESULT)\n }\n}", "function start() {\n console.log('Starting!');\n test1();\n}", "function ok(test, desc) { expect(test).toBe(true); }", "function generateTestCaseCallback(Y) {\r\n var testCases = new Array();\r\n var Assert = Y.Assert;\r\n\t\t\t\r\n testCases[0] = new Y.Test.Case({\r\n name: \"blackberry.app Tests\",\r\n\t\t\t\r\n\t\t\tsetUp : function () {\r\n\t\t\t\t//Order is a stack, last object will appear first in DOM\r\n\t\t\t\tframework.setupFailButton();\r\n\t\t\t\tframework.setupPassButton();\r\n\t\t\t\tframework.setupInstructions();\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\ttearDown : function () {\r\n\t\t\t\tframework.tearDownFailButton();\r\n\t\t\t\tframework.tearDownPassButton();\r\n\t\t\t\tframework.tearDownInstructions();\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t_should: {\r\n error: {\r\n \"blackberry.app.exit should return an error\" : \"Too many arguments\",\r\n \"blackberry.app.requestBackground should return an error\" : \"Too many arguments\",\r\n\t\t\t\t\t\"blackberry.app.requestForeground should return an error\" : \"Too many arguments\",\r\n\t\t\t\t\t\"blackberry.app.setHomeScreenIcon should return an error\" : \"Argument is not nullable\",\r\n\t\t\t\t\t\"blackberry.app.setHomeScreenName should return an error\" : \"Required argument missing\",\r\n } \r\n },\r\n\t\t\t\r\n\t\t\t\"blackberry.app should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.event should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.event);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.author should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.author);\r\n\t\t\t\tAssert.isString(blackberry.app.author);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.authorEmail should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.authorEmail);\r\n\t\t\t\tAssert.isString(blackberry.app.authorEmail);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.authorURL should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.authorURL);\r\n\t\t\t\tAssert.isString(blackberry.app.authorURL);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.copyright should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.copyright);\r\n\t\t\t\tAssert.isString(blackberry.app.copyright);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.description should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.description);\r\n\t\t\t\tAssert.isString(blackberry.app.description);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.id should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.id);\r\n\t\t\t\tAssert.isString(blackberry.app.id);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.isForeground should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.isForeground);\r\n\t\t\t\tAssert.isBoolean(blackberry.app.isForeground);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.license should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.license);\r\n\t\t\t\tAssert.isString(blackberry.app.license);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.licenseURL should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.licenseURL);\r\n\t\t\t\tAssert.isString(blackberry.app.licenseURL);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.name should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.name);\r\n\t\t\t\tAssert.isString(blackberry.app.name);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.version should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.version);\r\n\t\t\t\tAssert.isString(blackberry.app.version);\r\n\t\t\t},\r\n\t\t\r\n\t\t/* Missing Test cases\r\n\t\t\t\"blackberry.app.requestBackground should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.requestBackground);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.requestForeground should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.requestForeground);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.setHomeScreenIcon should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.setHomeScreenIcon);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.setHomeScreenName should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.setHomeScreenName);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.showBannerIndicator should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.showBannerIndicator);\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t\"blackberry.app.removeBannerIndicator should exist\" : function() {\r\n\t\t\t\tAssert.isNotUndefined(blackberry.app.removeBannerIndicator);\r\n\t\t\t},\r\n\t\t*/\r\n \r\n \"blackberry.app.exit should return an error\": function() {\r\n try {\r\n blackberry.app.exit(\"ppp\"); \r\n } catch (err) {\r\n throw new Error(err); \r\n }\r\n },\r\n \r\n \"blackberry.app.requestBackground should return an error\": function() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tblackberry.app.requestBackground(\"ppp\");\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t}\r\n },\t\t\t\r\n \r\n \"blackberry.app.requestForeground should return an error\": function() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tblackberry.app.requestForeground(\"ppp\");\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t}\r\n },\r\n \r\n \"blackberry.app.setHomeScreenIcon should return an error\": function() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tblackberry.app.setHomeScreenIcon(null);\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t} \r\n },\r\n \r\n \"blackberry.app.setHomeScreenName should return an error\": function() {\r\n\t\t\t\ttry { \r\n\t\t\t\t\tblackberry.app.setHomeScreenName();\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t}\r\n },\r\n\r\n\t\t\t\"blackberry.app properties should be readonly\": function() {\r\n\t\t\t\tvar readOnly = false;\r\n\t\t\t\t\r\n\t\t\t\tvar author = blackberry.app.author;\r\n\t\t\t\tvar authorEmail = blackberry.app.authorEmail;\r\n\t\t\t\tvar copyright = blackberry.app.copyright;\r\n\t\t\t\tvar description = blackberry.app.description;\r\n\t\t\t\tvar id = blackberry.app.id;\r\n\t\t\t\tvar isForeground = blackberry.app.isForeground;\r\n\t\t\t\tvar license = blackberry.app.license;\r\n\t\t\t\tvar licenseURL = blackberry.app.licenseURL;\r\n\t\t\t\tvar name = blackberry.app.name;\r\n\t\t\t\tvar version = blackberry.app.version;\r\n\t\t\t\t\r\n\t\t\t\tblackberry.app.author = \"Incorrect Author\";\r\n\t\t\t\tblackberry.app.authorEmail = \"[email protected]\";\r\n\t\t\t\tblackberry.app.copyright = \"1234\";\r\n\t\t\t\tblackberry.app.description = \"Incorrect Description\";\r\n\t\t\t\tblackberry.app.id = \"incorrect id\";\r\n\t\t\t\tblackberry.app.isForeground = false;\r\n\t\t\t\tblackberry.app.license = \"Incorrect License\";\r\n\t\t\t\tblackberry.app.licenseURL = \"IncorrectLicenseUrl\";\r\n\t\t\t\tblackberry.app.name = \"Incorrect Name\";\r\n\t\t\t\tblackberry.app.version = \"9.9.9\";\r\n\t\t\t\t\r\n\t\t\t\tif (author == blackberry.app.author && authorEmail == blackberry.app.authorEmail &&\r\n\t\t\t\tcopyright == blackberry.app.copyright && description == blackberry.app.description &&\r\n\t\t\t\tid == blackberry.app.id && isForeground == blackberry.app.isForeground &&\r\n\t\t\t\tlicense == blackberry.app.license && licenseURL == blackberry.app.licenseURL &&\r\n\t\t\t\tname == blackberry.app.name && version == blackberry.app.version) {\r\n\t\t\t\t\treadOnly = true;\r\n\t\t\t\t}\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tAssert.isTrue(readOnly)\r\n },\r\n\t\t\t\r\n\t\t\t//app.exit() function will not work as it closes the widget\t\t\t\t\t\r\n\t\t\t\r\n\t\t\t//requestBackground\r\n\t\t\t\"MANUAL 1 should put application into the background\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Application should have gone into the background.<br />Pass this test if this is true. Otherwise, fail.\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Application is going to call app.requestBackground and send application into background\");\r\n\t\t\t\tblackberry.app.requestBackground();\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//requestForeground\r\n\t\t\t\"MANUAL 2 should put application into the background and then foreground\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Application will go into background and then foreground.<br />Pass this test if this is true. Otherwise, fail.\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Application is going to background for 3 seconds and then call app.requestForeground and go back into foreground\");\r\n\t\t\t\tblackberry.app.requestBackground();\r\n\t\t\t\tsetTimeout('blackberry.app.requestForeground()', 3000);\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//setHomeScreenIcon (Local)\r\n\t\t\t\"MANUAL 3 should set the homescreen icon to a local image\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Sets homescreen icon to local image.<br />Pass this test if this is true. Otherwise, fail.\");\r\n\t\t\t\tvar uri = \"local:///img/sample2.gif\";\r\n\t\t\t\talert(\"Will attempt to set homescreen icon to local image\");\r\n\t\t\t\tblackberry.app.setHomeScreenIcon(uri);\r\n\t\t\t\talert(\"HomeScreenIcon has been set\");\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//setHomeScreenIcon (External)\r\n\t\t\t\"MANUAL 4 should set the homescreen icon to an external image\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Sets homescreen icon to an external image.<br />Pass this test if this is true. Otherwise, fail.\");\r\n\t\t\t\tvar uri = \"http://www.rim.com/images/layout/new_layout/topleft.gif\";\r\n\t\t\t\talert(\"Will attempt to set homescreen icon to external image\");\r\n\t\t\t\tblackberry.app.setHomeScreenIcon(uri);\r\n\t\t\t\talert(\"HomeScreenIcon has been set\");\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//setHomeScreenIcon (hover)\r\n\t\t\t\"MANUAL 5 should set the homescreen icon hover to an image\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Sets homescreen icon hover to an image.<br />Pass this test if this is true. Otherwise, fail.\");\r\n\t\t\t\tvar uri = \"http://www.rim.com/images/layout/new_layout/home_infoarea_smartphones.jpg\";\r\n\t\t\t\talert(\"Will attempt to set homescreen icon hover to image\");\r\n\t\t\t\tblackberry.app.setHomeScreenIcon(uri, true);\r\n\t\t\t\talert(\"HomeScreenIcon hover has been set\");\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//setHomeScreenName\r\n\t\t\t\"MANUAL 6 should set the homescreen name to Hello World\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Sets homescreen name to 'Hello World'<br />Pass this test if this is true. Otherwise, fail.\");\r\n\t\t\t\talert(\"Will attempt to set homescreen name to 'Hello World'\");\r\n\t\t\t\tblackberry.app.setHomeScreenName(\"Hello World\");\r\n\t\t\t\talert(\"HomeScreenName has been set\");\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//Show all Properties\r\n\t\t\t\"MANUAL 7 should show all the application properties\": function() {\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Shows all application properties<br />Pass this test if this is true. Otherwise, fail.<br />\" +\r\n\t\t\t\t\"author=\" + blackberry.app.author + \"<br />\" +\r\n\t\t\t\t\"authorEmail=\" + blackberry.app.authorEmail + \"<br />\" +\r\n\t\t\t\t\"authorURL=\" + blackberry.app.authorURL + \"<br />\" +\r\n\t\t\t\t\"copyright=\" + blackberry.app.copyright + \"<br />\" +\r\n\t\t\t\t\"description=\" + blackberry.app.description + \"<br />\" +\r\n\t\t\t\t\"id=\" + blackberry.app.id + \"<br />\" +\r\n\t\t\t\t\"isForeground=\" + blackberry.app.isForeground + \"<br />\" +\r\n\t\t\t\t\"license=\" + blackberry.app.license + \"<br />\" +\r\n\t\t\t\t\"licenseURL=\" + blackberry.app.licenseURL + \"<br />\" +\r\n\t\t\t\t\"name=\" + blackberry.app.name + \"<br />\" +\r\n\t\t\t\t\"version=\" + blackberry.app.version\r\n\t\t\t\t);\r\n\t\t\t\talert(\"Will attempt to show all blackberry.app properties\");\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click) *24hr wait since wait() has a bug*\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t//app.event.onExit() (set and unset) - will not work as it closes the widget and kills YUI - needs to be tested manually\r\n\t\t\t\r\n\t\t\t//onBackground (set)\r\n\t\t\t\"blackberry.app.event onBackground event should trigger when application is set to background\": function() {\r\n\t\t\t\t\r\n\t\t\t\t//Sets flag and makes sure the application is in the foreground to start the test\r\n\t\t\t\tvar eventFlag = false;\r\n\t\t\t\tblackberry.app.requestForeground();\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t//Sets onBackground event to function that sets a flag to be true\r\n\t\t\t\t//Then puts application into the background\r\n\t\t\t\tblackberry.app.event.onBackground(function() { eventFlag = true; });\r\n\t\t\t\tblackberry.app.requestBackground();\r\n\t\t\t\tsetTimeout('Assert.isTrue(eventFlag)', 500);\r\n },\r\n\t\t\t\r\n\t\t\t//onBackground (unset)\r\n\t\t\t\"blackberry.app.event onBackground event should not trigger when application is set to background\": function() {\r\n\t\t\t\t\r\n\t\t\t\t//Sets flag and makes sure the application is in the foreground to start the test\r\n\t\t\t\tvar eventFlag = false;\r\n\t\t\t\tblackberry.app.requestForeground();\r\n\t\t\t\t\r\n\t\t\t\t//Sets onBackground event to something and then unsets it\r\n\t\t\t\t//Then puts application into the background\r\n\t\t\t\tblackberry.app.event.onBackground(function() { eventFlag = true; });\r\n\t\t\t\tblackberry.app.event.onBackground(null);\r\n\t\t\t\tblackberry.app.requestBackground();\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t//eventFlag should remain false since event function has nothing in it\r\n\t\t\t\tsetTimeout('Assert.isFalse(eventFlag)', 500);\r\n },\r\n\t\t\t\r\n\t\t\t//onForeground (set)\r\n\t\t\t\"blackberry.app.event onForeground event should trigger when application is set to foreground\": function() {\r\n\t\t\t\t\r\n\t\t\t\t//Sets flag and makes sure the application is in the foreground to start the test\r\n\t\t\t\tvar eventFlag = false;\r\n\t\t\t\tblackberry.app.requestForeground();\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t//Sets onForeground event to function that sets a flag to be true\r\n\t\t\t\t//Puts application into background, waits 3 seconds and puts application in foreground\r\n\t\t\t\tblackberry.app.event.onForeground(function() { eventFlag = true; });\r\n\t\t\t\tblackberry.app.requestBackground();\r\n\t\t\t\tsetTimeout('blackberry.app.requestForeground()', 3000);\t\t\t\t\t\t\t\t\r\n\t\t\t\tsetTimeout('Assert.isTrue(eventFlag)', 500);\r\n },\r\n\t\t\t\r\n\t\t\t//onForeground (unset)\r\n\t\t\t\"blackberry.app.event onForeground event should not trigger when application is set to foreground\": function() {\r\n\t\t\t\t\r\n\t\t\t\t//Sets flag and makes sure the application is in the foreground to start the test\r\n\t\t\t\tvar eventFlag = false;\r\n\t\t\t\tblackberry.app.requestForeground();\r\n\t\t\t\t\r\n\t\t\t\t//Sets onForeground event to something and then unsets it\r\n\t\t\t\t//Puts application into background, waits 3 seconds and puts application in foreground\t\t\t\t\r\n\t\t\t\tblackberry.app.event.onForeground(function() { eventFlag = true; });\r\n\t\t\t\tblackberry.app.event.onForeground(null);\r\n\t\t\t\tblackberry.app.requestBackground();\r\n\t\t\t\tsetTimeout('blackberry.app.requestForeground()', 3000);\t\t\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t//eventFlag should remain false since event function has nothing in it\r\n\t\t\t\tsetTimeout('Assert.isFalse(eventFlag)', 500);\r\n },\r\n\t\t\t\r\n\t\t\t/***** BannerIndicator Tests *****/\r\n\t\t\t/*\t\t\t\r\n\t\t\t\"MANUAL 8a showBannerIndicator should add an indicator icon\": function() {\t\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Banner Indicator icon should be set.\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to set the banner indicator icon from local source (gif).\");\t\t\t\t\r\n\t\t\t\tblackberry.app.showBannerIndicator(\"icon.gif\");\r\n\t\t\t\t\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click)\r\n },\r\n\t\t\t\r\n\t\t\t\"MANUAL 8b showBannerIndicator should update an indicator icon\": function() {\t\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Banner Indicator icon should be updated.\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to update the banner indicator icon.\");\t\t\t\t\r\n\t\t\t\tblackberry.app.showBannerIndicator(\"icon2.gif\");\r\n\t\t\t\t\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click)\r\n },\r\n\t\t\t\r\n\t\t\t\"MANUAL 9 showBannerIndicator should add an indicator icon with value\": function() {\t\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Banner Indicator icon should be set with a value (15).\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to set the banner indicator icon with value.\");\t\t\t\t\r\n\t\t\t\tblackberry.app.showBannerIndicator(\"icon.gif\", 15);\r\n\t\t\t\t\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click)\r\n },\r\n\t\t\t\r\n\t\t\t\"MANUAL 10 showBannerIndicator should add an indicator icon with value larger than 99\": function() {\t\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Banner Indicator icon should be set with a value 99+.\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to set the banner indicator icon with value larger than 99.\");\t\t\t\t\r\n\t\t\t\tblackberry.app.showBannerIndicator(\"icon.gif\", 150);\r\n\t\t\t\t\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click)\r\n },\r\n\t\t\t\r\n\t\t\t\"MANUAL 11 removeBannerIndicator should remove Indicator\": function() {\t\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Banner Indicator should be removed.\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to remove the banner indicator.\");\t\t\t\t\r\n\t\t\t\tblackberry.app.removeBannerIndicator();\r\n\t\t\t\t\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click)\r\n },\r\n\t\t\t\r\n\t\t\t//ADD TO QC\r\n\t\t\t\"MANUAL 12 showBannerIndicator should work with jpg images\": function() {\t\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Banner Indicator icon should be set (jpg).\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to set the banner indicator icon from local source (jpg).\");\r\n\t\t\t\t//blackberry.app.showBannerIndicator(\"??.jpg\");\r\n\t\t\t\t\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click)\r\n },\r\n\t\t\t\r\n\t\t\t//ADD TO QC\r\n\t\t\t\"MANUAL 13 showBannerIndicator should work with png images\": function() {\t\r\n\t\t\t\tframework.test = this; //so pass() and fail() can access this test\r\n\t\t\t\tframework.setInstructions(\"Banner Indicator icon should be set (png).\");\r\n\t\t\t\t\r\n\t\t\t\talert(\"Will attempt to set the banner indicator icon from local source (png).\");\r\n\t\t\t\t//blackberry.app.showBannerIndicator(\"??.png\");\r\n\t\t\t\t\r\n\t\t\t\tframework.test.wait(24*60*60*1000); //wait until user inputs the test result (via button click)\r\n },\r\n\t\t\t\r\n\t\t\t//Negative BannerIndicator Tests\r\n\t\t\t\"blackberry.app.showBannerIndicator should throw an error when the icon path is incorrect\": function() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tblackberry.app.showBannerIndicator(\"noImage.gif\");\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t}\r\n },\r\n\t\t\t\r\n\t\t\t\"blackberry.app.showBannerIndicator should throw an error when passed a string to the value\": function() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tblackberry.app.showBannerIndicator(\"icon.gif\", \"error\");\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t}\r\n },\r\n\t\t\t\r\n\t\t\t\"blackberry.app.showBannerIndicator should throw an error when value passed without icon\": function() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tblackberry.app.showBannerIndicator();\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t}\r\n },\r\n\t\t\t\r\n\t\t\t//NEED TO ADD TO QC\r\n\t\t\t\"blackberry.app.removeBannerIndicator should throw an error when given parameter\": function() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tblackberry.app.removeBannerIndicator(\"string\");\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t}\r\n },\r\n\t\t\t\r\n\t\t\t//NEED TO ADD TO QC\r\n\t\t\t\"blackberry.app.showBannerIndicator should throw an error when given image larger than 32x32\": function() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\t//blackberry.app.showBannerIndicator(??); //Image larger than 32x32 pixels\r\n\t\t\t\t} catch (err) {\r\n\t\t\t\t\tthrow new Error(err);\r\n\t\t\t\t}\r\n },\r\n\t\t\t*/\r\n });\r\n\r\n return testCases;\r\n }", "function assert(test, test_number) {\n if (test) {\n console.log(test_number + \"false\");\n }\n else{\n\t console.log(test_number + \"true\");\n \treturn true;\n\t}\n}", "function runTest(oTest) {\n\t\t\tfunction onLoad() {\n\t\t\t\tvar oQUnit = oTest.frame.contentWindow.QUnit;\n\n\t\t\t\toTest.frame.removeEventListener(\"load\", onLoad);\n\t\t\t\t// see https://github.com/js-reporters/js-reporters (@since QUnit 2)\n\t\t\t\toQUnit.on(\"runStart\", function (oDetails) {\n\t\t\t\t\toTest.testCounts = oDetails.testCounts;\n\t\t\t\t\toTest.testCounts.finished = 0;\n\t\t\t\t\toTest.infoNode.data = \": 0/\" + oTest.testCounts.total;\n\t\t\t\t});\n\t\t\t\toQUnit.on(\"testEnd\", function () {\n\t\t\t\t\toTest.testCounts.finished += 1;\n\t\t\t\t\toTest.infoNode.data = \": \" + oTest.testCounts.finished + \"/\"\n\t\t\t\t\t\t+ oTest.testCounts.total;\n\t\t\t\t});\n\t\t\t\toQUnit.on(\"runEnd\", function (oDetails) {\n\t\t\t\t\toTest.testCounts = oDetails.testCounts;\n\t\t\t\t\tsummary(oDetails.runtime, oTest);\n\t\t\t\t\toTest.element.firstChild.classList.remove(\"running\");\n\t\t\t\t\tif (oDetails.status === \"failed\") {\n\t\t\t\t\t\toTest.element.firstChild.classList.add(\"failed\");\n\t\t\t\t\t\toFirstFailedTest = oFirstFailedTest || oTest;\n\t\t\t\t\t} else if (!mParameters.keepResults) {\n\t\t\t\t\t\t// remove iframe in order to free memory\n\t\t\t\t\t\tdocument.body.removeChild(oTest.frame);\n\t\t\t\t\t\toTest.frame = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tif (bVisible && oTest === oSelectedTest) {\n\t\t\t\t\t\tselect(oTest); // unselect the test to make it invisible\n\t\t\t\t\t}\n\t\t\t\t\tiRunningTests -= 1;\n\t\t\t\t\tnext();\n\t\t\t\t});\n\t\t\t}\n\n\t\t\toTest.top = iTop;\n\t\t\tiTop += 1000;\n\t\t\toTest.frame = document.createElement(\"iframe\");\n\t\t\toTest.frame.src = oTest.url;\n\t\t\toTest.frame.setAttribute(\"height\", \"900\");\n\t\t\toTest.frame.setAttribute(\"width\", \"1600\");\n\t\t\toTest.frame.style.position = \"fixed\";\n\t\t\toTest.frame.style.top = oTest.top + \"px\";\n\t\t\tdocument.body.appendChild(oTest.frame);\n\t\t\toTest.element.firstChild.classList.add(\"running\");\n\t\t\tiRunningTests += 1;\n\t\t\toTest.frame.addEventListener(\"load\", onLoad);\n\t\t\tif (bVisible) {\n\t\t\t\tselect(oTest);\n\t\t\t}\n\t\t}" ]
[ "0.7460813", "0.69406533", "0.6825967", "0.6769557", "0.67594725", "0.6685041", "0.6664985", "0.66433096", "0.66404855", "0.6636985", "0.65658647", "0.6559172", "0.6534115", "0.6496234", "0.64826566", "0.642303", "0.6373392", "0.63660884", "0.63588333", "0.6326417", "0.63031226", "0.63013065", "0.62984014", "0.62960273", "0.6282726", "0.6275355", "0.6261136", "0.6227133", "0.6224755", "0.6212218", "0.6200172", "0.6198381", "0.61683095", "0.6161542", "0.6157734", "0.614373", "0.61366016", "0.61324286", "0.61297476", "0.6118251", "0.61138046", "0.6111919", "0.609514", "0.60800034", "0.60717523", "0.60709655", "0.60709655", "0.6064964", "0.6060679", "0.6057042", "0.6047405", "0.60422635", "0.60361373", "0.60324055", "0.60188967", "0.5970679", "0.5963554", "0.59632885", "0.59547424", "0.5947563", "0.594728", "0.5945079", "0.5942155", "0.5937458", "0.5935045", "0.5932266", "0.5919469", "0.591686", "0.5916786", "0.5907007", "0.5904222", "0.5904181", "0.5896444", "0.58960223", "0.5891433", "0.5875834", "0.5875491", "0.58751553", "0.587143", "0.58633345", "0.5854007", "0.58393526", "0.5836243", "0.5830689", "0.5818994", "0.5816992", "0.58105624", "0.5810043", "0.5808585", "0.58077955", "0.57961136", "0.5795316", "0.57780313", "0.5776854", "0.5776596", "0.5776335", "0.5770566", "0.57668126", "0.5760741", "0.5750014", "0.5741197" ]
0.0
-1
Part Two Time to improve the polymer. One of the unit types is causing problems; it's preventing the polymer from collapsing as much as it should. Your goal is to figure out which unit type is causing the most problems, remove all instances of it (regardless of polarity), fully react the remaining polymer, and measure its length. For example, again using the polymer dabAcCaCBAcCcaDA from above: Removing all A/a units produces dbcCCBcCcD. Fully reacting this polymer produces dbCBcD, which has length 6. Removing all B/b units produces daAcCaCAcCcaDA. Fully reacting this polymer produces daCAcaDA, which has length 8. Removing all C/c units produces dabAaBAaDA. Fully reacting this polymer produces daDA, which has length 4. Removing all D/d units produces abAcCaCBAcCcaA. Fully reacting this polymer produces abCBAc, which has length 6. In this example, removing all C/c units was best, producing the answer 4. What is the length of the shortest polymer you can produce by removing all units of exactly one type and fully reacting the result?
function findWeakestLink(s) { var shortestOutput = 999999; for (let c = "A".charCodeAt(0); c < "Z".charCodeAt(0); c++) { var stripC = new RegExp(String.fromCharCode(c), "gi"); var output = react(s.replace(stripC, "")); if (output.length < shortestOutput) { shortestOutput = output.length; } } return shortestOutput; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function reduce3(polymer, ignoreUnit = \"_\") {\n const stack = [];\n /* for of loop is slower than for loop\n https://jsperf.com/for-loop-vs-for-of-strings/1\n */\n for (let i = 0; i < polymer.length; i++) {\n const u = polymer[i];\n if (isSameLetter(u, ignoreUnit)) {\n continue;\n } else if (stack.length && willCancel(stack[stack.length - 1], u)) {\n stack.pop();\n } else {\n stack.push(u);\n }\n }\n\n return stack.join(\"\");\n}", "function shortestSubset(polymer) {\n let letters = [ /a/gi, /b/gi, /c/gi, /d/gi, /e/gi, /f/gi, /g/gi, /h/gi, /i/gi, /j/gi, /k/gi, /l/gi, /m/gi, /n/gi, /o/gi, /p/gi, /q/gi, /r/gi, /s/gi, /t/gi, /u/gi, /v/gi, /w/gi, /x/gi, /y/gi, /z/gi ];\n let shortest = polymer.length;\n for (letter of letters) {\n\tlet newpoly = polymer.split(letter).join('');\n\tlet newlen = stripCommon(newpoly);\n\tif (newlen < shortest) {\n\t shortest = newlen;\n\t}\n }\n return shortest;\n}", "function reduce2(polymer, ignoreUnit = \"_\") {\n if (polymer.length === 2) {\n if (willCancel(...polymer)) {\n return \"\";\n }\n return reduce2(polymer[0], ignoreUnit) + reduce2(polymer[1], ignoreUnit);\n } else if (polymer.length === 1) {\n return !isSameLetter(polymer, ignoreUnit) ? polymer : \"\";\n }\n\n const middle = Math.trunc(polymer.length / 2);\n const left = polymer.slice(0, middle);\n const right = polymer.slice(middle);\n\n const leftRes = reduce2(left, ignoreUnit);\n const rightRes = reduce2(right, ignoreUnit);\n\n if (leftRes.length === 0 || rightRes.length === 0) {\n return leftRes + rightRes;\n }\n\n /* check if the 2 letters when the 2 halves join will cancel out\n ie. left is BaCD, and right is dcZa, when joined will be BaCDdcZa\n Dd is cancelled, then Cc\n */\n let l, r;\n for (\n l = leftRes.length - 1, r = 0;\n l >= 0 && r < rightRes.length && willCancel(leftRes[l], rightRes[r]);\n l--, r++\n ) {}\n\n return leftRes.slice(0, l + 1) + rightRes.slice(r);\n}", "function simplify(polymer) {\n let head, root;\n for (const letter of polymer) {\n if (head) {\n head = head.append(letter);\n } else {\n head = new DLLNode(letter);\n root = head;\n }\n }\n\n head = root;\n while (head) {\n const next = head.next;\n if(!next) break;\n\n const a = head.value;\n const b = next.value;\n if (a === b) {\n // Skip AA and aa\n head = next;\n } else if (a.toLowerCase() !== b.toLowerCase()) {\n // Skip anything which is not aA or Aa\n head = next;\n } else {\n if(head.previous) {\n const previous = head.previous;\n previous.next = next.next;\n if(previous.next) {\n previous.next.previous = previous;\n }\n head = previous;\n } else {\n root = next.next;\n root.previous = null;\n root.next.previous = root;\n head = root;\n }\n }\n }\n\n return root.toString();\n}", "function doHumanization (ms, options) {\n var i, len, piece\n\n // Make sure we have a positive number.\n // Has the nice sideffect of turning Number objects into primitives.\n ms = Math.abs(ms)\n\n var dictionary = options.languages[options.language] || languages[options.language]\n if (!dictionary) {\n throw new Error('No language ' + dictionary + '.')\n }\n\n var pieces = []\n\n // Start at the top and keep removing units, bit by bit.\n var unitName, unitMS, unitCount\n for (i = 0, len = options.units.length; i < len; i++) {\n unitName = options.units[i]\n unitMS = options.unitMeasures[unitName]\n\n // What's the number of full units we can fit?\n if (i + 1 === len) {\n unitCount = ms / unitMS\n } else {\n unitCount = Math.floor(ms / unitMS)\n }\n\n // Add the string.\n pieces.push({\n unitCount: unitCount,\n unitName: unitName\n })\n\n // Remove what we just figured out.\n ms -= unitCount * unitMS\n }\n\n var firstOccupiedUnitIndex = 0\n for (i = 0; i < pieces.length; i++) {\n if (pieces[i].unitCount) {\n firstOccupiedUnitIndex = i\n break\n }\n }\n\n if (options.round) {\n var ratioToLargerUnit, previousPiece\n for (i = pieces.length - 1; i >= 0; i--) {\n piece = pieces[i]\n piece.unitCount = Math.round(piece.unitCount)\n\n if (i === 0) { break }\n\n previousPiece = pieces[i - 1]\n\n ratioToLargerUnit = options.unitMeasures[previousPiece.unitName] / options.unitMeasures[piece.unitName]\n if ((piece.unitCount % ratioToLargerUnit) === 0 || (options.largest && ((options.largest - 1) < (i - firstOccupiedUnitIndex)))) {\n previousPiece.unitCount += piece.unitCount / ratioToLargerUnit\n piece.unitCount = 0\n }\n }\n }\n\n var result = []\n for (i = 0, pieces.length; i < len; i++) {\n piece = pieces[i]\n if (piece.unitCount) {\n result.push(render(piece.unitCount, piece.unitName, dictionary, options))\n }\n\n if (result.length === options.largest) { break }\n }\n\n if (result.length) {\n if (!options.conjunction || result.length === 1) {\n return result.join(options.delimiter)\n } else if (result.length === 2) {\n return result.join(options.conjunction)\n } else if (result.length > 2) {\n return result.slice(0, -1).join(options.delimiter) + (options.serialComma ? ',' : '') + options.conjunction + result.slice(-1)\n }\n } else {\n return render(0, options.units[options.units.length - 1], dictionary, options)\n }\n }", "function doHumanization(ms, options) {\n let i; let len; let piece;\n\n // Make sure we have a positive number.\n // Has the nice sideffect of turning Number objects into primitives.\n ms = Math.abs(ms);\n\n const dictionary = options.languages[options.language] || languages[options.language];\n if (!dictionary) {\n throw new Error(`No language ${dictionary}.`);\n }\n\n const pieces = [];\n\n // Start at the top and keep removing units, bit by bit.\n let unitName; let unitMS; let \n unitCount;\n for (i = 0, len = options.units.length; i < len; i++) {\n unitName = options.units[i];\n unitMS = options.unitMeasures[unitName];\n\n // What's the number of full units we can fit?\n if (i + 1 === len) {\n unitCount = ms / unitMS;\n } else {\n unitCount = Math.floor(ms / unitMS);\n }\n\n // Add the string.\n pieces.push({\n unitCount,\n unitName,\n });\n\n // Remove what we just figured out.\n ms -= unitCount * unitMS;\n }\n\n let firstOccupiedUnitIndex = 0;\n for (i = 0; i < pieces.length; i++) {\n if (pieces[i].unitCount) {\n firstOccupiedUnitIndex = i;\n break;\n }\n }\n\n if (options.round) {\n let ratioToLargerUnit; let \n previousPiece;\n for (i = pieces.length - 1; i >= 0; i--) {\n piece = pieces[i];\n piece.unitCount = Math.round(piece.unitCount);\n\n if (i === 0) { break; }\n\n previousPiece = pieces[i - 1];\n\n ratioToLargerUnit = options.unitMeasures[previousPiece.unitName] / options.unitMeasures[piece.unitName];\n if ((piece.unitCount % ratioToLargerUnit) === 0 || (options.largest && ((options.largest - 1) < (i - firstOccupiedUnitIndex)))) {\n previousPiece.unitCount += piece.unitCount / ratioToLargerUnit;\n piece.unitCount = 0;\n }\n }\n }\n\n const result = [];\n for (i = 0, pieces.length; i < len; i++) {\n piece = pieces[i];\n if (piece.unitCount) {\n result.push(render(piece.unitCount, piece.unitName, dictionary, options));\n }\n\n if (result.length === options.largest) { break; }\n }\n\n if (result.length) {\n if (!options.conjunction || result.length === 1) {\n return result.join(options.delimiter);\n } else if (result.length === 2) {\n return result.join(options.conjunction);\n } else if (result.length > 2) {\n return result.slice(0, -1).join(options.delimiter) + (options.serialComma ? ',' : '') + options.conjunction + result.slice(-1);\n }\n } else {\n return render(0, options.units[options.units.length - 1], dictionary, options);\n }\n }", "function reduce(polymer) {\n let reduced = false;\n let newPolymer = \"\";\n\n for (let i = 0; i < polymer.length - 1; i++) {\n if (willCancel(...polymer.substr(i, 2))) {\n polymer = polymer.slice(0, i) + polymer.slice(i + 2);\n reduced = true;\n }\n }\n\n if (reduced) {\n return reduce(polymer);\n }\n return polymer;\n}", "function getAudioTailLength(elem){\n\tswitch (elem.vb) {\n case \"find\":\n\t\tswitch (elem.adj){\n\t\t\tcase \"small\":\n\t\t\t\tvar audio_tail = 0.947;\n\t\t\t\tbreak;\n\t\t\tcase \"big\":\n\t\t\t\tvar audio_tail = 0.732;\n\t\t\t\tbreak;\n\t\t\tcase \"pretty\":\n\t\t\t\tvar audio_tail = 0.890;\n\t\t\t\tbreak;\n\t\t\tcase \"ugly\":\n\t\t\t\tvar audio_tail = 0.879;\n\t\t\t\tbreak;\n\t\t}\n\tcase \"seem\":\n\t\tswitch (elem.adj){\n\t\t\tcase \"small\":\n\t\t\t\tvar audio_tail = 1.259;\n\t\t\t\tbreak;\n\t\t\tcase \"big\":\n\t\t\t\tvar audio_tail = 1.108;\n\t\t\t\tbreak;\n\t\t\tcase \"pretty\":\n\t\t\t\tvar audio_tail = 1.150;\n\t\t\t\tbreak;\n\t\t\tcase \"ugly\":\n\t\t\t\tvar audio_tail = 1.286;\n\t\t\t\tbreak;\n\t\t}\n\tcase \"are\":\n\t\tswitch (elem.adj){\n\t\t\tcase \"small\":\n\t\t\t\tvar audio_tail = 0.956;\n\t\t\t\tbreak;\n\t\t\tcase \"big\":\n\t\t\t\tvar audio_tail = 0.715;\n\t\t\t\tbreak;\n\t\t\tcase \"pretty\":\n\t\t\t\tvar audio_tail = 0.882;\n\t\t\t\tbreak;\n\t\t\tcase \"ugly\":\n\t\t\t\tvar audio_tail = 0.875;\n\t\t\t\tbreak;\n\t\t}\n\t}\n \n \n\treturn audio_tail;\n}", "function stripCommon(polymer) {\n let poly = polymer;\n let common = /aA|bB|cC|dD|eE|fF|gG|hH|iI|jJ|kK|lL|mM|nN|oO|pP|qQ|rR|sS|tT|uU|vV|wW|xX|yY|zZ|Aa|Bb|Cc|Dd|Ee|Ff|Gg|Hh|Ii|Jj|Kk|Ll|Mm|Nn|Oo|Pp|Qq|Rr|Ss|Tt|Uu|Vv|Ww|Xx|Yy|Zz/g;\n while (true) {\n \tlet newpoly = poly.split(common).join('');\n \tif (newpoly === poly) break;\n\tpoly = newpoly;\n }\n return poly.length;\n}", "function calcPolsbyPopperCompactness(area, perimeter) {\n if (perimeter <= 0) return 0;\n return Math.abs(area) * Math.PI * 4 / (perimeter * perimeter);\n }", "convertTotalStemLengthsToUnits () {\n // Traverse the hierarchies and index Clumps at each level\n const hierarchyLevels = new Map()\n for (const leafLayoutNode of this.leaves.values()) {\n const leaf = leafLayoutNode\n const stem = leafLayoutNode.stem\n\n const leafTotalStemLength = stem.lengths.prescaledTotal\n // Include ancestor Clumps\n const ancestors = stem.ancestors.ids.length ? stem.ancestors.ids : [leaf.parentId]\n for (let depth in ancestors) {\n depth = parseInt(depth)\n if (!hierarchyLevels.has(depth)) {\n hierarchyLevels.set(depth, new HierarchyLevel(depth))\n }\n const hierarchyLevel = hierarchyLevels.get(depth)\n // Form Clump for given node at given level\n const ancestorId = ancestors[depth]\n if (!this.midPoints.get(ancestorId)) {\n continue\n }\n const ancestorAtDepthLayoutNode = this.layoutNodes.get(ancestorId)\n const ancestorAtDepth = ancestorAtDepthLayoutNode && ancestorAtDepthLayoutNode\n if (!hierarchyLevel.clumps.has(ancestorAtDepth)) {\n const previousHierarchyLevel = hierarchyLevels.get(depth - 1)\n const parentClump = previousHierarchyLevel ? previousHierarchyLevel.clumps.get(ancestorAtDepthLayoutNode.parent && ancestorAtDepthLayoutNode.parent) : null\n const ancestorClump = new Clump(ancestorAtDepthLayoutNode, parentClump, leafTotalStemLength)\n hierarchyLevel.clumps.set(ancestorAtDepth, ancestorClump)\n if (parentClump) {\n parentClump.childClumps.set(ancestorAtDepth, ancestorClump)\n }\n continue\n }\n // Determine which leaf is longest in the Clump\n const clumpAtDepth = hierarchyLevel.clumps.get(ancestorAtDepth)\n if (!clumpAtDepth.longestLeafLength || leafTotalStemLength > clumpAtDepth.longestLeafLength) {\n clumpAtDepth.longestLeafLength = leafTotalStemLength\n }\n }\n // Include leaf Clump\n const leafDepth = ancestors.length\n if (!hierarchyLevels.has(leafDepth)) {\n hierarchyLevels.set(leafDepth, new HierarchyLevel(leafDepth))\n }\n const hierarchyLevel = hierarchyLevels.get(leafDepth)\n const previousHierarchyLevel = hierarchyLevels.get(leafDepth - 1)\n const parentClump = previousHierarchyLevel.clumps.get(leafLayoutNode.parent && leafLayoutNode.parent)\n const leafClump = new Clump(leafLayoutNode, parentClump, leafTotalStemLength)\n hierarchyLevel.clumps.set(leaf, leafClump)\n if (parentClump) {\n parentClump.childClumps.set(leaf, leafClump)\n }\n }\n\n // Determine portion of space to allocate for each node\n for (let depth = 0; depth < hierarchyLevels.size; ++depth) {\n const hierarchyLevel = hierarchyLevels.get(depth)\n hierarchyLevel.sumLongestLeafLengths()\n for (const clumpAtDepth of hierarchyLevel.clumps.values()) {\n const parentUnits = clumpAtDepth.parentClump ? clumpAtDepth.parentClump.units : 1\n const proportionFactor = clumpAtDepth.parentClump ? clumpAtDepth.parentClump.getTotalChildrenLongestLeafLength() : hierarchyLevel.longestLeafLengthSum\n\n // In some cases e.g. root node, these can be 0; if so, set as 1. TODO: investigate this further\n const clumpUnits = ((parentUnits * clumpAtDepth.longestLeafLength) || 1) / (proportionFactor || 1)\n clumpAtDepth.units = clumpAtDepth.layoutNode.validateStat(clumpUnits)\n clumpAtDepth.layoutNode.position.units = clumpUnits\n }\n }\n }", "function calculateUnitRatios () {\n\t\n\t /************************\n\t Same Ratio Checks\n\t ************************/\n\t\n\t /* The properties below are used to determine whether the element differs sufficiently from this call's\n\t previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n\t of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n\t this is done to minimize DOM querying. */\n\t var sameRatioIndicators = {\n\t myParent: element.parentNode || document.body, /* GET */\n\t position: CSS.getPropertyValue(element, \"position\"), /* GET */\n\t fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n\t },\n\t /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n\t samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n\t /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n\t sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\t\n\t /* Store these ratio indicators call-wide for the next element to compare against. */\n\t callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n\t callUnitConversionData.lastPosition = sameRatioIndicators.position;\n\t callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\t\n\t /***************************\n\t Element-Specific Units\n\t ***************************/\n\t\n\t /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n\t of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n\t var measurement = 100,\n\t unitRatios = {};\n\t\n\t if (!sameEmRatio || !samePercentRatio) {\n\t var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\t\n\t Velocity.init(dummy);\n\t sameRatioIndicators.myParent.appendChild(dummy);\n\t\n\t /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n\t Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n\t /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n\t $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n\t Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n\t });\n\t Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n\t Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n\t Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\t\n\t /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n\t $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n\t Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n\t });\n\t /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n\t Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\t\n\t /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n\t unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n\t unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n\t unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\t\n\t sameRatioIndicators.myParent.removeChild(dummy);\n\t } else {\n\t unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n\t unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n\t unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n\t }\n\t\n\t /***************************\n\t Element-Agnostic Units\n\t ***************************/\n\t\n\t /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n\t once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n\t that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n\t so we calculate it now. */\n\t if (callUnitConversionData.remToPx === null) {\n\t /* Default to browsers' default fontSize of 16px in the case of 0. */\n\t callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n\t }\n\t\n\t /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n\t if (callUnitConversionData.vwToPx === null) {\n\t callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n\t callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n\t }\n\t\n\t unitRatios.remToPx = callUnitConversionData.remToPx;\n\t unitRatios.vwToPx = callUnitConversionData.vwToPx;\n\t unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\t\n\t if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\t\n\t return unitRatios;\n\t }", "function calculateUnitRatios () {\n\t\n\t /************************\n\t Same Ratio Checks\n\t ************************/\n\t\n\t /* The properties below are used to determine whether the element differs sufficiently from this call's\n\t previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n\t of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n\t this is done to minimize DOM querying. */\n\t var sameRatioIndicators = {\n\t myParent: element.parentNode || document.body, /* GET */\n\t position: CSS.getPropertyValue(element, \"position\"), /* GET */\n\t fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n\t },\n\t /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n\t samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n\t /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n\t sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\t\n\t /* Store these ratio indicators call-wide for the next element to compare against. */\n\t callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n\t callUnitConversionData.lastPosition = sameRatioIndicators.position;\n\t callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\t\n\t /***************************\n\t Element-Specific Units\n\t ***************************/\n\t\n\t /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n\t of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n\t var measurement = 100,\n\t unitRatios = {};\n\t\n\t if (!sameEmRatio || !samePercentRatio) {\n\t var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\t\n\t Velocity.init(dummy);\n\t sameRatioIndicators.myParent.appendChild(dummy);\n\t\n\t /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n\t Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n\t /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n\t $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n\t Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n\t });\n\t Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n\t Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n\t Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\t\n\t /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n\t $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n\t Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n\t });\n\t /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n\t Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\t\n\t /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n\t unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n\t unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n\t unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\t\n\t sameRatioIndicators.myParent.removeChild(dummy);\n\t } else {\n\t unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n\t unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n\t unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n\t }\n\t\n\t /***************************\n\t Element-Agnostic Units\n\t ***************************/\n\t\n\t /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n\t once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n\t that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n\t so we calculate it now. */\n\t if (callUnitConversionData.remToPx === null) {\n\t /* Default to browsers' default fontSize of 16px in the case of 0. */\n\t callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n\t }\n\t\n\t /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n\t if (callUnitConversionData.vwToPx === null) {\n\t callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n\t callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n\t }\n\t\n\t unitRatios.remToPx = callUnitConversionData.remToPx;\n\t unitRatios.vwToPx = callUnitConversionData.vwToPx;\n\t unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\t\n\t if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\t\n\t return unitRatios;\n\t }", "function calculateUnitRatios () {\n\n /************************\n Same Ratio Checks\n ************************/\n\n /* The properties below are used to determine whether the element differs sufficiently from this call's\n previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n this is done to minimize DOM querying. */\n var sameRatioIndicators = {\n myParent: element.parentNode || document.body, /* GET */\n position: CSS.getPropertyValue(element, \"position\"), /* GET */\n fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n },\n /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n /* Store these ratio indicators call-wide for the next element to compare against. */\n callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n callUnitConversionData.lastPosition = sameRatioIndicators.position;\n callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n /***************************\n Element-Specific Units\n ***************************/\n\n /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n var measurement = 100,\n unitRatios = {};\n\n if (!sameEmRatio || !samePercentRatio) {\n var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n Velocity.init(dummy);\n sameRatioIndicators.myParent.appendChild(dummy);\n\n /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n });\n Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n });\n /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n sameRatioIndicators.myParent.removeChild(dummy);\n } else {\n unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n }\n\n /***************************\n Element-Agnostic Units\n ***************************/\n\n /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n so we calculate it now. */\n if (callUnitConversionData.remToPx === null) {\n /* Default to browsers' default fontSize of 16px in the case of 0. */\n callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n }\n\n /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n if (callUnitConversionData.vwToPx === null) {\n callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n }\n\n unitRatios.remToPx = callUnitConversionData.remToPx;\n unitRatios.vwToPx = callUnitConversionData.vwToPx;\n unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n return unitRatios;\n }", "function lenFromRATri(hyp, len) {\n return Math.pow(Math.pow(hyp, 2) - Math.pow(len, 2), 0.5);\n}", "calculateType() {\n let ret;\n\n if (this.NoteLength === 4) {\n ret = 'w';\n } else if (this.NoteLength >= 2 && this.NoteLength <= 3) {\n ret = 'h';\n } else if (this.NoteLength >= 1 && this.NoteLength < 2) {\n ret = 'w';\n } else if (this.NoteLength === 0.25) {\n ret = 'q';\n } else if (this.NoteLength === 0.5) {\n ret = 'h';\n } else if (this.NoteLength <= (1 / 8)) {\n ret = Math.round(1 / (1 / 8)).toString();\n }\n return ret;\n }", "function calculateUnitRatios () {\n\n /************************\n Same Ratio Checks\n ************************/\n\n /* The properties below are used to determine whether the element differs sufficiently from this call's\n previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n this is done to minimize DOM querying. */\n var sameRatioIndicators = {\n myParent: element.parentNode || document.body, /* GET */\n position: CSS.getPropertyValue(element, \"position\"), /* GET */\n fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n },\n /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n /* Store these ratio indicators call-wide for the next element to compare against. */\n callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n callUnitConversionData.lastPosition = sameRatioIndicators.position;\n callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n /***************************\n Element-Specific Units\n ***************************/\n\n /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n var measurement = 100,\n unitRatios = {};\n\n if (!sameEmRatio || !samePercentRatio) {\n var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n Velocity.init(dummy);\n sameRatioIndicators.myParent.appendChild(dummy);\n\n /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n });\n Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n });\n /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n sameRatioIndicators.myParent.removeChild(dummy);\n } else {\n unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n }\n\n /***************************\n Element-Agnostic Units\n ***************************/\n\n /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n so we calculate it now. */\n if (callUnitConversionData.remToPx === null) {\n /* Default to browsers' default fontSize of 16px in the case of 0. */\n callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n }\n\n /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n if (callUnitConversionData.vwToPx === null) {\n callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n }\n\n unitRatios.remToPx = callUnitConversionData.remToPx;\n unitRatios.vwToPx = callUnitConversionData.vwToPx;\n unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n return unitRatios;\n }", "function calculateUnitRatios () {\n\n /************************\n Same Ratio Checks\n ************************/\n\n /* The properties below are used to determine whether the element differs sufficiently from this call's\n previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n this is done to minimize DOM querying. */\n var sameRatioIndicators = {\n myParent: element.parentNode || document.body, /* GET */\n position: CSS.getPropertyValue(element, \"position\"), /* GET */\n fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n },\n /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n /* Store these ratio indicators call-wide for the next element to compare against. */\n callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n callUnitConversionData.lastPosition = sameRatioIndicators.position;\n callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n /***************************\n Element-Specific Units\n ***************************/\n\n /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n var measurement = 100,\n unitRatios = {};\n\n if (!sameEmRatio || !samePercentRatio) {\n var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n Velocity.init(dummy);\n sameRatioIndicators.myParent.appendChild(dummy);\n\n /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n });\n Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n });\n /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n sameRatioIndicators.myParent.removeChild(dummy);\n } else {\n unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n }\n\n /***************************\n Element-Agnostic Units\n ***************************/\n\n /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n so we calculate it now. */\n if (callUnitConversionData.remToPx === null) {\n /* Default to browsers' default fontSize of 16px in the case of 0. */\n callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n }\n\n /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n if (callUnitConversionData.vwToPx === null) {\n callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n }\n\n unitRatios.remToPx = callUnitConversionData.remToPx;\n unitRatios.vwToPx = callUnitConversionData.vwToPx;\n unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n return unitRatios;\n }", "function calculateUnitRatios () {\n\n /************************\n Same Ratio Checks\n ************************/\n\n /* The properties below are used to determine whether the element differs sufficiently from this call's\n previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n this is done to minimize DOM querying. */\n var sameRatioIndicators = {\n myParent: element.parentNode || document.body, /* GET */\n position: CSS.getPropertyValue(element, \"position\"), /* GET */\n fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n },\n /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n /* Store these ratio indicators call-wide for the next element to compare against. */\n callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n callUnitConversionData.lastPosition = sameRatioIndicators.position;\n callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n /***************************\n Element-Specific Units\n ***************************/\n\n /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n var measurement = 100,\n unitRatios = {};\n\n if (!sameEmRatio || !samePercentRatio) {\n var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n Velocity.init(dummy);\n sameRatioIndicators.myParent.appendChild(dummy);\n\n /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n });\n Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n });\n /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n sameRatioIndicators.myParent.removeChild(dummy);\n } else {\n unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n }\n\n /***************************\n Element-Agnostic Units\n ***************************/\n\n /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n so we calculate it now. */\n if (callUnitConversionData.remToPx === null) {\n /* Default to browsers' default fontSize of 16px in the case of 0. */\n callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n }\n\n /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n if (callUnitConversionData.vwToPx === null) {\n callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n }\n\n unitRatios.remToPx = callUnitConversionData.remToPx;\n unitRatios.vwToPx = callUnitConversionData.vwToPx;\n unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n return unitRatios;\n }", "function calculateUnitRatios () {\n\n /************************\n Same Ratio Checks\n ************************/\n\n /* The properties below are used to determine whether the element differs sufficiently from this call's\n previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n this is done to minimize DOM querying. */\n var sameRatioIndicators = {\n myParent: element.parentNode || document.body, /* GET */\n position: CSS.getPropertyValue(element, \"position\"), /* GET */\n fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n },\n /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n /* Store these ratio indicators call-wide for the next element to compare against. */\n callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n callUnitConversionData.lastPosition = sameRatioIndicators.position;\n callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n /***************************\n Element-Specific Units\n ***************************/\n\n /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n var measurement = 100,\n unitRatios = {};\n\n if (!sameEmRatio || !samePercentRatio) {\n var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n Velocity.init(dummy);\n sameRatioIndicators.myParent.appendChild(dummy);\n\n /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n });\n Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n });\n /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n sameRatioIndicators.myParent.removeChild(dummy);\n } else {\n unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n }\n\n /***************************\n Element-Agnostic Units\n ***************************/\n\n /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n so we calculate it now. */\n if (callUnitConversionData.remToPx === null) {\n /* Default to browsers' default fontSize of 16px in the case of 0. */\n callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n }\n\n /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n if (callUnitConversionData.vwToPx === null) {\n callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n }\n\n unitRatios.remToPx = callUnitConversionData.remToPx;\n unitRatios.vwToPx = callUnitConversionData.vwToPx;\n unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n return unitRatios;\n }", "function calculateUnitRatios () {\n\n /************************\n Same Ratio Checks\n ************************/\n\n /* The properties below are used to determine whether the element differs sufficiently from this call's\n previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n this is done to minimize DOM querying. */\n var sameRatioIndicators = {\n myParent: element.parentNode || document.body, /* GET */\n position: CSS.getPropertyValue(element, \"position\"), /* GET */\n fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n },\n /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n /* Store these ratio indicators call-wide for the next element to compare against. */\n callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n callUnitConversionData.lastPosition = sameRatioIndicators.position;\n callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n /***************************\n Element-Specific Units\n ***************************/\n\n /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n var measurement = 100,\n unitRatios = {};\n\n if (!sameEmRatio || !samePercentRatio) {\n var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n Velocity.init(dummy);\n sameRatioIndicators.myParent.appendChild(dummy);\n\n /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n });\n Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n });\n /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n sameRatioIndicators.myParent.removeChild(dummy);\n } else {\n unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n }\n\n /***************************\n Element-Agnostic Units\n ***************************/\n\n /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n so we calculate it now. */\n if (callUnitConversionData.remToPx === null) {\n /* Default to browsers' default fontSize of 16px in the case of 0. */\n callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n }\n\n /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n if (callUnitConversionData.vwToPx === null) {\n callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n }\n\n unitRatios.remToPx = callUnitConversionData.remToPx;\n unitRatios.vwToPx = callUnitConversionData.vwToPx;\n unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n return unitRatios;\n }", "function calculateUnitRatios () {\n /* The properties below are used to determine whether the element differs sufficiently from this call's prior element to also differ in its unit conversion ratio.\n If the properties match up with those of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity, this is done to minimize DOM querying. */\n var sameRatioIndicators = {\n parent: element.parentNode, /* GET */\n position: CSS.getPropertyValue(element, \"position\"), /* GET */\n fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n },\n /* Determine if the same % ratio can be used. % is relative to the element's position and the parent's dimensions. */\n sameBasePercent = ((sameRatioIndicators.position === unitConversionRatios.lastPosition) && (sameRatioIndicators.parent === unitConversionRatios.lastParent)),\n /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n sameBaseEm = (sameRatioIndicators.fontSize === unitConversionRatios.lastFontSize);\n\n /* Store these ratio indicators call-wide for the next element to compare against. */\n unitConversionRatios.lastParent = sameRatioIndicators.parent;\n unitConversionRatios.lastPosition = sameRatioIndicators.position;\n unitConversionRatios.lastFontSize = sameRatioIndicators.fontSize;\n\n /* Whereas % and em ratios are determined on a per-element basis, the rem unit type only needs to be checked once per call since it is exclusively dependant upon the body element's fontSize.\n If this is the first time that calculateUnitRatios() is being run during this call, the remToPxRatio value will be null, so we calculate it now. */\n if (unitConversionRatios.remToPxRatio === null) {\n /* Default to most browsers' default fontSize of 16px in the case of 0. */\n unitConversionRatios.remToPxRatio = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n }\n\n var originalValues = {\n /* To accurately and consistently calculate conversion ratios, the element's overflow and box-sizing are temporarily disabled. Overflow must be manipulated on a per-axis basis\n since the plain overflow property overwrites its subproperties' values. */\n overflowX: null,\n overflowY: null,\n boxSizing: null,\n /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. Since they can be artificially constrained by their min-/max- equivalents, those properties are changed as well. */\n width: null,\n minWidth: null,\n maxWidth: null,\n height: null,\n minHeight: null,\n maxHeight: null,\n /* paddingLeft acts as our proxy for the em ratio. */\n paddingLeft: null\n },\n elementUnitRatios = {},\n /* Note: IE<=8 round to the nearest pixel when returning CSS values, thus we perform conversions using a measurement of 10 (instead of 1) to give our ratios a precision of at least 1 decimal value. */\n measurement = 10; \n\n /* For organizational purposes, active ratios calculations are consolidated onto the elementUnitRatios object. */\n elementUnitRatios.remToPxRatio = unitConversionRatios.remToPxRatio;\n\n /* Note: To minimize layout thrashing, the ensuing unit conversion logic is split into batches to synchronize GETs and SETs. */\n originalValues.overflowX = CSS.getPropertyValue(element, \"overflowX\"); /* GET */\n originalValues.overflowY = CSS.getPropertyValue(element, \"overflowY\"); /* GET */\n originalValues.boxSizing = CSS.getPropertyValue(element, \"boxSizing\"); /* GET */\n\n /* Since % values are relative to their respective axes, ratios are calculated for both width and height. In contrast, only a single ratio is required for rem and em. */\n /* When calculating % values, we set a flag to indiciate that we want the computed value instead of offsetWidth/Height, which incorporate additional dimensions (such as padding and border-width) into their values. */\n originalValues.width = CSS.getPropertyValue(element, \"width\", null, true); /* GET */\n originalValues.minWidth = CSS.getPropertyValue(element, \"minWidth\"); /* GET */\n /* Note: max-width/height must default to \"none\" when 0 is returned, otherwise the element cannot have its width/height set. */\n originalValues.maxWidth = CSS.getPropertyValue(element, \"maxWidth\") || \"none\"; /* GET */\n\n originalValues.height = CSS.getPropertyValue(element, \"height\", null, true); /* GET */\n originalValues.minHeight = CSS.getPropertyValue(element, \"minHeight\"); /* GET */\n originalValues.maxHeight = CSS.getPropertyValue(element, \"maxHeight\") || \"none\"; /* GET */\n\n originalValues.paddingLeft = CSS.getPropertyValue(element, \"paddingLeft\"); /* GET */\n\n if (sameBasePercent) {\n elementUnitRatios.percentToPxRatioWidth = unitConversionRatios.lastPercentToPxWidth;\n elementUnitRatios.percentToPxRatioHeight = unitConversionRatios.lastPercentToPxHeight;\n } else {\n CSS.setPropertyValue(element, \"overflowX\", \"hidden\"); /* SET */\n CSS.setPropertyValue(element, \"overflowY\", \"hidden\"); /* SET */\n CSS.setPropertyValue(element, \"boxSizing\", \"content-box\"); /* SET */\n\n CSS.setPropertyValue(element, \"width\", measurement + \"%\"); /* SET */\n CSS.setPropertyValue(element, \"minWidth\", measurement + \"%\"); /* SET */\n CSS.setPropertyValue(element, \"maxWidth\", measurement + \"%\"); /* SET */\n\n CSS.setPropertyValue(element, \"height\", measurement + \"%\"); /* SET */\n CSS.setPropertyValue(element, \"minHeight\", measurement + \"%\"); /* SET */\n CSS.setPropertyValue(element, \"maxHeight\", measurement + \"%\"); /* SET */\n }\n\n if (sameBaseEm) {\n elementUnitRatios.emToPxRatio = unitConversionRatios.lastEmToPx;\n } else {\n CSS.setPropertyValue(element, \"paddingLeft\", measurement + \"em\"); /* SET */\n }\n\n /* The following pixel-value GETs cannot be batched with the prior GETs since they depend upon the values temporarily set immediately above; layout thrashing cannot be avoided here. */\n if (!sameBasePercent) {\n /* Divide the returned value by the measurement value to get the ratio between 1% and 1px. */\n elementUnitRatios.percentToPxRatioWidth = unitConversionRatios.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(element, \"width\", null, true)) || 0) / measurement; /* GET */\n elementUnitRatios.percentToPxRatioHeight = unitConversionRatios.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(element, \"height\", null, true)) || 0) / measurement; /* GET */\n }\n\n if (!sameBaseEm) {\n elementUnitRatios.emToPxRatio = unitConversionRatios.lastEmToPx = (parseFloat(CSS.getPropertyValue(element, \"paddingLeft\")) || 0) / measurement; /* GET */\n }\n\n /* Revert each test property to its original value. */\n for (var originalValueProperty in originalValues) {\n CSS.setPropertyValue(element, originalValueProperty, originalValues[originalValueProperty]); /* SETs */\n }\n\n if ($.velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(elementUnitRatios), element);\n\n return elementUnitRatios;\n }", "function calculateUnitRatios () {\n\t\t\n\t\t /************************\n\t\t Same Ratio Checks\n\t\t ************************/\n\t\t\n\t\t /* The properties below are used to determine whether the element differs sufficiently from this call's\n\t\t previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n\t\t of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n\t\t this is done to minimize DOM querying. */\n\t\t var sameRatioIndicators = {\n\t\t myParent: element.parentNode || document.body, /* GET */\n\t\t position: CSS.getPropertyValue(element, \"position\"), /* GET */\n\t\t fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n\t\t },\n\t\t /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n\t\t samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n\t\t /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n\t\t sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\t\t\n\t\t /* Store these ratio indicators call-wide for the next element to compare against. */\n\t\t callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n\t\t callUnitConversionData.lastPosition = sameRatioIndicators.position;\n\t\t callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\t\t\n\t\t /***************************\n\t\t Element-Specific Units\n\t\t ***************************/\n\t\t\n\t\t /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n\t\t of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n\t\t var measurement = 100,\n\t\t unitRatios = {};\n\t\t\n\t\t if (!sameEmRatio || !samePercentRatio) {\n\t\t var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\t\t\n\t\t Velocity.init(dummy);\n\t\t sameRatioIndicators.myParent.appendChild(dummy);\n\t\t\n\t\t /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n\t\t Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n\t\t /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n\t\t $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n\t\t Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n\t\t });\n\t\t Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n\t\t Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n\t\t Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\t\t\n\t\t /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n\t\t $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n\t\t Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n\t\t });\n\t\t /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n\t\t Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\t\t\n\t\t /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n\t\t unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n\t\t unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n\t\t unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\t\t\n\t\t sameRatioIndicators.myParent.removeChild(dummy);\n\t\t } else {\n\t\t unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n\t\t unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n\t\t unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n\t\t }\n\t\t\n\t\t /***************************\n\t\t Element-Agnostic Units\n\t\t ***************************/\n\t\t\n\t\t /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n\t\t once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n\t\t that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n\t\t so we calculate it now. */\n\t\t if (callUnitConversionData.remToPx === null) {\n\t\t /* Default to browsers' default fontSize of 16px in the case of 0. */\n\t\t callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n\t\t }\n\t\t\n\t\t /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n\t\t if (callUnitConversionData.vwToPx === null) {\n\t\t callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n\t\t callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n\t\t }\n\t\t\n\t\t unitRatios.remToPx = callUnitConversionData.remToPx;\n\t\t unitRatios.vwToPx = callUnitConversionData.vwToPx;\n\t\t unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\t\t\n\t\t if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\t\t\n\t\t return unitRatios;\n\t\t }", "function degreesOfFreedom(p) {\n let onBoard = possibleMoves(p).filter(isOnBoard);\n let empties = onBoard.filter(isEmpty).length;\n let food = onBoard.filter(isFood).length;\n return empties + food; // could play with weights...\n }", "computePhandoryss(remainingAncientSouls) {\n const table = [\n {level: 1, as: 3},\n {level: 2, as: 10},\n {level: 3, as: 21},\n {level: 4, as: 36},\n {level: 5, as: 54},\n {level: 6, as: 60},\n {level: 7, as: 67},\n {level: 8, as: 75},\n {level: 9, as: 84},\n {level: 10, as: 94},\n {level: 11, as: 104},\n {level: 12, as: 117},\n {level: 14, as: 129},\n {level: 13, as: 143},\n {level: 15, as: 158},\n {level: 16, as: 174},\n {level: 17, as: 190},\n {level: 18, as: 208},\n {level: 19, as: 228}\n ];\n\n return table.filter(e => e.as <= remainingAncientSouls).pop().level;\n }", "function calculateUnitRatios () {\n\n\t /************************\n\t Same Ratio Checks\n\t ************************/\n\n\t /* The properties below are used to determine whether the element differs sufficiently from this call's\n\t previously iterated element to also differ in its unit conversion ratios. If the properties match up with those\n\t of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,\n\t this is done to minimize DOM querying. */\n\t var sameRatioIndicators = {\n\t myParent: element.parentNode || document.body, /* GET */\n\t position: CSS.getPropertyValue(element, \"position\"), /* GET */\n\t fontSize: CSS.getPropertyValue(element, \"fontSize\") /* GET */\n\t },\n\t /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */\n\t samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),\n\t /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */\n\t sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);\n\n\t /* Store these ratio indicators call-wide for the next element to compare against. */\n\t callUnitConversionData.lastParent = sameRatioIndicators.myParent;\n\t callUnitConversionData.lastPosition = sameRatioIndicators.position;\n\t callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;\n\n\t /***************************\n\t Element-Specific Units\n\t ***************************/\n\n\t /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement\n\t of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */\n\t var measurement = 100,\n\t unitRatios = {};\n\n\t if (!sameEmRatio || !samePercentRatio) {\n\t var dummy = Data(element).isSVG ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\") : document.createElement(\"div\");\n\n\t Velocity.init(dummy);\n\t sameRatioIndicators.myParent.appendChild(dummy);\n\n\t /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.\n\t Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */\n\t /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */\n\t $.each([ \"overflow\", \"overflowX\", \"overflowY\" ], function(i, property) {\n\t Velocity.CSS.setPropertyValue(dummy, property, \"hidden\");\n\t });\n\t Velocity.CSS.setPropertyValue(dummy, \"position\", sameRatioIndicators.position);\n\t Velocity.CSS.setPropertyValue(dummy, \"fontSize\", sameRatioIndicators.fontSize);\n\t Velocity.CSS.setPropertyValue(dummy, \"boxSizing\", \"content-box\");\n\n\t /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */\n\t $.each([ \"minWidth\", \"maxWidth\", \"width\", \"minHeight\", \"maxHeight\", \"height\" ], function(i, property) {\n\t Velocity.CSS.setPropertyValue(dummy, property, measurement + \"%\");\n\t });\n\t /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */\n\t Velocity.CSS.setPropertyValue(dummy, \"paddingLeft\", measurement + \"em\");\n\n\t /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */\n\t unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, \"width\", null, true)) || 1) / measurement; /* GET */\n\t unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, \"height\", null, true)) || 1) / measurement; /* GET */\n\t unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, \"paddingLeft\")) || 1) / measurement; /* GET */\n\n\t sameRatioIndicators.myParent.removeChild(dummy);\n\t } else {\n\t unitRatios.emToPx = callUnitConversionData.lastEmToPx;\n\t unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;\n\t unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;\n\t }\n\n\t /***************************\n\t Element-Agnostic Units\n\t ***************************/\n\n\t /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked\n\t once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time\n\t that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,\n\t so we calculate it now. */\n\t if (callUnitConversionData.remToPx === null) {\n\t /* Default to browsers' default fontSize of 16px in the case of 0. */\n\t callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, \"fontSize\")) || 16; /* GET */\n\t }\n\n\t /* Similarly, viewport units are %-relative to the window's inner dimensions. */\n\t if (callUnitConversionData.vwToPx === null) {\n\t callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */\n\t callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */\n\t }\n\n\t unitRatios.remToPx = callUnitConversionData.remToPx;\n\t unitRatios.vwToPx = callUnitConversionData.vwToPx;\n\t unitRatios.vhToPx = callUnitConversionData.vhToPx;\n\n\t if (Velocity.debug >= 1) console.log(\"Unit ratios: \" + JSON.stringify(unitRatios), element);\n\n\t return unitRatios;\n\t }", "function solution2(S, P, Q) {\n // Take two. After some research, realizing I was prefix summing the wrong thing: we don't\n // care about the sum of impact values (all that matters for those is relative min),\n // but we DO care about the counts of each nucleotide (starting with the lowest impact ones)\n\n // Init result array and 2d prefix count array\n const pCounts = [[0],[0],[0]]; // tracks sums of A, C, G nucleotides (don't need highest T)\n const result = [];\n\n // Create prefix counts array, one set of nucleotide counts for each step along the sequence\n for (let i = 0; i < S.length; i++){\n\n // Copy the previous counts for this set of counts - only one will change, done below\n pCounts[0].push(pCounts[0][i]);\n pCounts[1].push(pCounts[1][i]);\n pCounts[2].push(pCounts[2][i]);\n\n // Increment the corresponding nucleotide counter\n switch (S[i]){\n case \"A\":\n pCounts[0][i+1] += 1;\n break;\n case \"C\":\n pCounts[1][i+1] += 1;\n break;\n case \"G\":\n pCounts[2][i+1] += 1;\n break;\n }\n }\n\n // Now that prefix counts are created, for each query,\n // check for differences of each type in the P-Q range,\n // starting from lowest impact value\n for(let i = 0; i < Q.length; i++){\n // Check for A's (impact 1) - any increases in the A counts in range P-Q\n if(pCounts[0][Q[i]+1] - pCounts[0][P[i]] > 0){\n result.push(1);\n } else if(pCounts[1][Q[i]+1] - pCounts[1][P[i]] > 0){\n result.push(2);\n } else if(pCounts[2][Q[i]+1] - pCounts[2][P[i]] > 0){\n result.push(3);\n } else result.push(4)\n }\n return result;\n}", "function findQuantativeCharacteristic(speed, breakingTime, maxLoadOnProp, speedDown, greenProp, redProp) {\n var summMomentOfStrength = 0;\n pointsCollection.forEach(function (point) {\n if (point.getColor() == \"gray\") {\n var angle = Math.atan(Math.abs(greenProp.getPosition().y - point.getPosition().y) / Math.abs(point.getPosition().x - greenProp.getPosition().x));\n var projection = point.getMass() * speed * Math.cos(angle);\n var power = projection / breakingTime;\n var momentOfStrength = power * getLineLength(point.getPosition().x, point.getPosition().y, greenProp.getPosition().x, greenProp.getPosition().y);\n summMomentOfStrength += momentOfStrength;\n }\n });\n //n - a quantitative characteristic of the prop reaction\n var n = summMomentOfStrength / getLineLength(greenProp.getPosition().x, greenProp.getPosition().y, redProp.getPosition().x, redProp.getPosition().y);\n return n;\n}", "computeSquadStrength(){\n let totalHealth = this._units.reduce((accum, curUnit) => accum + curUnit.totalHealth(), 0.0);\n let experiencePerUnit = this._units.reduce((accum, curUnit) => accum + curUnit.experiencePerUnit(), 0.0) / this._units.length;\n let numberOfUnits = this._units.reduce((accum, curUnit) => accum + curUnit.totalNumberOfRelatedUnits(), 0.0);\n let totalDamage = this._units.reduce((accum, curUnit) => accum + curUnit.computeDamage(), 0.0);\n return totalHealth * experiencePerUnit * numberOfUnits * totalDamage;\n\n }", "function handleMeasurementsPartial(event) {\n var geometry = event.geometry;\n var units = event.units;\n var order = event.order;\n var measure = event.measure;\n var element = document.getElementById('salidaMedicion');\n var out = \"\";\n var geometriaAnterior = new OpenLayers.Geometry.LineString();\n if (order == 1) {\n var longitudAnterior = 0;\n var longitudUltimoTramo = 0;\n if (event.geometry.components.length > 2) {\n\n geometriaAnterior.components = event.geometry.components.slice(0, event.geometry.components.length - 1);\n longitudAnterior = this.getBestLength(geometriaAnterior)[0];\n console.log(longitudAnterior);\n longitudUltimoTramo = measure - longitudAnterior;\n }\n\n out += \"Longitud total: \" + measure.toFixed(2) + \" \" + units + \"<br>\" +\n \"Longitud anterior: \" + parseFloat(longitudAnterior).toFixed(2) + \" \" + units + \"<br>\" +\n \"Longitud tramo: \" + parseFloat(longitudUltimoTramo).toFixed(2) + \" \" + units + \"<br>\";\n }\n\n else {\n var perimetro = this.getBestLength(event.geometry);\n out += \"Área: \" + measure.toFixed(2) + \" \" + units + \"<sup>2</\" + \"sup><br>\" +\n \"Perímetro: \" + perimetro[0].toFixed(2) + \" \" + perimetro[1];\n }\n element.innerHTML = out;\n}", "pointDegradation(addToPaper){cov_1rtpcx8cw8.f[2]++;const letters=(cov_1rtpcx8cw8.s[6]++,addToPaper.split(''));let availableLetters=(cov_1rtpcx8cw8.s[7]++,'');// When you reach the end of the string, get out of loop\ncov_1rtpcx8cw8.s[8]++;for(let i=0;i<letters.length;i++){cov_1rtpcx8cw8.s[9]++;// If durability ever reaches 0, sharpen pencil\nif(this.durability===0){cov_1rtpcx8cw8.b[1][0]++;cov_1rtpcx8cw8.s[10]++;console.log(`Your pencil has a durability of 0! You need to sharpen it! Here's what I've written ${availableLetters}`);}else{cov_1rtpcx8cw8.b[1][1]++;}cov_1rtpcx8cw8.s[11]++;if((cov_1rtpcx8cw8.b[3][0]++,this.durability===0)&&(cov_1rtpcx8cw8.b[3][1]++,this.length===0)){cov_1rtpcx8cw8.b[2][0]++;cov_1rtpcx8cw8.s[12]++;break;}else{cov_1rtpcx8cw8.b[2][1]++;}// Check how many letters of the string you can write with pencil\ncov_1rtpcx8cw8.s[13]++;availableLetters+=letters[i];cov_1rtpcx8cw8.s[14]++;if(letters[i]===' '){cov_1rtpcx8cw8.b[4][0]++;cov_1rtpcx8cw8.s[15]++;this.durability-=0;}else{cov_1rtpcx8cw8.b[4][1]++;cov_1rtpcx8cw8.s[16]++;if((cov_1rtpcx8cw8.b[6][0]++,letters[i]!==letters[i].toUpperCase())||(cov_1rtpcx8cw8.b[6][1]++,letters[i].match(/^[.,:!?]/))){cov_1rtpcx8cw8.b[5][0]++;cov_1rtpcx8cw8.s[17]++;this.durability-=1;}else{cov_1rtpcx8cw8.b[5][1]++;cov_1rtpcx8cw8.s[18]++;if(letters[i]===letters[i].toUpperCase()){cov_1rtpcx8cw8.b[7][0]++;cov_1rtpcx8cw8.s[19]++;this.durability-=2;}else{cov_1rtpcx8cw8.b[7][1]++;}}}}cov_1rtpcx8cw8.s[20]++;return availableLetters;}", "removeSubPhrases (trendPhrases) {\n for (let i = 0; i < trendPhrases.length; i++) {\n for (let j = i + 1; j < trendPhrases.length; j++) {\n if (util.isSubPhrase(trendPhrases[i].phrase, trendPhrases[j].phrase)) {\n // keep the biggest one\n const spliceI = trendPhrases[i].length > trendPhrases[j].length ? j : i\n // remove the element from the array\n trendPhrases.splice(spliceI, 1)\n // start processing again from the element that was cut out\n i = j = spliceI\n }\n }\n }\n return trendPhrases\n }", "sharpen(){cov_1rtpcx8cw8.f[3]++;cov_1rtpcx8cw8.s[21]++;if(this.length===0){cov_1rtpcx8cw8.b[8][0]++;cov_1rtpcx8cw8.s[22]++;throw new Error('Your pencil has a length and durability of 0! You need a new one!');}else{cov_1rtpcx8cw8.b[8][1]++;cov_1rtpcx8cw8.s[23]++;this.durability=40000;cov_1rtpcx8cw8.s[24]++;this.length-=1;}}", "function removeLengthRelatedPatches(rawPatches){\n return rawPatches.filter(function(patch){\n return !/[/]length/ig.test(patch.path);\n })\n }", "function findShortestWordAmongMixedElements(arr) {\n // your code here\n if(!arr.length) {\n return \"\";\n }\n \n function hasString(arr) {\n return arr.some(element => typeof element === \"string\");\n }\n //var strings = arr.filter(element => typeof element === \"string\");\n //var shortestPos = Math.min(...strings.map(string => return string.length));\n if(!arr.length || !hasString(arr)) {\n return \"\";\n }\n var strings = arr.filter(element => typeof element === \"string\");\n var stringLengths = strings.map(string => string.length);\n console.log(stringLengths);\n var pos = Math.min(...stringLengths);\n var shortest = stringLengths.indexOf(pos);\n console.log(shortest);\n var ans = strings[shortest];\n return ans;\n}", "function createUnitAndSubtreeByXML(xmlUnit, parentUnit) {\n\n global_type = getAttribute(xmlUnit, \"type\"); \n var type = convertUnitType(getAttribute(xmlUnit, \"type\"));\n\n var id = getAttribute(xmlUnit, \"id\");\n\n var referentId = getAttribute(xmlUnit, \"referent\");\n if (referentId != null) {\n tempReferents.push([id, referentId]);\n }\n\n var uncertain = getAttribute(xmlUnit, \"uncertain\");\n var curUnit = new Unit(parentUnit, null, id);\n\n var remarks = getAttribute(xmlUnit, \"remarks\");\n if (remarks != null) {\n unitRemarks[id] = escapeRemark(remarks, false);\n }\n\n var unanalyzable = getAttribute(xmlUnit, \"unanalyzable\");\n if (unanalyzable == \"true\") {\n curUnit.unanalyzable = true;\n }\n else {\n curUnit.unanalyzable = false;\n }\n\n if (uncertain == \"true\") {\n curUnit.uncertain = true;\n }\n else {\n curUnit.uncertain = false;\n }\n \n curUnit.id = id;\n curUnit.type = type;\n if (type != 1) {\n curUnit.defaultType = false;\n }\n \n curUnit.setDisplayVal(curUnit.isPassage() || curUnit.isParagraph() || UNITTYPE[type].display);\n \n var unitGroupID = getAttribute(xmlUnit, \"unitGroupID\");\n if (unitGroupID != null) {\n allUnits[unitGroupID].addPart(curUnit);\n }\n \n for (var i=0; i < xmlUnit.childNodes.length; i++) {\n var curChild = xmlUnit.childNodes[i];\n if (curChild.nodeName == \"unit\") { \n var newUnit = createUnitAndSubtreeByXML(xmlUnit.childNodes[i], curUnit);\n curUnit.addChild(newUnit);\n }\n else if (curChild.nodeName == \"word\") {\n \tif (curChild.childNodes[0] == undefined) {\n \t\tcontinue;\n \t}\n var newAtom = new Atom(curChild.childNodes[0].data, false, getAttribute(curChild, \"id\"));\n curUnit.addChild(newAtom);\n }\n else if (curChild.nodeName == \"linkage\") {\n var linkedArgs = getAttribute(curChild, \"args\");\n if (linkedArgs == null) {\n tempLinkages.push(readLegacyLinkageRepresentation(id, curChild));\n }\n else {\n var linker = curUnit.id;\n tempLinkages.push([linkedArgs, linker]);\n }\n }\n else if (curChild.nodeName == \"remoteUnit\" || curChild.nodeName == \"implicitUnit\") {\n var remoteID = getAttribute(curChild, \"id\");\n var remoteType = convertUnitType(getAttribute(curChild, \"type\"));\n tempRemotes.push([curUnit.id, remoteID, (curChild.nodeName == \"implicitUnit\"), remoteType]);\n }\n }\n\n return curUnit;\n}", "function findShortestWordAmongMixedElements(arr) {\n if (arr.length === 0) {\n return '';\n }\n var storeArr = [];\n for (var i = 0; i < arr.length; i++) {\n if (typeof arr[i] === \"string\") {\n storeArr.push(arr[i]);\n }\n }\n if (storeArr.length === 0) {\n return '';\n }\n var storeWord = storeArr[0];\n for (var x = 0; x < storeArr.length; x++) {\n if (storeWord.length > storeArr[x].length) {\n storeWord = storeArr[x];\n }\n }\n return storeWord;\n }", "function PropulsionUnit() {\n }", "function PropulsionUnit() {\n }", "function PropulsionUnit() {\n\t}", "noteComboCheck() {\n let noteCombo = '';\n for (let i = 0; i < this.player.noteBar.length - 1; i++) {\n noteCombo += this.player.noteBar[i].frame.name;\n }\n //add code below to string compare which combo to play\n if (noteCombo == powerChordBar[0].powerChord) {\n console.assert(debugFlags.playerFlag, 'Reverse');\n this.player.particleManager.reverseParticles();\n this.physics.world.overlap(this.player.reverseRange, this.projectileGroup, (object1, object2) => {\n object2.redirect();\n }, (object1, object2) => {\n return (!object2.canCollideParent && object2.reverseable);\n }, this);\n } else if (noteCombo == powerChordBar[1].powerChord) { //MUST FIX, WHAT IF PLAYER RESIZES INTO A NARROW ENTRANCE?\n console.assert(debugFlags.playerFlag, 'Shrink');\n if (this.player.canShrink) {\n this.player.particleManager.shrinkParticles();\n this.player.setScale(0.5);\n this.player.setMaxVelocity(playerMaxVelocity/2);\n this.player.canShrink = false;\n this.time.delayedCall(3000, () => {\n this.player.setScale(1.0);\n this.player.setMaxVelocity(playerMaxVelocity);\n this.player.canShrink = true;\n }, null, this);\n }\n } else if (noteCombo == powerChordBar[2].powerChord) {\n console.assert(debugFlags.playerFlag, 'Shield');\n if (!this.player.shieldActive) {\n this.player.shieldActive = true;\n this.player.canCollide = false;\n //this.player.shield.setAlpha(1);\n this.tweens.add({\n targets: this.player.shield,\n alpha: {from: 0, to: 0.3},\n scale: {from: 0, to: 1},\n duration: 1000,\n repeat: 0,\n });\n this.player.setMaxVelocity(playerMaxVelocity/2);\n this.time.delayedCall(2000, () => {\n this.player.canCollide = true;\n this.player.shieldActive = false;\n this.player.shield.setAlpha(0);\n this.player.setMaxVelocity(playerMaxVelocity);\n }, null, this);\n }\n } else {\n this.player.particleManager.dudParticles();\n }\n //Reset the bar\n this.player.clearNoteBar();\n }", "function solution(juice, capacity) {\n // write your code in JavaScript (Node.js 8.9.4)\n\n let newCapacity = capacity;\n newCapacity.sort((a, b) => {\n return b - a;\n });\n let sumJuice = juice.reduce((a, b) => a + b, 0);\n\n if (newCapacity[0] >= sumJuice) {\n return juice.length;\n }\n\n let combine = juice.map((val, index) => {\n let spaceLeftInGlass = capacity[index] - val;\n let arr = [val, capacity[index], spaceLeftInGlass];\n return arr;\n });\n\n combine.sort((a, b) => {\n return b[2] - a[2] || b[1] - a[1];\n });\n\n let biggestSpace = combine[0][2];\n\n combine.splice(0, 1);\n combine.sort((a, b) => {\n return a[0] - b[0];\n });\n\n let maxMix = 1;\n\n for (let i = 0; i < combine.length; i++) {\n biggestSpace -= combine[i][0];\n\n if (biggestSpace < 0) {\n return maxMix;\n }\n maxMix++;\n }\n}", "function computeGreatestUnit(start,end){var i;var unit;var val;for(i=0;i<exports.unitsDesc.length;i++){unit=exports.unitsDesc[i];val=computeRangeAs(unit,start,end);if(val>=1&&isInt(val)){break;}}return unit;// will be \"milliseconds\" if nothing else matches\n}", "function buildSameUnits(chunks){var units=[];var i;var chunk;var tokenInfo;for(i=0;i<chunks.length;i++){chunk=chunks[i];if(chunk.token){tokenInfo=largeTokenMap[chunk.token.charAt(0)];units.push(tokenInfo?tokenInfo.unit:'second');// default to a very strict same-second\n}else if(chunk.maybe){units.push.apply(units,// append\nbuildSameUnits(chunk.maybe));}else{units.push(null);}}return units;}// Rendering to text", "measure() {\n // Check if the element is ready to be measured.\n // Placeholders are special. They are technically \"owned\" by parent AMP\n // elements, sized by parents, but laid out independently. This means\n // that placeholders need to at least wait until the parent element\n // has been stubbed. We can tell whether the parent has been stubbed\n // by whether a resource has been attached to it.\n if (\n this.isPlaceholder_ &&\n this.element.parentElement &&\n // Use prefix to recognize AMP element. This is necessary because stub\n // may not be attached yet.\n this.element.parentElement.tagName.startsWith('AMP-') &&\n !(RESOURCE_PROP_ in this.element.parentElement)\n ) {\n return;\n }\n if (\n !this.element.ownerDocument ||\n !this.element.ownerDocument.defaultView\n ) {\n // Most likely this is an element who's window has just been destroyed.\n // This is an issue with FIE embeds destruction. Such elements will be\n // considered \"not displayable\" until they are GC'ed.\n this.state_ = ResourceState_Enum.NOT_LAID_OUT;\n return;\n }\n\n this.isMeasureRequested_ = false;\n\n const oldBox = this.layoutBox_;\n this.computeMeasurements_();\n const newBox = this.layoutBox_;\n\n // Note that \"left\" doesn't affect readiness for the layout.\n const sizeChanges = !layoutRectSizeEquals(oldBox, newBox);\n if (\n this.state_ == ResourceState_Enum.NOT_LAID_OUT ||\n oldBox.top != newBox.top ||\n sizeChanges\n ) {\n if (this.element.isUpgraded()) {\n if (this.state_ == ResourceState_Enum.NOT_LAID_OUT) {\n // If the element isn't laid out yet, then we're now ready for layout.\n this.state_ = ResourceState_Enum.READY_FOR_LAYOUT;\n } else if (\n (this.state_ == ResourceState_Enum.LAYOUT_COMPLETE ||\n this.state_ == ResourceState_Enum.LAYOUT_FAILED) &&\n this.element.isRelayoutNeeded()\n ) {\n // If the element was already laid out and we need to relayout, then\n // go back to ready for layout.\n this.state_ = ResourceState_Enum.READY_FOR_LAYOUT;\n }\n }\n }\n\n if (!this.hasBeenMeasured()) {\n this.initialLayoutBox_ = newBox;\n }\n\n this.element.updateLayoutBox(newBox, sizeChanges);\n }", "function longerLouder(note) {\n let { duration } = note\n return {...note, velocity: 63 + duration / 4 * 32}\n}", "function generateLengths() {\n //start by making sure that the resolution is in the array of possible lengths\n var lengths = [resolution];\n\n //continue populationg the array until we have 3 additional random values\n while (lengths.length < 4) {\n var randomnumber = getRandomInt(minStep, maxStep);\n var found = false;\n for (var i = 0; i < lengths.length; i++) {\n if (lengths[i] == randomnumber) {\n found = true;break;\n }\n }\n if (!found) {\n lengths[lengths.length] = randomnumber;\n }\n }\n\n //depending on the difficulty, replace some of the length to be equal to some other\n if (nbOfRhythms == 1) {\n lengths[1] = lengths[0];\n lengths[2] = lengths[1];\n lengths[3] = lengths[2];\n } else if (nbOfRhythms == 2) {\n lengths[2] = lengths[1];\n lengths[3] = lengths[2];\n } else if (nbOfRhythms == 3) {\n lengths[3] = lengths[2];\n }\n\n //shuffle the array \n // if we only shuffle after the first element, we can make sure that the left foot\n // will get a sequence length = resolution, for an easier scenario\n if (getRandomFloat(0, 100) < (1 - nbOfRhythms) * 100) {\n lengths = lengths.slice(1, 4).shuffle();\n lengths.unshift(resolution);\n } else {\n lengths = lengths.shuffle();\n }\n\n lFootLength = lengths[0];\n lHandLength = lengths[1];\n rHandLength = lengths[2];\n rFootLength = lengths[3];\n\n if (forceLength) {\n lHandLength = forceLeftHand;\n lFootLength = forceLeftFoot;\n rHandLength = forceRightHand;\n rFootLength = forceRightFoot;\n }\n\n lengths = [lFootLength, lHandLength, rFootLength, rHandLength];\n\n // compute the max number of steps of the song\n max = getLoopLength(lengths);\n}", "function resolvedWeaksForSequence(codepoints, bidiTypes, sequence) {\n // merge together all the codepoint-slices and bidiType-slices\n // that each run in the sequence take\n const paragraph = codepoints.zip(bidiTypes);\n const [ codepointsFromSequence, bidiTypesFromSequence ] = unzip(\n sequence.get('runs').map(run => {\n const { from, to } = run.toJS();\n return paragraph.slice(from, to);\n }).flatten()\n );\n\n const rules = [\n nsm, // W1.\n en, // W2.\n al, // W3.\n es, // W4.\n et, // W5.\n on, // W6.\n enToL, // W7.\n resolveBrackets, // N0\n resolveIsolates, // N1\n resolveRemaining // N2\n ]; // [1]\n\n const newTypesFromSequence = rules.reduce((types, rule) => {\n const level = sequence.get('runs').first().get('level');\n // console.log(rule.name, ' types = ', types, '--', codepointsFromSequence)\n const t = rule(types, codepointsFromSequence, sequence.get('sos'), sequence.get('eos'), level, bidiTypesFromSequence);\n // console.log(rule.name, ' types = ', t, '--', codepointsFromSequence)\n return t;\n }, bidiTypesFromSequence); // [1]\n\n const offsets = sequence.get('runs').butLast().reduce((acc, run) => {\n const { from, to } = run.toJS();\n const size = to - from;\n const lastSize = acc.get(-1);\n return acc.push(size + lastSize);\n }, List.of(0));\n\n const slices = sequence.get('runs').zip(offsets).map(([run, offset]) => {\n const { from, to } = run.toJS();\n const size = to - from;\n return newTypesFromSequence.slice(offset, offset + size);\n });\n\n const newTypes = sequence.get('runs').zip(slices).reduce((types, [run, slice]) => {\n const { from, to } = run.toJS();\n return types\n .slice(0, from)\n .concat(slice)\n .concat(types.slice(to));\n }, bidiTypes);\n\n return newTypes;\n}", "function imperativeLengths(elements){\n\tlet lengths = {};\n\telements.forEach(function(element) {\n\t\tlengths[element] = element.length;\n\t});\n\treturn lengths;\n}", "units() {\n return this.growRight('#Unit').match('#Unit$')\n }", "parseIngredients() {\n\n // the order of these two arrays is important\n const unitsLong = ['tablespoons', 'tablespoon', 'ounces', 'ounce', 'teaspoons', 'teaspoon', 'cups', 'pounds'];\n const unitsShort = ['tbsp', 'tbsp', 'oz', 'oz', 'tsp', 'tsp', 'cup', 'pound'];\n const units = [...unitsShort, 'kg', 'g'];\n\n const newIngredients = this.ingredients.map(element => {\n // Standardize units\n let ingredient = element.toLowerCase();\n unitsLong.forEach((unit, index) => {\n ingredient = ingredient.replace(unit, unitsShort[index]);\n });\n\n // Remove parenthesis\n ingredient = ingredient.replace(/ *\\([^)]*\\) */g, \" \");\n\n // Parse ingredients into count, unit and ingredient\n\n const arrIngr = ingredient.split(' ');\n\n // findIndex - find which index contains the shortened unit (uses include to help find unit )\n const unitIndex = arrIngr.findIndex(el => units.includes(el));\n\n let objIngr;\n\n if (unitIndex > -1) {\n // Found a unit\n // Ex 4 1/2 cups, arrCount is [4, 1/2]\n // Ex 4 cups, arrCount is [4]\n const arrCount = arrIngr.slice(0, unitIndex);\n\n let count;\n if (arrCount.length === 1) {\n count = eval(arrIngr[0].replace('-', '+'));\n } else {\n count = eval(arrIngr.slice(0, unitIndex).join('+'));\n }\n\n objIngr = {\n count, // same as count: count - es6\n unit: arrIngr[unitIndex],\n ingredient : arrIngr.slice(unitIndex + 1).join(' ')\n };\n\n } else if (parseInt(arrIngr[0], 10)) {\n // There is NO unit, but first element is a number\n // eg 1 Tomato\n objIngr = {\n count: parseInt(arrIngr[0], 10),\n unit: '',\n ingredient: arrIngr.slice(1).join(' ') // slice from and including 2 element and join into a string\n // with a space delimiter\n };\n } else if (unitIndex === -1) {\n // Didnt find a unit and NO number in first position\n objIngr = {\n count: 1,\n unit: '',\n ingredient // same as ingredient: ingredient - es6\n };\n }\n\n return objIngr; // in map you have to return\n });\n\n this.ingredients = newIngredients;\n }", "function hasACompleteSetOf(type) {\n // Determine first how many are needed for this property type (default is 3)\n const needed = type === \"RR\" ? 4 : needTwo.includes(type) ? 2 : 3;\n\n // Get a reference to how many 'natural' dice of this type we have\n let has = quantities[type];\n\n // If the number we 'has' is more than or equal to the number we need (should never be more than), then return true\n if (has >= needed) {\n return true;\n } else if (availableWilds > 0 && needed - availableWilds <= has) {\n // We have enough wilds to compose a complete set, so subtract the needed wilds from the number available\n availableWilds -= needed - has;\n return true;\n } else {\n // Not enough naturals or wilds to complete the set for this property type, return false\n return false;\n }\n }", "function UNIVERSAL_LINEAR (plank_duration) {\n return plank_duration + UNIVERSAL_CONSTANT(plank_duration); // electron, qubit, super_plank stars, (1d projection into 2d spacetime)\n } // \"I want to build a Taj Mahal that will never get its last tile.\"", "sharpen(){cov_14q771vu2z.f[3]++;cov_14q771vu2z.s[22]++;if(this.length===0){cov_14q771vu2z.b[6][0]++;cov_14q771vu2z.s[23]++;throw new Error('Your pencil has a length and durability of 0! You need a new one!');}else{cov_14q771vu2z.b[6][1]++;cov_14q771vu2z.s[24]++;this.pencilDurability=40000;cov_14q771vu2z.s[25]++;this.length-=1;}}", "standardIngredients() {\n\n const usedUnits = ['tablespoons', 'tablespoon', 'ounces', 'ounce', 'teaspoons', 'teaspoon', 'cups', 'pounds', 'lbs', 'lb'];\n const standardUnits = ['tbsp', 'tbsp', 'oz', 'oz', 'tsp', 'tsp', 'cup', 'pound', 'lb', 'lb'];\n const units = [...standardUnits, 'kg', 'g'];\n const newIngredients = this.ingredients.map(element => {\n let ing = element.toLowerCase();\n usedUnits.forEach((unit, index) => {\n ing = ing.replace(unit, standardUnits[index]);\n });\n\n ing = ing.replace(/ *\\([^)]*\\) */g, ' '); //Removes the contents in () parenthesis\n\n const arrayIng = ing.split(' ');\n const unitIndex = arrayIng.findIndex(el => units.includes(el));\n let objectIng;\n if (unitIndex > -1) {\n const countIndex = arrayIng.slice(0, unitIndex); // Everything before Unit is considered as Count\n let count;\n if (countIndex.length === 1) {\n count = eval(arrayIng[0].replace('-', '+'));\n if (count === undefined) count = 1;\n } else {\n if(countIndex[1] === 'to') \n count = (parseInt(countIndex[0]) + parseInt(countIndex[2]))/2;\n else \n count = eval(arrayIng.slice(0, unitIndex).join('+'));\n }\n objectIng = {\n count,\n unit: arrayIng[unitIndex],\n name: arrayIng.slice(unitIndex + 1).join(' ')\n }\n\n } else if (parseInt(arrayIng[0], 10)) { //There is no unit but number is given\n objectIng = {\n count: parseInt(arrayIng[0], 10),\n unit: '',\n name: arrayIng.slice(1).join(' ')\n }\n } else if (unitIndex === -1) { //There is no unit and number given\n\n if (arrayIng[0] === 'a') { //If it starts with A , remove it. Eg : A bowl of butter ~ 1 bowl of butter\n objectIng = {\n count: 1,\n unit: '',\n name: arrayIng.slice(1).join(' ')\n }\n } else {\n objectIng = {\n count: 1,\n unit: '',\n name: ing\n }\n }\n }\n\n if(objectIng.count < 0) objectIng.count *=-1;\n return objectIng;\n });\n\n this.ingredients = newIngredients;\n }", "function organ(partials,length) {\n filterGrow(partials,length,0.05);\n filter1OverSquared(partials,length);\n filterLowPass(partials,length,0.1,0);\n filterOrganise(partials,length,0.4);\n}", "function calculatePermutations(){\n \n // Calculate number of possible permutations\n var permutations = str(adjective.length * medium.length * material1.length * material2.length * action.length * subject.length);\n \n return permutations;\n}", "function findShortestWordAmongMixedElements(arr) {\n if (arr.length < 1) {\n return '';\n } else {\n\n var auxArray = [];\n for (i = 0; i < arr.length; i++) {\n if (typeof arr[i] === 'string') {\n auxArray.push(arr[i]);\n }\n }\n\n if (auxArray.length < 1) {\n return '';\n } else {\n\n compareStrings(auxArray);\n return auxArray[0];\n }\n }\n\n function compareStrings(array) {\n\n for(var i = 0; i < array.length; i++) {\n var indexOfShortestString = i;\n\n for(var v = i + 1; v < array.length; v++) {\n if(array[v].length < array[indexOfShortestString].length) {\n indexOfShortestString = v;\n }\n }\n\n if (i !== indexOfShortestString) {\n var temporaryArray = array[i];\n array[i] = array[indexOfShortestString];\n array[indexOfShortestString] = temporaryArray;\n }\n }\n }\n}", "function getTuntematonLengths() {\n let tuntematonA = new Array();\n // get unknown words\n let tuntematonO = document.getElementsByClassName(\"tuntematon sana\")\n for (let item of tuntematonO) {\n let nums = getTuntematonLength( item.textContent );\n tuntematonA.push( nums );\n }\n return tuntematonA;\n}", "function findShortestWordAmongMixedElements(arr) {\n if (arr.length < 1) {\n return '';\n } else {\n\n var auxArray = [];\n for (i = 0; i < arr.length; i++) {\n if (typeof arr[i] === 'string') {\n auxArray.push(arr[i]);\n }\n }\n\n if (auxArray.length < 1) {\n return '';\n } else {\n\n auxArray.sort(function compareStrings(a, b) {\n if (a.length < b.length) {\n return -1;\n }\n if (a.length > b.length) {\n return 1;\n }\n return 0;\n });\n\n return auxArray[0];\n }\n }\n}", "function critique(type) {\n if (type === \"reset\") {\n for (i in weight) {\n weight[i] = 16.6;\n }\n return $.extend({}, weight);\n }\n\n var strength = 20;\n\n if (!weight.hasOwnProperty(type)) return; // only works if type is part of weight\n if (weight[type] == 100) return weight;\n\n oldWeightOfType = weight[type];\n weight[type] = Math.min(100, weight[type] + strength);\n\n var toSubtract = weight[type] - oldWeightOfType;\n var maxIterations = Math.round(strength * 100);\n var iterationCounter = 0;\n while (toSubtract > 0 && maxIterations >= iterationCounter) { // subtract as much from other weights as was added to weight[type]; if other weights are all 0, maxIterations prevents infinite loop\n for (i in weight) {\n if (i == type) continue;\n else {\n if (weight[i] > 0) {\n weight[i] = Math.max(0, weight[i] - 0.1); // use babysteps for more precision (otherwise if weight[i] == 0.2 and we remove 1, we have .8 too much in total)\n toSubtract -= 0.1;\n }\n }\n iterationCounter++;\n }\n }\n\n return $.extend({}, weight); // return copy of weight\n}", "function computeGreatestUnit(start, end) {\n var i;\n var unit;\n var val;\n for (i = 0; i < exports.unitsDesc.length; i++) {\n unit = exports.unitsDesc[i];\n val = computeRangeAs(unit, start, end);\n if (val >= 1 && isInt(val)) {\n break;\n }\n }\n return unit; // will be \"milliseconds\" if nothing else matches\n}", "function computeGreatestUnit(start, end) {\n var i;\n var unit;\n var val;\n for (i = 0; i < exports.unitsDesc.length; i++) {\n unit = exports.unitsDesc[i];\n val = computeRangeAs(unit, start, end);\n if (val >= 1 && isInt(val)) {\n break;\n }\n }\n return unit; // will be \"milliseconds\" if nothing else matches\n}", "function computeGreatestUnit(start, end) {\n var i;\n var unit;\n var val;\n for (i = 0; i < exports.unitsDesc.length; i++) {\n unit = exports.unitsDesc[i];\n val = computeRangeAs(unit, start, end);\n if (val >= 1 && isInt(val)) {\n break;\n }\n }\n return unit; // will be \"milliseconds\" if nothing else matches\n}", "function computeGreatestUnit(start, end) {\n var i;\n var unit;\n var val;\n for (i = 0; i < exports.unitsDesc.length; i++) {\n unit = exports.unitsDesc[i];\n val = computeRangeAs(unit, start, end);\n if (val >= 1 && isInt(val)) {\n break;\n }\n }\n return unit; // will be \"milliseconds\" if nothing else matches\n}", "function newPhase() {\n\touter.clear(); q.clear(); link.fill(0); state.fill(0);\n\troots.clear();\n\tfor (let k = pmax; k >= 0; k--) {\n\t\tsteps++;\n\t\tif (!first[k]) continue;\n\t\tfor (let u = first[k]; u; u = plists.next(u)) {\n\t\t\tbase[u] = u; steps++;\n\t\t\tif (!match.at(u)) {\n\t\t\t\tstate[u] = 1;\n\t\t\t\tif (k > 0) roots.enq(u);\n\t\t\t}\n\t\t}\n\t}\n\tlet r = 0;\n\twhile (q.empty() && !roots.empty()) {\n\t\tr = roots.deq(); add2q(r);\n\t}\n\treturn r;\n}", "get newLength() {\n let result = 0;\n for (let i = 0; i < this.sections.length; i += 2) {\n let ins = this.sections[i + 1];\n result += ins < 0 ? this.sections[i] : ins;\n }\n return result;\n }", "async function positiveDuration (element) {\n if (store.getters.getEndTime(element) <= store.getters.getStartTime(element)) {\n return { element: {\n [element._id]: [{\n class: 'strict',\n finding: 'The end time lies before the start time. This is probably not good.',\n source: {\n id: element._id,\n type: 'element'\n },\n id: `${element._id}_positiveDuration`\n }]\n }}\n }\n}", "function computeGreatestUnit(start, end) {\n\tvar i, unit;\n\tvar val;\n\n\tfor (i = 0; i < unitsDesc.length; i++) {\n\t\tunit = unitsDesc[i];\n\t\tval = computeRangeAs(unit, start, end);\n\n\t\tif (val >= 1 && isInt(val)) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn unit; // will be \"milliseconds\" if nothing else matches\n}", "function computeGreatestUnit(start, end) {\n\tvar i, unit;\n\tvar val;\n\n\tfor (i = 0; i < unitsDesc.length; i++) {\n\t\tunit = unitsDesc[i];\n\t\tval = computeRangeAs(unit, start, end);\n\n\t\tif (val >= 1 && isInt(val)) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn unit; // will be \"milliseconds\" if nothing else matches\n}", "function computeGreatestUnit(start, end) {\n\tvar i, unit;\n\tvar val;\n\n\tfor (i = 0; i < unitsDesc.length; i++) {\n\t\tunit = unitsDesc[i];\n\t\tval = computeRangeAs(unit, start, end);\n\n\t\tif (val >= 1 && isInt(val)) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn unit; // will be \"milliseconds\" if nothing else matches\n}", "function computeGreatestUnit(start, end) {\n\tvar i, unit;\n\tvar val;\n\n\tfor (i = 0; i < unitsDesc.length; i++) {\n\t\tunit = unitsDesc[i];\n\t\tval = computeRangeAs(unit, start, end);\n\n\t\tif (val >= 1 && isInt(val)) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn unit; // will be \"milliseconds\" if nothing else matches\n}", "function computeGreatestUnit(start, end) {\n\tvar i, unit;\n\tvar val;\n\n\tfor (i = 0; i < unitsDesc.length; i++) {\n\t\tunit = unitsDesc[i];\n\t\tval = computeRangeAs(unit, start, end);\n\n\t\tif (val >= 1 && isInt(val)) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn unit; // will be \"milliseconds\" if nothing else matches\n}", "static lengthFor(values, elementType, unit) {\n const elementTraits = getElementTraits(elementType);\n return elementTraits.requiredUnits * values.length * getStorageConstructor(unit).BYTES_PER_ELEMENT;\n }", "function stantonMeasure(arr) {\n let n = arr.filter(a => a === 1).length;\n return arr.filter(b => b === n).length;\n}", "function rhythmPattern( duration, speed, loudness, pauses,dictionInd){ \n\n this.loudnessArr = function (){\n\tvar s = 1, w=0.5;\n\tvar temp = generateBaseValue(duration,w);\n\tvar arr = temp.map(function(s,index){\n\t if(arrElementCmp(index,loudness) == 1){\n\t\treturn s;\n\t }\n\t if(arrElementCmp(index,pauses) == 1){\n\t\treturn 0;\n\t }\n\t else{\n\t\treturn w;\n\t }\n\t});\n\tarr = arr.map(function(s,index){\n\t if(arrElementCmp(index,speed) == 1 && arrElementCmp(index,pauses) == 0){\n\t\treturn [w,w];\n\t }\t \n\t else return [s];\n\t});\t\n\n\treturn arr;\n };\n\t\n this.speedArr = function(){\n\tvar temp = generateBaseValue(duration,2);\n\tvar arr = temp.map(function(s,index){\n\t if(arrElementCmp(index,speed) == 1 && arrElementCmp(index,pauses) == 0){\n\t\treturn [4,4];\n\t }\n\t else{\n\t\treturn [2];\n\t }\n\t});\n\treturn arr;\n };\n\n this.diction = function strokeSequence(){\n\n\tvar arr;\n\tif(dictionInd == -1){ //manual reference diction\n\t arr = document.getElementById(\"refDiction\").split(\",\");\n\t}\n\telse if(dictionInd == -2){ // default automatic reference diction\n\t arr = generateBaseValue(duration,\"ta\");\n\t}\n\telse{\n\t //three common solkattu used for accompaniment\n\t var Solkattu = [[\"tum\",\"ta\",\"tum\",\"ta\",\"ta\",\"tum\",\"tum\",\"ta\"],[\"ta\",\"ta\",\"tum\",\"tum\",\"ta\",\"tum\",\"tum\",\"ta\"],[\"ta\",\"tum\",\"tum\",\"ta\",\"ta\",\"tum\",\"tum\",\"ta\"]];\n\t \n\t var temp = Solkattu[dictionInd];\n\t \n\t var i = 0;\n\t var str = temp.join(\",\"), temp2 = str;\n\t while(i < (duration/8)-1){ // n-1 times\n\t\ttemp2 = temp2 + \",\" + str ;\n\t\ti++;\n\t }\n\t arr = temp2.split(\",\");\n\n\t arr = arr.map(function(s,index){\n\t\tif(arrElementCmp(index,speed)== 1 && arrElementCmp(index,pauses) == 0 ){\n\t\t return \"ta te\";\n\t\t}\n\t\telse if(arrElementCmp(index,pauses) == 1){\n\t\t return \".\";\n\t\t}\n\t\telse return s;\n\t });\n\n\t var sol = [arr, arr.map(function(s){\n\t\tif(s == \"tum\"){\n\t\t return \"tumki\";\n\t\t}\n\t\telse return s;\n\t })];\n\t \n\t arr = sol[wholeRand(0,1)];\t \n\t}\n\tarr = arr.map(function(s,index){\n\t return s.split(\" \");\n\t});\n\treturn arr;\t\n }\n\n this.accent = function(loudnessArr,speedArr,diction){\n\n\tvar lArr = loudnessArr();\n\tvar sArr = speedArr();\n\tvar dict = diction();\n\tvar s = 1, w=0.5; \n\tvar weightedArr = lArr.map(function(s,index){\n\t return s[0];\n\t});\n\n\tweightedArr = dict.map(function(s,index){\n\n\t if(s.length > 1){\n\t\ts = s.join(\"\");\n\t }\n\t var stroke = 0;\n\t if( s!= \".\"){stroke = getEle(s);}\n\t var weight = stroke + weightedArr[index];\n\t if(index == duration - 1){\n\t\tweight -= 0.1;\n\t }\n\t return weight;\n\t \n\t \n\t});\n\n\tvar fAccent = weightedArr;\n\t\n\tvar w1 = parseFloat(document.getElementById(\"backWeight\").value), w2 = parseFloat(document.getElementById(\"frontWeight\").value);\n\n\tvar contrastedArr = fAccent.map(function(s,index,arr){\n\t return 1*s - w1*arr[modnum(duration,index,1)] - w2*arr[(index+1)%duration];\n\t}); \n\t//document.getElementById(str + \"Diction\").split(\",\");generateBaseValue(duration,\"ta\");\n\tvar accentStruct = contrastedArr.map(function(s,index,arr){\n\t var max = maxi(s,arr[modnum(duration,index,1)],arr[(index+1)%duration]);\n\t if( max != -1 && max == s){\n\t\treturn 1;\n\t }\n\t else{\n\t\treturn 0;\n\t }\n\t});\n\n\treturn [accentStruct,weightedArr];\n };\n \n var acc = accent(loudnessArr,speedArr,diction);\n var play = [multiTo1DArray(loudnessArr()),multiTo1DArray(diction()),multiTo1DArray(speedArr())]\n return [acc,play];\n //this.accentStr = accent[0];\n //this.weightedArr = accent[1];\n \n}", "function prune() {\n\tlet newComps = [];\n\tlet pruneCount = 0;\n\tconst oLen = components.length; //set to initial length\n\tfor (let i=0; i<components.length; i++) {\n\t\tif (components[i].qty <= 0) {\n\t\t\tpruneCount++;\n\t\t} else {\n\t\t\tnewComps.push(components[i]);\n\t\t}\n\t}\n\tcomponents = newComps;\n\tconsole.log(\"Pruned \"+pruneCount+\" component items out of an initial \"+oLen);\n}", "function part1(input) {\n // for each key in the orbit map, count the path length\n const orbits = buildOrbitRelationships(input);\n return Object.keys(orbits)\n .map(key => getPathLength(orbits, key))\n .reduce((a, b) => a + b, 0);\n}", "function buildChords() {\n // DIATONIC\n\n // create as many triads as the notes\n chords = []; // array of strings like [\"C\", \"Em\"...]\n var wholeChord = []; // array with 1st, 3rd, 5th and 7th of a scale ['C', 'D'...]\n seventh = [];\n let values = [];\n for (let i = 0; i < scale.length; i++) {\n wholeChord = [scale[i], scale[(i+2)%scale.length], scale[(i+4)%scale.length], scale[(i+6)%scale.length]];\n values = evaluatedChord(wholeChord);\n chords[i] = values[0]; //chord\n seventh[i] = values[1]; //seventh\n }\n \n // DOMINANT\n domchords = [];\n // 1st and 7th chords dominant wont be calculated\n for (let i = 1; i < scale.length-1; i++) {\n domchords[i] = notes[(notes.indexOf(scale[i]) + 7) % 12]; \n // in major minor always a perfect fifth from the current note\n domseventh[i] = \"7\";\n }\n domchords[0] = \"-\";\n domchords[scale.length-1] = \"-\";\n domseventh[0] = \"\";\n domseventh[scale.length-1] = \"\";\n\n //PARALLEL\n if (scaletype == \"Major\" | scaletype == \"Harmonic Minor\" | scaletype == \"Melodic Minor\") {\n parchords = []; // array of strings like [\"C\", \"Em\"...]\n wholeChord = []; // array with 1st, 3rd, 5th and 7th of a scale ['C', 'D'...]\n parseventh = [];\n let tmpscaletype;\n if (scaletype == \"Major\") tmpscaletype = \"Harmonic Minor\";\n if (scaletype == \"Harmonic Minor\" | scaletype == \"Melodic Minor\") tmpscaletype = \"Major\";\n //if (scaletype == \"Major Pentatonic\") tmpscaletype = \"Minor Pentatonic\";\n //if (scaletype == \"Major\") tmpscaletype = \"Minor\";\n let parscale = buildScale(scale[0], tmpscaletype, 0)[1];\n for (let i = 0; i < parscale.length; i++) {\n wholeChord = [parscale[i], parscale[(i+2)%parscale.length], parscale[(i+4)%parscale.length], parscale[(i+6)%parscale.length]];\n values = evaluatedChord(wholeChord);\n parchords[i] = values[0];\n parseventh[i] = values[1];\n }\n } else {\n parscale = [\"-\", \"-\", \"-\", \"-\", \"-\", \"-\", \"-\"];\n parchords = [\"\", \"\", \"\", \"\", \"\", \"\", \"\"];\n parseventh = [\"\", \"\", \"\", \"\", \"\", \"\", \"\"];\n }\n \n\n //NEGATIVE\n\n}", "_updateWire (wire) {\n // to allow function hoisting\n const self = this\n\n if (wire.peerChoking) return\n if (!wire.downloaded) return validateWire()\n\n const minOutstandingRequests = getBlockPipelineLength(wire, PIPELINE_MIN_DURATION)\n if (wire.requests.length >= minOutstandingRequests) return\n const maxOutstandingRequests = getBlockPipelineLength(wire, PIPELINE_MAX_DURATION)\n\n trySelectWire(false) || trySelectWire(true)\n\n function genPieceFilterFunc (start, end, tried, rank) {\n return i => i >= start && i <= end && !(i in tried) && wire.peerPieces.get(i) && (!rank || rank(i))\n }\n\n // TODO: Do we need both validateWire and trySelectWire?\n function validateWire () {\n if (wire.requests.length) return\n\n let i = self._selections.length\n while (i--) {\n const next = self._selections[i]\n let piece\n if (self.strategy === 'rarest') {\n const start = next.from + next.offset\n const end = next.to\n const len = end - start + 1\n const tried = {}\n let tries = 0\n const filter = genPieceFilterFunc(start, end, tried)\n\n while (tries < len) {\n piece = self._rarityMap.getRarestPiece(filter)\n if (piece < 0) break\n if (self._request(wire, piece, false)) return\n tried[piece] = true\n tries += 1\n }\n } else {\n for (piece = next.to; piece >= next.from + next.offset; --piece) {\n if (!wire.peerPieces.get(piece)) continue\n if (self._request(wire, piece, false)) return\n }\n }\n }\n\n // TODO: wire failed to validate as useful; should we close it?\n // probably not, since 'have' and 'bitfield' messages might be coming\n }\n\n function speedRanker () {\n const speed = wire.downloadSpeed() || 1\n if (speed > SPEED_THRESHOLD) return () => true\n\n const secs = Math.max(1, wire.requests.length) * Piece.BLOCK_LENGTH / speed\n let tries = 10\n let ptr = 0\n\n return index => {\n if (!tries || self.bitfield.get(index)) return true\n\n let missing = self.pieces[index].missing\n\n for (; ptr < self.wires.length; ptr++) {\n const otherWire = self.wires[ptr]\n const otherSpeed = otherWire.downloadSpeed()\n\n if (otherSpeed < SPEED_THRESHOLD) continue\n if (otherSpeed <= speed) continue\n if (!otherWire.peerPieces.get(index)) continue\n if ((missing -= otherSpeed * secs) > 0) continue\n\n tries--\n return false\n }\n\n return true\n }\n }\n\n function shufflePriority (i) {\n let last = i\n for (let j = i; j < self._selections.length && self._selections[j].priority; j++) {\n last = j\n }\n const tmp = self._selections[i]\n self._selections[i] = self._selections[last]\n self._selections[last] = tmp\n }\n\n function trySelectWire (hotswap) {\n if (wire.requests.length >= maxOutstandingRequests) return true\n const rank = speedRanker()\n\n for (let i = 0; i < self._selections.length; i++) {\n const next = self._selections[i]\n\n let piece\n if (self.strategy === 'rarest') {\n const start = next.from + next.offset\n const end = next.to\n const len = end - start + 1\n const tried = {}\n let tries = 0\n const filter = genPieceFilterFunc(start, end, tried, rank)\n\n while (tries < len) {\n piece = self._rarityMap.getRarestPiece(filter)\n if (piece < 0) break\n\n // request all non-reserved blocks in this piece\n while (self._request(wire, piece, self._critical[piece] || hotswap)) {}\n\n if (wire.requests.length < maxOutstandingRequests) {\n tried[piece] = true\n tries++\n continue\n }\n\n if (next.priority) shufflePriority(i)\n return true\n }\n } else {\n for (piece = next.from + next.offset; piece <= next.to; piece++) {\n if (!wire.peerPieces.get(piece) || !rank(piece)) continue\n\n // request all non-reserved blocks in piece\n while (self._request(wire, piece, self._critical[piece] || hotswap)) {}\n\n if (wire.requests.length < maxOutstandingRequests) continue\n\n if (next.priority) shufflePriority(i)\n return true\n }\n }\n }\n\n return false\n }\n }", "_updateWire (wire) {\n // to allow function hoisting\n const self = this\n\n if (wire.peerChoking) return\n if (!wire.downloaded) return validateWire()\n\n const minOutstandingRequests = getBlockPipelineLength(wire, PIPELINE_MIN_DURATION)\n if (wire.requests.length >= minOutstandingRequests) return\n const maxOutstandingRequests = getBlockPipelineLength(wire, PIPELINE_MAX_DURATION)\n\n trySelectWire(false) || trySelectWire(true)\n\n function genPieceFilterFunc (start, end, tried, rank) {\n return i => i >= start && i <= end && !(i in tried) && wire.peerPieces.get(i) && (!rank || rank(i))\n }\n\n // TODO: Do we need both validateWire and trySelectWire?\n function validateWire () {\n if (wire.requests.length) return\n\n let i = self._selections.length\n while (i--) {\n const next = self._selections[i]\n let piece\n if (self.strategy === 'rarest') {\n const start = next.from + next.offset\n const end = next.to\n const len = end - start + 1\n const tried = {}\n let tries = 0\n const filter = genPieceFilterFunc(start, end, tried)\n\n while (tries < len) {\n piece = self._rarityMap.getRarestPiece(filter)\n if (piece < 0) break\n if (self._request(wire, piece, false)) return\n tried[piece] = true\n tries += 1\n }\n } else {\n for (piece = next.to; piece >= next.from + next.offset; --piece) {\n if (!wire.peerPieces.get(piece)) continue\n if (self._request(wire, piece, false)) return\n }\n }\n }\n\n // TODO: wire failed to validate as useful; should we close it?\n // probably not, since 'have' and 'bitfield' messages might be coming\n }\n\n function speedRanker () {\n const speed = wire.downloadSpeed() || 1\n if (speed > SPEED_THRESHOLD) return () => true\n\n const secs = Math.max(1, wire.requests.length) * Piece.BLOCK_LENGTH / speed\n let tries = 10\n let ptr = 0\n\n return index => {\n if (!tries || self.bitfield.get(index)) return true\n\n let missing = self.pieces[index].missing\n\n for (; ptr < self.wires.length; ptr++) {\n const otherWire = self.wires[ptr]\n const otherSpeed = otherWire.downloadSpeed()\n\n if (otherSpeed < SPEED_THRESHOLD) continue\n if (otherSpeed <= speed) continue\n if (!otherWire.peerPieces.get(index)) continue\n if ((missing -= otherSpeed * secs) > 0) continue\n\n tries--\n return false\n }\n\n return true\n }\n }\n\n function shufflePriority (i) {\n let last = i\n for (let j = i; j < self._selections.length && self._selections[j].priority; j++) {\n last = j\n }\n const tmp = self._selections[i]\n self._selections[i] = self._selections[last]\n self._selections[last] = tmp\n }\n\n function trySelectWire (hotswap) {\n if (wire.requests.length >= maxOutstandingRequests) return true\n const rank = speedRanker()\n\n for (let i = 0; i < self._selections.length; i++) {\n const next = self._selections[i]\n\n let piece\n if (self.strategy === 'rarest') {\n const start = next.from + next.offset\n const end = next.to\n const len = end - start + 1\n const tried = {}\n let tries = 0\n const filter = genPieceFilterFunc(start, end, tried, rank)\n\n while (tries < len) {\n piece = self._rarityMap.getRarestPiece(filter)\n if (piece < 0) break\n\n // request all non-reserved blocks in this piece\n while (self._request(wire, piece, self._critical[piece] || hotswap)) {}\n\n if (wire.requests.length < maxOutstandingRequests) {\n tried[piece] = true\n tries++\n continue\n }\n\n if (next.priority) shufflePriority(i)\n return true\n }\n } else {\n for (piece = next.from + next.offset; piece <= next.to; piece++) {\n if (!wire.peerPieces.get(piece) || !rank(piece)) continue\n\n // request all non-reserved blocks in piece\n while (self._request(wire, piece, self._critical[piece] || hotswap)) {}\n\n if (wire.requests.length < maxOutstandingRequests) continue\n\n if (next.priority) shufflePriority(i)\n return true\n }\n }\n }\n\n return false\n }\n }", "function dominantDirection(text) {\n //useing the first part of countBy \n let scripts = countBy(text, char => {\n let script = characterScript(char.codePointAt(0));\n return script ? script.direction : \"none\";\n }).filter(({name}) => name != \"none\");\n // at this point the 100% latin will be \n // 0: {name: \"ltr\", count: 5} \n // length: 1\n \n // at this point the 25% Latin, 75% Arabic will be \n // 0: {name: \"ltr\", count: 3} \n // 1: {name: \"rtl\", count: 9} \n // length: 2\n \n //we will have to use two sets of if statments. first if there is no value, then we \n //test if there is onle one value, and finalit if there are more that one we will \n //test if they are equal or witch one is dominant\n \n //if there is no length there is no direction\n if (scripts.length === 0){\n return 'no dominant direction found';\n //if the length is one there will be only one direction\n } else if (scripts.length === 1) {\n return scripts[0].name;\n //more than one we will have to test if they are equal or witch one will have the dominatDirection\n } else {\n // useing reduce if both values are equal there is no dominant value\n if (scripts.reduce((accum, current) => accum.count === current.count)) {\n return 'no dominant direction found';\n //in all other cases the greater of the \n } else {\n return scripts.reduce((accum, current) => accum.count >= current.count ? accum.name : current.name);\n }\n }\n}", "function part2(data) {\n let items = data\n .map(answer => {\n let sorted = answer.join('').split('').sort().join('');\n let letterGroups = sorted.match(/(\\S)\\1*/g);\n return letterGroups.filter(letterGroup => letterGroup.length == answer.length).length;\n })\n .reduce((acc, cur) => acc + cur);\n return items;\n}", "_prepareCharacterData (actorData) {\n const data = actorData.data\n let will\n let savedAncestry = null\n let pathHealthBonus = 0\n let ancestryFixedArmor = false\n\n data.characteristics.insanity.max = data.attributes.will.value\n\n const characterbuffs = this.generateCharacterBuffs()\n const ancestries = this.getEmbeddedCollection('OwnedItem').filter(\n (e) => e.type === 'ancestry'\n )\n\n for (const ancestry of ancestries) {\n savedAncestry = ancestry\n\n if (!game.settings.get('demonlord', 'useHomebrewMode')) {\n data.attributes.strength.value = parseInt(\n ancestry.data.attributes?.strength.value\n )\n data.attributes.agility.value = parseInt(\n ancestry.data.attributes?.agility.value\n )\n data.attributes.intellect.value = parseInt(\n ancestry.data.attributes?.intellect.value\n )\n data.attributes.will.value = parseInt(\n ancestry.data.attributes?.will.value\n )\n\n data.characteristics.insanity.max = ancestry.data.attributes?.will.value\n\n // Paths\n if (data.level > 0) {\n for (let i = 1; i <= data.level; i++) {\n const paths = this.getEmbeddedCollection('OwnedItem').filter(\n (e) => e.type === 'path'\n )\n paths.forEach((path) => {\n path.data.levels\n .filter(function ($level) {\n return $level.level == i\n })\n .forEach(function ($level) {\n // Attributes\n if ($level.attributeStrengthSelected) {\n data.attributes.strength.value += parseInt(\n $level.attributeStrength\n )\n }\n if ($level.attributeAgilitySelected) {\n data.attributes.agility.value += parseInt(\n $level.attributeAgility\n )\n }\n if ($level.attributeIntellectSelected) {\n data.attributes.intellect.value += parseInt(\n $level.attributeIntellect\n )\n }\n if ($level.attributeWillSelected) {\n data.attributes.will.value += parseInt($level.attributeWill)\n }\n\n if ($level.attributeSelectIsFixed) {\n if ($level.attributeStrength > 0) {\n data.attributes.strength.value += parseInt(\n $level.attributeStrength\n )\n }\n if ($level.attributeAgility > 0) {\n data.attributes.agility.value += parseInt(\n $level.attributeAgility\n )\n }\n if ($level.attributeIntellect > 0) {\n data.attributes.intellect.value += parseInt(\n $level.attributeIntellect\n )\n }\n if ($level.attributeWill > 0) {\n data.attributes.will.value += parseInt(\n $level.attributeWill\n )\n }\n }\n\n pathHealthBonus += $level.characteristicsHealth\n\n switch (path.data.type) {\n case 'novice':\n data.paths.novice = path.name\n break\n case 'expert':\n data.paths.expert = path.name\n break\n case 'master':\n data.paths.master = path.name\n break\n default:\n break\n }\n })\n })\n }\n }\n } else {\n // Paths\n if (data.level > 0) {\n for (let i = 1; i <= data.level; i++) {\n const paths = this.getEmbeddedCollection('OwnedItem').filter(\n (e) => e.type === 'path'\n )\n paths.forEach((path) => {\n path.data.levels\n .filter(function ($level) {\n return $level.level == i\n })\n .forEach(function ($level) {\n pathHealthBonus += $level.characteristicsHealth\n\n switch (path.data.type) {\n case 'novice':\n data.paths.novice = path.name\n break\n case 'expert':\n data.paths.expert = path.name\n break\n case 'master':\n data.paths.master = path.name\n break\n default:\n break\n }\n })\n })\n }\n }\n }\n\n // Calculate Health and Healing Rate\n if (game.settings.get('demonlord', 'reverseDamage')) {\n if (data.characteristics.health.value < 0) {\n data.characteristics.health.value =\n parseInt(data.attributes.strength.value) +\n parseInt(ancestry.data.characteristics?.healthmodifier) +\n characterbuffs.healthbonus +\n pathHealthBonus\n }\n data.characteristics.health.max =\n parseInt(data.attributes.strength.value) +\n parseInt(ancestry.data.characteristics?.healthmodifier) +\n characterbuffs.healthbonus +\n pathHealthBonus\n } else {\n data.characteristics.health.max =\n parseInt(data.attributes.strength.value) +\n parseInt(ancestry.data.characteristics?.healthmodifier) +\n characterbuffs.healthbonus +\n pathHealthBonus\n }\n if (data.level >= 4) {\n if (game.settings.get('demonlord', 'reverseDamage')) {\n if (data.characteristics.health.value == 0) {\n data.characteristics.health.value += parseInt(\n ancestry.data.level4?.healthbonus\n )\n }\n data.characteristics.health.max += parseInt(\n ancestry.data.level4?.healthbonus\n )\n } else {\n data.characteristics.health.max += parseInt(\n ancestry.data.level4?.healthbonus\n )\n }\n }\n data.characteristics.health.healingrate =\n Math.floor(parseInt(data.characteristics.health.max) / 4) +\n parseInt(ancestry.data.characteristics?.healingratemodifier)\n // ******************\n\n data.attributes.perception.value =\n parseInt(data.attributes.intellect.value) +\n parseInt(ancestry.data.characteristics.perceptionmodifier)\n\n if (parseInt(ancestry.data.characteristics?.defensemodifier) > 10) {\n data.characteristics.defense = parseInt(\n ancestry.data.characteristics?.defensemodifier\n )\n ancestryFixedArmor = true\n } else {\n data.characteristics.defense =\n parseInt(data.attributes.agility.value) +\n parseInt(ancestry.data.characteristics.defensemodifier)\n }\n\n data.characteristics.power = parseInt(\n ancestry.data.characteristics?.power\n )\n data.characteristics.speed = parseInt(\n ancestry.data.characteristics?.speed\n )\n data.characteristics.size = ancestry.data.characteristics.size\n\n // These were still breaking the sanity/corruption fields..\n // data.characteristics.insanity.value += parseInt(\n // ancestry.data.characteristics.insanity\n // )\n // data.characteristics.corruption += parseInt(\n // ancestry.data.characteristics.corruption\n // )\n }\n\n if (savedAncestry == null && this.data.type != 'creature') {\n data.attributes.perception.value = parseInt(\n data.attributes.intellect.value\n )\n data.characteristics.defense = parseInt(data.attributes.agility.value)\n\n if (game.settings.get('demonlord', 'reverseDamage')) {\n if (data.characteristics.health.value == 0) {\n data.characteristics.health.value =\n parseInt(data.attributes.strength.value) +\n characterbuffs.healthbonus\n }\n data.characteristics.health.max =\n parseInt(data.attributes.strength.value) + characterbuffs.healthbonus\n } else {\n data.characteristics.health.max =\n parseInt(data.attributes.strength.value) + characterbuffs.healthbonus\n }\n }\n\n // Paths\n let pathDefenseBonus = 0\n if (data.level > 0) {\n const actor = this\n\n for (let i = 1; i <= data.level; i++) {\n const paths = this.getEmbeddedCollection('OwnedItem').filter(\n (e) => e.type === 'path'\n )\n paths.forEach((path) => {\n path.data.levels\n .filter(function ($level) {\n return $level.level == i\n })\n .forEach(function ($level) {\n // Characteristics\n data.characteristics.power =\n parseInt(data.characteristics.power) +\n parseInt($level.characteristicsPower)\n pathDefenseBonus = $level.characteristicsDefense\n data.characteristics.speed += $level.characteristicsSpeed\n data.attributes.perception.value +=\n $level.characteristicsPerception\n })\n })\n }\n }\n\n // Loop through ability scores, and add their modifiers to our sheet output.\n for (const [key, attribute] of Object.entries(data.attributes)) {\n if (attribute.value > attribute.max) {\n attribute.value = attribute.max\n }\n if (attribute.value < attribute.min) {\n attribute.value = attribute.min\n }\n\n attribute.modifier = attribute.value - 10\n attribute.label = CONFIG.DL.attributes[key].toUpperCase()\n }\n\n const armors = this.getEmbeddedCollection('OwnedItem').filter(\n (e) => e.type === 'armor'\n )\n let armorpoint = 0\n let agilitypoint = 0\n let defenseBonus = 0\n let speedPenalty = 0\n for (const armor of armors) {\n if (armor.data.wear) {\n // If you wear armor and do not meet or exceed its requirements: -2 speed\n if (\n !armor.data.isShield &&\n armor.data.strengthmin != '' &&\n !ancestryFixedArmor &&\n parseInt(armor.data.strengthmin) >\n parseInt(data.attributes.strength.value)\n ) {\n speedPenalty = -2\n }\n\n if (armor.data.agility && agilitypoint == 0) {\n agilitypoint = parseInt(armor.data.agility)\n }\n if (armor.data.fixed) armorpoint = parseInt(armor.data.fixed)\n if (armor.data.defense) defenseBonus = parseInt(armor.data.defense)\n }\n }\n\n if (ancestryFixedArmor) {\n if (armorpoint > data.characteristics.defense) {\n data.characteristics.defense = armorpoint\n }\n data.characteristics.defense +=\n pathDefenseBonus + defenseBonus + characterbuffs.defensebonus\n } else if (armorpoint >= 11) {\n data.characteristics.defense =\n parseInt(armorpoint) +\n parseInt(defenseBonus) +\n pathDefenseBonus +\n characterbuffs.defensebonus\n } else {\n data.characteristics.defense =\n parseInt(data.characteristics.defense) +\n parseInt(defenseBonus) +\n parseInt(agilitypoint) +\n pathDefenseBonus +\n characterbuffs.defensebonus\n }\n\n if (data.characteristics.defense > 25) data.characteristics.defense = 25\n\n characterbuffs.speedbonus += speedPenalty\n\n if (game.settings.get('demonlord', 'useHomebrewMode')) {\n data.characteristics.health.healingrate = Math.floor(\n parseInt(data.characteristics.health.max) / 4\n )\n }\n\n // Afflictions\n if (data.afflictions.slowed) {\n data.characteristics.speed = Math.floor(\n parseInt(data.characteristics.speed + speedPenalty) / 2\n )\n } else {\n data.characteristics.speed =\n parseInt(data.characteristics.speed) +\n parseInt(characterbuffs.speedbonus)\n }\n\n if (data.afflictions.defenseless) data.characteristics.speed = 5\n\n if (data.afflictions.blinded) {\n data.characteristics.speed =\n parseInt(data.characteristics.speed) < 2\n ? parseInt(data.characteristics.speed)\n : 2\n }\n\n data.characteristics.power += parseInt(characterbuffs.powerbonus)\n\n if (data.afflictions.immobilized) data.characteristics.speed = 0\n\n if (data.afflictions.unconscious) data.characteristics.defense = 5\n }", "function solution_1 (words) {\r\n\r\n // SOLUTION 1 [\r\n // O(nl time (n is # of words, l is longest length. the first few steps of the algo are n time, but the biggest time sink is the queue. if each of your n words has l letters, then\r\n // your queue will go through l \"major cycles\" (such that each major cycle adds up to n or fewer iterations) since 1 letter gets removed each time. thus, n*l),\r\n // O(nl) space (prereqs object is arguably constant because at most 26 letters, 25 prereqs each. similarly, all sets/arrays such as lettersSeen or noPrereqs will have no more\r\n // than 26 elements. however, the queue matters. n is # of words, l is longest length. the first element in queue takes up n*l characters in total. those words will be distributed \r\n // in some way into potentially 26 buckets, but it will still be at most n words, each of which will be at most (l - 1) length. whenever anything is added to the queue, the amount\r\n // added will always be less than amount recently shifted out, so the space occupied by the queue should not exceed the initial nl)\r\n // ]:\r\n // in this solution we create a prereqs object where every unique letter found inside the alien dictionary will eventually be a key in prereqs, and the values will be sets containing\r\n // any letter that must go before the corresponding key. to build this, we will use a queue, where every element in the queue will be a subarray of words that have an equal basis of\r\n // comparison prior to its first letter. thus, the initial input will be the first element in the queue. (thereafter, all words beginning with the same letter will go into their own\r\n // subarrays and be added to the queue.)\r\n // (1) when analyzing a particular subarray of words, the first order of business is to make sure that the words within are properly grouped by first\r\n // letter. in other words, you shouldn't have something like ['axx', 'ayy', 'bxxx', 'azz'] because the a...b...a is invalid (a cannot be both before and after b).\r\n // if a violation is found we can immediately return '' because the entire alien dictionary is invalid.\r\n // (2) next, we iterate through the subarray of words. since we know the words are properly grouped by their first letters, we just need to iterate through the words, and every time\r\n // we encounter a new first letter, we will add all previously seen first letters to the prerequisite of the current first letter. additionally, we should start creating new\r\n // subarrays for each new first letter to enter the queue, and we should push in each word.slice(1) into that subarray, for future processing. for example, if the current block is\r\n // ['axx', 'byy', 'bzz'] we want to push in ['xx'] (for the a) followed by ['yy', 'zz'] (for the b).\r\n // after doing all of that, the prereqs object has now been properly constructed. this is now effectively a graph! the final step is to start building the output string. while the\r\n // output string has a length less than the total number of unique letters in the dictionary, we keep going. for every iteration, we search the prereqs object for letters that have no\r\n // prerequisites (set size is 0). we add these letters to a list of processedLetters, we delete the entries for those letters from the prereqs object, and we add that letter to the end\r\n // of output. if we find that no letters had zero prerequisites (i.e. the list of processedLetters is empty) then there must be a cycle in the graph, because every letter depends on\r\n // something else, and so the alien dictionary is invalid - return ''. otherwise, we simply run through the prereqs object a second time, removing all processedLetters from the sets\r\n // of all remaining letters.\r\n // eventually, if and when the while loop exits, then the alien dictionary is valid and the output string has been built out, so we return the output string as required.\r\n\r\n // INITIALIZE prereqs GRAPH\r\n const prereqs = {}; // keys are letters, and values are a set of prerequisite letters that must go before the given letter\r\n \r\n // CONFIGURE prereqs OBJECT. EACH SET OF ENTRIES FROM THE QUEUE HAS EQUAL BASIS OF COMPARISON PRIOR TO ITS FIRST LETTER\r\n const queue = [words]; // initialize with all words\r\n while (queue.length) {\r\n // shift out currentWords from queue\r\n const currentWords = queue.shift();\r\n \r\n // identical first letters must be adjacent. check for something like a...b...a which would invalidate the entire dictionary\r\n const lettersSeen = new Set();\r\n for (let i = 0; i < currentWords.length; i++) {\r\n if (i && currentWords[i][0] === currentWords[i - 1][0]) continue; // same letter as previous? skip\r\n if (lettersSeen.has(currentWords[i][0])) return ''; // else, it's a new letter. make sure you haven't seen it yet\r\n lettersSeen.add(currentWords[i][0]); // add this letter to the list of letters seen\r\n }\r\n \r\n // update the prerequisites\r\n lettersSeen.clear(); // this now represents all letters seen so far for each new block\r\n for (let i = 0; i < currentWords.length; i++) {\r\n const char = currentWords[i][0];\r\n if (!i || char !== currentWords[i - 1][0]) { // if new letter...\r\n if (!(char in prereqs)) prereqs[char] = new Set(); // (initialize prereqs entry if necessary)\r\n prereqs[char] = new Set([...prereqs[char], ...lettersSeen]); // add all letters seen so far in this block to the prereqs for this char\r\n lettersSeen.add(char); // add this char to letters seen so far in this block\r\n queue.push([]); // set up new subarray (new queue entry) for this letter. it's possible this will be empty, but that's fine\r\n }\r\n if (currentWords[i].length > 1) { // whether or not new letter, if and only if there are letters after current char\r\n queue[queue.length - 1].push(currentWords[i].slice(1)); // then push those remaining letters into the latest queue entry (there will always be something)\r\n }\r\n }\r\n }\r\n \r\n // BUILD output STRING BASED ON prereqs OBJECT\r\n let output = '';\r\n const totalLetters = Object.keys(prereqs).length; // this is simply the number of unique letters found anywhere in the dictionary. each letter should have a prereqs entry\r\n while (output.length < totalLetters) {\r\n const noPrereqs = []; // this holds letters with no prerequisites, which can therefore be added to output\r\n for (const letter in prereqs) { // pass 1: find and process all letters with no prereqs\r\n if (!prereqs[letter].size) { // if a letter has no prereqs, then process it\r\n noPrereqs.push(letter);\r\n output += letter;\r\n delete prereqs[letter];\r\n }\r\n }\r\n if (!noPrereqs.length) return ''; // if you didn't find any prereqs, then you have a cycle in the graph - invalid!\r\n for (const letter in prereqs) { // pass 2: delete all processed letters from the prereqs of all remaining letters\r\n for (const processedLetter of noPrereqs) {\r\n prereqs[letter].delete(processedLetter);\r\n }\r\n }\r\n }\r\n\r\n return output;\r\n}", "static estimateMeasureHeight(measure, layout) {\n let heightOffset = 50; // assume 5 lines, todo is non-5-line staffs\n let yOffset = 0;\n let flag = '';\n let lyricOffset = 0;\n if (measure.forceClef) {\n heightOffset += vexGlyph.clef(measure.clef).yTop + vexGlyph.clef(measure.clef).yBottom;\n yOffset = yOffset - vexGlyph.clef(measure.clef).yTop;\n }\n\n if (measure.forceTempo) {\n yOffset = Math.min(-1 * vexGlyph.tempo.yTop, yOffset);\n }\n measure.voices.forEach((voice) => {\n voice.notes.forEach((note) => {\n const bg = suiLayoutAdjuster._beamGroupForNote(measure, note);\n flag = SmoNote.flagStates.auto;\n if (bg && note.noteType === 'n') {\n flag = bg.notes[0].flagState;\n // an auto-flag note is up if the 1st note is middle line\n if (flag === SmoNote.flagStates.auto) {\n const pitch = bg.notes[0].pitches[0];\n flag = smoMusic.pitchToLedgerLine(measure.clef, pitch)\n >= 2 ? SmoNote.flagStates.up : SmoNote.flagStates.down;\n }\n } else {\n flag = note.flagState;\n // an auto-flag note is up if the 1st note is middle line\n if (flag === SmoNote.flagStates.auto) {\n const pitch = note.pitches[0];\n flag = smoMusic.pitchToLedgerLine(measure.clef, pitch)\n >= 2 ? SmoNote.flagStates.up : SmoNote.flagStates.down;\n }\n }\n const hiloHead = suiLayoutAdjuster._highestLowestHead(measure, note);\n if (flag === SmoNote.flagStates.down) {\n yOffset = Math.min(hiloHead.lo, yOffset);\n heightOffset = Math.max(hiloHead.hi + vexGlyph.stem.height, heightOffset);\n } else {\n yOffset = Math.min(hiloHead.lo - vexGlyph.stem.height, yOffset);\n heightOffset = Math.max(hiloHead.hi, heightOffset);\n }\n // Lyrics will be rendered below the lowest thing on the staff, so add to\n // belowBaseline value based on the max number of verses and font size\n // it will extend\n const lyrics = note.getTrueLyrics();\n if (lyrics.length) {\n const maxLyric = lyrics.reduce((a, b) => a.verse > b.verse ? a : b);\n const fontInfo = suiLayoutAdjuster.textFont(maxLyric);\n const maxHeight = fontInfo.maxHeight;\n lyricOffset = Math.max((maxLyric.verse + 2) * fontInfo.maxHeight, lyricOffset);\n }\n const dynamics = note.getModifiers('SmoDynamicText');\n dynamics.forEach((dyn) => {\n heightOffset = Math.max((10 * dyn.yOffsetLine - 50) + 11, heightOffset);\n yOffset = Math.min(10 * dyn.yOffsetLine - 50, yOffset)\n });\n });\n });\n heightOffset += lyricOffset;\n return { belowBaseline: heightOffset, aboveBaseline: yOffset };\n }", "function EResonanceWeights(numelement, element){\n if(numelement>=2){\n score+=5;\n switch(element){\n case \"pyro\":\n outputstr += \"Fervent Flames</br>\\u2265 2 pyro: Elemental and Physical RES +15%</br></br>\"\n break;\n case \"cryo\":\n outputstr += \"Shattering Ice</br>\\u2265 2 cryo: 40% less time affected by electro element. For enemies affected by cryo, CRIT rate is incresed by 15%</br></br>\"\n break;\n case \"hydro\":\n outputstr += \"Soothing Waters</br>\\u2265 2 hydro: Pyro effects are less probable (by 40% of the time). 30% more healing.</br></br>\"\n break;\n case \"geo\":\n outputstr += \"Enduring Rock</br>\\u2265 2 geo: 15% more shield strength. Characters with shield have 15% more DMG, and for 15 seconds attacked enemies will have 20% less geo RES</br></br>\"\n break;\n case \"anemo\":\n outputstr += \"Impetuous Winds</br>\\u2265 2 anemo: Consumed stamina decreased by 15%, faster movement speed (by 10%), and skill CD a shorter time (by 5%)</br></br>\"\n break;\n case \"electro\":\n outputstr += \"High Voltage</br>\\u2265 2 electro: Overload, electro-charge, and superconduct are guaranteed to create an electro particle with CD of 5 seconds. Cryo effects are less probable (by 40% of the time)</br></br>\"\n break;\n }\n }\n}", "function getOffensiveMaterialDeduction(text) {\r\n\tvar maximumDeduction = commentMaxOffensiveWordDeduction; \r\n\tvar offensiveWordCount = wordFilter.countOffensiveWords(text); \r\n\treturn (offensiveWordCount > maximumDeduction) ? -maximumDeduction : -offensiveWordCount; \r\n}", "function minimumBribes(q) {\n let bribe = 0;\n let chaotic = false;\n let minBribe;\n\n for (let i = 0; i < q.length; i++) {\n const position = i + 1;\n const elementI = q[i];\n\n if (elementI - position >= 3) {\n chaotic = true;\n minBribe = 'Too chaotic';\n } else {\n for (let j = Math.max(0, elementI - 2); j < i; j++) {\n const elementJ = q[j];\n if (elementJ > elementI) {\n bribe++;\n }\n }\n }\n }\n if (!chaotic) {\n minBribe = bribe;\n }\n return minBribe;\n}", "function doHumanization(ms, options) {\n\n // Make sure we have a positive number.\n // Has the nice sideffect of turning Number objects into primitives.\n ms = Math.abs(ms);\n\n if (ms === 0) {\n return \"0\";\n }\n\n var dictionary = options.languages[options.language] || languages[options.language];\n if (!dictionary) {\n throw new Error(\"No language \" + dictionary + \".\");\n }\n\n var result = [];\n\n // Start at the top and keep removing units, bit by bit.\n var unitName, unitMS, unitCount, mightBeHalfUnit;\n for (var i = 0, len = options.units.length; i < len; i ++) {\n\n unitName = options.units[i];\n if (unitName[unitName.length - 1] === \"s\") { // strip plurals\n unitName = unitName.substring(0, unitName.length - 1);\n }\n unitMS = UNITS[unitName];\n\n // If it's a half-unit interval, we're done.\n if (result.length === 0 && options.halfUnit) {\n mightBeHalfUnit = (ms / unitMS) * 2;\n if (mightBeHalfUnit === Math.floor(mightBeHalfUnit)) {\n return render(mightBeHalfUnit / 2, unitName, dictionary, options.spacer);\n }\n }\n\n // What's the number of full units we can fit?\n if ((i + 1) === len) {\n unitCount = ms / unitMS;\n if (options.round) {\n unitCount = Math.round(unitCount);\n }\n } else {\n unitCount = Math.floor(ms / unitMS);\n }\n\n // Add the string.\n if (unitCount) {\n result.push(render(unitCount, unitName, dictionary, options.spacer));\n }\n\n // Remove what we just figured out.\n ms -= unitCount * unitMS;\n\n }\n\n return result.join(options.delimiter);\n\n }", "checkUnits(){\n let logger = this.namespace.container.logger;\n\n let leftSideUnit = this.unitsParsed;\n if (typeof leftSideUnit === 'undefined') {\n logger.warn(`No units set for \"${this.index}\"`);\n }\n for (const scope in this.assignments) {\n let rightSideExpr = this.assignments[scope];\n if (typeof rightSideExpr.num === 'undefined') { // skip numbers\n let rightSideUnit = rightSideExpr.calcUnit(this);\n if (typeof rightSideUnit === 'undefined') {\n logger.warn(`Cannot calculate right side units in \"${this.index}\" for scope \"${scope}\".`);\n } else if (leftSideUnit && !leftSideUnit.equal(rightSideUnit, true)) {\n let leftUnitString = leftSideUnit.toString();\n let rightUnitString = rightSideUnit.simplify().toString();\n logger.warn(`Units inconsistency in \"${this.index}\" for scope \"${scope}\". Left: \"${leftUnitString}\". Right: \"${rightUnitString}\"`);\n }\n }\n }\n }", "function num_lost_words(pre_set_word_array_array, min_length){\n let lost_options = 0;\n for(let pre_set_word_array of pre_set_word_array_array){\n let lost_len = min_length - pre_set_word_array.length;\n lost_options += Math.pow(letters.length,lost_len);\n }\n return lost_options;\n }", "pointDegradation(addToPaper){cov_14q771vu2z.f[2]++;const letters=(cov_14q771vu2z.s[8]++,addToPaper.split(''));let whatICanWrite=(cov_14q771vu2z.s[9]++,'');// When you reach the end of the string, get out of loop\ncov_14q771vu2z.s[10]++;for(let i=0;i<letters.length;i++){cov_14q771vu2z.s[11]++;// If pencilDurability ever reaches 0, sharpen pencil\nif(this.pencilDurability===0){cov_14q771vu2z.b[1][0]++;cov_14q771vu2z.s[12]++;console.log(`Your pencil has a durability of 0! You need to sharpen it! Here's what I've written \"${whatICanWrite}\".`);cov_14q771vu2z.s[13]++;break;}else{cov_14q771vu2z.b[1][1]++;}// Check how many letters of the string you can write with pencil\ncov_14q771vu2z.s[14]++;whatICanWrite+=letters[i];cov_14q771vu2z.s[15]++;if(letters[i]===' '){cov_14q771vu2z.b[2][0]++;cov_14q771vu2z.s[16]++;this.pencilDurability-=0;}else{cov_14q771vu2z.b[2][1]++;cov_14q771vu2z.s[17]++;if((cov_14q771vu2z.b[4][0]++,letters[i]!==letters[i].toUpperCase())||(cov_14q771vu2z.b[4][1]++,letters[i].match(/^[.,:!?]/))){cov_14q771vu2z.b[3][0]++;cov_14q771vu2z.s[18]++;this.pencilDurability-=1;}else{cov_14q771vu2z.b[3][1]++;cov_14q771vu2z.s[19]++;if(letters[i]===letters[i].toUpperCase()){cov_14q771vu2z.b[5][0]++;cov_14q771vu2z.s[20]++;this.pencilDurability-=2;}else{cov_14q771vu2z.b[5][1]++;}}}}cov_14q771vu2z.s[21]++;return whatICanWrite;}", "function findPaths(startElement, remainingElements) {\n if (startElement.getType?.() === \"negativeTerminal\") {\n // If at a negativeTerminal, then successfully end recursion.\n const path = [\n {\n id: startElement.getId(),\n element: startElement,\n },\n ];\n\n if (startElement.getResistance() === 0) {\n path.hasZeroResistance = true;\n }\n\n return path;\n }\n\n if (startElement.getResistance?.() === Infinity) {\n return [];\n }\n\n const nextElements = getConnectedElectricElements(startElement).filter(\n (element) => remainingElements.indexOf(element) > -1\n );\n\n let paths = [];\n const pathsOfZeroResistance = [];\n\n for (let i = 0; i < nextElements.length; i++) {\n const nextElement = nextElements[i];\n const nextRemainingElements = remainingElements.filter(\n (element) => element.getId() !== nextElement.getId()\n );\n\n const pathsFromNextElement = findPaths(nextElement, nextRemainingElements);\n\n if (pathsFromNextElement.hasZeroResistance) {\n pathsOfZeroResistance.push(pathsFromNextElement);\n }\n\n if (pathsFromNextElement.length > 0) {\n // Only store paths that lead to a negativeTerminal.\n paths.push(pathsFromNextElement);\n }\n }\n\n if (pathsOfZeroResistance.length > 0) {\n // If there is a path with zero resistance,\n // then ignore all paths with resistance > 0.\n paths = pathsOfZeroResistance;\n }\n\n if (paths.length > 1) {\n paths = [\n {\n id: startElement.getId(),\n element: startElement,\n },\n paths,\n ];\n } else if (paths.length === 1) {\n paths = [\n {\n id: startElement.getId(),\n element: startElement,\n },\n ...paths[0],\n ];\n } else {\n // If there is no path to a negativeTerminal along remaining elements,\n // then return an empty path.\n return [];\n }\n\n if (\n pathsOfZeroResistance.length > 0 &&\n startElement.getResistance?.() === 0\n ) {\n paths.hasZeroResistance = true;\n }\n\n return paths;\n}", "function countSyllablesAndPolys (wordList) {\n let syllablesTotal = 0, polysTotal = 0;\n wordList.forEach((word) => {\n if (word === \"'\"||word===\"’\") {return;} //bandaid solution.\n if (word.length <= 2) {syllablesTotal += 1; return;} //quick return on short words\n let syllables = 0;\n if (word.endsWith(\"s'\")||word.endsWith(\"s’\")) {word.slice(-1);} //ending with s'\n if (word.endsWith(\"s's\")||word.endsWith(\"s’s\")) {word.slice(-1,-3);} //ending with s's\n const cEndings = word.match(/(?<=\\w{3})(side|\\wess|(?<!ed)ly|ment|ship|board|ground|(?<![^u]de)ville|port|ful(ly)?|berry|box|nesse?|such|m[ae]n|wom[ae]n|horse|anne)s?$/mi);\n if (cEndings) {word = word.replace(cEndings[0],\"\\n\" + cEndings[0]);} //Splits into two words and evaluates them as such\n const cBeginnings = word.match(/^(ware|side|p?re(?!ach|agan|al|au))/mi);\n if (cBeginnings) {word = word.replace(cBeginnings[0],\"\"); syllables++;}\n const esylp = word.match(/ie($|l|t|rg)|([cb]|tt|pp)le$|phe$|kle(s|$)|[^n]scien|sue|aybe$|[^aeiou]shed|[^lsoai]les$|([^e]r|g)ge$|(gg|ck|yw|etch)ed$|(sc|o)he$|seer|^re[eiuy]/gmi);\n if (esylp) {syllables += esylp.length;} //E clustered positive\n const esylm = word.match(/every|some([^aeiouyr]|$)|[^trb]ere(?!d|$|o|r|t|a[^v]|n|s|x)|[^g]eous|niet/gmi);\n if (esylm) {syllables -= esylm.length;} //E clustered negative\n const isylp = word.match(/rie[^sndfvtl]|(?<=^|[^tcs]|st)ia|siai|[^ct]ious|quie|[lk]ier|settli|[^cn]ien[^d]|[aeio]ing$|dei[tf]|isms?$/gmi);\n if (isylp) {syllables += isylp.length;} //I clustered positive\n const osylp = word.match(/nyo|osm(s$|$)|oinc|ored(?!$)|(^|[^ts])io|oale|[aeiou]yoe|^m[ia]cro([aiouy]|e)|roe(v|$)|ouel|^proa|oolog/gmi);\n if (osylp) {syllables += osylp.length;} //O clustered positive\n const osylm = word.match(/[^f]ore(?!$|[vcaot]|d$|tte)|fore|llio/gmi);\n if (osylm) {syllables -= osylm.length;} //O clustered negative\n const asylp = word.match(/asm(s$|$)|ausea|oa$|anti[aeiou]|raor|intra[ou]|iae|ahe$|dais|(?<!p)ea(l(?!m)|$)|(?<!j)ean|(?<!il)eage/gmi);\n if (asylp) {syllables += asylp.length;} //A clustered positive\n const asylm = word.match(/aste(?!$|ful|s$|r)|[^r]ared$/gmi);\n if (asylm) {syllables -= asylm.length;} //A clustered negative\n const usylp = word.match(/uo[^y]|[^gq]ua(?!r)|uen|[^g]iu|uis(?![aeiou]|se)|ou(et|ille)|eu(ing|er)|uye[dh]|nuine|ucle[aeiuy]/gmi);\n if (usylp) {syllables += usylp.length;} //U clustered positive\n const usylm = word.match(/geous|busi|logu(?!e|i)/gmi);\n if (usylm) {syllables -= usylm.length;} //U clustered negative\n const ysylp = word.match(/[ibcmrluhp]ya|nyac|[^e]yo|[aiou]y[aiou]|[aoruhm]ye(tt|l|n|v|z)|dy[ae]|oye[exu]|lye[nlrs]|(ol|i|p)ye|aye(k|r|$|u[xr]|da)|saye\\w|wy[ae]|[^aiou]ying/gmi);\n if (ysylp) {syllables += ysylp.length;} //Y clustered positive\n const ysylm = word.match(/arley|key|ney$/gmi);\n if (ysylm) {syllables -= ysylm.length;}\n const essuffix = word.match(/((?<!c[hrl]|sh|[iszxgej]|[niauery]c|do)es$)/gmi);\n if (essuffix) {syllables--;}//es suffix\n const edsuffix = word.match(/([aeiouy][^aeiouyrdt]|[^aeiouy][^laeiouyrdtbm]|ll|bb|ield|[ou]rb)ed$|[^cbda]red$/gmi);\n if (edsuffix) {syllables--}\n const csylp = word.match(/chn[^eai]|mc|thm/gmi);\n if (csylp) {syllables += csylp.length;} //Consonant clustered negative\n const eVowels = word.match(/[aiouy](?![aeiouy])|ee|e(?!$|-|[iua])/gmi);\n if (eVowels) {syllables += eVowels.length;} //Applicable vowel count (all but e at end of word)\n if (syllables <= 0) {syllables = 1;} //catch-all\n if (word.match(/[^aeiou]n['’]t$/i)) {syllables ++;} //ending in n't, but not en't\n if (word.match(/en['’]t$/i)) {syllables --;} //ending in en't\n if (syllables >= 3) {polysTotal++;}\n syllablesTotal += syllables;\n });\n return [syllablesTotal, polysTotal];\n }", "createChipsLayout() {\n let fragment = document.createDocumentFragment();\n let chipsLayout = [];\n let valueChips;\n\n while (chipsLayout.length < 16) {\n valueChips = this.randomInteger(1, 16);\n\n if (chipsLayout.indexOf(valueChips) < 0) {\n chipsLayout.push(valueChips);\n }\n }\n\n //check the layout for solvability (https://ru.wikipedia.org/wiki/%D0%98%D0%B3%D1%80%D0%B0_%D0%B2_15)\n let numberStringEmptyChip;\n if (chipsLayout.indexOf(16) < 4) {\n numberStringEmptyChip = 1;\n } else if (chipsLayout.indexOf(16) > 3 && chipsLayout.indexOf(16) < 8) {\n numberStringEmptyChip = 2;\n } else if (chipsLayout.indexOf(16) > 7 && chipsLayout.indexOf(16) < 12) {\n numberStringEmptyChip = 3;\n } else {\n numberStringEmptyChip = 4;\n }\n\n let indexLastChip = chipsLayout.indexOf(16);\n let copyChipsLayout = chipsLayout.slice();\n copyChipsLayout.splice(indexLastChip, 1); //Deleted elem with value \"16\"\n\n let solvability = copyChipsLayout.reduce(\n (accumulate, elValue, indexValue, arr) => {\n for (let i = indexValue; i < arr.length; ++i) {\n if (elValue > arr[i]) {\n ++accumulate;\n }\n }\n return accumulate;\n },\n 0\n );\n\n if ((solvability + numberStringEmptyChip) % 2 === 0) {\n chipsLayout.forEach((chip) => {\n let chipElement = document.createElement(\"div\");\n chipElement.classList.add(\"chip\");\n chipElement.textContent = chip;\n //make the sixteenth chip empty\n if (chip == 16) {\n chipElement.classList.add(\"empty\");\n chipElement.id = \"empty\";\n }\n fragment.appendChild(chipElement);\n });\n } else {\n this.elementsGame.playingField.appendChild(this.createChipsLayout());\n }\n\n return fragment;\n }", "function harmlessRansomNote(noteText, magazineText) {\n var noteArr = noteText.split(' ');\n var magazineArr = magazineText.split(' ');\n var magazineObj = {};\n \n magazineArr.forEach(word => {\n if (!magazineObj[word]) magazineObj[word] = 0;\n magazineObj[word]++;\n });\n \n var noteIsPossible = true;\n noteArr.forEach(word => {\n if (magazineObj[word]) {\n magazineObj[word]--;\n if (magazineObj[word] < 0) noteIsPossible = false;\n }\n else noteIsPossible = false; \n });\n \n return noteIsPossible;\n}", "function calculateElementalReaction(){\n var elementsInTeam = [characters.get(lastChar[0]).Element,characters.get(lastChar[1]).Element, \n characters.get(lastChar[2]).Element,characters.get(lastChar[3]).Element];\n var reaction = new Boolean(false); \n outputstr += \"<h3>Elemental Reactions:</h3>\"; \n outputstr += \"Your team is capable of the following reactions:</br>\"; \n for(var i= 0; i<4;i++){ \n if(elementsInTeam[i] == \"Anemo\"){ \n for(var j= 0; j<4;j++){ \n if(elementsInTeam[j] == \"Hydro\" || elementsInTeam[j] == \"Cryo\" || elementsInTeam[j] == \"Electro\" || elementsInTeam[j] == \"Pyro\" && j !=i){\n score+=25; \n outputstr += \"Swirl with \"+lastChar[i]+\" and \"+lastChar[j]+\"</br>\"; \n reaction =true; \n } \n } \n }\n\tif(elementsInTeam[i] == \"Geo\"){ \n for(var j= 0; j<4;j++){ \n if(elementsInTeam[j] == \"Hydro\" || elementsInTeam[j] == \"Cryo\" || elementsInTeam[j] == \"Electro\" || elementsInTeam[j] == \"Pyro\" && j !=i){\n score+=25;\n outputstr += \"Crystalize with \"+lastChar[i]+\" and \"+lastChar[j]+\"</br>\";\n reaction =true; \n } \n } \n }\n\tif(elementsInTeam[i]== \"Electro\" || elementsInTeam[i] == \"Cryo\"){ \n for(var j= 0; j<4;j++){ \n if((elementsInTeam[j] == \"Cryo\" && elementsInTeam[i] == \"Electro\") && j !=i){\n score+=50;\n outputstr += \"Superconduct with \"+lastChar[i]+\" and \"+lastChar[j]+\"</br>\" \n reaction =true; \n } \n } \n } \n\tif(elementsInTeam[i] == \"Hydro\" || elementsInTeam[i] == \"Pyro\"){ \n for(var j= 0; j<4;j++){ \n if((elementsInTeam[i] == \"Hydro\" && elementsInTeam[j] == \"Pyro\") && j !=i){\n score+=70;\n outputstr += \"Vaporize with \"+lastChar[i]+\" and \"+lastChar[j]+\"</br>\" \n reaction =true; \n } \n } \n }\n\tif(elementsInTeam[i] == \"Cryo\" || elementsInTeam[i] == \"Pyro\"){\n for(var j= 0; j<4;j++){ \n if((elementsInTeam[i] == \"Pyro\" && elementsInTeam[j] == \"Cryo\") && j !=i){\n score+=60;\n outputstr += \"Melt with \"+lastChar[i]+\" and \"+lastChar[j]+\"</br>\"\n reaction =true; \n } \n } \n\t}\n\t if(elementsInTeam[i] == \"Electro\" || elementsInTeam[i] == \"Pyro\"){\n for(var j= 0; j<4;j++){ \n if((elementsInTeam[i] == \"Electro\" && elementsInTeam[j] == \"Pyro\") && j !=i){\n score+=50;\n outputstr += \"Overload with \"+lastChar[i]+\" and \"+lastChar[j]+\"</br>\"\n reaction =true; \n } \n }\t\n\t}\n\t if(elementsInTeam[i] == \"Hydro\" || elementsInTeam[i] == \"Cryo\"){\t\n for(var j= 0; j<4;j++){ \n if(elementsInTeam[i] == \"Hydro\" && elementsInTeam[j] == \"Cryo\" && j !=i){\n score+=25; \n outputstr += \"Freeze with \"+lastChar[i]+\" and \"+lastChar[j]+\"</br>\"; \n reaction =true; \n } \n }\n\t}\n }\n}", "getStemDuration(noteValue) {\n if (noteValue == \"DottedHalf\")\n return \"Half\";\n else if (noteValue == \"DottedQuarter\")\n return \"Quarter\";\n else if (noteValue == \"DottedEighth\")\n return \"Eighth\";\n else\n return noteValue;\n }", "get degrees() {\n if (this.__degrees)\n return this.__degrees;\n\n let degrees = []; // [Degree]\n\n // Go through all the chord tones\n for (let extension = 1; extension <= this.extension; extension += 2) {\n\n // XXX: Note that using if..else if may be an issue because\n // it is only assumed that alterations and removals might not\n // be of the same degree simultaneously\n if (this.removedNotes.filter(x => x.degree === extension).length !== 0) {\n // XXX: Naive implementation\n // Accidental part of a removed note's degree is ignored, still\n // unsure whether this will bring up any problems later on\n\n let noDeg = this.applyGenderToExtension(extension);\n noDeg.source = DegreeSource.NO;\n degrees.push(noDeg);\n } else if (extension === 3 && this.suspension !== SusMode.NONE) {\n // If the degree is the supended third, exclude the third by marking the\n // 3rd degree as SUSPENDED_THIRD, and replace the third with either\n // the 4th or 2nd depending on the specified suspension degree\n // denoted by the SUSPESION degree source.\n let susDeg = new Degree(\n this.suspension === SusMode.FOUR ? '4' : '2',\n DegreeSource.SUSPENSION);\n\n degrees.push(susDeg);\n degrees.push(new Degree('3', DegreeSource.SUSPENDED_THIRD));\n } else if (!this.alterations[extension]) {\n // Otherwise, if not altered, note is a normal chord tone\n // All the alterations will be added later, as some alterations\n // may not necessarily be included in the tertian stack\n // (e.g. the bb7 in a dom-5 dim chord)\n\n let normalDeg = this.applyGenderToExtension(extension);\n normalDeg.source = DegreeSource.QUALITY;\n degrees.push(normalDeg);\n }\n }\n\n // Add all the alterations\n\n for (let alterations of this.alterations) {\n if (!alterations || alterations.length === 0)\n continue;\n\n for (let d of alterations) {\n\n let source = DegreeSource.UNSPECIFIED;\n // Not all alterations may necessarily be included in the tertian stack\n // (The quasi-quality alterations may have excluded degrees)\n let included = d.degree <= this.extension;\n\n if (this.dimMode === DimMode.FULL && ['b3', 'b5', 'bb7'].includes(d.toString())) {\n source = DegreeSource.ALT_DIM;\n } else if (this.dimMode === DimMode.HALF && ['b3', 'b5'].includes(d.toString())) {\n source = DegreeSource.ALT_HDIM;\n } else if (this.aug && d.toString() === '#5') {\n source = DegreeSource.ALT_AUG;\n } else {\n source = DegreeSource.ALTERATION;\n }\n\n degrees.push(new Degree(d.toString(), source, included));\n }\n }\n\n // Add all the added notes... very simple\n\n for (let addDeg of this.addedNotes) {\n degrees.push(new Degree(addDeg.toString(), DegreeSource.ADDITION));\n }\n\n // done!\n\n this.__degrees = degrees;\n return this.__degrees;\n }", "function assonance(pronun) {\n var laststress = pronun.length - 1;\n while (laststress >= 0) {\n var stress = pronun[laststress--];\n if (isVowel(stress) == 3) {\n return stress;\n }\n };\n}" ]
[ "0.63914067", "0.5853434", "0.5441584", "0.52097565", "0.51795906", "0.5162899", "0.51582384", "0.51555383", "0.5133454", "0.5057177", "0.49457815", "0.47984436", "0.47984436", "0.47755983", "0.47750214", "0.4735101", "0.47300556", "0.47300556", "0.47300556", "0.47300556", "0.47300556", "0.47070202", "0.46826196", "0.46807286", "0.46617687", "0.46375757", "0.46340802", "0.46316722", "0.4621098", "0.4621095", "0.4609001", "0.46083394", "0.4595712", "0.45714563", "0.4570459", "0.45452404", "0.45449296", "0.4539161", "0.4539161", "0.4536561", "0.45330995", "0.452801", "0.45279485", "0.45267957", "0.45164952", "0.45015335", "0.4499257", "0.44861472", "0.4480499", "0.44772652", "0.44703105", "0.44689348", "0.44674525", "0.44624913", "0.44542184", "0.44503844", "0.44490623", "0.4441485", "0.4439219", "0.44200528", "0.4419832", "0.44064692", "0.44064692", "0.44064692", "0.44064692", "0.4404166", "0.44029552", "0.4400334", "0.4399455", "0.4399455", "0.4399455", "0.4399455", "0.4399455", "0.43979314", "0.43967438", "0.43896002", "0.43879816", "0.438071", "0.43805754", "0.43775684", "0.43775684", "0.43766183", "0.43711054", "0.4360162", "0.4349245", "0.4344177", "0.43416002", "0.43346676", "0.43298155", "0.4327845", "0.4323727", "0.4314807", "0.43128178", "0.43106338", "0.43049094", "0.43025187", "0.42994177", "0.42974645", "0.42963502", "0.42950553", "0.4288387" ]
0.0
-1
update button color when clicked
function updateButtonColors(button, parent) { parent.selectAll("rect") .attr("fill",defaultColor) button.select("rect") .attr("fill",pressedColor) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateButton(button, clicked) {\n button.innerText = clicked ? \"Pause\" : \"Animate\";\n updateColor(button, button.value);\n}", "function buttonColorIn(ev) {\n ev.target.style.backgroundColor = \"orange\";\n}", "function colorButton(button) {\n d3.selectAll('button')\n .transition()\n .style('background-color', blue3);\n button\n .transition()\n .style('background-color', blue2);\n }", "function onbuttoncolor()\n {\n \tvar on=document.getElementById(\"imgbttn\");\n \ton.style.backgroundColor = \"#009688\";\n \ton.style.color=\"white\";\n }", "function updateColor(button, value) {\n button.style.backgroundColor =\n value == \"1\" ? \"#b786f0\" : \"#525aff\" /* blue */;\n}", "function engineipClicked() {\n document.getElementById(\"engineipBtn\").style.backgroundColor = \"red\";\n}", "function updateColor(e) {\n var colorHasChanged = !tinycolor.equals(get(), colorOnShow);\n\n if (colorHasChanged) {\n if (clickoutFiresChange && e !== \"cancel\") {\n updateOriginalInput(true);\n } else {\n revert();\n }\n }\n }", "function setBtnColor(btn, press) {\n\tif (press)\n\t\tbtn.style.backgroundColor = '#e74c3c';\n\telse\n\t\tbtn.style.backgroundColor = '#3d4450';\n}", "function itsClicked1(event) {\n r = r + 1;\n result.style.backgroundColor = \"rgb(\" + r + \",\" + g + \",\" + b + \")\";\n color.innerHTML = `${r},${g},${b}`;\n}", "function colorState(){\n\t$('#black-white-button').click(function(){\n\t\tcolorCondition = false;\n\t\t$(this).addClass('activeButton');\n\t\t$(\"#color-button\").removeClass('activeButton');\n\t})\n\t$('#color-button').click(function(){\n\t\tcolorCondition = true;\n\t\t$(this).addClass('activeButton');\n\t\t$(\"#black-white-button\").removeClass('activeButton');\n\t})\n}", "function changeColor(e) {}", "function questionThreeAction() {\r\n $('button').css(\"background-color\", \"brown\");\r\n}", "changeColor() {\n this.elem.style.backgroundColor = buttonStates[this.state].color;\n if (this.state !== 0) {\n this.elem.style.boxShadow = '0px 0px 20px -5px' + buttonStates[this.state].color;\n } else {\n this.elem.style.boxShadow = 'none';\n }\n }", "function button_color ( color ) {\r\n\tvar obj = event.srcElement;\r\n\tif ( obj.tagName == \"INPUT\" && obj.type == \"button\" ) event.srcElement.style.backgroundColor = color;\r\n}", "_updateColor() {\n\t\tthis.props.onSelected(this.props.name, this.colorValue);\n\t}", "function setAllBtnColor() {\n\tsetBtnColor(idName('pen'), (mouse.status == mouseStatus.paint));\n\tsetBtnColor(idName('eraser'),\n\t\t(mouse.status == mouseStatus.erase));\n\tif (mouse.status == mouseStatus.other)\n\t\tclickShape();\n\telse\n\t\tclickPaint();\n}", "function incrementClickedColor() {\n if (clickedColor === 'red') {\n redClicks++;\n $('#red').text(redClicks);\n } else if (clickedColor === 'yellow') {\n yellowClicks++;\n $('#yellow').text(yellowClicks);\n } else if (clickedColor === 'green') {\n greenClicks++;\n $('#green').text(greenClicks);\n } else if (clickedColor === 'blue') {\n blueClicks++;\n $('#blue').text(blueClicks);\n }\n}", "function replyClick(clickedId) {\n currentColor = clickedId;\n}", "function onColorUpdate(e){\n current.color = e.target.className.split(' ')[1];\n }", "function liElementClicked() {\n changeColor()\n }", "function buttonColor() {\n $(\"button\").attr(\"id\", \"buttonloading\");\n}", "function outbuttoncolor()\n {\n \tvar out=document.getElementById(\"imgbttn\");\n \tout.style.backgroundColor = \"white\";\n \tout.style.color=\"black\";\n }", "function colorClick() {\n color = document.querySelector('#colorPicker').value;\n event.target.style.backgroundColor = color;\n }", "function RefreshClickListener() {\n var current_color;\n $('.color').off;\n\n $('.color').on('click', function() {\n current_color = $(this).data('color');\n selected_colors.push(current_color);\n $(this).addClass('selected');\n\n // Update span replacement-color\n $('span.replacement-color').text(current_color);\n });\n}", "onClick() {\n if (globalMode === 'edit') {\n\n // increment state and change color\n this.state++;\n if (this.state >= buttonStates.length) this.state = 0;\n\n this.changeColor();\n\n } else if (globalMode === 'strike') {\n\n // generate a random number as a unique strike ID, \n // so cells won't keep triggering eachother\n this.strike(Math.floor(Math.random()*100));\n\n }\n }", "function camipClicked() {\n document.getElementById(\"camipBtn\").style.backgroundColor = \"red\";\n}", "function onClickColor(index) {\n // set clicked = true and set the color that is clicked to pass to colorbox.js\n setClicked(true);\n setCircleClicked(index);\n\n // set the color in app.js\n setSelectedColor(index);\n\n // console.log('clicked: ', index);\n }", "function handleButtonClick(event) {\n\n // The element that was clicked is in the target \n // property of the event.\n let btn = event.target;\n\n // Remove styling from the previously selected color.\n // Note: we could run querySelector on the whole document,\n // however it is more efficient to run it on localized portion\n // of it: the parent element of all the buttons.\n let current = btn.parentElement.querySelector(`.${selectedClassName}`);\n \n // Another color selected.\n if (current && current !== btn) {\n // classList is a special object to manipulating CSS classes.\n // https://www.w3schools.com/jsref/prop_element_classlist.asp\n current.classList.remove(selectedClassName);\n }\n\n // Retrieve the color from the element's dataset \n // property (more on this special property below).\n let color = btn.dataset.color;\n\n // Add the class to to the element.\n btn.classList.add(selectedClassName);\n \n // Chrome API: storage.\n //\n // The Chrome storage extends standard local storage. The main \n // advantage is its ability to store any data format, not just strings. \n //\n // Local Storage:\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage\n // Chrome Storage:\n // https://developer.chrome.com/docs/extensions/reference/storage/\n chrome.storage.sync.set({ color });\n}", "function color_button(event) {\n selectors.forEach(reset_buttons);\n if (event.target.className == \"LinBtn\") {\n ShowPage(0);\n selectors[0].style.background = \"black\";\n selectors[0].style.color = \"#dce1d5\";\n };\n if (event.target.className == \"IrrBtn\") {\n ShowPage(1);\n selectors[4].style.background = \"black\";\n selectors[4].style.color = \"#dce1d5\";\n };\n if (event.target.className == \"ClvBtn\") {\n ShowPage(2);\n selectors[8].style.background = \"black\";\n selectors[8].style.color = \"#dce1d5\";\n };\n\n}", "function coloredButtons() {\r\n\r\n\t\t\t\t$('.nectar-button.see-through[data-color-override], .nectar-button.see-through-2[data-color-override], .nectar-button.see-through-3[data-color-override]').each(function () {\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar $usingMaterialSkin = ($('body.material[data-button-style^=\"rounded\"]').length > 0) ? true : false;\r\n\t\t\t\t\t$(this).css('visibility', 'visible');\r\n\t\t\t\t\t\r\n\t\t\t\t\tif ($(this).hasClass('see-through-3') && $(this).attr('data-color-override') == 'false') {\r\n\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar $color;\r\n\t\t\t\t\tvar $that;\r\n\t\t\t\t\t\r\n\t\t\t\t\tif ($(this).attr('data-color-override') != 'false') {\r\n\t\t\t\t\t\t$color = $(this).attr('data-color-override');\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($(this).parents('.dark').length > 0) {\r\n\t\t\t\t\t\t\t$color = '#000000';\r\n\t\t\t\t\t\t}\telse {\r\n\t\t\t\t\t\t\t$color = '#ffffff';\r\n\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\tif (!$(this).hasClass('see-through-3')) {\r\n\t\t\t\t\t\t$(this).css('color', $color);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t$(this).find('i').css('color', $color);\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar colorInt = parseInt($color.substring(1), 16);\r\n\t\t\t\t\tvar $hoverColor = ($(this).has('[data-hover-color-override]')) ? $(this).attr('data-hover-color-override') : 'no-override';\r\n\t\t\t\t\tvar $hoverTextColor = ($(this).has('[data-hover-text-color-override]')) ? $(this).attr('data-hover-text-color-override') : '#fff';\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar R = (colorInt & 0xFF0000) >> 16;\r\n\t\t\t\t\tvar G = (colorInt & 0x00FF00) >> 8;\r\n\t\t\t\t\tvar B = (colorInt & 0x0000FF) >> 0;\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar $opacityStr = ($(this).hasClass('see-through-3')) ? '1' : '0.75';\r\n\t\t\t\t\t\r\n\t\t\t\t\t$(this).css('border-color', 'rgba(' + R + ',' + G + ',' + B + ',' + $opacityStr + ')');\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Material theme skin buttons w/ icons starting\r\n\t\t\t\t\tif ($usingMaterialSkin) {\r\n\t\t\t\t\t\t$(this).find('i').css({\r\n\t\t\t\t\t\t\t'background-color': 'rgba(' + R + ',' + G + ',' + B + ',1)',\r\n\t\t\t\t\t\t\t'box-shadow': '0px 8px 15px rgba(' + R + ',' + G + ',' + B + ',0.24)'\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\tif ($(this).hasClass('see-through')) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$that = $(this);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$(this).on('mouseenter touchstart', function () {\r\n\t\t\t\t\t\t\t$that.css('border-color', 'rgba(' + R + ',' + G + ',' + B + ',1)');\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$(this).on('mouseleave touchtouchend', function () {\r\n\t\t\t\t\t\t\t$that.css('border-color', 'rgba(' + R + ',' + G + ',' + B + ',1)');\r\n\t\t\t\t\t\t\t$opacityStr = ($(this).hasClass('see-through-3')) ? '1' : '0.75';\r\n\t\t\t\t\t\t\t$that.css('border-color', 'rgba(' + R + ',' + G + ',' + B + ',' + $opacityStr + ')');\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$(this).find('i').css('color', $hoverTextColor);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($hoverColor != 'no-override') {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$that = $(this);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$(this).on('mouseenter touchstart', function () {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t$that.css({\r\n\t\t\t\t\t\t\t\t\t'border-color': $hoverColor,\r\n\t\t\t\t\t\t\t\t\t'background-color': $hoverColor,\r\n\t\t\t\t\t\t\t\t\t'color': $hoverTextColor\r\n\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\t// Material buttons w/ icons over\r\n\t\t\t\t\t\t\t\tif ($usingMaterialSkin) {\r\n\t\t\t\t\t\t\t\t\t$that.find('i').css({\r\n\t\t\t\t\t\t\t\t\t\t'background-color': '',\r\n\t\t\t\t\t\t\t\t\t\t'box-shadow': ''\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\t\r\n\t\t\t\t\t\t\t$(this).on('mouseleave touchtouchend', function () {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t$opacityStr = ($(this).hasClass('see-through-3')) ? '1' : '0.75';\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif ($usingMaterialSkin) {\r\n\t\t\t\t\t\t\t\t\t$that.find('i').css({\r\n\t\t\t\t\t\t\t\t\t\t'background-color': 'rgba(' + R + ',' + G + ',' + B + ',1)',\r\n\t\t\t\t\t\t\t\t\t\t'box-shadow': '0px 8px 15px rgba(' + R + ',' + G + ',' + B + ',0.24)'\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\t\r\n\t\t\t\t\t\t\t\tif (!$that.hasClass('see-through-3')) {\r\n\t\t\t\t\t\t\t\t\t$that.css({\r\n\t\t\t\t\t\t\t\t\t\t'border-color': 'rgba(' + R + ',' + G + ',' + B + ',' + $opacityStr + ')',\r\n\t\t\t\t\t\t\t\t\t\t'background-color': 'transparent',\r\n\t\t\t\t\t\t\t\t\t\t'color': $color\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t$that.css({\r\n\t\t\t\t\t\t\t\t\t\t'border-color': 'rgba(' + R + ',' + G + ',' + B + ',' + $opacityStr + ')',\r\n\t\t\t\t\t\t\t\t\t\t'background-color': 'transparent'\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\t\r\n\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$that = $(this);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$(this).on('mouseenter touchstart', function () {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t$that.css({\r\n\t\t\t\t\t\t\t\t\t'border-color': $hoverColor,\r\n\t\t\t\t\t\t\t\t\t'color': $hoverTextColor\r\n\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\t\r\n\t\t\t\t\t\t\t$(this).on('mouseleave touchtouchend', function () {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t$opacityStr = ($that.hasClass('see-through-3')) ? '1' : '0.75';\r\n\t\t\t\t\t\t\t\t$that.css({\r\n\t\t\t\t\t\t\t\t\t'border-color': 'rgba(' + R + ',' + G + ',' + B + ',' + $opacityStr + ')',\r\n\t\t\t\t\t\t\t\t\t'color': $hoverTextColor\r\n\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\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t\r\n\t\t\t\t$('.nectar-button:not(.see-through):not(.see-through-2):not(.see-through-3)[data-color-override]').each(function () {\r\n\t\t\t\t\t\r\n\t\t\t\t\t$(this).css('visibility', 'visible');\r\n\t\t\t\t\t\r\n\t\t\t\t\tif ($(this).attr('data-color-override') != 'false') {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $color = $(this).attr('data-color-override');\r\n\r\n\t\t\t\t\t\t$(this)\r\n\t\t\t\t\t\t\t.removeClass('accent-color')\r\n\t\t\t\t\t\t\t.removeClass('extra-color-1')\r\n\t\t\t\t\t\t\t.removeClass('extra-color-2')\r\n\t\t\t\t\t\t\t.removeClass('extra-color-3')\r\n\t\t\t\t\t\t\t.css('background-color', $color);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t});\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t// Solid color tilt \r\n\t\t\t\tif ($('.swiper-slide .solid_color_2').length > 0 || $('.tilt-button-inner').length > 0) {\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar $tiltButtonCssString = '';\r\n\t\t\t\t\tvar $color;\r\n\t\t\t\t\t\r\n\t\t\t\t\t$('.swiper-slide .solid_color_2 a').each(function (i) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$(this).addClass('instance-' + i);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($(this).attr('data-color-override') != 'false') {\r\n\t\t\t\t\t\t\t$color = $(this).attr('data-color-override');\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tif ($(this).parents('.dark').length > 0) {\r\n\t\t\t\t\t\t\t\t$color = '#000000';\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t$color = '#ffffff';\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$(this).css('color', $color);\r\n\t\t\t\t\t\t$(this).find('i').css('color', $color);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $currentColor = $(this).css('background-color'),\r\n\t\t\t\t\t\t$topColor = shadeColor($currentColor, 0.13),\r\n\t\t\t\t\t\t$bottomColor = shadeColor($currentColor, -0.15);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$tiltButtonCssString += '.swiper-slide .solid_color_2 a.instance-' + i + ':after { background-color: ' + $topColor + '; }' + ' .swiper-slide .solid_color_2 a.instance-' + i + ':before { background-color: ' + $bottomColor + '; } ';\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\t$('.tilt-button-wrap a').each(function (i) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$(this).addClass('instance-' + i);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $currentColor = $(this).css('background-color');\r\n\t\t\t\t\t\tvar $color;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($(this).attr('data-color-override') != 'false') {\r\n\t\t\t\t\t\t\t$color = $(this).attr('data-color-override');\r\n\t\t\t\t\t\t\t$(this).css('background-color', $color);\r\n\t\t\t\t\t\t\t$currentColor = $color;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $topColor = shadeColor($currentColor, 0.13),\r\n\t\t\t\t\t\t$bottomColor = shadeColor($currentColor, -0.15);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$tiltButtonCssString += '.tilt-button-wrap a.instance-' + i + ':after { background-color: ' + $topColor + '; }' + ' .tilt-button-wrap a.instance-' + i + ':before { background-color: ' + $bottomColor + '; } ';\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// Style\r\n\t\t\t\t\tnectarCreateStyle($tiltButtonCssString, 'tilt-button');\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t// Transparent 3D\r\n\t\t\t\tif ($('.nectar-3d-transparent-button').length > 0) {\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar $3dTransButtonCssString = '';\r\n\t\t\t\t\t$('.nectar-3d-transparent-button').each(function (i) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $that = $(this),\r\n\t\t\t\t\t\t$size \t\t= $that.attr('data-size'),\r\n\t\t\t\t\t\t$padding \t= 0,\r\n\t\t\t\t\t\tv1 \t\t\t\t= 1.5,\r\n\t\t\t\t\t\tv2 \t\t\t\t= 1.65,\r\n\t\t\t\t\t\t$font_size;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Size\r\n\t\t\t\t\t\tif ($size == 'large') {\r\n\t\t\t\t\t\t\t$padding \t\t= 46;\r\n\t\t\t\t\t\t\t$font_size \t= 16;\r\n\t\t\t\t\t\t\tv1 \t\t\t\t\t= 1.5;\r\n\t\t\t\t\t\t\tv2 \t\t\t\t\t= 1.7;\r\n\t\t\t\t\t\t} else if ($size == 'medium') {\r\n\t\t\t\t\t\t\t$padding \t\t= 30;\r\n\t\t\t\t\t\t\t$font_size \t= 16;\r\n\t\t\t\t\t\t} else if ($size == 'small') {\r\n\t\t\t\t\t\t\t$padding \t\t= 20;\r\n\t\t\t\t\t\t\t$font_size \t= 12;\r\n\t\t\t\t\t\t} else if ($size == 'jumbo') {\r\n\t\t\t\t\t\t\t$padding \t\t= 54;\r\n\t\t\t\t\t\t\t$font_size \t= 24;\r\n\t\t\t\t\t\t\tv1 \t\t\t\t\t= 1.5;\r\n\t\t\t\t\t\t\tv2 \t\t\t\t\t= 1.68;\r\n\t\t\t\t\t\t} else if ($size == 'extra_jumbo') {\r\n\t\t\t\t\t\t\t$padding \t\t= 100;\r\n\t\t\t\t\t\t\t$font_size \t= 64;\r\n\t\t\t\t\t\t\tv1 \t\t\t\t\t= 1.6;\r\n\t\t\t\t\t\t\tv2 \t\t\t\t\t= 1.6;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$that.find('svg text').attr('font-size', $font_size);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $boundingRect = $(this).find('.back-3d .button-text')[0].getBoundingClientRect(),\r\n\t\t\t\t\t\t$text_width = $boundingRect.width,\r\n\t\t\t\t\t\t$text_height = $font_size * 1.5;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$that.css({\r\n\t\t\t\t\t\t\t'width': ($text_width + $padding * 1.5) + 'px',\r\n\t\t\t\t\t\t\t'height': ($text_height + $padding) + 'px'\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$that.find('> a').css({\r\n\t\t\t\t\t\t\t'height': ($text_height + $padding) + 'px'\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$that.find('.back-3d svg, .front-3d svg').css({\r\n\t\t\t\t\t\t\t'width': ($text_width + $padding * 1.5) + 'px',\r\n\t\t\t\t\t\t\t'height': ($text_height + $padding) + 'px'\r\n\t\t\t\t\t\t}).attr('viewBox', '0 0 ' + ($text_width + $padding) + ' ' + ($text_height + $padding));\r\n\r\n\t\t\t\t\t\t$that.find('svg text').attr('transform', 'matrix(1 0 0 1 ' + ($text_width + $padding * v1) / 2 + ' ' + (($text_height + $padding) / v2) + ')');\r\n\t\t\t\t\t\t$that.find('.front-3d, .back-3d').css('transform-origin', '50% 50% -' + ($text_height + $padding) / 2 + 'px');\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Mask\r\n\t\t\t\t\t\t$(this).find('.front-3d svg > rect').attr('id', 'masked-rect-id-' + i);\r\n\t\t\t\t\t\t$(this).find('.front-3d defs mask').attr('id', 'button-text-mask-' + i);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$that.css('visibility', 'visible');\r\n\t\t\t\t\t\t$3dTransButtonCssString += '#masked-rect-id-' + i + ' { mask: url(#button-text-mask-' + i + '); -webkit-mask: url(#button-text-mask-' + i + ')} ';\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// Extra jumbo resize\r\n\t\t\t\t\tcreateExtraJumboSize();\r\n\t\t\t\t\t$window.on('smartresize', createExtraJumboSize);\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Style\r\n\t\t\t\t\tnectarCreateStyle($3dTransButtonCssString, 'nectar-td-button');\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Gradient btn init\r\n\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\t$('.nectar-button[class*=\"color-gradient\"] .start').removeClass('loading');\r\n\t\t\t\t}, 150);\r\n\t\t\t\t// No grad for ff\r\n\t\t\t\tif (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 || \r\n\t\t\t\tnavigator.userAgent.indexOf(\"MSIE \") > -1 || \r\n\t\t\t\tnavigator.userAgent.match(/Trident\\/7\\./)) {\r\n\t\t\t\t\t$('.nectar-button[class*=\"color-gradient\"] .start').addClass('no-text-grad');\r\n\t\t\t\t}\r\n\t\t\t}", "function activeWeekly () {\n var button = document.getElementById(\"weeklyTraffic\");\n button.style.color=\"white\";\n button.style.backgroundColor=\"green\";\n}", "function changeColorSize (button, selectedButton, colorText) {\r\n\t\t\tfor (var i = 0; i < selectedButton.length; i++){\r\n\t\t\t\tselectedButton[i].setAttribute('class', 'colorButton');\r\n\t\t\t}\r\n\r\n \t\tbutton.setAttribute('class', 'colorButton_s');\r\n \t\tcolorText.innerHTML = button.id;\r\n \t\tcurrentColor = colorText.innerHTML;\r\n\r\n\r\n \t\tvar productImg = document.getElementById(\"productImg\");\r\n\r\n \t\tproductImg.src = \"images/\"+ button.id + \".png\"\r\n\r\n\r\n\t\t\t}", "clickedTargetColor(p, c) {\n \n if(p) {\n this.upperBarCounterCircles.children[c-1].style = \"background-color: #0ebb25;\"; \n } else {\n this.upperBarCounterCircles.children[c-1].style = \"background-color: #bb263a;\";\n }\n }", "function initColorChange(){\n var colorButton = document.querySelectorAll('.circle');\n [].forEach.call(colorButton,function(item) {\n item.addEventListener('click',function (e) {\n [].forEach.call(colorButton,function (item) {\n if(item.classList.contains('selected')){\n item.classList.remove('selected');\n }\n })\n model.data.currentColor = colorList.indexOf(item.id);\n update();\n })\n\n })\n}", "blueClick() {\n\t\tthis._actions.onNext('blue');\n\t}", "function handleColorClick(event) {\n event.preventDefault();\n var color = event.target.className;\n /* color should be valid following dell.led.colors array */\n dell.led.changeColor(color);\n chrome.runtime.sendMessage({\n color: color\n }, null);\n currentSelectedColor = color;\n}", "function ChangeButtonColor(commandID, id, defaultColor) {\n var commandNode = document.getElementById(commandID);\n if (commandNode) {\n var color = commandNode.getAttribute(\"state\");\n var button = document.getElementById(id);\n if (button) {\n button.setAttribute(\"color\", color);\n\n // No color or a mixed color - get color set on page or other defaults.\n if (!color || color == \"mixed\") {\n color = defaultColor;\n }\n\n button.setAttribute(\"style\", \"background-color:\" + color + \" !important\");\n }\n }\n}", "function ChangeColor(n){\n noteBackground = n;\n let button = document.getElementById(\"add\");\n if(n==='white' || n===\"yellow\"){\n button.style.background=n;\n button.style.color='black'\n }\n else{\n button.style.background=n;\n button.style.color='white'\n }\n \n }", "function setColor(btn,Mode,location, row, column, setOnly, reset) {\n \n var property = document.getElementById(btn);\n\t if (reset) {\n\t\tif(Mode=='Status'){\n\t\t\tvm.lock=0;\n \t\tvm.Initialized = 0;\n\t \t\tdocument.getElementById('StatusButtonText').innerHTML='Confirm';\n\t \t\tdocument.getElementById('TextInstruction').innerHTML='Initialize positions of the blocks and confirm';\n\t\t\tvm.ColorControlValue[Mode][1]=0;\n\t\t\tvm.ColorControlValue[Mode][2]=0;\n\t\t\tvm.ColorControlValue[Mode][3]=0;\n\t\t\tvm.ColorControlValue[Mode][4]=0;\n\t\t\tproperty.style.backgroundColor = \"#FFFFFF\";\n \tvm.ButtonColour[Mode][location][row][column] = 0;\n\t\t\tdocument.getElementById('ProggressUpdate').innerHTML='No orders under construction';\n\t\t}\n\t\telse if(Mode=='NewOrder' && vm.lock==0){\n\t\t\tvm.ColorControlValue[Mode][1]=vm.ColorControlValue['Status'][1];\n\t\t\tvm.ColorControlValue[Mode][2]=vm.ColorControlValue['Status'][2];\n\t\t\tvm.ColorControlValue[Mode][3]=vm.ColorControlValue['Status'][3];\n\t\t\tvm.ColorControlValue[Mode][4]=vm.ColorControlValue['Status'][4];\n\t\t\tproperty.style.backgroundColor = \"#FFFFFF\";\n \tvm.ButtonColour[Mode][location][row][column] = 0;\n\t\t}\n \n }\n\t else{\n\t \tif(vm.Initialized ==0 && Mode=='Status' || Mode=='NewOrder' && vm.Initialized ==1 && vm.lock==0){\n\t\t if (!setOnly && vm.activeColour>0) {\n\t\t if(vm.ButtonColour[Mode][location][row][column] == vm.activeColour){\n\t\t vm.ButtonColour[Mode][location][row][column] = 0;\n\t\t\t if(Mode=='Status'){\n\t\t\t vm.ColorControlValue[Mode][vm.activeColour]= parseInt(vm.ColorControlValue[Mode][vm.activeColour]) - 1;\n\t\t\t }\n\t\t\t else if(Mode=='NewOrder'){\n\t\t\t\tvm.ColorControlValue[Mode][vm.activeColour]= parseInt(vm.ColorControlValue[Mode][vm.activeColour]) + 1;\n\t\t\t }\n\t\t\t}\n\t\t else{\n\t\t\t\tif(vm.ButtonColour[Mode][location][row][column] != 0){\n\t\t\t\t if(Mode=='Status'){\n\t\t\t\t\tvm.ColorControlValue[Mode][vm.ButtonColour[Mode][location][row][column]]=parseInt(vm.ColorControlValue[Mode][vm.ButtonColour[Mode][location][row][column]]) - 1;\n\t\t\t\t\tvm.ButtonColour[Mode][location][row][column] = vm.activeColour;\n\t\t\t\t }\n\t\t\t\t else if(Mode=='NewOrder' && vm.ColorControlValue[Mode][vm.activeColour]>0){\n\t\t\t\t\tvm.ColorControlValue[Mode][vm.ButtonColour[Mode][location][row][column]]=parseInt(vm.ColorControlValue[Mode][vm.ButtonColour[Mode][location][row][column]]) + 1;\n\t\t\t\t\tvm.ButtonColour[Mode][location][row][column] = vm.activeColour;\n\t\t\t\t }\n\t\t\t\t}\n \t\n\t\t\t\tif(Mode=='Status'){\n\t\t\t\t\tvm.ColorControlValue[Mode][vm.activeColour]=parseInt(vm.ColorControlValue[Mode][vm.activeColour]) + 1;\n\t\t\t\t\tvm.ButtonColour[Mode][location][row][column] = vm.activeColour;\n\t\t\t\t }\n\t\t\t\t else if(Mode=='NewOrder' && vm.ColorControlValue[Mode][vm.activeColour]>0){\n\t\t\t\t\tvm.ColorControlValue[Mode][vm.activeColour]=parseInt(vm.ColorControlValue[Mode][vm.activeColour]) - 1;\n\t\t\t\t\tvm.ButtonColour[Mode][location][row][column] = vm.activeColour;\n\t\t\t\t }\n\t\t \t}\n\t\t }\n\t\t}\n switch (vm.ButtonColour[Mode][location][row][column]) {\n case 1://YELLOW = 1\n property.style.backgroundColor = \"#ffff66\";\n break;\n case 2://GREEN = 2\n property.style.backgroundColor = \"#5cd65c\";\n break;\n case 3://RED = 3\n property.style.backgroundColor = \"#ff3333\";\n break;\n case 4://BLUE = 4\n property.style.backgroundColor = \"#0066ff\";\n break;\n default: //white by default\n property.style.backgroundColor = \"#FFFFFF\";\n }\n\t }\n\tdocument.getElementById(1).value=vm.ColorControlValue[Mode][1];\n\tdocument.getElementById(2).value=vm.ColorControlValue[Mode][2];\n\tdocument.getElementById(3).value=vm.ColorControlValue[Mode][3];\n\tdocument.getElementById(4).value=vm.ColorControlValue[Mode][4];\n\t\n }", "function handleClick() {\n // retrieve the index of the button in the node list\n const index = [...buttons].findIndex(button => button === this);\n\n // color and rescale every button up to the selected one\n [...buttons].slice(rating, index + 1).forEach((button, i) => {\n // transition delay for the change in color and scale, on the button\n // animation delay inherited by the pseudo elements, to add a small detail\n // both based on the total number of stars\n const stars = (index + 1) - rating;\n button.style.transitionDelay = `${i * duration / stars}s`;\n button.style.animationDelay = `${i * duration / stars}s`;\n // class allowing to style the button and animate the pseudo elements\n button.classList.add('active');\n });\n\n // remove the class allowing the animation from every button after the selected one\n [...buttons].slice(index + 1, rating).forEach((button, i) => {\n // delay on the transition to have the buttons styled progressively and in the opposite order\n const stars = rating - (index + 1);\n button.style.transitionDelay = `${(stars - i - 1) * duration / stars}s`;\n button.classList.remove('active');\n });\n\n // update rating to refer to the new index\n rating = index + 1;\n}", "changeColor() {\n //this.color = \n }", "function hoverButtonColorOn(e) {\n e.target.style.background = '#c4941c';\n}", "function changeColor() {\n\t// Create random RGB values (used 180 instead of 256 to keep colors darker)\n\tvar red = Math.floor(Math.random() * 180 );\n\tvar green = Math.floor(Math.random() * 180 );\n\tvar blue = Math.floor(Math.random() * 180 );\n\t// Create variable that stores the random values in a string: rgb(x, y, z)\n\tvar rgbcolor = \"rgb(\" + red + \", \" + green + \", \" + blue + \")\";\n\t//change the body background to the rgb color\n\tdocument.body.style.backgroundColor = rgbcolor;\n\t//change the button background to the rgb color\n\tdocument.getElementById('loadQuote').style.backgroundColor = rgbcolor;\n}", "function buttonColors(color) {\n\t$('.button').css(\"background\", color);\n\t$('.button[disabled]').css({\"background\": lighterColor(color, .5), \"color\": color});\n}", "function changeColor(){\n play1button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play2button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play3button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play4button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play5button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play6button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play7button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play8button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n play9button.style.backgroundColor = allColors[getRndInteger(0, allColors.length)]\n colordiv.style.color = (allButtons[getRndInteger(0, allColors.length)]).style.backgroundColor;\n }", "function buttonColorOut(ev) {\n ev.target.style.backgroundColor = \"\";\n}", "function selectedButton(buttonSelected){\n var buttonList = buttonSelected.parentElement.children\n resetButtonColour(buttonList);\n for (var button of buttonList){\n if (button == buttonSelected){\n buttonSelected.style = \"background: hsla(0, 0%, 0%, 1); color: hsla(50, 90%, 50%, 1);\";\n }\n }\n}", "function buttonUpdate() {\n //Storage button updater\n if (gameData.currentStorage != storageNums.length) {\n setBackgroundIf(\"upgradeStorage\", gameData.cash >= storageNums[gameData.currentStorage].cost, \"#05D36B\", \"#af4c4c\");\n }\n setBackgroundIf(\"eggCollector\", gameData.cash >= gameData.eggcollectorCost, \"#05D36B\", \"#af4c4c\");\n setBackgroundIf(\"eggRobotCollector\", gameData.cash >= gameData.roboteggcollectorCost, \"#05D36B\", \"#af4c4c\");\n setBackgroundIf(\"eggClickers\", gameData.cash >= gameData.click_increment_cost, \"#05D36B\", \"#af4c4c\");\n setBackgroundIf(\"upgradeEgg\", gameData.cash >= gameData.cost_increase_cost, \"#05D36B\", \"#af4c4c\");\n}", "function determinebuton(e) {\n if (e.target.tagName == 'BUTTON' && gameState === true) {\n if( colordiv.style.color == document.getElementById(e.target.id).style.backgroundColor){\n playerScore = playerScore + 1\n document.getElementById(\"points\").innerHTML = \"Score: \"+ playerScore\n moveButton()\n changeColor()\n }\n else{\n playerScore = playerScore - 1\n document.getElementById(\"points\").innerHTML = \"Score: \"+ playerScore\n moveButton()\n changeColor()\n }\n }\n}", "function color(id, v, f){\n\n dots.style(\"fill\", function(d){return f(d[v])})\n dots.style(\"opacity\", 1)\n\n d3.selectAll(\"button\")\n .classed(\"button-primary\", false);\n\n d3.select(id)\n .classed(\"button-primary\", true);\n }", "function colorClicked(event) {\n switch (event.target.id) {\n case \"blueBtn\":\n isBlueSelected = !isBlueSelected;\n updateColorSelectionUI(event.target.id, isBlueSelected);\n break;\n case \"redBtn\":\n isRedSelected = !isRedSelected;\n updateColorSelectionUI(event.target.id, isRedSelected);\n break;\n case \"greenBtn\":\n isGreenSelected = !isGreenSelected;\n updateColorSelectionUI(event.target.id, isGreenSelected);\n break;\n case \"blackBtn\":\n isBlackSelected = !isBlackSelected;\n updateColorSelectionUI(event.target.id, isBlackSelected);\n break;\n }\n\n //If none are selected, select all colors and update UI\n checkColorSelectionAndReset();\n\n //Gather Playable Cards Again\n gatherAllPlayableCards();\n shufflePlayableCards();\n\n //Reset All UI\n removeCardFromUI();\n\n cardPosition = 0;\n selectedCard = playableCards[cardPosition];\n showSelectedCard(selectedCard);\n\n resetUI();\n}", "function ChangeColorPallette(){\n updateColorPallette();\n}", "function HighlightButton(){\n document.querySelector(\"#button\").style.backgroundColor = '#46c75f';\n}", "function buttonStyleHandler(_this) {\r\n\r\n//get all the button elements and their details \r\nconst list = document .getElementsByClassName(\"btn-secondary\"); \r\n //switch the current status of the button that was pressed. \r\n _this.activated = !_this.activated;\r\n \r\n //if the button that was pressed was inactive but is now active.... \r\n if ( _this.activated == 1) {\r\n \r\n if(_this.id == \"button1\"){ \r\n _this.style.backgroundColor = \"#00ba19\";\r\n }\r\n else{\r\n _this.style.backgroundColor =\"#005019\";\r\n } \r\n _this.style.color = \"white\";\r\n }\r\n \r\n //if the button is now inactive \r\n else {\r\n \r\n _this.style.backgroundColor = \"buttonface\";\r\n _this.style.color = \"black\";\r\n \r\n if (buttonStatus[0] == true){\r\n \r\n list[0].activated = false;\r\n list[0].style.backgroundColor = \"buttonface\";\r\n list[0].style.color = \"black\";\r\n \r\n } \r\n \r\n }\r\n \r\n //handle the button All being pressed \r\n if (_this.id == \"button1\"){ \r\n \r\n var i;\r\n \r\n for(i=0;i<list.length;i++){\r\n \r\n if(list[i].id == \"button1\"){\r\n \r\n }\r\n else{ \r\n list[i].activated = _this.activated; \r\n \r\n //turn on all buttons \r\n if (list[i].activated == 1){\r\n \r\n list[i].style.backgroundColor = \"#005019\";\r\n list[i].style.color = \"white\";\r\n \r\n }\r\n \r\n //turn off all buttons if all button is turned off. \r\n else {\r\n \r\n list[i].style.backgroundColor = \"buttonface\";\r\n list[i].style.color = \"black\";\r\n \r\n }\r\n }\r\n } \r\n }\r\n \r\n //update the status of all buttons. \r\n var j;\r\n for(j=0;j<list.length;j++){\r\n\r\n buttonStatus[j] = list[j].activated;\r\n\r\n }\r\n\r\n console.log(buttonStatus); \r\n}", "function redColor(){\n document.getElementById(\"button\").style.backgroundColor = \"red\";\n}", "function changeColor(){\n// giving jobs for the button to do when clicked.\n// set variables of each red, green, and blue and grab the value.\n// because the value is a string, make them change to numbers.\n\tvar redValue = document.getElementById('red').value;\n\t\tredValue = parseInt(redValue);\n\tvar greenValue = document.getElementById('green').value;\n\t\tgreenValue = parseInt(greenValue);\n\tvar blueValue = document.getElementById('blue').value;\n\t\tblueValue = parseInt(blueValue);\n\t\n\tvar colorStr = 'rgb(' + redValue + ',' + greenValue + ',' + blueValue + ')';\n// set a new variable that concatenate all 3 values\n\tdocument.getElementById('colorful-text').innerHTML = colorStr;\n// grab the text element, and re-write it with colorStr\t\n\tvar backgroundColor = document.getElementById('wrapper');\n\tbackgroundColor.style.background= colorStr;\n\tconsole.log(colorStr);\n// grabbing the whole wrapper - setting it to a variable so you know what is going on, \n// and changing the css of the element to reflect the new rgb values \n// ex: background-color: (rgb(255, 0, 4))\n}", "function changeColor(type)\n{\n var color=$(\".color\");\n if (color.hasClass(\"unclickedColor\"))\n {\n color.removeClass(\"unclickedColor\").addClass(\"clickedColor\");\n } \n\n else if (color.hasClass(\"clickedColor\"))\n {\n color.removeClass(\"clickedColor\").addClass(\"unclickedColor\");\n }\n}", "function changeBtnColor(x){\n\tif(x == 1)\n\t{\n\t\t$(\"#yesBtn\").addClass(\"btn-default\");\n\t\t$(\"#yesBtn\").removeClass(\"btn-info\");\n\t\t$(\"#noBtn\").removeClass(\"btn-default\");\n\t\t$(\"#noBtn\").addClass(\"btn-info\");\n\n\t}\n\telse\n\t{\n\t\t$(\"#noBtn\").addClass(\"btn-default\");\n\t\t$(\"#noBtn\").removeClass(\"btn-info\");\n\t\t$(\"#yesBtn\").removeClass(\"btn-default\");\n\t\t$(\"#yesBtn\").addClass(\"btn-info\");\n\t}\n}", "function changeColorBtn(e) {\n e.preventDefault();\n let element = document.getElementById('html').attributes;\n\n if(element[2].value === 'dark') {\n // change loupe\n let loupe = document.getElementById('loupe');\n loupe.src = '/assets/lupa_light.svg';\n // change text color button\n let textBtn = document.querySelector('#btn-search');\n textBtn.style.color = '#FFFFFF';\n // change background button search\n let color = document.querySelector('.submit');\n color.style.background = '#EE3EFE';\n color.style.border = '1px solid #110038';\n } else {\n // change luope\n let loupe = document.getElementById('loupe');\n loupe.src = '/assets/lupa.svg';\n // change text color button\n let textBtn = document.querySelector('#btn-search');\n textBtn.style.color = '#110038';\n // change background button search\n let color = document.querySelector('.submit');\n color.style.background = '#F7C9F3';\n color.style.border = '1px solid #110038';\n }\n}", "function originalColor() {\n $(\".btn-teal\").css(\"background-color\", \"rgba(78, 160, 174, 0.5)\");\n $(\".btn-white\").css(\"background-color\", \"rgba(237, 239, 251, 0.5)\");\n $(\".btn-purple\").css(\"background-color\", \"rgba(108, 83, 164, 0.5)\");\n $(\".btn-grey\").css(\"background-color\", \"rgba(4, 0, 0, 0.5)\");\n}", "function newColorButton(){\n var r=Math.floor(Math.random()*256);\n var g=Math.floor(Math.random()*256);\n var b=Math.floor(Math.random()*256);\n\n rrggbb= `rgb(` + r + `,` + g + `,` + b + `)`;\n\n document.style.getElementById(\"loadQuote\").id.background = rrggbb;\n\n\n}", "function coloring(event) {\n event.target.style.backgroundColor = pickColor();\n}", "function changeScribbleColor(e){\n pureweb.getFramework().getState().setValue('ScribbleColor', document.getElementById('color').value);\n}", "function draw(e) {\n e.target.style.backgroundColor = choosenColor();\n}", "function mouseClicked() {\r\n if(value === 0) {\r\n value = 200;\r\n bgcolor = color(value, opacity);\r\n } else {\r\n value = 0;\r\n bgcolor = color(value, opacity);\r\n }\r\n}", "onColorClick (event) {\n let pos = getDOMOffset(this.colorPicker);\n pos.x += 30;\n pos.y = editor.heightAtLine(this.line) - 15;\n\n this.picker = new ColorPicker(this.colorPicker.style.backgroundColor);\n\n this.picker.presentModal(pos.x, pos.y);\n this.picker.on('changed', this.onColorChange.bind(this));\n }", "handleClick(){\n this.setState({\n color: this.generateColor() \n });\n }", "function click() {\r\n /* i need to check if the current color is the last object\r\n in the array. If it is, i set the value back to 0 (the\r\n first color in the array. Otherwise, i have to increment the\r\n current color by 1. */\r\n \r\n if (presentColor == colors.length-1) presentColor = 0;\r\n else presentColor++; \r\n // here now i can set the body's style - backgroundColor to the new color. \r\n document.body.style.backgroundColor = colors[presentColor];\r\n }", "function changeColor(e){\n e.target.style.color = \"blue\"\n }", "function increaseColor(event){\n red = red + 1;\n colorChange();\n}", "function changeColor (event){\n event.currentTarget.style.color = rgb(); //se llama a la primera función\n}", "function buttonColor() {\n if (vm.clientmanagement.inactive) {\n return 'btn btn-success';\n }\n else {\n return 'btn btn-warning';\n }\n }", "function changeButtonColor(button) {\n button.style.backgroundColor = __WEBPACK_IMPORTED_MODULE_0__config_js__[\"a\" /* buttonColor */];\n}", "function changeColor (){\n\t\t$(this).css('background-color', 'red');\t\n\t}", "function changeColors(color, textColor, goColor, goTextColor) {\r\n resetButton.style.backgroundColor = goColor;\r\n quickButton.style.backgroundColor = color;\r\n bubbleButton.style.backgroundColor = color;\r\n mergeButton.style.backgroundColor = color;\r\n\r\n resetButton.style.color = goTextColor;\r\n quickButton.style.color = textColor;\r\n bubbleButton.style.color = textColor;\r\n mergeButton.style.color = textColor;\r\n}", "function changeColorById(n){\n elementNearClicked = document.getElementById(n);\n changeColor(elementNearClicked);\n }", "function changeColorById(n){\n elementNearClicked = document.getElementById(n);\n changeColor(elementNearClicked);\n }", "_sortButtonColoring(button){\n\t\t// \n\t\tfor(var i = 0; i< this.buttons.length; i++){\n\t\t\tif(this.buttons[i][0] != button && this.buttons[i].attr('class') == 'button-blue'){\n\t\t\t\tthis._alterButton(this.buttons[i], \"button-blue\", \"button-normal\");\n\t\t\t//clciked button\t\n\t\t\t}else if(this.buttons[i][0] == button ){\n\t\t\t\tif(this.buttons[i].attr('class') == 'button-blue'){\n\t\t\t\t\tthis._alterButton(this.buttons[i], 'button-blue','button-normal');\n\t\t\t\t \tthis.clicked_button.className = 'button-normal';\n\t\t\t\t}else{\n\t\t\t\t\tthis._alterButton(this.buttons[i], 'button-normal','button-blue');\n\t\t\t\t\tthis.clicked_button.className = 'button-blue';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}", "updateButtonColor() {\n // get button\n const shadow = this.shadowRoot;\n const buttonInput = shadow.querySelector(\"button\");\n\n // get the type of the element\n const elemType = this.getAttribute(\"type\");\n const isPlain = this.hasAttribute(\"plain\");\n var elemTypeString = elemType;\n if (\n elemType != \"primary\" &&\n elemType != \"success\" &&\n elemType != \"info\" &&\n elemType != \"warning\" &&\n elemType != \"danger\"\n ) {\n elemTypeString = \"default\";\n }\n\n if (!isPlain) {\n buttonInput.style.setProperty(\n \"--bg-color\",\n types[elemTypeString][\"bg-color\"]\n );\n buttonInput.style.setProperty(\n \"--txt-color\",\n types[elemTypeString][\"txt-color\"]\n );\n buttonInput.style.setProperty(\n \"--border-color\",\n types[elemTypeString][\"border-color\"]\n );\n buttonInput.style.setProperty(\n \"--hover-bg\",\n types[elemTypeString][\"hover-bg\"]\n );\n buttonInput.style.setProperty(\n \"--hover-txt\",\n types[elemTypeString][\"hover-txt\"]\n );\n buttonInput.style.setProperty(\n \"--hover-border\",\n types[elemTypeString][\"hover-border\"]\n );\n } else {\n buttonInput.style.setProperty(\n \"--bg-color\",\n types[elemTypeString][\"plain-bg-color\"]\n );\n buttonInput.style.setProperty(\n \"--txt-color\",\n types[elemTypeString][\"plain-txt-color\"]\n );\n buttonInput.style.setProperty(\n \"--border-color\",\n types[elemTypeString][\"plain-border-color\"]\n );\n buttonInput.style.setProperty(\n \"--hover-bg\",\n types[elemTypeString][\"plain-hover-bg\"]\n );\n buttonInput.style.setProperty(\n \"--hover-txt\",\n types[elemTypeString][\"plain-hover-txt\"]\n );\n buttonInput.style.setProperty(\n \"--hover-border\",\n types[elemTypeString][\"plain-hover-border\"]\n );\n }\n }", "function colorSelect() {\n let id = parseInt(this.id);\n\n changeColor(id, this);\n color = true;\n}", "function changeColor(data){\n //Changes Color of Button\n let sequencerIndex = parseInt(data.sequencerIndex);\n let presetIndex = parseInt(data.presetIndex);\n let voteCount = parseInt(data.voteCount);\n\n voteCountPercentage = voteCount/255\n console.log(voteCountPercentage)\n \n let redColor = (voteCountPercentage * 2) * 255\n let greenColor = 255\n\n if (voteCountPercentage > 0.5) {\n redColor = 255\n greenColor = 255 - (255 * ((voteCountPercentage - 0.5) * 2))\n }\n let displayColor = '#' + redColor.toString(16) + greenColor.toString(16) + '00'\n mainPresetButtons[sequencerIndex][presetIndex-1].style('background-color', displayColor)\n\n //Vote Procedure\n if (voteCount === 0){\n let whichButton = {...mainPresets[sequencerIndex+1][presetIndex]};\n\n // deep clone an array of arrays\n let setSequence = whichButton.sequence.map(i => ([...i]));\n let setEnvelope = {...whichButton.envelope};\n\n let setAttack = setEnvelope.attack\n let setDecay = setEnvelope.decay\n let setSustain = setEnvelope.sustain\n let setRelease = setEnvelope.release\n\n let setWaveform = whichButton.waveform;\n let setPitchScheme = whichButton.pitchArray;\n\n mainSynth[sequencerIndex].set({\n 'oscillator': {\n 'type': setWaveform\n },\n 'envelope': {\n 'attack': setAttack,\n 'decay': setDecay,\n 'sustain': setSustain,\n 'release': setRelease\n }\n });\n mainSequencer[sequencerIndex].polyMatrix = setSequence;\n mainSequencer[sequencerIndex].polyNotes = setPitchScheme;\n\n mainSequencer[sequencerIndex].drawMatrix();\n mainSequencer[sequencerIndex].polyMatrixNotes();\n console.log('changed!')\n }\n \n \n}", "function changeBackgound(button, another_button)\n{ \n button.css(\"background-color\",\"rgb(232, 234, 237)\");\n button.css(\"color\",\"rgb(32, 33, 36)\");\n \n another_button.css(\"background-color\",\"rgb(32, 33, 36)\");\n another_button.css(\"color\",\"rgb(232, 234, 237)\");\n}", "function colorChange(){\n //Write the current color in a div with the rgb value\n document.getElementById('currentColor').textContent = \"Current Color: rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n //change the color of the div based on the values determined earlier, as the user presses the buttons these values change and this should update each time if done correctly.\n Display.style.backgroundColor = \"rgb(\" + red + \",\" + green + \",\" + blue + \")\";\n}", "function changeColor(){\n console.log('change color activated');\n\n $(this).css('background-color','black');\n } // end changeColor", "function updateColorSelectionUI(colorId, isColorSelected) {\n var colorBtn = document.getElementById(colorId);\n if (isColorSelected) {\n colorBtn.classList.add(\"selected\"); \n }\n else {\n colorBtn.classList.remove(\"selected\");\n }\n}", "function Button202(){\n $('h2').css('color','green');\n}", "function changeButtonColor () {\n if (isUpOrDown) {\n document.getElementById(\"submit_button1\").className = 'btn btn-danger';\n document.getElementById(\"submit_button2\").className = 'btn btn-success';\n } else {\n document.getElementById(\"submit_button1\").className = 'btn btn-success';\n document.getElementById(\"submit_button2\").className = 'btn btn-danger';\n }\n}", "function updateDayToggleSkin(isSelected, buttonObject) {\n if (isSelected) {\n buttonObject.skin = \"jumpStartGreenButton90\";\n } else {\n buttonObject.skin = \"jumpStartGrayButton90\";\n }\n}", "function checkRedPressed() {\n isRedElementClicked = true;\n}", "function latestclick54() { // This uses the prvClicks array to accessed the latest click button\n latest54 = prvClicks[prvClicks.length - 1]\n let clickid54style = document.getElementById(latest54).style.background\n document.getElementById(latest54).style.background=\"#000\"\n setTimeout(function(){\n if(clickid54style=='rgb(125, 235, 52)') {\n document.getElementById(latest54).style.background=\"rgb(125, 235, 52)\"\n } else {\n document.getElementById(latest54).style.background=\"#fff\"\n }}, 500)\n}", "function clickedColor(){\n\tfor(i = 0; i < squares.length; i++){\n\t\tsquares[i].style.backgroundColor = colors[i];\n\t\tsquares[i].addEventListener(\"click\", \n\t\t\tfunction(){\n\t\t\t\tvar clickedColor = this.style.backgroundColor;\n\t\t\t\tif(clickedColor === pickedColor){\n\t\t\t\t\tmessage.textContent = \"Correct!\";\n\t\t\t\t\tchangeColors(clickedColor);\n\t\t\t\t\th1.style.backgroundColor = clickedColor;\n\t\t\t\t\treset.textContent = \"Try Again?\";\n\t\t\t\t}else{\n\t\t\t\t\tthis.style.backgroundColor = \"#232323\";\n\t\t\t\t\tmessage.textContent = \"Try Again.\";\n\t\t\t\t}\n\n\t\t\t});\n\t}\n}", "function mouseClicked() {\n colorindex = ((colorindex+1)%colors.length)\n bgColor = colors[2][1]\n circleColor = colors[2][0];\n}", "function whenClicked(){\n divBtn.style.backgroundColor = 'red';\n alert('button was click');\n}", "function pressed(num){\n\tif (num == 1) {\n\t\teensButton.style.background = \"green\";\n\t\toneensButton.style.background = \"grey\";\n\t\thuidig = true;\n\t\tsubmitButton.style.display = \"inline-block\"\n\t}\n\telse if (num == 2) {\n\t\teensButton.style.background = \"grey\";\n\t\toneensButton.style.background = \"green\";\n\t\thuidig = false;\n\t\tsubmitButton.style.display = \"inline-block\"\n\t}\n\telse {\n\t\teensButton.style.background = \"grey\";\n\t\toneensButton.style.background = \"grey\";\n\t\thuidig = null;\n\t\tsubmitButton.style.display = \"none\"\n\t}\n}", "function clickBG(btnId) {\n if (btnId.style.backgroundColor == 'white') {\n btnId.style.backgroundColor = '#7C3AED';\n btnId.style.color = 'white';\n } else {\n btnId.style.backgroundColor = 'white';\n btnId.style.color = 'black';\n }\n}", "function click_color_selection(id, color) {\n var split_id = id.split('-');\n var filetype = split_id[1];\n var forebackground = split_id[2];\n var filetype_id = available_filetypes.indexOf(filetype);\n (forebackground == 'foreground' ? selected_foreground_colors : selected_background_colors)[filetype_id] = color;\n\n update_everything();\n }", "function changeButton () {\n this.setAttribute(\"class\", \"highlightButton\");\n this.innerHTML = \"GO!\";\n}", "function Button201(){\n $('body').css('background-color','pink');\n}", "function updateColor(){\r\n color = colorSelector.value;\r\n}", "function turnOnAllButtons(){\r\nconst list = document .getElementsByClassName(\"btn-secondary\"); \r\n var i;\r\n \r\n for(i=0;i<list.length;i++){\r\n \r\n buttonStatus[i] = true;\r\n if(list[i].id == \"button1\"){ \r\n //list[i].style.backgroundColor = \"#29d148\";\r\n list[i].style.backgroundColor = \"#00ba19\";\r\n console.log(\"button1\");\r\n }\r\n \r\n else{\r\n //list[i].style.backgroundColor = \"#339966\";\r\n list[i].style.backgroundColor = \"#005019\";\r\n }\r\n list[i].style.color = \"white\"; \r\n list[i].activated = true;\r\n }\r\n}" ]
[ "0.72542405", "0.7214219", "0.719813", "0.71524817", "0.7030263", "0.7025146", "0.7020735", "0.70176566", "0.6937343", "0.69048613", "0.6898962", "0.68876934", "0.683276", "0.68285376", "0.6785288", "0.6777175", "0.67688817", "0.6745452", "0.6721171", "0.67191696", "0.6683228", "0.66785485", "0.6657041", "0.6655069", "0.66472894", "0.6625999", "0.65999216", "0.65984064", "0.6592498", "0.6582054", "0.65721285", "0.6538276", "0.6533239", "0.6524993", "0.6493869", "0.64925337", "0.64747554", "0.6462576", "0.6444443", "0.644204", "0.64400905", "0.6433986", "0.642935", "0.6422185", "0.6417887", "0.6417217", "0.6416811", "0.6410292", "0.6389455", "0.6383862", "0.6376154", "0.63662547", "0.63630205", "0.6359768", "0.6354219", "0.6347608", "0.63364017", "0.6335784", "0.6333658", "0.63314193", "0.6312651", "0.6312651", "0.63119394", "0.6306846", "0.6302445", "0.62921107", "0.62867445", "0.6278941", "0.62777776", "0.62743294", "0.6274106", "0.62697494", "0.62670636", "0.6264381", "0.62613726", "0.6261175", "0.6261175", "0.62605643", "0.6251626", "0.6249174", "0.62442935", "0.62383205", "0.6235587", "0.62304443", "0.62299633", "0.622527", "0.6213898", "0.6212549", "0.6201443", "0.61976415", "0.619204", "0.6189512", "0.61886317", "0.61858547", "0.61834496", "0.6179491", "0.61788994", "0.61771953", "0.6172484", "0.6171801" ]
0.69733685
8
BBB Generator base constructor Extend Yeoman base generator
function Generator(args, options, config) { var self = this; yeoman.generators.Base.apply(this, arguments); // Check parents directory recursively for a config file (only if we're not in bbb:init) if (this.constructor._name !== "bbb:init") { var root = grunt.file.findup(".bbb-rc.json"); if (root) { root = path.dirname(root); process.chdir(root); } } // Set default paths this.destinationRoot(process.cwd()); this.sourceRoot(path.join(__dirname, "../../templates")); // Extend grunt.file to namespace with source and destination directory. // Note: I don't like Yeoman file API, so here I use a wrapped Grunt instead. this.src = {}; this.dest = {}; _.assign(this.src, grunt.file, function(thisSrc, gruntFunc) { return function() { var src = arguments[0]; var args = Array.prototype.slice.call(arguments, 1); if (!grunt.file.isPathAbsolute(src)) { src = path.join(this.sourceRoot(), src); } args.unshift(src); return gruntFunc.apply(grunt.file, args); }.bind(this); }, this); _.assign(this.dest, grunt.file, function(thisSrc, gruntFunc) { return function() { var src = arguments[0]; var args = Array.prototype.slice.call(arguments, 1); if (!grunt.file.isPathAbsolute(src)) { src = path.join(this.destinationRoot(), src); } args.unshift(src); return gruntFunc.apply(grunt.file, args); }.bind(this); }, this); // `write` and `copy` are specials as they should check for collision before this.dest.write = _.bind(this.write, this); this.dest.copy = _.bind(this.copy, this); // Get existing configurations var packageJSON; try { packageJSON = this.dest.readJSON("package.json"); } catch(e) { packageJSON = {}; } var bbbrc; try { bbbrc = this.dest.readJSON(".bbb-rc.json"); } catch(e) { bbbrc = {}; } this.pkg = packageJSON; this.bbb = _.defaults(bbbrc, { name : "", testFramework : "qunit", moduleStyle : "amd", templateEngine : "underscore", indent : { char : "space", size : 2 }, paths : { base : ".", tests : "test", modules : "app/modules" } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "constructor() { super(new GeneratorParser(true)) }", "function GeneratorClass () {}", "constructor(generator) {\n this.generator = generator;\n }", "constructor() {\n super();\n\n this.generateModules();\n }", "constructor(args, opts) {\n // Calling the super constructor is important so our generator is correctly set up\n super(args, opts);\n }", "constructor(args, opts) {\n // Calling the super constructor is important so our generator is correctly set up\n super(args, opts);\n\n // Next, add your custom code\n this.option('babel'); // This method adds support for a `--babel` flag\n }", "constructor(args, opts) {\n // Calling the super constructor is important so our generator is correctly set up\n super(args, opts);\n\n // Next, add your custom code\n this.option(\"babel\"); // This method adds support for a `--babel` flag\n }", "constructor( args, opts ) {\n\n // Calling the super constructor is important so our generator is correctly set up\n super( args, opts );\n\n }", "function Generator(){}", "function Generator(){}", "function Generator(){}", "function Generator(){}", "function Generator(){}", "function Generator(){}", "constructor (args, options) {\n\n super(...arguments);\n\n Object.assign(this, {\n publicDir: './', // public dir of the frontend app parts\n srcDir: './src', // soruce dir, contains all ng modules created by generator\n module: {\n name: '', // angular module name\n nameCamel: '', // camelcse version of name, ideal for js class name\n label: '', // module human name\n dir: '', // module directory name\n path: '', // full path to module dir\n },\n file: {\n name: '', // dasshed name of the file, includes module name and all path\n label: '', // label is human redable title version of name\n nameLowCamel: '', // camelcase with firs lower letter, ideal for dirctive name\n nameCamel: '', // camecase of the name, ideal for controller or js clsass name\n dir: '',\n dirParts: ''\n },\n\n moduleRequired: true, // is name argument required\n nameRequired: true, // is name argument required\n nameDescription: 'in most cases it\\'s file name you want to generate', // give the halp description of the name argument\n\n nameSuffix: '', // suffix for name attribute\n\n fileSuffix: '', // suffix for name file\n fileSubDir: '', // suffix for name file\n /**\n * remove one last level of dir for the file,\n * example: when set to true\n * user/login/form\n * will be\n * user/login/user-login-form.js\n * otherwise\n * user/login/form/user-login-form.js\n */\n fileSliceDir: true,\n\n })\n\n this._ = _;\n\n if(!this.config.get('publicDir')) {\n this.error(\"you have to init your app with yo angular-flow command, or make sure you run commands at root level of your project\");\n }\n\n // config props\n this.publicDir = this.config.get('publicDir') || this.publicDir;\n this.srcDir = path.join(this.publicDir, this.config.get('srcDir'));\n\n // module name is required\n this.argument('moduleName', { type: String, required: false });\n\n // subGenerator name is optional, depends on this.requiredName prop, witch you can be overwrite\n this.argument('fileName', { type: String, required: false });\n this.moduleName = this.options.moduleName;\n this.fileName = this.options.fileName;\n\n if(!this.moduleName) {\n this.log.error('Module name is required, try: yo:'+this.options.namespace+' [moduleName]');\n this.log('available modules: ', this.getModules());\n this.exit();\n }\n if(this.nameRequired && !this.fileName) {\n this.log.error('Name is required, try: yo:'+this.options.namespace+' [moduleName] [fileName]');\n this.log(this.nameDescription);\n this.exit();\n }\n\n // set module and file properties based on user input\n this.setModule(this.moduleName);\n this.setName(this.fileName, this.nameSuffix);\n this.setFile(this.fileName, this.fileSuffix);\n\n // console.log(\"MODULE\\n\", this.module);\n // console.log(\"NAME\\n\", this.name);\n // console.log(\"FILE\\n\", this.file);\n\n // test if module exists\n var moduleFile = this.module.path;\n // if we createin new module, tyr if it already exists\n if((this.options.namespace === 'angular-flow:module') && fs.existsSync(moduleFile)) {\n this.error('Module \"'+this.module.dir+'\" already exist, can\\'t overwrite it');\n }\n // if you create somethink for the module, test if it exists\n if((this.options.namespace !== 'angular-flow:module') && !fs.existsSync(moduleFile)) {\n this.error('Module \"'+this.module.dir+'\" does not exist, create it first with angular-flow:module [moduleName]' );\n }\n }", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}", "function Generator() {}" ]
[ "0.7307889", "0.71404356", "0.68152285", "0.67347217", "0.6701433", "0.6694148", "0.6639879", "0.6621982", "0.6364974", "0.6364974", "0.6364974", "0.6364974", "0.6364974", "0.6364974", "0.6312817", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555", "0.6187555" ]
0.0
-1
Finds the highest common factor of 2 numbers
function highestCommonFactor2(a, b) { if (b === 0) { return a; } return highestCommonFactor2(b, a%b); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function greatest_common_factor(number1, number2) {\n let divider = 1;\n let largeNum = number1 >= number2 ? number1 : number2;\n let smallNum = largeNum === number1 ? number2 : number1;\n while (divider <= smallNum) {\n let testNum = smallNum / divider;\n if (largeNum % testNum === 0) {\n return testNum;\n }\n divider++;\n }\n}", "function highestCommonFactor1(a, b) {\n if (b === 0) {\n return a;\n }\n return highestCommonFactor1(b, a%b);\n}", "function hcf(){\n let a = 144;\n let b = 96;\n while (b > 0){\n let temp = a;\n a = b;\n b = temp%b;\n };\n console.log('The highest common factor is: '+ a);\n}", "function commonFactors(num1, num2) {\n const factors = []\n let max\n max = num1 > num2 ? num1 : num2\n for (let i = max; i >= 1; i--) {\n if (num1 % i === num2 % i) {\n factors.push(i)\n }\n }\n return factors\n}", "function gcd(a, b) {\n const commonFactors = [];\n const min = Math.min(a, b);\n const max = Math.max(a, b);\n for (let i = 1; i <= min; i++) {\n if (min % i === 0 && max % i === 0) {\n commonFactors.push(i);\n }\n }\n return commonFactors[commonFactors.length - 1];\n}", "function gcd(num1, num2) {\n var commonDivisor = [ ];\n let highNum = num1;\n if(num1 < num2){\n highNum = num2;\n \n }\n \n for (let i = 1; i <= highNum; i++) {\n if(num1 % i === 0 && num2 % i === 0){\n commonDivisor.push(i);\n }\n } \n const returnNum = Math.max(...commonDivisor);\n return returnNum; \n \n}", "function greatestCommonDivisor (a, b) {\n var gcd = 1;\n var low = a <= b ? a : b;\n for (var i = 2; i < low; i++) {\n if (a % i == 0 && b % i == 0 ) {\n gcd *= i;\n a /= i; \n b /= i;\n low /= i;\n }\n }\n return gcd;\n}", "function leastCommonMultiple(num1, num2){\n // your code here...\n}", "function gcf(num1, num2){\n if (num1 > num2){ //this ensures num1 is the smaller number\n var temp = num1; // 1...\n num1 = num2;\n num2 = temp;\n }\n for (var i = num1; i > 1; i--){ // n - dictated by size of num1\n if (num1 % i === 0 && num2 % i === 0){ // 2\n return i;\n }\n }\n return 1;\n}", "function gcd (num1, num2) {\n var num1Factors = [];\n var num2Factors = [];\n for (var i = 1; i <= num1; i++) {\n if (num1 % i === 0) {\n num1Factors.push(i);\n }\n }\n for (var j = 1; j <= num2; j++) {\n if (num2 % j === 0) {\n num2Factors.push(j);\n }\n }\n var commonFactors = [];\n for (var k = 0; k < num1Factors.length; k++) {\n for (var m = 0; m < num2Factors.length; m++) {\n if (num1Factors[k] === num2Factors[m]) {\n commonFactors.push(num1Factors[k])\n }\n }\n }\n return commonFactors.pop();\n}", "function lcm(num1, num2) {\n var least = num2;\n if(num1 > num2){\n least = num1;\n }\n\n while (true) {\n if(least % num1 === 0 && least % num2 === 0){\n return least;\n }\n least += 1;\n }\n}", "function greatestDicisor(x, y) {\n if (x <= y) {\n var pom = x;\n }else{\n pom = y;\n }\n for (var i = pom; i > 0; i--) {\n if (x % i === 0 && y % i === 0) {\n return i\n }\n } \n}", "function commonDivisor (numb1, numb2) {\n var divisor = 0;\n var min = numb1;\n if (numb2 < min) {\n min = numb2;\n }\n for (var i = min; i > 0; i--) {\n if (numb1 % i === 0 && numb2 % i === 0) {\n divisor = i;\n break;\n }\n }\n return divisor;\n}", "function GreatestCOmmonDivisor(a, b){\n var divisor = 2;\n greatestDivisor = 1;\n\n if (a < 2 || b < 2){\n return 1;\n }\n\n while(a >= divisor && b >= divisor){\n if (a % divisor == 0 && b% divisor == 0) {\n greatestDivisor = divisor;\n }\n divisor ++;\n }\n return greatestDivisor;\n}", "function greatestCommonDivisor(a, b) {\n\tvar divisor = 2,\n\t\tgreatestDivisor = 1;\n\n\tif (a < 2 || b < 2) \n\t\treturn 1;\n\n\twhile (a >= divisor && b >= divisor) {\n\t\tif (a % divisor == 0 && b % divisor == 0) {\n\t\t\tgreatestDivisor = divisor;\n\t\t}\n\n\t\tdivisor++;\n\t}\n\n\treturn greatestDivisor;\n}", "function smallestCommons(arr) {\n // Sort the array\n let sorted = arr.sort((a, b) => a - b);\n let max = 1;\n\n // Worst case scenario, the common multiple is factorial\n for (let j = sorted[0]; j <= sorted[1]; j++) {\n max *= j;\n }\n\n // Build the range array\n let range = Array(sorted[1] - sorted[0] + 1)\n .fill(sorted[0])\n .map((num, ind) => num + ind);\n\n let k = sorted[0];\n let multiple = sorted[1] * k;\n while (multiple < max) {\n multiple = sorted[1] * k;\n if (range.every((divisor) => multiple % divisor == 0)) {\n return multiple;\n }\n k++;\n }\n return max;\n}", "function leastCommonMultiple(num1, num2){\n var smallerNumber = Math.min(num1, num2);\n var largerNumber = Math.max(num1, num2);\n var multiple = smallerNumber;\n\n while(true) {\n if (multiple % largerNumber === 0) {\n return multiple;\n }\n multiple += smallerNumber;\n }\n}", "function gcd(a,b){\n let am=Math.abs(a), bm=Math.abs(b), min=Math.min(a,b);\n for (var i=min;i>0;i--){\n if (am%i===0 && bm%i===0) return i;\n }\n }", "function leastCommonMultiple(num1, num2){\n if (num1 === 2 || num2 === 2) {\n return num1 * num2\n }\n else if (num1 % 2 === 0) {\n return (num1 / 2) * num2;\n }\n else if (num2 % 2 === 0) {\n return (num2 / 2) * num1;\n }\n else {\n return num1 * num2;\n }\n}", "function greatesrDivisor(num1, num2) {\n let divisors = [];\n for(i=1; i <= num2; i++)\n if(num1%i === 0 && num2%i === 0){\n divisors.push(i)\n }\n let largestDivisors = divisors.reduce(function(a,b){\n return Math.max(a, b);\n })\n return largestDivisors;\n\n}", "function smallestCommons(arr) {\n\n\t// use only one order to simplify things\n\tarr = (arr[0] < arr[1]) ? arr : arr.reverse();\n\n\tlet found = false;\n\tlet curr = arr[1];\n\n\twhile (found === false) {\n\n\t\t// key to efficiency is increase by largest factor each pass\n\t\tcurr += arr[1];\n\t\t\n\n\t\t// flag to switch off if a remainder from division attempt\n\t\tlet divisible = true;\n\t\tfor (let i = arr[1]; i >= arr[0]; i--) {\n\t\t\t\n\t\t\tif(curr % i !== 0) {\n\n\t\t\t\tdivisible = false;\n\n\t\t\t\t// we need to return to while loop to try a bigger num\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// if we are still divisible here we made it through inner loop,\n\t\t// this will be our lowest multiple.\n\t\tif(!divisible) {\n\t\t\tcontinue;\n\t\t}\n\t\telse {\n\t\t\tfound = curr;\n\t\t\tbreak;\n\t\t}\n\t}\n\n return found;\n\t\t\n}", "function greatestCommonDivisor(a, b){\n if(b == 0)\n return a;\n else \n return greatestCommonDivisor(b, a%b);\n}", "function lcmOfTwo( a, b ) {\n return ( a * b ) / gcd( a, b );\n}", "findGCD (num1, num2) {\n let max = num1 > num2 ? num1 : num2\n let min = num1 > num2 ? num2 : num1\n let diff = max - min\n while (diff !== 0) { \n let temp = min % diff\n min = diff\n diff = temp\n }\n return min\n }", "function greatestCommonDivisor(num1, num2) {\n var divisor = 2,\n greatestDivisor = 1;\n\n // if num1 or num2 are negative values\n if (num1 < 2 || num2 < 2) return 1;\n\n while (num1 >= divisor && num2 >= divisor) {\n if (num1 % divisor == 0 && num2 % divisor == 0) {\n greatestDivisor = divisor;\n }\n divisor++;\n }\n return greatestDivisor;\n}", "function smallestCommons(arr) {\n let newArr = [], multiplier = 2\n arr.sort(function(a,b){\n return b - a;\n })\n\n for(let i = arr[0]; i >=arr[1]; i--){\n newArr.push(i)\n }\n \n for (let j = 0; j < newArr.length; j++){\n if ((newArr[0] * multiplier) % newArr[j] !== 0){\n multiplier += 1\n j = 0\n }\n }\n\n return newArr[0] * multiplier \n}", "function smallestCommons(arr) {\r\n arr = arr.sort();\r\n\r\n let range = (function() {\r\n let range = [];\r\n for (let i = arr[0]; i <= arr[1]; i++) {\r\n range.push(i);\r\n }\r\n return range;\r\n })();\r\n\r\n let count = 0;\r\n let mult = range[range.length - 1];\r\n\r\n while (count < range.length) {\r\n count = 0;\r\n for (let i = range[0]; i <= range[range.length - 1]; i++) {\r\n if (mult % i === 0) count++;\r\n }\r\n mult += range[range.length - 1];\r\n }\r\n return mult - range[range.length - 1];\r\n}", "function lcm(){\nalert(\"To find the LCM of a set of numbers first express each number as a product of its prime factors.\"); alert(\"For example find the LCM of 18 and 24.Expressing 18 as a product of its prime factors: 2√18=9 next 3√9=3 next 3√3=1 hence 18=2×3×3.Expressing 24 as a product of its prime factors: 2√24=12 next 2√12=6 next 2√6=3 next 3√3=1 hence 24=2×2×2×3. Take each factor where it appears most ie take all the 2's in 24 and the 3's in 18 hence LCM=2×2×2×3×3=72.\");\n}", "function greatestCommonDivisor(a, b) {\n var divisor = 2,\n greatestDivisor = 1;\n\n if (a < 2 || b < 2) {\n return 1;\n }\n\n while (a >= divisor && b >= divisor) {\n if (a % divisor == 0 && b % divisor == 0) {\n greatestDivisor = divisor;\n }\n divisor++;\n }\n return greatestDivisor;\n}", "function lcm(a, b) {\r\n /**Return lowest common multiple.**/\r\n return Math.floor((a * b) / gcd(a, b));\r\n }", "function smallestCommons(arr) {\n\tarr = arr.sort((a, b) => a - b);\n\tconst myArr = [];\n\tlet every;\n\tfor (let i = arr[0]; i <= arr[1]; i++) {\n\t\tmyArr.unshift(i);\n\t}\n\tlet lcm = myArr[0] * myArr[1];\n\twhile (!every) {\n\t\tevery = myArr.every(num => lcm % num === 0);\n\t\tif (!every) {\n\t\t\tlcm += arr[1];\n\t\t}\n\t}\n\treturn lcm;\n}", "function greatestCommonDivisor(a, b) {\n if(b == 0) {\n return a;\n } else {\n return greatestCommonDivisor(b, a%b);\n }\n}", "function gcd(num1, num2){\n let numArray1 = [];\n let numArray2 = [];\n let finalArray = [];\n let longestArray;\n let shortestArray;\n for (let i = 1; i <= Math.floor(num1); i++) {\n if (num1 % i === 0) {\n numArray1.push(i);\n } \n }\n for (let i = 1; i <= Math.floor(num2); i++) {\n if (num2 % i === 0) {\n numArray2.push(i);\n } \n } \n for (let i = 0; i < numArray1.length || i < numArray2.length; i++) {\n if (numArray1.length > numArray2.length){\n longestArray = numArray1;\n shortestArray = numArray2;\n }\n else {\n longestArray = numArray2;\n shortestArray = numArray1;\n }\n }\n for (let i = 0; i < shortestArray.length; i++) {\n if(longestArray.indexOf(shortestArray[i]) > -1){\n finalArray.push(shortestArray[i]);\n } \n }\n return Math.max(...finalArray);\n }", "function greatestCommonDivisor(a, b) {\n if (b === 0) {\n return a;\n }\n return greatestCommonDivisor(b, a % b);\n}", "function hcf(a, b) {\r\n if (a == 0) {\r\n return b;\r\n } else if (b == 0) {\r\n return a;\r\n } else if (a > b) {\r\n return hcf(b, a % b);\r\n } else {\r\n return hcf(a, b % a);\r\n }\r\n}", "function smallestCommon(arr) {\n var range = [];\n for (var i = Math.max(arr[0], arr[1]); i >= Math.min(arr[0], arr[1]); i--) {\n range.push(i);\n }\n\n // can use reduce() in place of this block\n var lcm = range[0];\n for (i = 1; i < range.length; i++) {\n var GCD = gcd(lcm, range[i]);\n // debugger;\n lcm = (lcm * range[i]) / GCD;\n }\n return lcm;\n\n function gcd(x, y) { // Implements the Euclidean Algorithm\n if(x%y === 0){\n return y;\n }else{\n return gcd(y, x%y);\n }\n }\n}", "function Division(num1,num2) { \n var gcf = 1; // gcf represents the greatest common factor, which is what we're ultimately trying to figure out here. The GCD for 2 numbers is always at least 1.\n for (var i = 0; i <= num1 && i <= num2; i++){ // FOR-LOOP: Starting at 0, and up until i reaches either the value of num1 or num2 (whichever is lesser), for each number up to that point...\n if (num1 % i == 0 && num2 % i == 0){ // IF: i is a common factor of both num1 and num2... \n // ^ Think about the code here. var i reprsents potential common factors. If there is no remainder after dividing num1 by i, then i is a factor of num1. Using the && allows us to test if i is a COMMON factor b/w num1 and num2\n\n gcf = i; // -> if i is a common factor -> then make the value of i as the greatest common factor (which is subject to change as we proceed thru the for-loop)\n }\n }\n return gcf; // return the value of the greatest common factor\n}", "function lcm(num1, num2){\n var sumNum = num1 * num2;\n// console.log(sumNum);\n //Using Math.min() returns the lowest number:\n if(sumNum % num1 !== 0 && sumNum % num2 !== 0){\n // console.log(Math.min(num1, num2));\n return Math.min(sumNum);\n }\n }", "static smallestCommonMultiple(arr) {\n\n const gcd = (num1, num2) => {\n for(let i = Math.min(num1, num2) ; i >= 2 ; --i) {\n if( (num1 % i == 0) && (num2 % i == 0) ) {\n return i;\n }\n }\n return 1;\n }\n \n let min = Math.min(...arr);\n let max = Math.max(...arr);\n let gcm = min;\n for(let i = min + 1; i <= max ; ++i) {\n gcm = (gcm * i) / gcd( gcm, i);\n }\n return gcm;\n\n }", "function fpb(angka1, angka2) \n{\n console.log('\\n', 'case for - FPB', angka1, angka2, '\\n ------------------------------------');\n\n var factorAngkaSatu = []\n var factorAngkaDua = []\n\n\n for (var x = 1; x<=angka1; x++)\n {\n if( angka1 % x === 0)\n {\n factorAngkaSatu.push(x)\n }\n }\n \n for (var x = 1; x<=angka2; x++)\n {\n if( angka2 % x === 0)\n {\n factorAngkaDua.push(x)\n }\n }\n \n // console.log(factorAngkaSatu)\n // console.log(factorAngkaDua)\n\n var commonFactor = []\n\n for (var x = 0; x < factorAngkaSatu.length; x++)\n {\n for (var y =0; y < factorAngkaDua.length; y++)\n {\n if( factorAngkaSatu[x] === factorAngkaDua[y])\n {\n commonFactor.push(factorAngkaSatu[x])\n }\n\n }\n\n }\n\n // console.log(commonFactor)\n \n var fpb = commonFactor[0]\n // console.log(fpb)\n \n if ( commonFactor.length === 1)\n {\n return fpb\n }\n else\n {\n\n for( var x = 1; x <= commonFactor.length-1; x++)\n {\n if( commonFactor[x] > fpb)\n {\n fpb = commonFactor[x]\n }\n }\n\n return fpb\n }\n\n}", "function greatestDivisor(x, y) {\n \n if (x <= y) {\n var res = x;\n }else{\n res = y;\n }\n for (var i = res; i > 0; i--) {\n if (x % i === 0 && y % i === 0) {\n return i\n }\n } \n}", "function findLCM(a, b) {\r\n return (a * b / findHCF(a, b));\r\n}", "function smallestCommons(arr) {\n const [min,mix] = arr.sort((a,b)=> a-b);\n const numberDivisors = max - min + 1;\n let upperBound = 1 ;\n for (let i = min; i <= max; i++) {\n upperBound *= i;\n }\n for (let multiple = max; multiple <= upperBound; multiple += max) {\n // Check if every value in range divides 'multiple'\n let divisorCount = 0;\n for (let i = min; i <= max; i++) {\n // Count divisors\n if (multiple % i === 0) {\n divisorCount += 1;\n }\n }\n if (divisorCount === numberDivisors) {\n return multiple;\n }\n }\n}", "function lcm(a,b)\n{\n return (a*b)/gcd(a,b);\n}", "function smallestCommons(arr) {\n //find min and max numbers, push to array in order of smaller to larger number\n var range = [];\n\n var min = Math.min(arr[0], arr[1]);\n console.log(min);\n var max = Math.max(arr[0], arr[1]);\n console.log(max);\n\n for (var x = min; x <= max; x++) {\n //get range of numbers between min and max, push to array\n range.push(x);\n }\n\n var lcm = range[0];\n\n for (i = 1; i < range.length; i++) {\n var GCD = gcd(lcm, range[i]);\n lcm = (lcm * range[i]) / GCD;\n }\n return lcm;\n //Euclidean algorithm\n function gcd(x, y) {\n if (y === 0)\n return x;\n else\n return gcd(y, x % y);\n }\n}", "function lcm(a, b) {\n\treturn a * b / gcd(a,b);\n}", "function smallestCommons(arr) {\n\tarr.sort(function (a, b) {\n\t\treturn b - a;\n\t});\n\tconst smallest = arr[1];\n\tconst biggest = arr[0];\n\tlet solution = biggest;\n\n\tfor (let i = biggest; i >= smallest; i--) {\n\t\tif (solution % i) {\n\t\t\tsolution += biggest;\n\t\t\ti = biggest;\n\t\t}\n\t}\n\treturn solution;\n}", "function smallestCommons(arr) {\n const min = Math.min(arr[0], arr[1]),\n max = Math.max(arr[0], arr[1]);\n\n function range(min, max) {\n let arr = [];\n\n for (let i = max; i >= min; i--) {\n arr.push(i);\n }\n return arr;\n }\n\n function gcd(x,y) {\n return y === 0 ? x : gcd(y, x % y);\n }\n\n function lcm(x, y) {\n return (x * y) / gcd(x, y);\n }\n\n let multiple = min;\n\n range(min, max).forEach(value => {\n multiple = lcm(multiple, value);\n });\n\n return multiple;\n}", "function lcm(a, b) {\n\treturn console.log((a * b) / maximoComunDenominador(a, b))\n}", "function findHCF(a, b) {\r\n while (b > 0) {\r\n var temp = a;\r\n a = b;\r\n b = temp % b;\r\n }\r\n return a;\r\n}", "function sc_lcm() {\n var lcm = 1;\n for (var i = 0; i < arguments.length; i++) {\n\tvar f = Math.round(arguments[i] / sc_euclid_gcd(arguments[i], lcm));\n\tlcm *= Math.abs(f);\n }\n return lcm;\n}", "function smallestCommons(arr) {\r\n var scm = 0,\r\n tryAgain = true;\r\n\r\n arr.sort(function(a, b) {\r\n \"use strict\";\r\n return a > b;\r\n });\r\n\r\n scm = arr[0];\r\n\r\n while (tryAgain) {\r\n while(scm % arr[1] !== 0) {\r\n scm += arr[0];\r\n }\r\n\r\n for(var i = arr[0]; i <= arr[1]; i += 1) {\r\n if(scm % i !== 0) {\r\n scm += arr[0];\r\n break;\r\n }\r\n if(i === arr[1]) {\r\n tryAgain = false;\r\n }\r\n }\r\n }\r\n\r\n return scm;\r\n}", "function smallestCommons(arr) {\r\n\tstart = arr[0] < arr[1] ? arr[0] : arr[1];\r\n\tend = arr[1] > arr[0] ? arr[1] : arr[0];\r\n\tvar mult = 1;\r\n\tvar needs = (end - start) + 1;\r\n\twhile (true) {\r\n\t\thas = 0;\r\n\t\tfor (var i = start; i <= end; i++) {\r\n\t\t\tif (mult % i === 0) {\r\n\t\t\t\thas++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (has === needs) {\r\n\t\t\treturn mult;\r\n\t\t}\r\n\t\tmult++;\r\n\t}\r\n}", "function smallestCommons(arr) {\n let newArr = [];\n for(let i = Math.max(...arr); i >= Math.min(...arr); i--){\n newArr.push(i);\n }\n let odd = 1;\n if(newArr[0]%2 !== 0){\n odd = newArr[0];\n newArr.splice(0,1);\n }\n if(newArr.length === 2){\n return odd * newArr[0] * newArr[1];\n }\n\n let product = (odd * newArr[0] * newArr[1] * newArr[2]) /2;\n\n if(newArr.length === 3){\n return product;\n }else if(Math.min(...newArr) <= newArr[0]/2){\n newArr = newArr.filter(x => x > newArr[0]/2);\n if(newArr.length <= 3){\n return odd * smallestCommons(newArr);\n }\n }\n for(let i = 3; i < newArr.length; i++){\n var greatestCD = gcd(product, newArr[i]);\n product = product * newArr[i]/greatestCD;\n }\n return product;\n\n function gcd(x, y) {\n // Implements the Euclidean Algorithm\n if (y === 0)\n return x;\n else\n return gcd(y, x%y);\n }\n}", "function lcm_more_than_two_numbers(input_array) {\n if (toString.call(input_array) !== \"[object Array]\") \n return false; \n var r1 = 0, r2 = 0;\n var l = input_array.length;\n for(i=0;i<l;i++) {\n r1 = input_array[i] % input_array[i + 1];\n if(r1 === 0) {\n input_array[i + 1] = (input_array[i] * input_array[i+1]) / input_array[i + 1];\n }\n else {\n r2 = input_array[i + 1] % r1;\n if(r2 === 0) {\n input_array[i + 1] = (input_array[i] * input_array[i + 1]) / r1;\n }\n else {\n input_array[i+1] = (input_array[i] * input_array[i + 1]) / r2;\n }\n }\n }\n return input_array[l - 1];\n}", "function bgstdivisorskp2 (n) {\n\tvar number = n, divisor,sqrt;\n\n\twhile ( number % 2 == 0 ) { \n\t\tnumber /= 2;\n\t}\n\n\tif (number < 1) return 2;\n\n\tdivisor = 3;\n\tsqrt = Math.sqrt(n);\n\twhile ( number > 1 && divisor < sqrt ) { //when reaches biggest factor, number will be 0;\n\t\tif ( number % divisor == 0 ) {\n\t\t\tnumber /= divisor;\n\t\t\tdivisor -= 2;//Try this factor again...\n\t\t}\n\t\tdivisor += 2; //Skip over even numbers\n\t}\n\treturn divisor;\n}", "function gcd(a, b) {\n\tvar t;\t\t\t\t\t\t\t\t\t\t// variavel temp para troca de valores\n\tif (a < b) t=b, b=a, a=t;\t\t\t\t\t// garante que a >= b\n\twhile (b != 0) t=b, b=a%b, a=t;\t\t\t\t// algoritmo de Euclides para MDC\n\treturn a;\n}", "function lcm(a, b) {\n return (a * b) / gcd(a, b); \n }", "function Division(num1, num2) {\n var greatestSoFar = 1;\n var min = Math.min(num1, num2);\n for(var i = 2; i <= min; i++) {\n if(num1%i === 0 && num2%i === 0) {\n greatestSoFar = i;\n }\n }\n return greatestSoFar;\n}", "function smallestCommons(arr) {\n var workArr = [];\n for (var x = Math.min(arr[0], arr[1]); x <= Math.max(arr[0], arr[1]); x++) {\n workArr.push(x);\n }\n //Euclidean Algorithm maybe... Math isn't my thing\n function gcd(a, b) {\n return !b ? a : gcd(b, a % b);\n }\n \n function lcm(a, b) {\n return (a * b) / gcd(a, b); \n }\n\n var smallestCommon = workArr[0];\n workArr.forEach(function(n) {\n smallestCommon = lcm(smallestCommon, n);\n console.log(smallestCommon)\n });\n\n return smallestCommon;\n}", "function gcd(num1, num2) {\n\n}", "function gcdMoreThanTwoNum(input){\n if (toString.call(input) !== \"[object Array]\"){\n return false;\n }\n var len, a, b;\n len = input.length;\n if (!len){\n return null;\n }\n a = input[0];\n for (var i=1; i<len; i++){\n b = input[i];\n a = gcdTwoNum(a, b);\n }\n return a;\n}", "function gcdTwoNum(m, n){\n var result = [];\n var limit = Math.max(Math.min(m, n), Math.floor(Math.max(m, n)/2));\n for (var i=1; i<=limit; i++ ){\n if(m % i === 0 && n % i === 0){\n result.push(i);\n }\n }\n return Math.max.apply(null, result);\n}", "function findFactor (target) {\n const targetSqrt = Math.ceil(Math.sqrt(target)), // Maximum possible prime factor\n resultMax = targetSqrt % 2 === 0 ? targetSqrt + 1 : targetSqrt; // If sqrt is even, use sqrt + 1 (odd)\n\n // Check all odd numbers from resultMax to 3\n for (let i = resultMax; i > 2; i -= 2) {\n\n // If candidate is divisible by target and is prime, return candidate\n if (target % i == 0 && isPrime(i)) return i;\n }\n \n // If no larger factor was found\n if (target % 2 === 0) return 2;\n return 1;\n}", "function lcm(num1, num2) {\n if ((num1 === 2 || num2 === 2) || (num1 === 1 || num2 === 1)) return num1 * num2;\n\n if (num1 % 2 === 0) return (num1 / 2) * num2;\n\n if (num2 % 2 === 0) return (num2 / 2) * num1;\n\n if (num1 % 2 !== 0 && num2 % 2 !== 0) return num1 * num2;\n}", "function gcd_more_than_two_numbers(input) {\n if (toString.call(input) !== \"[object Array]\") \n return false; \n var len, a, b;\n len = input.length;\n if ( !len ) {\n return null;\n }\n a = input[ 0 ];\n for ( var i = 1; i < len; i++ ) {\n b = input[ i ];\n a = gcd_two_numbers( a, b );\n }\n return a;\n }", "function gcd(a, b)\n{\n\t// a should be largest\n\tif (a < b)\n\t{\n\t\t[a, b] = [b, a];\n\t}\n\t\n\twhile (b !== 0)\n\t{\n\t\tconst t = b;\n\t\tb = a % b;\n\t\ta = t;\n\t}\n\treturn a;\n}", "function smallestCommons(arr) {\n function multipleArr(num) {\n return Array.from(\n {\n length: 10000\n },\n (v, k) => k * num\n );\n }\n\n function divideLst(arr, step) {\n let start = Math.min(arr[0], arr[1]);\n let end = Math.max(arr[0], arr[1]);\n return Array.from(\n {\n length: (end - start) / step + 1\n },\n (_, i) => start + i * step\n );\n }\n var lst1 = multipleArr(arr[0]);\n var lst2 = multipleArr(arr[1]);\n var divider = divideLst(arr, 1);\n var multLst = [];\n for (let i = 0; i < lst1.length; i++) {\n if (lst2.indexOf(lst1[i]) > 0) {\n multLst.push(lst1[i]);\n }\n }\n for (let x = 0; x < multLst.length; x++) {\n for (let y = 0; y < divider.length; y++) {\n if (multLst[x] % divider[y] !== 0) {\n delete multLst[x];\n }\n }\n }\n return multLst.filter(Boolean)[0];\n}", "function lcm(num1, num2) {\n if (num1 === 2 || num2 === 2) {\n return num1 * num2;\n } else if (num1 === 1 || num2 === 1) {\n return num1 * num2;\n } else if (num1 % 2 === 0) {\n return (num1 / 2) * num2;\n } else if (num2 % 2 === 0) {\n return (num2 / 2) * num1;\n } else if (num1 % 2 !== 0 && num2 % 2 !== 0) {\n return num1 * num2;\n }\n}", "function gcd(a, b) {\r\n if (b > a) return gcd(b, a)\r\n if (b === 0) return a\r\n return gcd(b, a % b)\r\n}", "function smallestCommons(arr) {\n let lcm = (a, b) => {\n let gcd = (a, b) => {\n let min = Math.min(a, b);\n let max = Math.max(a, b);\n while (min !== 0) {\n let c = max % min;\n max = min;\n min = c;\n }\n return max;\n };\n return a * b / gcd(a, b);\n };\n return Array.from({length: Math.max(...arr) - Math.min(...arr) + 1 }, (_, v) => v + Math.min(...arr))\n .reduce((p, v) => lcm(p, v));\n}", "function LCF(n1, n2) {\n while (n1 !== n2) {\n if (n1 > n2) {\n n1 = n1 - n2;\n } else {\n n2 = n2 - n1;\n }\n }\n return n1;\n}", "function findLCM([input1, input2]) {\n let multiples = [];\n if (input1 < input2) {\n for (let i = input1; i <= input2; i++) {\n for (let j = 0; j < 1000; j++) {\n if (j * i) {\n multiples.push(j);\n }\n }\n }\n }\n if (input1 > input2) {\n for (let i = input2; i <= input1; i++) {\n for (let j = 0; j < 1000; j++) {\n if (j * i) {\n multiples.push(j);\n }\n }\n }\n }\n return Math.min.apply(null, multiples);\n}", "function gcd_two_numbers(x, y) {\n if ((typeof x !== 'number') || (typeof y !== 'number')) \n return false;\n x = Math.abs(x);\n y = Math.abs(y);\n while(y) {\n var t = y;\n y = x % y;\n x = t;\n }\n return x;\n }", "function leastCommonMultiple(min, max) {\n function range(min, max) {\n var arr = [];\n for (var i = min; i <= max; i++) {\n arr.push(i);\n }\n return arr;\n }\n\n function gcd(a, b) {\n return !b ? a : gcd(b, a % b);\n }\n\n function lcm(a, b) {\n return (a * b) / gcd(a, b);\n }\n\n var multiple = min;\n range(min, max).forEach(function (n) {\n multiple = lcm(multiple, n);\n });\n\n return multiple;\n}", "lcm(a, b) {\n return a.mul(b).div(integer.gcd(a, b)).toInteger();\n }", "function lessCommonMultiplier(a, b) {\n return (a * b) / greatestCommonDivisor(a, b);\n}", "function lcmTwoNumbers(x, y) {\n if ((typeof x !== 'number') || (typeof y !== 'number'))\n return false;\n return (!x || !y) ? 0 : Math.abs((x * y) / lcmTwoNumbers(x, y));\n}", "function gcd(firstNumber, secondNumber) {\n var gcdArray = []\n\n for (var i = 0; i <= secondNumber; i++){\n if( (firstNumber % i == 0) && (secondNumber % i == 0)){\n gcdArray.push(i)\n }\n }\n\n var orderedArray = gcdArray.reverse()\n\n return orderedArray[0]\n}", "function smallestCommons(arr) {\n let smallestMult = 0\n let range = []\n for (let i = Math.min(...arr); i <= Math.max(...arr); i++) {\n range.push(i)\n }\n\n while (true) {\n smallestMult += range[range.length - 1]\n let check = false\n for (let i = 0; i < range.length; i++) {\n if (smallestMult%range[i] !== 0) {\n break\n }\n if (i === range.length -1) {\n check = true\n }\n }\n if (check) {\n break\n }\n }\n console.log(smallestMult)\n return smallestMult;\n}", "function smallestCommons(arr) {\n\tvar lCM;\n\tvar myArr = [];\n\tif (arr[1] < arr[0]) {\n\t\tmyArr.push(arr[1]);\n\t\tmyArr.push(arr[0]);\n\t} else {\n\t\tmyArr = arr;\n\t}\n\tvar allNumsArr = [];\n\tfor (var i = myArr[0]; i <= myArr[1]; i++) {\n\t\tallNumsArr.push(i);\n\t}\n\n\tvar numsToMultiply = [];\n\n\tfor (var j = 10; j > 0; j--) {\n\t\tvar passed = allNumsArr.every(function (currVal) {\n\t\t\treturn currVal % j === 0;\n\t\t});\n \n\t\t//numsToMultiply.push(j);\n\t\tallNumsArr = allNumsArr.map(function (e) {\n\t\t\tif (e % j === 0) {\n\t\t\t\treturn e / j;\n\t\t\t} else {\n\t\t\t\treturn e;\n\t\t\t}\n\t\t});\n\n\t}\n\n\n\n}", "function lcm (A, B) {\n let min = Math.min(A, B)\n while(true) {\n if(min % A === 0 && min % B === 0) {\n return min\n } \n min++\n }\n}", "function smallestCommons(arr) {\n // sort arr in an ascending order\n arr = arr.sort((a, b) => a - b);\n // create an arr that holds all number between the two nums\n const newArr = [];\n for (let i = arr[0]; i <= arr[1]; i++) newArr.push(i);\n // iterate thru the 2nd arr\n for (let num = arr[0]; num < Infinity; num++) {\n // check if the num is divisible by all num in arr\n let isDivisible = newArr.every((el) => num % el === 0);\n // return the num\n if (isDivisible) return num;\n }\n}", "function smallestCommons(arr) {\n let multiplier = 1;\n let result = 0;\n const max = Math.max(...arr);\n\n while (true) {\n result = max * multiplier;\n let isCommon = true;\n for (let min = Math.min(...arr); min < max; min++) {\n // console.log('result',result,'min',min)\n if (result % min !== 0) {\n isCommon = false;\n break;\n }\n }\n if (isCommon) return result;\n multiplier++;\n }\n}", "function smallestCommons(arr) {\n let beginRange = Math.min(...arr);\n let endRange = Math.max(...arr);\n let smallesCommonMultiple = beginRange;\n for (let i = Math.min(endRange, beginRange + 1); i <= endRange; i++) {\n smallesCommonMultiple = lcm(smallesCommonMultiple, i);\n }\n return smallesCommonMultiple;\n}", "function numberMax(n1, n2) {\n // bit problem\n}", "function gcd(a,b)\n{\nif (b == 0)\n {return a}\nelse\n {return gcd(b, a % b)}\n}", "function gcd(testVariable1, testVariable2) {\nlet value=0;\nfor(let i = 0; i< testVariable1; i++){\n for(let j= 0; j < testVariable2;j++){\n\n if((testVariable1%i==0)&&(testVariable2%j==0)){\n value=i;\n }\n }\n}\n\n return value;\n}", "function commonFactors(num1, num2) {\n var num1Factors = factors(num1);\n var num2Factors = factors(num2);\n var result = [];\n\n for (var i = 0; i < num1Factors.length; i++) {\n var ele1 = num1Factors[i];\n\n for (var j = 0; j < num2Factors.length; j++) {\n var ele2 = num2Factors[j];\n\n if (ele1 === ele2) {\n result.push(ele1);\n }\n }\n }\n\n return result;\n}", "function gcd(a,b) {\n if (Math.floor(a)!=a || Math.floor(b)!=b) return 1; // se i numeri non sono interi restituisce 1\n a = Math.abs(a); b = Math.abs(b);\n if (b > a)\n b = (a += b -= a) - b; // scambia le variabili in modo che b<a\n while (b !== 0) {\n var m = a % b;\n a = b;\n b = m;\n }\n return a;\n}", "function largestPrimeFactor(number) {\n var divider = 2;\n while (divider !== number && divider * divider <= number) {\n if (number % divider === 0) {\n number /= divider;\n } else {\n divider++;\n }\n }\n\n return number;\n}", "function lcmOfTwo(m, n){\n //check type is number\n return (!m || !n) ? 0 : Math.abs(m * n) / gcdTwoNum(m, n);\n}", "function leastFactor(composite) {\n\n // if (isNaN(n) || !isFinite(n)) return NaN;\n\n if (composite === 0n) return 0n;\n if (composite % 1n || composite*composite < 2n) return 1n;\n if (composite % 2n === 0n) return 2n;\n if (composite % 3n === 0n) return 3n;\n if (composite % 5n === 0n) return 5n;\n\n for (let i = 7n; (i * i) < composite; i += 30n) {\n if (composite % i === 0n) return i;\n if (composite % (i + 4n) === 0n) return i + 4n;\n if (composite % (i + 6n) === 0n) return i + 6n;\n if (composite % (i + 10n) === 0n) return i + 10n;\n if (composite % (i + 12n) === 0n) return i + 12n;\n if (composite % (i + 16n) === 0n) return i + 16n;\n if (composite % (i + 22n) === 0n) return i + 22n;\n if (composite % (i + 24n) === 0n) return i + 24n;\n }\n\n // it is prime\n return composite;\n}", "function largestPrimeFactor(number) {\n if(isPrime(number)) return number\n \n let sqrt = Math.floor(Math.sqrt(number))\n \n sqrt = sqrt % 2 === 0 ? sqrt + 1 : sqrt\n \n for( let i = sqrt; i >= 1; i-= 2){\n if(((number % i) === 0) && isPrime(i)){\n return i\n }\n }\n }", "function largestPrimeFactor(number) {\n if (number % 2 === 0) {\n return 2;\n }\n let arrayOfPrimeFctors = [];\n let i = 3;\n while(number != 1) {\n if (number % i === 0) {\n number /= i;\n arrayOfPrimeFctors.push(i);\n } else {\n i += 2;\n }\n }\n return arrayOfPrimeFctors[arrayOfPrimeFctors.length - 1];\n }", "function smallestCommons(arr) {\r\n let max = Math.max(...arr);\r\n let min = Math.min(...arr);\r\n\r\n //Start with result = max (smallest possible common multiple) and decrement through array \r\n let result = max;\r\n for (let i = max; i >= min; i--) {\r\n //if not divisible, jump to next increment of the array max and restart for loop\r\n if (result % i) {\r\n result += max; \r\n i = max; //Need to set i back to max because may not be not finished with loop\r\n }\r\n }\r\n //will exit loop when everything is divisible by result\r\n return result;\r\n}", "function gcd(a, b) {\r\n /**Return the greatest common divisor of the given integers**/\r\n if (b == 0) {\r\n return a;\r\n } else {\r\n return gcd(b, a % b);\r\n }\r\n }", "function leastCommonMultiple(arr) {\n if (arr.length == 1) {\n return arr[0];\n }\n for (let i = 0; i < arr.length - 1; i++) {\n arr[i + 1] = (arr[i] * arr[i + 1]) / (greatestCommonDenominator([arr[i], arr[i + 1]]));\n }\n return arr[arr.length - 1];\n }", "function GCDivisor(a ,b){\n if (b == 0){\n return a;\n } else {\n return GCDivisor(b, a % b)\n }\n}", "worstSatisfactionDegree() {\n\t\tlet cs = 1;\n\t\tfor (const c of this._cons) {\n\t\t\tconst s = c.satisfactionDegree();\n\t\t\tif (s === Constraint.UNDEFINED) return Constraint.UNDEFINED;\n\t\t\tif (s < cs) cs = s;\n\t\t}\n\t\treturn cs;\n\t}" ]
[ "0.79636997", "0.7768438", "0.7726953", "0.71830165", "0.7154436", "0.71394604", "0.71362287", "0.7019485", "0.701093", "0.69473815", "0.69366544", "0.6888408", "0.6885753", "0.6877195", "0.6808772", "0.67977816", "0.67941904", "0.6786153", "0.6780309", "0.6754238", "0.6741573", "0.6738339", "0.6713983", "0.6687162", "0.6658514", "0.665445", "0.6650897", "0.66329026", "0.661821", "0.6613462", "0.66110915", "0.6606781", "0.6599579", "0.65930945", "0.6588524", "0.65833014", "0.656331", "0.65600806", "0.65457094", "0.6540028", "0.6528918", "0.6502553", "0.64943904", "0.64845943", "0.64729756", "0.64702564", "0.64608973", "0.64607954", "0.64488494", "0.64456505", "0.6442418", "0.6406187", "0.6402957", "0.64022005", "0.6400367", "0.63931537", "0.63927054", "0.6392512", "0.6392171", "0.6388916", "0.63823205", "0.6357512", "0.63536626", "0.63448894", "0.63411367", "0.63405615", "0.6339236", "0.6334454", "0.632286", "0.6299594", "0.62976557", "0.6287049", "0.6281577", "0.62735915", "0.6263756", "0.62602764", "0.6249681", "0.6245952", "0.6245143", "0.6237298", "0.6223867", "0.6210054", "0.6206302", "0.62040406", "0.619018", "0.6188789", "0.61822236", "0.6182064", "0.6179287", "0.6174198", "0.61672676", "0.6164711", "0.614708", "0.61448514", "0.61382926", "0.61271006", "0.6117819", "0.6083486", "0.60829276", "0.6069306" ]
0.8107598
0
calculate2 the sum of the two fractions
function calculate2(radius){ var angle2 = 2 * Math.PI /commonMultiple2; x2 = canvas2.width/3; y2 = canvas2.height*2/3; var j= 0; var i= 0; if(j<number2){ context2.fillStyle = '#f00'; context2.fillText('=', 100,280); for(i=0; i < commonMultiple2; i++){ context2.beginPath(); context2.moveTo(x2+150*j, y2); context2.arc(x2+150*j, y2, radius, i*angle2, (i +1)*angle2, false); context2.lineWidth = segmentDepth2; context2.fillStyle = '#C45AEC'; context2.fill(); context2.lineWidth = 2; context2.strokeStyle = '#444'; context2.stroke(); } } if (newresNumerator2!==0){ context2.fillStyle = '#f00'; context2.fillText('=', 100,280); for(i=0; i < commonMultiple2; i++){ context2.beginPath(); context2.moveTo(x2 +150+150*j,y2); context2.arc(x2 +150+ 150*j, y2, radius, i*angle2, (i +1)*angle2, false); context2.lineWidth = segmentDepth2; if(i<newresNumerator2){ context2.fillStyle = '#C45AEC'; }else{ context2.fillStyle = '#fff'; } context2.fill(); context2.lineWidth = 2; context2.strokeStyle = '#444'; context2.stroke(); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function calculate(num1, num2) {\n var suma = returnNumberIntOrWithDecimal(num1 + num2);\n result.push(num1 + \" + \" + num2 + \" = \" + suma);\n\n var resta = returnNumberIntOrWithDecimal(num1 - num2);\n result.push(num1 + \" - \" + num2 + \" = \" + resta);\n\n var mult = returnNumberIntOrWithDecimal(num1 * num2);\n result.push(num1 + \" * \" + num2 + \" = \" + mult);\n\n var div = returnNumberIntOrWithDecimal(num1 / num2);\n result.push(num1 + \" / \" + num2 + \" = \" + div);\n}", "function divison(num1, num2) {\n var divisonTotal = num1 / num2;\n return divisonTotal;\n}", "function equation2(num1, num2) {\n var total = num1 + num2;\n var avg = total /2;\n console.log(avg);\n}", "function divise(nbr1, nbr2){\n\t\tif(nbr2 == 0){\n\t\t\tresultat = \"math error !\"\n\t\t}else{\n\t\t\tresultat = nbr1 / nbr2;\n\t\t}\n\n\t}", "function calculate(n1, op, n2) {\n switch (op) {\n case '+':\n return n1 + n2;\n case '-':\n return n1 - n2;\n case '/':\n return n2 !== 0 ? n1 / n2 : null;\n case '*':\n return n1 * n2;\n default:\n return null;\n }\n}", "function cal(num1,num2,op){\n let y ;\n if(op == \"*\"){\n return duplicate(num1,num2);\n }\n else if(op == \"/\"){\n return division(num1,num2);\n }\n else if(op == \"-\"){\n y = num1.valueOf() - num2.valueOf(); \n return y.toString();\n }\n else if(op == \"+\"){\n num1 = parseFloat(num1);\n num2 = parseFloat(num2);\n y = num1+ num2;\n return y.toString();\n }\n\n }", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function fraction(a, b) {\n var k = a / (a + b);\n if (k > 0 && k < 1) {\n var t0, t1 = Math.pow(12 * k * Math.PI, 1 / 3);\n for (var i = 0; i < 10; ++i) { // Solve for theta numerically.\n t0 = t1;\n t1 = (Math.sin(t0) - t0 * Math.cos(t0) + 2 * k * Math.PI) / (1 - Math.cos(t0));\n }\n k = (1 - Math.cos(t1 / 2)) / 2;\n }\n return k;\n}", "function calc2(var1, var2) {\n var total = var1 + var2;\n return total;\n}", "function division(num1, num2){\n return -1;\n }", "function division(n1 ,n2){\n\tverify(n1, n2 );\t\n\tif(isZero(n2)){\n\t\tthrow new Error(\"division by 0\");\n\t}\n\tif(isZero(n1)){\n\t\treturn \"0\";\n\t}\n\tlet result = \"0\";\n\tlet isResultNegative = (!isNegative(n1)&&isNegative(n2))||(isNegative(n1)&&!isNegative(n2));\n\tif(n2===\"1\"){\n\t\treturn n1;\n\t}else if(n2===\"-1\"){\n\t\treturn isNegative(n1)?convertToPositive(n1):convertToNegative(n1);\n\t}\n\tn1 = convertToPositive(n1);\n\tn2 = convertToPositive(n2);\n\tlet i = n1;\n\tdo{\n\t\ti = minus(i, n2);\n\t\tif(!isNegative(i)){\n\t\t\tresult = plus(result, \"1\");\n\t\t}\n\t}while(!isNegative(i)&&!isZero(i));\n\tif(isResultNegative){\n\t\tresult = convertToNegative(result);\n\t}\n\treturn result;\t\n}", "function mathResaults(num1, num2) {\n console.log(num1, num2);\n console.log(num1 + num2);\n if(num1 <= num2){\n console.log(num2 - num1);\n } else {\n console.log(num1 - num2);\n }\n console.log(num1 * num2);\n if(num1 <= num2){\n console.log(num2 / num1);\n } else {\n console.log(num1 / num2);\n }\n console.log(num1 % num2);\n console.log(num2 % num1);\n}", "function diviser(n1,n2){\n if(n2 != 0){\n ajouterHistorique(n1 + ' ÷ ' + n2);\n return n1 / n2;\n }else{\n return '∞';\n }\n}", "add(val) {\r\n let a = ((this.a * val.b) + (val.a * this.b));\r\n let b = (this.b * val.b);\r\n if(a==0){ return new Rational(0,1) }\r\n return new Rational(a,b)\r\n }", "function avr(a,b) {\n return (a+b)/2;\n \n}", "function calculate(num1, num2) {\n return toBase10(num1) + toBase10(num2)\n}", "function calcular(){\r\n num1 = parseFloat(num1);\r\n num2 = parseFloat(num2);\r\n switch(operador){\r\n case operacion.SUMAR:\r\n num1+=num2;\r\n break;\r\n case operacion.RESTAR:\r\n num1 = num1-num2;\r\n break;\r\n case operacion.MULTIPLICAR:\r\n num1*=num2;\r\n break;\r\n case operacion.DIVIDIR:\r\n num1 = (num1/num2);\r\n break;\r\n case operacion.PORTENCIA:\r\n num1 = Math.pow(num1,num2);\r\n break;\r\n }\r\n actualizarValor1();\r\n num2 = 0;\r\n actualizarValor2();\r\n}", "function divide(num1, num2 = 0) {\n const total = num1 + num2;\n return total;\n}", "function calculatePoints(p1, p2, result){\n\tvar q1 = Math.pow(10, p1.points / 400);\n\tvar q2 = Math.pow(10, p2.points / 400);\n\tvar esperado = q1 / (q1 + q2);\n\tvar nivel = obtenerNivel(p1);\n\tvar res = p1.points + (nivel * (result - esperado));\n\tif ( res > 0 )\n\t\treturn res;\n\telse\n\t\treturn 0;\n}", "function calcSum(num1, num2) {\n const sum = num1 + num2;\n return sum;\n}", "function calc(op, n1, n2) {\n var result = 0;\n switch (op) {\n case \"+\":\n result = n1 + n2;\n break;\n case \"-\":\n result = n1 - n2;\n break;\n case \"x\":\n result = n1 * n2;\n break;\n case \"/\":\n result = n1 / n2;\n break;\n }\n return result;\n}", "function calculateRatio(l1, l2) {\n\t\treturn l1 > l2 ? l1 / l2 : l2 / l1;\n\t}", "function calculate(first, second, operator) {\n switch (operator) {\n case '+':\n return Number(first) + Number(second);\n break;\n case '-':\n return Number(first) - Number(second);\n break;\n case '*':\n return Number(first) * Number(second);\n break;\n case '/':\n return Number(first) / Number(second);\n break;\n }\n}", "function subOddNumb(num1,num2) {\n \n var sum1 = 0;\n var sum2 = 0;\n \n for ( var i = 1; i <= num1; i++) {\n if ( i % 2 === 0) {\n sum1 += i;\n }\n }\n for ( var j = 1; j <= num2; j++) {\n if ( j % 2 !== 0 ) {\n sum2 += j;\n }\n }\n \n return (sum1 - sum2) * 12.5;\n}", "function summation2(num) {\n return num * (num + 1) / 2\n }", "function calculadora(num1,num2,operador){\n if (operador=='+') \n {return num1+num2}\n if (operador=='-') \n {return num1-num2}\n if (operador=='/' && num2!=0) \n {return num1/num2}\n if(operador=='*') \n {return num1*num2}\n else{return 'nunca dividiras por 0'}\n \n}", "function doMath(num1 ,num2 , operator) {\n if (num2 == null) {\n if(totalInt2 == null){\n totalInt2 = parseFloat(num1);\n }\n num2 = totalInt2;\n storeNum2 = parseFloat(num2);\n\n }\n if (operator == \"+\") {\n num1 = parseFloat(num1) + parseFloat(num2);\n }\n else if (operator == \"-\") {\n num1 = parseFloat(num1) - parseFloat(num2);\n }\n else if (operator == \"/\") {\n if(num2 == 0){\n $(\"#displayScreen p\").text(\"Error\");\n totalInt2 = null;\n return;\n }\n num1 = parseFloat(num1) / parseFloat(num2);\n }\n else if (operator == \"X\") {\n num1 = parseFloat(num1) * parseFloat(num2);\n }\n return num1.toFixed(3);\n}", "function getResult(val1, val2, operation) {\n\t\tif (operation === '+') {\n\t\t\treturn val1 + val2;\n\t\t} else if (operation === '-') {\n\t\t\treturn val1 - val2;\n\t\t} else if (operation === '*') {\n\t\t\treturn val1 * val2;\n\t\t} else {\n\t\t\treturn val1 / val2;\t\n\t\t} \n\t}", "function doCalculation(num1, num2) {\n var result;\n switch (operation) {\n case \"add\":\n result = num1 + num2;\n break;\n case \"subtract\":\n result = num1 - num2;\n break;\n case \"multiply\":\n result = num1 * num2;\n break;\n case \"divide\":\n if (num2 !== 0) {\n result = num1 / num2;\n } else {\n result = \"Division by zero\";\n calcComplete = true;\n }\n break;\n }\n // Note - can't do parseFloat here because text is returned in the case of division by 0.\n return result;\n }", "function calculated (operator, a, b) {\n if (operator === '+') {\n return Math.round((a + b) * 1000000) / 1000000\n } else if (operator === '-') {\n return Math.round((a - b) * 1000000) / 1000000\n } else if (operator === '*') {\n return Math.round((a * b) * 1000000) / 1000000\n } else if (operator === '/') {\n return Math.round((a / b) * 1000000) / 1000000\n }\n }", "function formula(var1, var2) {\r\n return var1 + var2 + factor;\r\n}", "function calculateNum(firstNumber, operator, secondNumber) {\n if (operator === '+') { //.toFixed to round to 1 decimal point\n result = (firstNumber + secondNumber).toFixed(1);\n } else if (operator === '-') {\n result = (firstNumber - secondNumber).toFixed(1);\n } else if (operator === '*') {\n result = (firstNumber * secondNumber).toFixed(1);\n } else if (operator === '/') {\n result = (firstNumber / secondNumber).toFixed(1);\n }\n return result;\n}", "function addAndReturn2DecimalPlaces(num1, num2) {\n return result = Number((num1+num2).toFixed(2));;\n}", "function calculating (num1,num2){\n\n\n\t// Compruebo si los dos numeros han sido validados como tales y en caso afiramtivo los calculo\n\tif (numberValidation(num1) == true && numberValidation(num2) == true) {\n\n\t\t\tresultsA[0] = Number(num1) + Number(num2)\n\t\t\tresultsA[1] = num1 - num2\n\t\t\tresultsA[2] = num1 / num2\n\t\t\tresultsA[3] = num1 * num2\n\n\t\t\tconsole.log('Suma: ' + decimalComprobation(resultsA[0]) + '.');\n\t\t\tconsole.log('Resta: ' + decimalComprobation(resultsA[1]) + '.');\n\t\t\tconsole.log('Division: ' + decimalComprobation(resultsA[2]) + '.');\n\t\t\tconsole.log('Multiplication: ' + decimalComprobation(resultsA[3]) + '.');\n\n\n\t//Ahora hago la validacion para primer numero\n\t} else if (numberValidation(num1) == true) {\n\t\t\n\t\t\tresultsB[0] = Math.sqrt(num1);\t\n\t\t\tconsole.log('Square root of first number is: ' + decimalComprobation(resultsB[0]))\t\t\n\n\t// Ahora la el segundo\n\t} else if (numberValidation(num2) == true) {\n\n\t\t\tresultsB[1] = Math.sqrt(num2);\n\t\t\tconsole.log('Square root of second number is: ' + decimalComprobation(resultsB[1]))\n\n\t//Si ninguno de los valores pasan la validacion, salta el mensaje que pide introducir numeros!\n\t} else {\n\n\t\t\talert('Please, use only numbers!');\n\t}\n}", "function div(num1,num2)\n{\n return num1/num2;\n}", "function toDivision(num1, num2){\n let quotient = num1 / num2\n output(quotient)\n}", "function mathResults (num1, num2) {\n console.log(snum1, num2);\n\n // sum\n var sum = num1 + num2\n console.log(\"The sum of these numbers is \" + sum);\n\n //diference\n console.log(num1 - num2);\n\n //product\n var product = num1 * num2;\n console.log(product)\n\n //divided\n console.log(num1 / num2);\n\n //remainder\n var remainder = num1 % num2;\n console.log(remainder;\n\n}", "function calcular(a, b) {\r\n console.log(\"SUMA: \" + (a + b));\r\n console.log(\"RESTA: \" + (a - b));\r\n console.log(\"MULTIPLICACIÓN: \" + (a * b));\r\n console.log(\"DIVISIÓN: \" + (a / b));\r\n}", "function addSub(type, fractions) {\n\n const denominator = Math.lcm(fractions.map(frac => frac[1]));\n const numerator = fractions.map(frac => denominator / frac[1] * frac[0]).reduce((a, b) => type == 0? a + b : a - b);\n\n return Fraction.simp([numerator, denominator]);\n}", "function div2 (n1,n2) {\n return(n1%n2+10)\n}", "function calculate(num1, num2, method) {\n\tif (method === 'add' ) {\n\t\treturn num1 + num2\n\t} else if (method === 'subtract') {\n\t\treturn num1 - num2\n\t} else if (method === 'multiply') {\n\t\treturn num1 * num2\n\t} else if (method === 'divide') {\n\t\treturn num1 / num2\n\t}\n\n}", "toFraction(a, b) {\n var r = Fraction(a, b);\n if (algebraicMode && r.den == 1)\n return r.num;\n else\n return r;\n }", "function div(num1, num2) {\n return num1 / num2;\n}", "function answer(val1, val2){\n\n if(operation === '+'){return val1 + val2;}\n if(operation === '-'){return val1 - val2;}\n if(operation === 'X'){return val1 * val2;}\n if(operation === '/'){return (val1 / val2);}\n if(operation === '%'){return val1 % val2;}\n }", "function calc4(var1, var2) {\n var total = var1 + var2;\n return total;\n}", "function calcular(num1,num2,sumarCB,restarCB){\n var suma = num1 + num2;\n var resta = num1-num2;\n sumarCB(suma);\n restarCB(resta);\n}", "function findedge (l, p1 , p2) {\n var m = (p1[1] - p2[1])/(p1[0] - p2[0]);\n var b = p1[1] - m*p1[0];\n var y = l + p1[1];\n \n return [(y - b)/m, y];\n }", "function gcd(num1, num2) {\n\n}", "function Fraction(numerator, denominator)\n{\n /* double argument invocation */\n if (numerator && denominator) {\n if (typeof(numerator) === 'number' && typeof(denominator) === 'number') {\n this.numerator = numerator;\n this.denominator = denominator;\n } else if (typeof(numerator) === 'string' && typeof(denominator) === 'string') {\n // what are they?\n // hmm....\n // assume they are ints?\n this.numerator = parseInt(numerator);\n this.denominator = parseInt(denominator);\n }\n /* single-argument invocation */\n } else if (!denominator) {\n num = numerator; // swap variable names for legibility\n if (typeof(num) === 'number') { // just a straight number init\n this.numerator = num;\n this.denominator = 1;\n } else if (typeof(num) == 'string') {\n var a, b; // hold the first and second part of the fraction, e.g. a = '1' and b = '2/3' in 1 2/3\n // or a = '2/3' and b = undefined if we are just passed a single-part number\n [a, b] = num.split(' ');\n /* compound fraction e.g. 'A B/C' */\n if (isInteger(a) && b && b.match('/')) {\n return (new Fraction(a)).add(new Fraction(b));\n } else if (a && !b) {\n /* simple fraction e.g. 'A/B' */\n if (typeof(a) == 'string' && a.match('/')) {\n // it's not a whole number... it's actually a fraction without a whole part written\n var f = a.split('/');\n this.numerator = f[0]; this.denominator = f[1];\n /* string floating point */\n } else if (typeof(a) == 'string' && a.match('\\.')) {\n return new Fraction(parseFloat(a));\n /* whole number e.g. 'A' */\n } else { // just passed a whole number as a string\n this.numerator = parseInt(a);\n this.denominator = 1;\n }\n } else {\n return undefined; // could not parse\n }\n }\n }\n this.normalize();\n}", "function sumOfTwoNumbers() {}", "function calculate(firstNum, secondNum, operator) {\n\tswitch(operator) {\n\t\tcase \"+\":\n\t\t\treturn firstNum + secondNum;\n\t\tcase \"-\":\n\t\t\treturn firstNum - secondNum;\n\t\tcase \"*\":\n\t\t\treturn firstNum * secondNum;\n\t\tcase \"/\":\n\t\t\treturn firstNum / secondNum;\n\t\tdefault:\n\t\t\tthrow \"Incorrect Operator\";\n\t}\n}", "function add(nbr1, nbr2){\n\t\tresultat = Number(nbr1) + Number(nbr2);\n\t}", "function penjumlahanDuaBujurSangkar(a, b) {\n\n let total = a * a + b * b;\n\n return total;\n}", "function revDivided(v1,v2){\r\n //return v1/v2;\r\n console.log(v1/v2);\r\n }", "function mask_add(m1, m2, kk, b, gfc, shortblock) {\n var ratio;\n\n if (m2 > m1) {\n if (m2 < (m1 * ma_max_i2))\n ratio = m2 / m1;\n else\n return (m1 + m2);\n } else {\n if (m1 >= (m2 * ma_max_i2))\n return (m1 + m2);\n ratio = m1 / m2;\n }\n\n /* Should always be true, just checking */\n assert(m1 >= 0);\n assert(m2 >= 0);\n\n m1 += m2;\n //if (((long)(b + 3) & 0xffffffff) <= 3 + 3) {\n if ((b + 3) <= 3 + 3) {\n /* approximately, 1 bark = 3 partitions */\n /* 65% of the cases */\n /* originally 'if(i > 8)' */\n if (ratio >= ma_max_i1) {\n /* 43% of the total */\n return m1;\n }\n\n /* 22% of the total */\n var i = 0 | (Util.FAST_LOG10_X(ratio, 16.0));\n return m1 * table2[i];\n }\n\n /**\n * <PRE>\n * m<15 equ log10((m1+m2)/gfc.ATH.cb[k])<1.5\n * equ (m1+m2)/gfc.ATH.cb[k]<10^1.5\n * equ (m1+m2)<10^1.5 * gfc.ATH.cb[k]\n * </PRE>\n */\n var i = 0 | Util.FAST_LOG10_X(ratio, 16.0);\n if (shortblock != 0) {\n m2 = gfc.ATH.cb_s[kk] * gfc.ATH.adjust;\n } else {\n m2 = gfc.ATH.cb_l[kk] * gfc.ATH.adjust;\n }\n assert(m2 >= 0);\n if (m1 < ma_max_m * m2) {\n /* 3% of the total */\n /* Originally if (m > 0) { */\n if (m1 > m2) {\n var f, r;\n\n f = 1.0;\n if (i <= 13)\n f = table3[i];\n\n r = Util.FAST_LOG10_X(m1 / m2, 10.0 / 15.0);\n return m1 * ((table1[i] - f) * r + f);\n }\n\n if (i > 13)\n return m1;\n\n return m1 * table3[i];\n }\n\n /* 10% of total */\n return m1 * table1[i];\n }", "function mask_add(m1, m2, kk, b, gfc, shortblock) {\n var ratio;\n\n if (m2 > m1) {\n if (m2 < (m1 * ma_max_i2))\n ratio = m2 / m1;\n else\n return (m1 + m2);\n } else {\n if (m1 >= (m2 * ma_max_i2))\n return (m1 + m2);\n ratio = m1 / m2;\n }\n\n /* Should always be true, just checking */\n assert(m1 >= 0);\n assert(m2 >= 0);\n\n m1 += m2;\n //if (((long)(b + 3) & 0xffffffff) <= 3 + 3) {\n if ((b + 3) <= 3 + 3) {\n /* approximately, 1 bark = 3 partitions */\n /* 65% of the cases */\n /* originally 'if(i > 8)' */\n if (ratio >= ma_max_i1) {\n /* 43% of the total */\n return m1;\n }\n\n /* 22% of the total */\n var i = 0 | (Util.FAST_LOG10_X(ratio, 16.0));\n return m1 * table2[i];\n }\n\n /**\n * <PRE>\n * m<15 equ log10((m1+m2)/gfc.ATH.cb[k])<1.5\n * equ (m1+m2)/gfc.ATH.cb[k]<10^1.5\n * equ (m1+m2)<10^1.5 * gfc.ATH.cb[k]\n * </PRE>\n */\n var i = 0 | Util.FAST_LOG10_X(ratio, 16.0);\n if (shortblock != 0) {\n m2 = gfc.ATH.cb_s[kk] * gfc.ATH.adjust;\n } else {\n m2 = gfc.ATH.cb_l[kk] * gfc.ATH.adjust;\n }\n assert(m2 >= 0);\n if (m1 < ma_max_m * m2) {\n /* 3% of the total */\n /* Originally if (m > 0) { */\n if (m1 > m2) {\n var f, r;\n\n f = 1.0;\n if (i <= 13)\n f = table3[i];\n\n r = Util.FAST_LOG10_X(m1 / m2, 10.0 / 15.0);\n return m1 * ((table1[i] - f) * r + f);\n }\n\n if (i > 13)\n return m1;\n\n return m1 * table3[i];\n }\n\n /* 10% of total */\n return m1 * table1[i];\n }", "function percentage(a, b){\n\t var increase = b - a;\n\t var step2 = increase / a;\n\t return step2 * 100;\n\t}", "function getCalculation(num1, num2, oparetor) {\n switch (oparetor) {\n case '+':\n return num1 + num2;\n case '-':\n return num1 - num2;\n case '*':\n return num1 * num2;\n case '/':\n return num1 / num2;\n default:\n return num1 % num2;\n }\n\n}", "function calculate(operand1, operand2, operator) {\n if (operator == \"+\") {\n return operand1 + operand2;\n } else if (operator == \"-\") {\n return operand1 - operand2;\n } else if (operator == \"*\") {\n return operand1 * operand2;\n } else if (operator == \"/\") {\n return operand1 / operand2;\n }\n}", "function divide(n1, n2) {\n return n1 / n2;\n }", "function result(number1, number2) {\n if (number1 === number2) {\n return (number1 + number2) * 3;\n } else {\n return number1 + number2;\n }\n}", "function div(num1, num2) {\n\tconsole.log(\"4) \" + (num1 / num2));\n\n}", "function percentOf(num1, num2) {\r\n var result = (num1 / num2) * 100;\r\n console.log(num1 + \" is \" + result + \"% of \" + num2);\r\n return result;\r\n}", "function divide (num1,num2) {\n return num1/num2;\n}", "function add(num1, num2) {\n var cardinal = Math.pow(10, 10);\n return Math.round((num1 + num2) * cardinal) / cardinal;\n}", "function division(a, b) {\n\treturn printResult(parseInt(a) / parseInt(b));\n}", "function percentOf (num1, num2) {\n\tvar percent = (num1 / num2) * 100;\n\tconsole.log('3) ' + num1 + ' is ' + percent + '% of ' + num2 + '.');\n\treturn percent;\n}", "function divNums(n1,n2) {\n console.log(n1/n2)\n}", "function sum( num1 , num2 ) {\n return num1 + num2;\n }", "function calculate(a,b) {\n console.log('Sum:',a+b)\n console.log('Difference:',a-b)\n console.log('Product:',a*b)\n console.log('Division:',a/b)\n }", "function Calculate() {\n var a, b, h, myResult;\n\n a = document.getElementById('a').value;\n b = document.getElementById('b').value;\n h = document.getElementById('h').value;\n myResult = ((+a + +b) / 2) * +h ;\n\n document.getElementById('out').innerHTML = myResult;\n}", "function suma(o,o1,o2,oT)\n{\n\tvar t=0;\n\tif (EsReal(o.value))\n\t{\n\t\tt+=parseFloat(o.value);\n\t}\n\tif (EsReal(o1.value))\n\t{\n\t\tt+=parseFloat(o1.value);\n\t}\n\tif (o2!=null)\n\t{\n\t\tif (EsReal(o2.value))\n\t\t{\n\t\t\tt+=parseFloat(o2.value);\n\t\t}\n\t}\n\tt=redondear(t,2)\n\toT.value=t;\n}", "function divide1(a, b) {\n return a / b; \n}", "function calcul(a,b)\n\t\t{\n\t\treturn a+b;\n\t\t}" ]
[ "0.6793922", "0.6394161", "0.62732226", "0.62624997", "0.6213587", "0.61953163", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6186537", "0.6174303", "0.61528", "0.61266285", "0.6118944", "0.6118167", "0.6080256", "0.6066088", "0.60569274", "0.6033022", "0.60265183", "0.6008767", "0.6004412", "0.5954181", "0.5935758", "0.59333783", "0.59249604", "0.59207946", "0.59104615", "0.5901552", "0.5890383", "0.588989", "0.5868884", "0.5863783", "0.58559716", "0.58387846", "0.5824662", "0.582367", "0.5810173", "0.5804715", "0.5790334", "0.57840496", "0.5782427", "0.5774832", "0.57731223", "0.5765345", "0.5762704", "0.5756486", "0.5756207", "0.57481474", "0.5747709", "0.574683", "0.57411075", "0.57369435", "0.5727518", "0.5725382", "0.57236063", "0.5722911", "0.5722911", "0.5721716", "0.57167727", "0.5713918", "0.5704434", "0.5691805", "0.5691802", "0.56890666", "0.56864077", "0.56841797", "0.56838644", "0.5680644", "0.5678322", "0.5675731", "0.566536", "0.5651046", "0.5647961", "0.5645761", "0.5644288" ]
0.0
-1
should substitute clientgenerated ids in main with promises of linked ids
function mix(main, linked, linkedModel){ //Main is defined but could mix existing resources and those to create return RSVP.all(_.map(_.isArray(main) ? main : [main], function(item){ var toCreate = _.find(linked, function(l){ return _.has(l, 'id') && l.id === item; }); if (!toCreate) return item; if (toCreate.$$createPromise) return toCreate.$$createPromise; toCreate.$$createPromise = createLinked(linkedModel, _.omit(toCreate, 'id')); return toCreate.$$createPromise; })).then(function(result) { return _.isArray(main) ? result : result[0]; }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function fillInIds() {\n entityObj.curRcrds = attachTempIds(entityObj.curRcrds); //console.log(\"entityObj.curRcrds = %O\", entityObj.curRcrds)\n }", "all(inner, outer, traceId) {\n // NOTE: `reject` does not settle nested promises!\n const rootId = this.getCurrentVirtualRootContextId();\n const from = inner.map(p => getPromiseId(p)).filter(Boolean);\n // const from = getPromiseId(inner);\n const to = getPromiseId(outer);\n // if (!from || !to) {\n // this.logger.error(`resolve link failed: promise did not have an id, from=${from}, to=${to}, trace=${traceCollection.makeTraceInfo(traceId)}`);\n // }\n // else {\n return nestedPromiseCollection.addLink(PromiseLinkType.All, from, to, traceId, rootId);\n }", "function getId(){\n let newId = ids.next();\n ids.claim(newId)\n return newId\n}", "async fetch_ids() {\n\n let app = await BeetClientDB.apps.where(\"identityhash\").equals(this.identity.identityhash).first();\n let id = app.next_id;\n let new_id = await this.next_id();\n let next_hash = await CryptoJS.SHA256('' + new_id).toString();\n return {\n id: id,\n next_hash: next_hash.toString()\n };\n }", "async function getIds(){\n console.log(\"Lider caido, escogiendo nuevo lider...\")\n serversHiguer = [];\n console.log(\"Recoger Id's...\")\n await getRequest('id_server')\n chooseHiguer();\n}", "async function ids(node, s)\n{\n for(let i=0;i<=2;i++){\n await rdls(node, s, 0, i)\n\n }\n}", "function syncEntriesDownstream2(entryDetails) {\n var defer = $q.defer();\n var entries = [];\n console.log(\"aalatief - syncEntriesDownstream2 global.status = \" + global.status);\n console.log(\"aalatief - syncEntriesDownstream2 entryDetails = \" + JSON.stringify(entryDetails)); \n var promises = [];\n var listlocalid;\n var itemlocalid;\n entries.push(entryDetails.entry.entry) ;\n console.log(\"aalatief - entries =\" + JSON.stringify(entries));\n//aalatief testing \n Promise.all([dbHelper.getLocalIdFromServerId(entries.listServerId,'list'),dbHelper.getLocalIdFromServerId(entries.itemServerId,'item')]) \n \n .then(function (results) { \n console.log(\"aalatief - results = \" +JSON.stringify(results));\n })\n \n \n //aalatief calls pending entries postponed for now\n buildPromise(entryDetails, \"CREATE\").then(function (response) {\n\n console.log(\"syncEntriesDownstream server response \" + angular.toJson(response));\n\n /* syncDependentDownstream(response.data.item, response.data.retailers).then(function () {*/\n\n dbHelper.buildLocalIds2(entries).then(function (result) {\n console.log(\"serverHandlerEntryV2 localIds = \" + angular.toJson(result));\n affectedLists = result.lists;\n var insertPromises = [];\n for (var i = 0; i < entries.length; i++) {\n\n var localIds = dbHelper.getLocalIds(entries[i], result);\n console.log(\"syncEntriesDownstream entry i =\" + i + \" \" + angular.toJson(response.data.entries[i]));\n console.log(\"syncEntriesDownstream localIds =\" + angular.toJson(localIds));\n \n var retailerLocalId = '';\n var uom;\n if (entries[i].uom) {\n uom = entries[i].uom;\n } else {\n uom = \"PCS\";\n }\n\n var qty;\n if (entries[i].qty) {\n qty = entries[i].qty;\n } else {\n qty = 1.0;\n }\n console.log(\"serverHandlerEntry.syncEntriesDownstream localValues listLocalId = \" + angular.toJson(localIds));\n console.log(\"syncEntriesDownstream localValues qty = \" + qty);\n console.log(\"syncEntriesDownstream localValues uom = \" + uom);\n\n var entry = {\n /* listLocalId: listlocalid,\n itemLocalId: itemlocalid,*/\n /*itemName: localIds.itemName,\n categoryName: localIds.categoryName,*/\n quantity: qty,\n uom: uom,\n entryCrossedFlag: 0,\n deleted: 0,\n updatedFlag: 0,\n flag: 5,\n //seenFlag: 0,\n retailerLocalId: retailerLocalId,\n //retailerName: localIds.retailerName,\n language: 'EN' /*response.data.entries[i].entryServerId.language*/,\n entryServerId: entries[i].entryServerId,\n userServerId: entries[i].userServerId\n }; \n \n\n \n \n console.log(\"syncEntriesDownstream localIds =\" + JSON.stringify(entryDetails));\n $q.all([dbHelper.getLocalIdFromServerId(entries[i].listServerId,'list'),\n dbHelper.getLocalIdFromServerId(entries[i].itemServerId,'item')])\n .then(function(localId){\n listlocalid = localId[0].localId;\n itemlocalid = localId[1].localId;\n \n entry.listLocalId = listlocalid;\n entry.itemLocalId = itemlocalid;\n \n console.log(\"aalatief - syncEntriesDownstream2 localId =\" + JSON.stringify(localId));\n console.log(\"aalatief -itemlocalid: \"+itemlocalid+\" listlocalid \"+listlocalid);\n console.log(\"aalatief - entries =\" + JSON.stringify(entries[i]));\n \n \n \n \n console.log(\"syncEntriesDownstream $state.current.name = \" + $state.current.name);\n console.log(\"syncEntriesDownstream localIds.listLocalId = \" + listlocalid);\n console.log(\"syncEntriesDownstream global.currentList = \" + global.currentList);\n console.log(\"syncEntriesDownstream global.status = \" + global.status);\n\n if ($state.current.name == 'item' && global.currentList.listLocalId == listlocalid && global.status == 'foreground') {\n entry.flag = 6;\n entry.createStatus = 'FE_SEEN'\n }\n console.log(\"aalatief - syncEntriesDownstream addEntry = \" + JSON.stringify(entry)); \n insertPromises.push(addEntry(entry, 'S'));\n \n \n \n },function(error){\n console.log(\"aalatief - syncEntriesDownstream2 localId error=\" + JSON.stringify(error));\n }) ; \n\n /* if (!localIds.retailerLocalId)\n localIds.retailerLocalId = '';*/\n \n\n }\n $q.all(insertPromises).then(function () {\n console.log(\"syncEntriesDownstream db insert success\"+JSON.stringify(entries));\n \n //confirm Deleviry\n serverHandlerEntryEvents.syncBackEvent(entries, \"CREATE\"); \n //sync other seen entris\n serverHandlerEntryEvents.syncEventUpstream('CREATE-SEEN');\n //update new count flag in local database +1\n serverHandlerEntryEvents.updateListNotificationCount('newCount', affectedLists);\n defer.resolve(affectedLists);\n }, function () {\n console.error(\"syncEntriesDownstream did not insert resolving affected lists \" + angular.toJson(affectedLists));\n defer.resolve(affectedLists);\n });\n },\n function (err) {\n console.error(\"syncEntriesDownstream localIds errors\");\n defer.reject(err);\n });\n /* });*/\n }, function (err) {\n console.error(\"syncEntriesDownstream server response error \" + err.message);\n defer.reject(err);\n });\n return defer.promise;\n /* })*/\n }", "async function s$1(s,e,m){const n=r$1(s);return f(n,R.from(e),{...m}).then((o=>o.data.objectIds))}", "resolve(inner, outer, rootId, promiseLinkType, traceId, asyncPromisifyPromiseId) {\n // const rootId = this.getCurrentVirtualRootContextId();\n const from = getPromiseId(inner);\n const to = getPromiseId(outer);\n // if (!from || !to) {\n // this.logger.error(`resolve link failed: promise did not have an id, from=${from}, to=${to}, trace=${traceCollection.makeTraceInfo(traceId)}`);\n // }\n // else {\n return nestedPromiseCollection.addLink(promiseLinkType, from, to, traceId, rootId, asyncPromisifyPromiseId);\n }", "async function betterWay() {\n const IDs = await getIDs;\n console.log(IDs);\n const firstRecipe = await getRecipe(IDs[2]);\n console.log(firstRecipe);\n const secondRecipe = await getRelated('Code Dozman');\n console.log(secondRecipe);\n}", "async function getRecipesAW() {\n const IDs = await getIDs; //receives the resolve value of the promise\n console.log(IDs);\n \n const recipe = await getRecipe(IDs[2]);\n console.log(recipe);\n \n const related = await getRelated('Jonas');\n console.log(related);\n \n return recipe;\n}", "populateLinkedResources() {\n Promise.all([\n getResourcesTxtFromCustomField(this.props.client),\n this.props.client.metadata(),\n getTokens(this.props.client)\n ])\n .then(values => {\n const resourcesArr = decodeLinkedResources(values[0]),\n domain = values[1].settings.bloomfire_domain,\n loginToken = values[2].loginToken;\n getResources(this.props.client, resourcesArr)\n .then(linkedResources => {\n let i = linkedResources.length;\n while (i--) { // loop backwards since we may slice while iterating\n if (linkedResources[i].code === 'not_found') {\n this.removeLinkedResourceFromTicket(linkedResources.splice(i, 1)[0]); // remove from ticket data and array\n }\n }\n linkedResources = linkedResources.map(normalizeResource); // remove unnecessary properties\n addHrefs(domain, linkedResources, loginToken);\n this.setState({ linkedResources });\n });\n });\n }", "async function getRecipesAW(){\n\t\t//waits till the promise is fulfilled and then stores the resolved value in the variable ie. Ids ,recipe ,related here\n\t\tconst Ids = await getIds; \n\t\tconsole.log(Ids);\n\t\tconst recipe=await getRecipe(Ids[2]);\n\t\tconsole.log(recipe);\n\t\tconst related = await getRelated('Jonas');\n\t\tconsole.log(related);\n\t\t\n\t\treturn recipe; //async function also returns a promise always!\n\t}", "function workFlowId2Au(entitiesId1,entitiesId2) {\n getReference(entitiesId1);\n\t\n var AfIds = getAuthorAfIds(entitiesId2);\n\tvar exprs = setExprAfIds(AfIds.array);\n\tgetAfIdsPlus(entitiesId1,exprs);\n \n var paths = [];\n \n var Id1 = parseInt(entitiesId1.Id);\n var Id2 = parseInt(entitiesId2.Id);\n \n // 1-hop\n entitiesId1.forEach((entity) => {\n entity.AA.forEach( (itemAA) => {\n if(itemAA.AuId === entitiesId2.Id) {\n paths.push([Id1,Id2]);\n }\n });\n });\n \n // hops id-..-id-au\n entitiesId2.forEach((entity)=>{\n // console.log(`RId : ${JSON.stringify(entity)}`);\n entitiesId = [entity];\n entitiesId['Id'] = entity.Id;\n var subPaths = getHopId2Id(entitiesId1,entitiesId);\n subPaths.forEach( (path) => {\n path.push(Id2);\n paths.push(path);\n });\n });\n \n // hops id-au-af-au\n\tvar auIds = getEntityAuIds(entitiesId1[0]);\n var authorIndex = 0;\n // hops id-id-id-au\n var Ids = getEntitiesIds(entitiesId2);\n var referenceIndex = 0;\n while(true) {\n if(globalAfIdsQueryCount <= 0 && globalReferenceQueryCount <= 0) {\n if(authorIndex >= globalAuthorArray.length\n\t\t\t\t&& referenceIndex >= globalReferenceArray.length) {\n break;\n }\n } else {\n if(authorIndex >= globalAuthorArray.length\n\t\t\t\t&& referenceIndex >= globalReferenceArray.length) {\n deasync.sleep(5);\n\t\t\t\tcontinue;\n }\n }\n while(authorIndex < globalAuthorArray.length) {\n var AA = globalAuthorArray[authorIndex];\n if(AfIds.hasOwnProperty(AA.AfId) && auIds.hasOwnProperty(AA.AuId)) {\n\t\t\t\tpaths.push([Id1,AA.AuId,AA.AfId,Id2]);\n\t\t\t}\n authorIndex ++;\n }\n\t\t\n while(referenceIndex < globalReferenceArray.length) {\n var entity = globalReferenceArray[referenceIndex];\n \n if(entity.hasOwnProperty('RId')) {\n entity.RId.forEach((RId) => {\n if(Ids.hasOwnProperty(RId)) {\n paths.push([Id1,entity.Id,RId,Id2]);\n }\n });\n }\n referenceIndex ++;\n }\n }\n \n return paths;\n}", "async function capturaIdGado() {\n var ids = [];\n var itemsProcessed = 0;\n\n await new Promise((resolve) => {\n //Percorrendo tabela, capturando num_brinco e pegadando o id\n $('#tb-id-gado tbody tr ').each(function () {\n var brinco = $(this).find('#num-brinco').html();\n console.log(brinco);\n\n var urlAll = \"http://localhost:8080/lotes/listalotes\";\n var lt = document.getElementById(\"combo-idlotes\");\n var lote = lt.selectedIndex;\n\n fetch(urlAll).then(res => res.json()).then(resJ => {\n if (resJ.length > 0) {\n //resJ.forEach(element => {\n \n // if(element.id == loteSelect){ //pega pelo lote selecionado \n //itemsProcessed++;\n resJ[lote-1].gado_bovino.forEach(gado => {\n\n if (brinco == gado.numeroBrinco) { //compara o brinco da tabela com o do objeto vindo do endpoint\n itemsProcessed++;\n var id = {\n id: gado.id\n }\n console.log(id);\n ids.push(id);\n\n if (itemsProcessed === resJ[lote-1].gado_bovino.length) {\n resolve(console.log(\"ALL DONE HERE\"));\n }\n }\n\n });\n // if(itemsProcessed === resJ.length){\n // resolve(console.log(\"ALL DONE HERE\"));\n // }\n // }\n // });\n\n }\n });//---Fim do fetch().then\n });//---Fim do $().each\n });\n\n console.log(\"Now this\");\n capturaDados(ids);\n}", "function spid_populate(url_da_config) {\n let spid_elements = document.querySelectorAll('ul[data-spid-remote]')\n if (spid_elements.length > 0 ) {\n fetch(queryURL)\n .then(function (response) {\n return response.json();\n })\n .then(function (idps) {\n idps = idps.sort(() => Math.random() - 0.5)\n for (var u = 0; u < spid_elements.length; u++) {\n for (var i = 0; i < idps.length; i++) {spid_addIdpEntry(idps[i], spid_elements[u],url_da_config);}\n\n }\n })\n .catch(function (error) {\n console.log('Error during fetch: ' + error.message);\n idps.sort(() => Math.random() - 0.5)\n for (var u = 0; u < spid_elements.length; u++) {\n for (var i = 0; i < idps.length; i++) { spid_addIdpEntry(idps[i], spid_elements[u],url_da_config); }\n }\n });\n }\n }", "async function resolveItems( ids ){\n const arrayOfPromises = ids.map( id => Item.findById(id) );\n const arrayOfItems = await Promise.all(arrayOfPromises);\n return arrayOfItems;\n}", "function workFlowAu2Id(entitiesId1,entitiesId2) {\n\t\n var AfIds = getAuthorAfIds(entitiesId1);\n\tvar exprs = setExprAfIds(AfIds.array);\n\tgetAfIdsPlus(entitiesId2,exprs);\n\t\n\tif(entitiesId2[0].CC > 10) {\n\t\tvar exprs = setExprRefs(entitiesId1);\n\t\tgetCitationPlus(entitiesId2,exprs);\n\t} else {\n\t\tgetCitation(entitiesId2);\n\t}\n\t\n var paths = [];\n \n var Id1 = parseInt(entitiesId1.Id);\n var Id2 = parseInt(entitiesId2.Id);\n \n // 1-hop\n entitiesId2.forEach((entity) => {\n entity.AA.forEach( (itemAA) => {\n if(itemAA.AuId === entitiesId1.Id) {\n paths.push([Id1,Id2]);\n }\n });\n });\n \n // hops au-id-..-id\n entitiesId1.forEach((entity)=>{\n // console.log(`RId : ${JSON.stringify(entity)}`);\n entitiesId = [entity];\n entitiesId['Id'] = entity.Id;\n var subPaths = getHopId2Id(entitiesId,entitiesId2);\n subPaths.forEach( (path) => {\n path.unshift(Id1);\n paths.push(path);\n });\n });\n \n // hops au-af-au-id\n\tvar auIds = getEntityAuIds(entitiesId2[0]);\n var authorIndex = 0;\n // hops au-id-id-id\n var Ids = [];\n var citationIndex = 0;\n while(true) {\n if(globalAfIdsQueryCount <= 0 && globalCitationQueryCount <= 0) {\n if(authorIndex >= globalAuthorArray.length\n\t\t\t\t&& citationIndex >= globalCitationArray.length) {\n break;\n }\n } else {\n if(authorIndex >= globalAuthorArray.length\n\t\t\t\t&& citationIndex >= globalCitationArray.length) {\n deasync.sleep(5);\n\t\t\t\tcontinue;\n }\n }\n while(authorIndex < globalAuthorArray.length) {\n var AA = globalAuthorArray[authorIndex];\n if(AfIds.hasOwnProperty(AA.AfId) && auIds.hasOwnProperty(AA.AuId)) {\n\t\t\t\tpaths.push([Id1,AA.AfId,AA.AuId,Id2]);\n\t\t\t}\n authorIndex ++;\n }\n while(citationIndex < globalCitationArray.length) {\n var entity = globalCitationArray[citationIndex];\n Ids[entity.Id] = 1;\n citationIndex ++;\n }\n }\n \n entitiesId1.forEach((entity)=>{\n entity.RId.forEach((RId) => {\n if(Ids.hasOwnProperty(RId)) {\n paths.push([Id1,entity.Id,RId,Id2]);\n // console.log(`path: ${JSON.stringify(paths[paths.length-1])}`);\n }\n });\n });\n \n return paths;\n}", "async function betterWay() {\n const IDs = await getIDs;\n console.log(IDs);\n const firstRecipe = await getRecipe(IDs[2]);\n console.log(firstRecipe);\n const secondRecipe = await getRelated('Code Dozman');\n console.log(secondRecipe);\n\n return secondRecipe;\n // return firstRecipe\n}", "function makeId() {\n //create an id from praxis number, username and suffix\n //complete version\n vm.setId = praxis+''+vm.name+''+vm.ownId;\n console.log('Setting own id from '+vm.setId+' to '+vm.ownId);\n //send complete peer id to all clients\n socket.emit('update:pid', vm.setId);\n }", "async substantiate(ids) {\n let returnedList = []\n for (let id of ids) {\n let comment = await this.getCommentById(id)\n let user = await usersData.getUserById(comment.userId)\n comment.commenter =user.basicInfo.username\n returnedList.push(comment)\n }\n return returnedList\n }", "async function getRecipeAW() { // the function always return a Promises\n //the await will stop executing the code at this point until the Promises is full filled\n // the await can be used in only async function\n const id = await getID;\n console.log(id)\n console.log('here 2');\n const recipe = await getRecipe(id[1]);\n console.log(recipe);\n const related = await getRelated('Publisher');\n console.log(related);\n\n return recipe;\n}", "function initializeIds(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName) {\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__awaiter\"])(this, void 0, void 0, function () {\n var dynamicConfigPromise, fidPromise, _a, dynamicConfig, fid, configProperties;\n var _b;\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__generator\"])(this, function (_c) {\n switch (_c.label) {\n case 0:\n dynamicConfigPromise = fetchDynamicConfigWithRetry(app);\n // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.\n dynamicConfigPromise\n .then(function (config) {\n measurementIdToAppId[config.measurementId] = config.appId;\n if (app.options.measurementId &&\n config.measurementId !== app.options.measurementId) {\n logger.warn(\"The measurement ID in the local Firebase config (\" + app.options.measurementId + \")\" +\n (\" does not match the measurement ID fetched from the server (\" + config.measurementId + \").\") +\n \" To ensure analytics events are always sent to the correct Analytics property,\" +\n \" update the\" +\n \" measurement ID field in the local config or remove it from the local config.\");\n }\n })\n .catch(function (e) { return logger.error(e); });\n // Add to list to track state of all dynamic config promises.\n dynamicConfigPromisesList.push(dynamicConfigPromise);\n fidPromise = validateIndexedDB().then(function (envIsValid) {\n if (envIsValid) {\n return installations.getId();\n }\n else {\n return undefined;\n }\n });\n return [4 /*yield*/, Promise.all([\n dynamicConfigPromise,\n fidPromise\n ])];\n case 1:\n _a = _c.sent(), dynamicConfig = _a[0], fid = _a[1];\n // Detect if user has already put the gtag <script> tag on this page.\n if (!findGtagScriptOnPage()) {\n insertScriptTag(dataLayerName, dynamicConfig.measurementId);\n }\n // This command initializes gtag.js and only needs to be called once for the entire web app,\n // but since it is idempotent, we can call it multiple times.\n // We keep it together with other initialization logic for better code structure.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n gtagCore('js', new Date());\n configProperties = (_b = {},\n // guard against developers accidentally setting properties with prefix `firebase_`\n _b[ORIGIN_KEY] = 'firebase',\n _b.update = true,\n _b);\n if (fid != null) {\n configProperties[GA_FID_KEY] = fid;\n }\n // It should be the first config command called on this GA-ID\n // Initialize this GA-ID and set FID on it using the gtag config API.\n // Note: This will trigger a page_view event unless 'send_page_view' is set to false in\n // `configProperties`.\n gtagCore(GtagCommand.CONFIG, dynamicConfig.measurementId, configProperties);\n return [2 /*return*/, dynamicConfig.measurementId];\n }\n });\n });\n}", "async function main() {\n try {\n var id_data = await get_changed_ids_prices();\n console.log(id_data);\n //use the chained async functions to get the data to update\n //wait for it to complete\n await update_prices(id_data);\n //update the database, wait for it to complete\n db.close();\n }\n catch (e) {\n console.log(\"error\");\n console.log(e);\n }\n}", "async function manageIdSeller(id, account) {\n try {\n let reference = await EventsModule.GetRef(id); // We fetch the reference\n\n reference.initialPrice = web3.utils.fromWei((reference.initialPrice).toString(), \"ether\");\n reference.currentPrice = await getCurrentPrice(account, id);\n\n const clients = await transactions.GetClients(account, id);\n let total_clients = clients.length;\n\n let ClientsWhoReceivedHashes = await EventsModule.GetEncryptedKeysSent(id);\n let num_clients_step1 = total_clients - ClientsWhoReceivedHashes.length; // Number of clients we need to send K^K2^K3 to\n\n let KeysSent = await EventsModule.GetKeysSent(id);\n let ReceivedHashes = await EventsModule.GetClientsWhoSentHashes(id);\n\n let num_clients_step2 = ReceivedHashes.length - KeysSent.length; // Number of clients we need to verify the hashes of and eventually send K2\n\n let KeyEvent = await EventsModule.ReferenceKeySent(id); // To check if we already set the final reference key\n\n let Key = 0;\n if (KeyEvent.length > 0) {\n let buffer = Buffer.from(web3.utils.hexToBytes(KeyEvent[0].returnValues[1]));\n Key = buffer.toString('hex'); // Eventually load the reference key we sent\n }\n\n // To compute the time left\n let d = new Date();\n let n = d.getTime() / 1000;\n let timeLeft = reference.endTime - n;\n if (timeLeft < 0) {\n timeLeft = 0;\n }\n let TLESAddedEvents = await EventsModule.NewTLEEvent(id)\n let numberTLES = TLESAddedEvents.length;\n let minNumberTLE = reference.minimumData;\n return [reference, total_clients, num_clients_step1, num_clients_step2, Key, timeLeft, numberTLES, minNumberTLE];\n\n } catch (e) {\n throw e;\n }\n}", "function workWithIssue(repoSet, usecase_name){\r\n\r\n var getDiffTask = function(one_issue){\r\n return function(){\r\n return getDiff(one_issue).catch(function(error){})}};\r\n\r\n\r\n return new Promise(function(bigresolve){\r\n\r\n issue.doIt(repoSet, usecase_name).then(function (issue_set) {\r\n\r\n var getDiff_ta = []; // task array\r\n\r\n console.log(\"FOUND \"+ issue_set.length + \" ISSUES\" );\r\n\r\n for (var i in issue_set){\r\n console.log(issue_set[i].info.owner+\" \"+issue_set[i].info.repo+\" \"+issue_set[i].sim);\r\n getDiff_ta.push(getDiffTask(issue_set[i]));\r\n }\r\n\r\n console.log(\"Pocet issue: \" + issue_set.length);\r\n console.log(\"Pocet task: \" + getDiff_ta.length);\r\n\r\n sequence(getDiff_ta, function (results) {\r\n\r\n var id_set = [];\r\n\r\n // find which issues had sentence extracted from them\r\n for(var i in results){\r\n id_set.push(results[i].issue.id);\r\n }\r\n\r\n\r\n console.log(medzicas()+\" Got code ready\");\r\n console.log(id_set);\r\n\r\n // get issue messages\r\n getMsg(results).then(function (results2) {\r\n\r\n console.log(medzicas()+\" Got messages\");\r\n\r\n for (var i in results2) {\r\n var good_sentence = func.extractFromTags(results2[i].msg);\r\n if (good_sentence != undefined){\r\n results2[i].msg = good_sentence;\r\n }\r\n else{\r\n console.log(\"not good\");\r\n }\r\n }\r\n\r\n setIds(results2).then(function(issues_with_ids){\r\n bigresolve(issues_with_ids);\r\n });\r\n });\r\n });\r\n });\r\n });\r\n}", "function executeCall(id) {\n promises[id] = fetch(`restaurants/${id}`)\n .then(response => {\n if (response instanceof Promise) {\n response.then(() => executeCall(id))\n throw new Error('Unathorized by Token')\n }\n return response\n })\n .then(data => mapData(Object.assign(data, { id })))\n\n return promises[id]\n}", "function getNewID() {\n /*\n Each client registered in each installation of FreeField has a numerical\n ID assigned to it that is auto-incremented for each new client in the\n database. The ID is used to connect changes made on the client-side form\n in /includes/admin/api.php to the proper API client to apply the changes\n to server-side, identifying a particular client in the database.\n\n Webhooks and geofences use an 8-character random alphanumeric ID to\n identify themselves and to avoid concurrency issues. However, API\n clients use numerical IDs to take advantage of AUTO_INCREMENT in the\n database table.\n\n If a user adds a new API client, an ID then has to be assigned to that\n client so that the server has a reference to the client for later use.\n However, the user cannot generate this ID client-side, because multiple\n users could potentially be modifying and adding API clients at the same\n time, and since IDs are sequential, there would be collisions between\n the clients. The solution to this is to have the browser generate a\n temporary ID that is only used to collect all the attributes of a client\n (such as label, color, permission level, etc.) into a single object for\n processing server-side. This means a newly added client would have the\n HTML form fields `an_ID[name]`, `an_ID[color]` etc, where \"an\" means\n \"API client new\", and combined with an ID, automatically forms an array\n `an_ID` in PHP which contains all of the properties of the newly created\n client.\n\n When the client is inserted into the database, the generated ID of the\n client is ignored, as ID generation is handled by the SQL server.\n /admin/apply-api.php performs an INSERT query on the database without\n passing any ID, and the ID is internally generated upon insertion as an\n incremented integer value.\n\n Because the browser generated IDs are ignored on the server, there is no\n need for the client-side IDs to be globally unique. The only requirement\n is that there are no ID collisions between two or more added API clients\n within the context of a single user. If the same ID is generated for\n two different groups in the same browser window, the latter of the\n clients in the list would overwrite the former, and the first client\n would never be added. This can be avoided entirely using a local\n collision check. Functions which call `getNewID()` will confirm that the\n generated ID is not in use by any existing newly created clients, and if\n a collision is found, it will randomly generate another ID instead.\n\n An alternative would be to have an incrementing variable for this\n function, that would return the value of the previously generated ID\n plus one for every invocation. However, for consistency with other ID\n generation functions in FreeField, we will be generating alphanumeric\n IDs instead.\n */\n return Math.random().toString(36).substr(2, 8);\n}", "async function obtenerPersonajes(){\nvar ids=[1,2,3,4,5,6,7]\n\nvar promesas = ids.map(id=> obtenerPersonaje(id))\n\n//wait detiene la ejecucion de la funcion hasta que se hayan cargado todas las promesas\ntry{\n \n var personajes= await Promise.all(promesas)\n console.log(personajes)\n\n}catch(id){\n error(id)\n}\n\n}", "consumeNeoIdMap() {\n if (Neo.idMap) {\n this.add(Object.values(Neo.idMap));\n delete Neo.idMap;\n }\n }", "function getProofsByIDV1 (req, res, next) {\n let hashIdResults = []\n\n // check if hash_id parameter was included\n if (req.params && req.params.hash_id_node) {\n // a hash_id was specified in the url, so use that hash_id only\n\n if (!uuidValidate(req.params.hash_id_node, 1)) {\n return next(new restify.InvalidArgumentError('invalid request, bad hash_id'))\n }\n\n hashIdResults.push(req.params.hash_id_node)\n } else if (req.headers && req.headers.hashids) {\n // no hash_id was specified in url, read from headers.hashids\n hashIdResults = req.headers.hashids.split(',')\n }\n\n // ensure at least one hash_id was submitted\n if (hashIdResults.length === 0) {\n return next(new restify.InvalidArgumentError('invalid request, at least one hash id required'))\n }\n\n // ensure that the request count does not exceed the maximum setting\n if (hashIdResults.length > env.GET_PROOFS_MAX_REST) {\n return next(new restify.InvalidArgumentError('invalid request, too many hash ids (' + env.GET_PROOFS_MAX_REST + ' max)'))\n }\n\n // prepare results array to hold proof results\n hashIdResults = hashIdResults.map((hashId) => {\n return { hash_id_node: hashId.trim(), proof: null, anchors_complete: [] }\n })\n let requestedType = req.accepts(JSONLD_MIME_TYPE) ? JSONLD_MIME_TYPE : BASE64_MIME_TYPE\n\n async.eachLimit(hashIdResults, 50, (hashIdResult, callback) => {\n // validate id param is proper UUIDv1\n if (!uuidValidate(hashIdResult.hash_id_node, 1)) return callback(null)\n // validate uuid time is in in valid range\n let uuidEpoch = parseInt(uuidTime.v1(hashIdResult.hash_id_node))\n var nowEpoch = new Date().getTime()\n let uuidDiff = nowEpoch - uuidEpoch\n let maxDiff = env.PROOF_EXPIRE_MINUTES * 60 * 1000\n if (uuidDiff > maxDiff) return callback(null)\n // retrieve proof from storage\n redis.get(hashIdResult.hash_id_node, (err, proofBase64) => {\n if (err) return callback(null)\n chpBinary.binaryToObject(proofBase64, (err, proofObj) => {\n if (err) return callback(null)\n let anchorsComplete = utils.parseAnchorsComplete(proofObj)\n hashIdResult.anchors_complete = anchorsComplete\n if (requestedType === BASE64_MIME_TYPE) {\n hashIdResult.proof = proofBase64\n return callback(null)\n } else {\n hashIdResult.proof = proofObj\n return callback(null)\n }\n })\n })\n }, (err) => {\n if (err) return next(new restify.InternalError(err))\n res.contentType = 'application/json'\n res.send(hashIdResults)\n return next()\n })\n}", "async function main() {\n // create the promises first\n var call1 = myApiClient(1)\n var call2 = myApiClient(2)\n\n // then wait for them\n var response1 = await call1\n var response2 = await call2\n\n // do something with the responses\n var message = response1['message'] + ' ' + response2['message']\n console.log(message)\n}", "function syncEntriesDownstream(entryDetails) {\n var defer = $q.defer();\n\n console.log(\"syncEntriesDownstream global.status = \" + global.status);\n\n buildPromise(entryDetails, \"CREATE\").then(function (response) {\n\n console.log(\"syncEntriesDownstream server response \" + angular.toJson(response));\n\n syncDependentDownstream(response.data.items, response.data.retailers).then(function () {\n\n dbHelper.buildLocalIds(response.data.entries).then(function (result) {\n console.log(\"serverHandlerEntryV2 localIds = \" + angular.toJson(result));\n affectedLists = result.lists;\n var insertPromises = [];\n for (var i = 0; i < response.data.entries.length; i++) {\n\n var localIds = dbHelper.getLocalIds(response.data.entries[i].entryServerId, result);\n console.log(\"syncEntriesDownstream entry i =\" + i + \" \" + angular.toJson(response.data.entries[i]));\n console.log(\"syncEntriesDownstream localIds =\" + angular.toJson(localIds));\n\n \n \n\n if (!localIds.retailerLocalId)\n localIds.retailerLocalId = '';\n\n var uom;\n if (response.data.entries[i].uom) {\n uom = response.data.entries[i].uom;\n } else {\n uom = \"PCS\";\n }\n\n var qty;\n if (response.data.entries[i].qty) {\n qty = response.data.entries[i].qty;\n } else {\n qty = 1.0;\n }\n// console.log(\"serverHandlerEntry.syncEntriesDownstream localValues listLocalId = \" + angular.toJson(localIds));\n console.log(\"syncEntriesDownstream localValues qty = \" + qty);\n console.log(\"syncEntriesDownstream localValues uom = \" + uom);\n\n var entry = {\n listLocalId: localIds.listLocalId,\n itemLocalId: localIds.itemLocalId,\n itemName: localIds.itemName,\n categoryName: localIds.categoryName,\n quantity: qty,\n uom: uom,\n entryCrossedFlag: 0,\n deleted: 0,\n updatedFlag: 0,\n flag: 5,\n createStatus:'FE_CREATED', \n //seenFlag: 0,\n retailerLocalId: localIds.retailerLocalId,\n retailerName: localIds.retailerName,\n language: response.data.entries[i].entryServerId.language,\n entryServerId: response.data.entries[i].entryServerId._id,\n userServerId: response.data.entries[i].entryServerId.userServerId\n };\n console.log(\"syncEntriesDownstream $state.current.name = \" + $state.current.name);\n console.log(\"syncEntriesDownstream localIds.listLocalId = \" + localIds.listLocalId);\n console.log(\"syncEntriesDownstream global.currentList = \" + global.currentList);\n console.log(\"syncEntriesDownstream global.status = \" + global.status);\n\n if ($state.current.name == 'item' && global.currentList.listLocalId == localIds.listLocalId && global.status == 'foreground') {\n entry.flag = 6;\n createStatus:'FE_SEEN'; \n }\n\n insertPromises.push(addEntry(entry, 'S'));\n }\n $q.all(insertPromises).then(function () {\n console.log(\"syncEntriesDownstream db insert success\");\n serverHandlerEntryEvents.syncBackEvent(response.data.entries, \"CREATE\");\n serverHandlerEntryEvents.syncEventUpstream('CREATE-SEEN');\n serverHandlerEntryEvents.updateListNotificationCount('newCount', affectedLists);\n defer.resolve(affectedLists);\n }, function () {\n console.error(\"syncEntriesDownstream did not insert resolving affected lists \" + angular.toJson(affectedLists));\n defer.resolve(affectedLists);\n });\n },\n function (err) {\n console.error(\"syncEntriesDownstream localIds errors\");\n defer.reject(err);\n });\n });\n }, function (err) {\n console.error(\"syncEntriesDownstream server response error \" + err.message);\n defer.reject(err);\n });\n return defer.promise;\n }", "function addAsyncClient(x,y){\n console.log(\"[SC] triggering add\");\n addAsync(x,y, function(err, result){\n if (err){\n console.log(\"error occured..\", err);\n return;\n }\n console.log(\"[SC] result = \", result); \n });\n}", "async function myLoadAddressesFromSeed(myPassedSeed){\n\n\tvar options = {\n index : global.myRecieveIndex,\n checksum: true,\n\t\tsecurity: 2,\n returnAll: true\n\n\t}\n\n\niota\n .getNewAddress(myPassedSeed, options)\n .then(myGenAddress => {\n console.log('Your set of address are (unused is last): ' + JSON.stringify(myGenAddress, null, 3) )\n // global.myResponse0 = '<h2>My Next '+myMaxArray+' Addresses: </h2>' + '<pre id=\"myPre01\">'+JSON.stringify(myGenAddress, null, 3)+'</pre>' + '<hr>'; // hopefully this is global\n\n global.myArrayOfAddresses = myGenAddress\n\n global.myPendingAddress = global.myArrayOfAddresses[global.myArrayOfAddresses.length-1]\n global.myReceiveAddress = global.myPendingAddress\n // console.log('global.myPendingAddress')\n // console.log(global.myPendingAddress)\n\n // now show all previous confirmed messages\n for (myLoop=global.myRecieveIndex; myLoop < global.myArrayOfAddresses.length; myLoop++){ // loop from old address index to index before unused address\n mySendConfirmed(global.myArrayOfAddresses[myLoop])\n }\n\n })\n .catch(err => {\n console.log(err)\n })\n\n\n}", "async publishData(id, dataList) {\n const client = this.clientThings[id];\n return Promise.all(dataList.map(data => (\n promisify(client, 'published', client.publishData.bind(client), data.sensorId, data.value)\n )));\n }", "static async getPlantsByIds(ids) {\n console.log(\"getPlantsByIds:\", ids);\n\n // Fetch any of the plants we haven't already cached\n const promises = [];\n for (let id of ids) {\n if (!PlantCache.has(id)) {\n promises.push(TrefleApi._request(\"GET\", `/${id}`));\n console.log(\" fetching\", id);\n }\n }\n\n // Once they are all resolved, add them to cache\n const responses = await Promise.all(promises);\n for (let resp of responses) {\n const plant = resp.data.data;\n PlantCache.set(plant.id, plant);\n console.log(\" caching\", plant.id);\n }\n\n // Create a \"faux\" response\n const plants = ids.map((id) => PlantCache.get(id));\n const fauxResponse = {\n ok: true,\n data: { data: plants }\n };\n\n return fauxResponse;\n }", "function grabNextId() {\n\n\treturn nextId++;\n\n }", "exchangeIds(store, dataModelName, entityName, data) {\n this.exchangeId(store, dataModelName, entityName, data);\n const exchangeIdPromises = [];\n store.entitySchema.columns.forEach(col => {\n if (col.foreignRelations) {\n col.foreignRelations.forEach(foreignRelation => {\n if (data[col.fieldName]) { // if id value\n this.exchangeId(store, dataModelName, foreignRelation.targetEntity, data, col.fieldName);\n }\n if (data[foreignRelation.sourceFieldName]) { // if object reference\n exchangeIdPromises.push(this.localDBManagementService.getStore(dataModelName, foreignRelation.targetEntity)\n .then(refStore => {\n return this.exchangeIds(refStore, dataModelName, foreignRelation.targetEntity, data[foreignRelation.sourceFieldName]);\n }));\n }\n });\n }\n });\n return Promise.all(exchangeIdPromises);\n }", "async function sendDecoderKey(id, Account) {\n try {\n let ClientsWhoSentHashes = await EventsModule.GetClientsWhoSentHashes(id); // This is a list of events corresponding to clients who sent me a hash\n let ClientsReceivedK2 = await EventsModule.GetKeysSent(id); // This is a list of events corresponding to the clients I already answered concerning their hashes\n let Address_ListClientsWhoSentHashes = await EventsModule.EventsToAddresses(ClientsWhoSentHashes); // Transformed into a list of addresses\n let Address_ListClientsWhoReceivedK2 = await EventsModule.EventsToAddresses(ClientsReceivedK2); // Transformed into a list of addresses\n let ClientsToDo = await EventsModule.ComputeLeft(Address_ListClientsWhoSentHashes, Address_ListClientsWhoReceivedK2); // Then i find who is left...\n\n // Now We have to: Verify each hash received with the ones we had saved\n\n let done = 0; // To check how many were successful at the end...\n for (let i = 0; i < ClientsToDo.length; i++) {\n let myRef_obj = await readwrite.ReadAsObjectRefSeller(__dirname + '/../Database/RefSeller' + id.toString() + '_' + ClientsToDo[i] + '.txt');\n\n let client_address = ClientsToDo[i];\n\n let correctHash = myRef_obj.hash;\n\n let eventReceivedHash = await EventsModule.GetHashFromClient(client_address, id);\n let receivedHash = eventReceivedHash[0].returnValues.encodedKeyHash;\n\n\n if (correctHash === receivedHash) {\n let receipt = await transactions.sendDecoderKey(Account, id, client_address, myRef_obj.K2);\n if (receipt) {\n done += 1;\n }\n }\n }\n return [ClientsToDo.length, done];\n } catch (e) {\n throw e;\n }\n\n}", "async function obtenerPersonajes() {\n var ids = [1, 2, 3, 4, 5, 6, 7]\n var promesas = ids.map(id => obtenerPersonaje(id))\n //toda la parte asyncrona va dentro de un bloque try catch\n try{\n //await detiene la ejecucion donde se coloca, hasta que las promesas sean resueltas\n var personajes = await Promise.all(promesas)\n personajes.map(personaje => {console.log(`El personaje es ${personaje.name}`)})\n } catch (id) {\n onError(id)\n }\n }", "async function fetchEmployees(){\n\t\t\t\tconst ids = [8569129, 254808831, 58197, 651065]\n\t\t\t\t//const promises = ids.map(id => API.getEmployee(id))\n\t\t\t\tconst promises = ids.map(API.getEmployee)\n\t\t\t\treturn Promise.all(promises)\n\n\t\t\t\t// solution (2)\n\t\t\t\t/*const p1 = await API.getEmployee(8569129)\n\t\t\t\tconst p2 = await API.getEmployee(254808831)\n\t\t\t\tconst p3 = await API.getEmployee(58197)\n\t\t\t\tconst p4 = await API.getEmployee(651065)\n\t\t\t\treturn Promise.all[e1, e2, e3, e4] */\n\n\t\t\t\t// solution (3)\n\t\t\t\t/*const p1 = await API.getEmployee(8569129)\n\t\t\t\tconst p2 = await API.getEmployee(254808831)\n\t\t\t\tconst p3 = await API.getEmployee(58197)\n\t\t\t\tconst p4 = await API.getEmployee(651065)\n\t\t\t\treturn [await e1, await e2, await e3, await e4] */\n\n\t\t\t\t// solution (4) - parallel requests + parallel awaiting\n\t\t\t\t/*const res = []\n\t\t\t\tconst promises = ids.map(async (id, idx) => {\n\t\t\t\t\tconst e = await API.getEmployee(id)\n\t\t\t\t\tres[idx] = e\n\t\t\t\t}) \n\t\t\t\tawait Promise.all(promises)\n\t\t\t\treturn res*/\n\t\t\t}", "insertRecipe(db, ingredients, newRecipe, recipeIngredients) {\n let newRecipeId;\n return (\n db\n // using a transaction with async/await in order to ensure proper order of data submission based on dependencies\n // transaction will rollback if an error occurs at any point in the process to prevent incomplete data insertion\n .transaction(async trx => {\n // insert ingredients data, and for each ingredient, assign id returned from database to associated recipeIngredients entry\n await trx\n .into(\"ingredients\")\n .insert(ingredients)\n .returning(\"*\")\n .then(ingredients => {\n for (let i = 0; i < ingredients.length; i++) {\n recipeIngredients[i].ingredient_id = ingredients[i].id;\n }\n });\n // insert recipe data, and assign recipe_id returned from database to each entry in recipeIngredients\n await trx\n .into(\"recipes\")\n .insert(newRecipe)\n .returning(\"id\")\n .then(([recipeId]) => recipeId)\n .then(recipeId => {\n for (let recipeIngredient of recipeIngredients) {\n recipeIngredient.recipe_id = recipeId;\n }\n newRecipeId = recipeId;\n });\n // insert recipeIngredients data\n await trx.into(\"recipes_ingredients\").insert(recipeIngredients);\n })\n // query database for recipe data based on new recipe ID and return response\n .then(() => {\n return RecipesService.getById(db, newRecipeId);\n })\n );\n }", "getRandomId() {\n return fetch(`${remoteURL}/brands`)\n .then(result => result.json())\n .then(brands => {\n // random function, many ways out there to get random\n const randomIndex = Math.floor(Math.random() * brands.length);\n //look at the id of the reuturning brands, and assign to randomBrand and return the id of that brand \n const randomBrand = brands[randomIndex];\n return randomBrand.id;\n });\n}", "function request_device_id(devicename, remoteAddress){\n\treturn new Promise( (resolve,reject) => {\n\t\t\"use strict\";\n\t\tif(devicename==undefined){\n\t\t\treject(\"devicename is undefined\");\n\t\t}else{\n\t\t\tvar currentdate = dateFormat(new Date(), \"yyyy-mm-dd'T'HH:MM:ss.l\");\n\t\t\tvar result_count = DeviceModule.query_count_device(es_servername + \":\" + es_port, SERVERDB, devicename);\n\t\t\tresult_count.then((resultResolve) => {\n\t\t\t\tif(resultResolve==0){//new entry (2) we resister new entry\n\t\t\t\t\tvar jsontext= {\n\t\t\t\t\t\t\"device\": devicename,\n\t\t\t\t\t\t\"device_length\": devicename.length,\n\t\t\t\t\t\t\"hide\": \"false\"\n\t\t\t\t\t};\n\t\t\t\t\tvar result = DeviceModule.register_json(es_servername + \":\" + es_port,SERVERDB, jsontext, remoteAddress, 'devices');\n\t\t\t\t\tresult.then((resultResolve) => {\n\t\t\t\t\t\tvar result_id = DeviceModule.find_device_id(es_servername + \":\" + es_port,SERVERDB, devicename);\n\t\t\t\t\t\tresult_id.then((result_idResolve) => {\n\t\t\t\t\t\t\tresolve (result_idResolve);\n\t\t\t\t\t\t},(result_idReject)=> {//error finding the device id\n\t\t\t\t\t\t\treject(\"error requesting id\");\n\t\t\t\t\t\t});\n\t\t\t\t\t},(resultReject)=> {//error regsiterning the new devicename\n\t\t\t\t\t\treject (resultReject.text);\n\t\t\t\t\t});\n\t\t\t\t}else{\n\t\t\t\t\tvar result_id = DeviceModule.find_device_id(es_servername + \":\" + es_port,SERVERDB, devicename);\n\t\t\t\t\tresult_id.then((result_idResolve) => {\n\t\t\t\t\t\tresolve(result_idResolve);\n\t\t\t\t\t},(result_idReject)=> {//error finding the device id\n\t\t\t\t\t\treject( \"error requesting id\");\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},(resultReject)=> { //error looking for devicename\n\t\t\t\treject(resultReject);\n\t\t\t});\n\t\t}\n\t});\n}//request_device_id", "function replaceId() {\r\n\r\n let testalex = new SCFile(\"testalex\");\r\n let testalexResult = testalex.doSelect(\"true\");\r\n\r\n let testalexCompanyId;\r\n let secompany = new SCFile(\"secompany\");\r\n let secompanyResult;\r\n\r\n while (testalexResult == RC_SUCCESS) {\r\n testalexCompanyId = testalex[\"company.id\"];\r\n secompanyResult = secompany.doSelect(\"company.id = \\\"\" + testalexCompanyId + \"\\\"\"); // select company.id=\"CPY00000123\"\r\n\r\n if (secompanyResult == RC_SUCCESS) {\r\n\r\n testalex[\"company.id\"] = secompany[\"company\"]; //replace value\r\n } else {\r\n testalex[\"company.id\"] = \"x\"; //replace values\r\n };\r\n testalex.doAction(\"save\");\r\n testalexResult = testalex.getNext();\r\n\r\n };\r\n}", "updateAssignmentResourceIds() {\n this.assigned.forEach(assignment => {\n assignment.resourceId = this.id;\n });\n }", "async asyncPromiseChain() {\n\n this.showSubmit = false;\n this.selectedAccount = true;\n this.foundAccounts = false;\n this.isLoading = true;\n this.rowData.forEach(d => {\n this.SelectedAccId = d.accountId;\n this.SelectedAccName = d.name;\n this.SelectedAccPhone = d.phone;\n });\n\n let conResp = await getRelatedContactList({ id: this.SelectedAccId });\n if (conResp && conResp.length > 0) {\n conResp.forEach((d, i) => {\n this.conData.push({\n id: d.Id,\n first: d.FirstName,\n last: d.LastName,\n email: d.Email\n })\n console.log(this.conData[i]);\n })\n this.foundContacts = true;\n }\n let oppResp = await getRelatedOpptyList({ id: this.SelectedAccId });\n if (oppResp && oppResp.length > 0) {\n oppResp.forEach((d, i) => {\n this.oppData.push({\n id: d.Id,\n stage: d.StageName,\n amount: '$' + d.Amount,\n source: d.LeadSource\n })\n console.log(this.oppData[i]);\n })\n this.foundOpptys = true;\n }\n this.isLoading = oppResp != null && conResp != null;\n }", "bulkRetrieveCheckIns(options){\n return new Promise((resolve, reject) => {\n let personIDs = options.personIDs.split(',');\n console.log(personIDs);\n checkIfUserHasAccess(options.user, options.eventID).then(() => {\n return eventDao.bulkRetrieveCheckIns({\n 'personIDs' : personIDs,\n 'orgGuid' : options.user.orgGuid,\n 'eventID' : options.eventID\n });\n }).then((checkIns) => {\n resolve(checkIns);\n }).catch((error) => {\n reject(error);\n });\n });\n }", "static resync(callback) {\n let client = config.redis.client;\n let tasks = [];\n\n return client.smembers(config.redis.keys.mappings, (error, mappings) => {\n if (error != null) { Logger.error(\"[IDMapping] error getting list of mappings from redis:\", error); }\n\n mappings.forEach(id => {\n tasks.push(done => {\n client.hgetall(config.redis.keys.mapping(id), function(error, mappingData) {\n if (error != null) { Logger.error(\"[IDMapping] error getting information for a mapping from redis:\", error); }\n\n if (mappingData != null) {\n let mapping = new IDMapping();\n mapping.fromRedis(mappingData);\n mapping.save(function(error, hook) {\n if (mapping.id >= nextID) { nextID = mapping.id + 1; }\n done(null, mapping);\n });\n } else {\n done(null, null);\n }\n });\n });\n });\n\n return async.series(tasks, function(errors, result) {\n mappings = _.map(IDMapping.allSync(), m => m.print());\n Logger.info(\"[IDMapping] finished resync, mappings registered:\", mappings);\n return (typeof callback === 'function' ? callback() : undefined);\n });\n });\n }", "addRestChain (identifier){\n local_RestChains.push(identifier);\n }", "function recreateIdentities(universe, accountId, oldIdentities) {\n let identities = [];\n for (let [,oldIdentity] in Iterator(oldIdentities)) {\n identities.push({\n id: accountId + '/' + $a64.encodeInt(universe.config.nextIdentityNum++),\n name: oldIdentity.name,\n address: oldIdentity.address,\n replyTo: oldIdentity.replyTo,\n signature: oldIdentity.signature,\n });\n }\n return identities;\n}", "updateAutoIdProducts() {\n const statement = 'SELECT setval(\\'products_id_seq\\', max(id)) FROM products;';\n return new Promise((resolve, reject) => {\n db.connection.query(statement, (err, results) => {\n console.log('results', results);\n console.log('err', err);\n if (err) return reject(err);\n return resolve(results);\n });\n });\n }", "function main() {\n return Promise.all([1, 2, 3, 4].map((value) => asyncThing(value)))\n}", "async function syncPipeline() {\n await generateAllowance();\n // await confirmPendingBookings();\n // the server-side script does this now\n await updateContactList();\n await updateTourList();\n}", "function addIDandSelfLink(req, item){\n item.id = item[Datastore.KEY].id;\n item.self = \"https://\" + req.get(\"host\") + req.route.path + \"/\"+ item.id;\n return item;\n}", "function generateUserID() {\n console.log('generating id...');\n let newID;\n do {\n newID = Math.floor(Math.random() * 900000000);\n } while (getIndexOfConnection(newID) !== -1);\n console.log('the id is:' + newID);\n return newID;\n }", "function dbGetNewClientID(){\r\n\tlet newId = Clients.getLastId()\r\n\r\nconsole.log(newId)\r\n\r\n\r\n\r\n\t// lastIdJson = dbGetData(aws+\"/clients/lastid\")\r\n\tnewId = newId.clientId\r\n\r\nconsole.log(newId)\r\n\r\nreturn\r\n\r\n\tlet notEmpty = true\r\n\twhile (notEmpty) {\r\n\t\tresult = dbGetData(aws+\"/clients/exists/\" + newId)\r\n\t\tif (result.count == 0) {\r\n\t\t\tnotEmpty = false\r\n\t\t} else {\r\n\t\t\tnewId++\r\n\t\t}\r\n\t}\r\n\trequest = {}\r\n\tnewId = newId.toString()\r\n\trequest['lastId']=newId\r\n\tresult = dbPostData(aws+\"/clients/lastid\",JSON.stringify(request))\r\n\tconsole.log(result)\r\n\tif (result != \"success\") {\r\n\t\tutilBeep()\r\n\t\tconsole.log(\"Last client ID not Saved\")\r\n\t}\r\n\treturn newId\r\n}", "async function manageIdBuyer(id, account) {\n try {\n let reference = await EventsModule.GetRef(id);\n\n let eventEncryptedReceived = await EventsModule.GetEncryptedKeySentSpecific(id, account.address); //To check if we received the encrypted encoded key\n let eventDecoderReceived = await EventsModule.GetKeySentSpecific(id, account.address); //To check if we received the decoder KEy\n let eventHashSent = await EventsModule.GetHashFromClient(account.address, id); //To check if we sent our hash\n\n // !! allows to convert to boolean\n let decoderReceived = !!eventDecoderReceived.length;\n let encryptedEncodedReceived = !!eventEncryptedReceived.length;\n let hashSent = !!eventHashSent.length;\n\n let key = 0;\n let keyRefEvent = await EventsModule.ReferenceKeySent(id);\n if (keyRefEvent.length > 0) {\n const buffer = Buffer.from(web3.utils.hexToBytes(keyRefEvent[0].returnValues.referenceKey));\n key = buffer.toString('hex');\n }\n return [reference, hashSent, encryptedEncodedReceived, decoderReceived, key];\n } catch (e) {\n throw e;\n }\n}", "createRecipe (title, ingredients, steps) {\n return recipes().then((recipeCollection) => {\n let newRecipe = {\n _id: uuid.v4(),\n title: title,\n ingredients: ingredients,\n steps: steps,\n };\n return recipeCollection.insertOne(newRecipe)\n .then((newRecipeInformation) => {\n return newRecipeInformation.insertedId;\n })\n .then((newRecipeId) => {\n return this.getRecipeById(newRecipeId);\n }\n );\n });\n}", "loadPatent(id) {\n const patents = this.state.patentsInstance;\n const requests = this.state.requestsInstance;\n return new Promise((resolve, reject) => {\n let patent = { id };\n patents.getPatentOwner.call(patent.id).then(owner => {\n patent['ownerAddress'] = owner;\n return patents.getTimestamp.call(patent.id, 0)\n }).then(timestamp => {\n patent['timestamp'] = timestamp.toNumber();\n return patents.getPatentName.call(patent.id);\n }).then(name => {\n patent['name'] = name;\n return patents.getOwnerName.call(patent.id);\n }).then(name => {\n patent['ownerName'] = name;\n return requests.getRequestStatus.call(patent.id, this.state.web3.eth.accounts[0]);\n }).then(status => {\n patent['status'] = status.toNumber();\n return patents.getMaxLicence.call(patent.id);\n }).then(maxLicence => {\n patent['maxLicence'] = maxLicence.toNumber();\n patent['rates'] = [];\n return patents.getNumRequests.call(patent.id);\n }).then(numRequests => {\n for (let j = 0; j < numRequests.toNumber(); j++) {\n patents.getBuyers.call(patent.id, j).then(userID => {\n return patents.getRate.call(patent.id, userID);\n }).then(rate => {\n if (rate > 0) {\n patent.rates.push(rate.toNumber());\n }\n })\n }\n return patents.isDeleted.call(patent.id);\n }).then(isDeleted => {\n patent['deleted'] = isDeleted;\n return patents.getPrices.call(patent.id);\n }).then(prices => {\n patent['prices'] = prices.map(price => price.toNumber());\n return Promise.all(prices.map(price => patents.getEthPrice(price)));\n }).then(ethPrices => {\n patent['ethPrices'] = ethPrices.map(price => price.toNumber());\n resolve(patent);\n }).catch(reject);\n })\n }", "function recreateIdentities(universe, accountId, oldIdentities) {\n var identities = [];\n for (var iter in Iterator(oldIdentities)) {\n var oldIdentity = iter[1];\n identities.push({\n id: accountId + '/' + $a64.encodeInt(universe.config.nextIdentityNum++),\n name: oldIdentity.name,\n address: oldIdentity.address,\n replyTo: oldIdentity.replyTo,\n signature: oldIdentity.signature,\n signatureEnabled: oldIdentity.signatureEnabled\n });\n }\n return identities;\n}", "function updateEntityIds (elem) {\n if (elem && elem.__data__) {\n var data = elem.__data__;\n var idFields = ['startId', 'endId', 'originId'];\n idFields.forEach(function(field){\n if (data.hasOwnProperty(field)) {\n data[field] = guid();\n }\n });\n\n // 'id' field is obligatory\n data.id = guid();\n }\n\n return elem;\n }", "function createOrderWithItems(customer,noItems){\n //created this to be async to run multiple orders\n let prom = new Promise(function(resolve,reject){\n var today = new Date();\n //ORDER\n //Generate Order with UUID\n let orderId = `order-${uuidv4()}`;\n console.log(\"Order UUID: \" + orderId)\n console.log(\"Order Created: \" + dateFormat(today))\n //Static customerID\n let custId = customer;\n //Today's Date\n let datePlaced = dateFormat(today,\"isoDateTime\");\n //Initial Order Status\n let status = 'UNFILLED';\n //How many order items do you want to generate?\n let numOfOrderItems = noItems;\n \n \n //Put Query Parameters for Order\n var params = {\n \"TableName\":\"dwf\",\n \"Item\":{\n \"pk\":{\"S\":orderId},\n \"sk\":{\"S\":custId},\n \"date-placed\":{\"S\":datePlaced},\n \"gsi1-sk\":{\"S\":status}\n },\n \"ReturnConsumedCapacity\":\"TOTAL\"\n };\n\n //Begin insert of ORDER (async)\n var orderPromise = dyn.putItem(params).promise();\n orderPromise\n //.then(print)\n .catch(print)\n //Push generated order items onto this array:\n let orderItems = [];\n\n //GENERATE RANDOM ORDER ITEMS\n //For each order, generate random product id (5 chars, only alpha)\n for(let i = 0; i < numOfOrderItems; i++){\n let prodId = `prod-${randomString.generate({\n length:5,\n charset:'alphabetic'\n })}`;\n //Random quantity (1-15)\n let quantity = getRandomInt(1,16);\n //Put Query for each OrderItem\n let obj = {\n PutRequest:{\n Item:{\n \"pk\":{S: orderId},\n \"sk\":{S: prodId},\n \"gsi1-sk\":{S: custId},\n //I didn't know what to do for price,\n //so I just picked the first character's UTF code\n //This means that there is some randomization,\n //but the price is always consistent for that ID\n \"price\":{N: `${prodId.charCodeAt(5)}`},\n \"qty\":{N: `${quantity}`},\n \"date-placed\":{\"S\":datePlaced}\n }\n }\n }\n //Push each query onto the orderItems array\n //for batch put (supposedly more efficient)\n orderItems.push(obj);\n }\n\n //This array will hold all the batch jobs so that\n //I can call Promise.All() to measure the approximate\n //time for completion\n let pendingPromises = []\n\n //Batch Put if there are multiple items\n if(orderItems.length >= 1){ \n //Set up counter of remaining items\n let remainingItems = orderItems.length \n //Track current index for orderItems array\n let currIndex = 0 \n //Begin Batch operation timer\n console.time(`${noItems}_Items`)\n\n //While we still have items to process..\n while(remainingItems > 0){\n \n var batchPromise;\n\n //if remaining > 25, then we work on\n //25 items (the max that BatchWrite can handle) \n if(remainingItems >= 25){\n //Begin insert of ORDER ITEMS batch\n batchPromise = dyn.batchWriteItem({\n \"RequestItems\":{\n //Take 25 items, starting at the index\n \"dwf\":orderItems.slice(currIndex, currIndex + 25)\n },\n \"ReturnConsumedCapacity\":\"TOTAL\"\n }).promise()\n //Push the promise onto array to track when all promises are complete\n pendingPromises.push(batchPromise)\n //Catch any errors\n batchPromise\n //.then(print)\n .catch(print);\n //decrement remaining items \n remainingItems -= 25\n //move index up for next batch of items\n currIndex += 25\n }\n //There are less than 25 items,\n //take the rest of the items\n else{\n batchPromise = dyn.batchWriteItem({\n \"RequestItems\":{\n \"dwf\":orderItems.slice(currIndex, currIndex + remainingItems)\n },\n \"ReturnConsumedCapacity\":\"TOTAL\" \n }).promise()\n pendingPromises.push(batchPromise)\n batchPromise\n //.then(print)\n .catch(print)\n remainingItems = 0;\n \n }\n }\n //Wait for all promises to be fulfilled,\n //Then stop the timer\n Promise.all(pendingPromises).then(\n function(){\n console.timeEnd(`${noItems}_Items`)\n console.log();\n resolve()\n } \n );\n }else{\n console.log(\"0 items specified in order, nothing created.\\n\")\n }\n //Generate Random Number\n //From Mozilla Developer Network:\n //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random\n function getRandomInt(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min)) + min;\n }\n });//end Promise\n return prom;\n}", "async function executeSeqWithForAwait(urls) {\n const responses = [];\n const promises = urls.map((url) => {\n return fetchUrlDataWithAsyncAwait(url);\n });\n\n for await (const res of promises) {\n console.log(res);\n responses.push(res);\n }\n console.log(responses);\n}", "async function main() {\n let exchange1 = {};\n let exchange2 = {};\n let lastPrice = \"\";\n let seconds = 0;\n let initialBalance = {};\n\n // TODO el exchange debe pasarse: conf.exchange1.apiKey; conf.exchange1.secret\n function init() {\n try {\n exchange1 = exchange.setExchange(conf.exch1Name, conf.exch1.apiKey, conf.exch1.secret, conf.exch1.uid);\n exchange2 = exchange.setExchange(conf.exch2Name, conf.exch2.apiKey, conf.exch2.secret);\n seconds = exchange2.seconds() * 1000;\n } catch (error) {\n log.bright.red(\"ERROR\", error.message)\n }\n };\n\n // TODO es resp de order\n async function cancelMultipleOrders(symbol, lowerId, uperId) {\n for (let i = lowerId; i <= uperId; i++) {\n try {\n let canceled = await exchange2.cancelOrder(i, symbol)\n log(canceled)\n } catch (error) {\n log(error)\n }\n }\n };\n\n function sleep(ms) {\n return new Promise(resolve => {\n setTimeout(resolve, ms)\n })\n };\n\n try {\n let isFirstIteration = true;\n init();\n price.basePrice = await price.lastPrice(symbol2, exchange1);\n log(\"price at generation\", price.basePrice);\n initialBalance = await exchange.balances(exchange2);\n await order.placeScaledOrders(exchange2, conf.amount, symbol);\n await trade.getTradesByBalance(exchange1, exchange2, initialBalance, order.placedOrders, isFirstIteration); \n //await cancelMultipleOrders(symbol, 6064, 6251);\n } catch (error) {\n log(error);\n }\n}", "fetchObject( id, force = false, autosubscribe = true )\n\t {\n\t if( typeof id !== \"string\" )\n\t {\n\t let result = [];\n\t for( let i = 0; i < id.length; ++i )\n\t result.push( this.fetchObject( id[i], force, autosubscribe ) );\n\t return result;\n\t }\n\n\t if(DEBUG) console.log( \"!!! fetchObject: \", id, this.subscribed, !this.subscribed && !force );\n\t if( !this.subscribed && !force ) return undefined;\n\n\t if(DEBUG) console.log( \"maybe fetch object: \", id );\n\t if( !__WEBPACK_IMPORTED_MODULE_3__ChainValidation__[\"a\" /* default */].is_object_id(id) )\n\t throw Error( \"argument is not an object id: \" + id );\n\n\t if( id.search(\"1.2.\") === 0 ) return this.fetchFullAccount( id, autosubscribe );\n\t if (id.search(witness_prefix) === 0) this._subTo(\"witnesses\", id);\n\t if (id.search(committee_prefix) === 0) this._subTo(\"committee\", id);\n\n\t let result = this.objects_by_id.get( id );\n\t if( result === undefined ) { // the fetch\n\t if(DEBUG) console.log( \"fetching object: \", id );\n\t this.objects_by_id.set( id, true );\n\t if (!__WEBPACK_IMPORTED_MODULE_1_cybexjs_ws__[\"Apis\"].instance().db_api()) return null;\n\t __WEBPACK_IMPORTED_MODULE_1_cybexjs_ws__[\"Apis\"].instance().db_api().exec( \"get_objects\", [ [id] ] ).then( optional_objects => {\n\t //if(DEBUG) console.log(\"... optional_objects\",optional_objects ? optional_objects[0].id : null)\n\t for(let i = 0; i < optional_objects.length; i++) {\n\t let optional_object = optional_objects[i];\n\t if( optional_object )\n\t this._updateObject( optional_object, true );\n\t else {\n\t this.objects_by_id.set( id, null );\n\t this.notifySubscribers();\n\t }\n\t }\n\t }).catch( error => { // in the event of an error clear the pending state for id\n\t console.log(\"!!! Chain API error\",error);\n\t this.objects_by_id.delete(id);\n\t });\n\t }\n\t else if( result === true ) // then we are waiting a response\n\t return undefined;\n\t return result; // we have a response, return it\n\t }", "async function obtenerIdsUsuarios(idEstudiante) {\n let vectorIdsUsuarios = [];\n await Estudiante.findById(idEstudiante, {\n adultoResponsable: 1,\n _id: 0,\n }).then(async (objConids) => {\n for (const idAR of objConids.adultoResponsable) {\n await AdultoResponsable.findById(idAR, { idUsuario: 1, _id: 0 }).then(\n (objConId) => {\n vectorIdsUsuarios.push(objConId.idUsuario);\n }\n );\n }\n });\n return vectorIdsUsuarios;\n}", "function fetchContent(_idsArr,_authHeader,_hostName,_projectName,_dateFilter)\n{\n return new Promise(function(resolve, reject) {\n\n authHeader=_authHeader;\n hostName=_hostName;\n projectName=_projectName;\n\n try\n {\n //Fetch all updates from workitems with ids in the _idsArray\n var promiseArr=new Array(_idsArr.length);\n for (var i=0;i<_idsArr.length;i++){\n promiseArr[i]=getPooledHttpRequest(hostName,projectName,_idsArr[i].id, _idsArr[i].rev,MAXPOOLITEMSRESTAPI);\n }\n \n //reduce the array of arrays into an array\n promiseArr=promiseArr.reduce(function(a, b) { return a.concat(b); }, []);\n\n allProgress(promiseArr,\n (p) => {\n updateProgress(50+Math.floor(p.toFixed(0)/2));\n })\n .then(function(values) {\n var updates=FlattenArr(values);\n console.log(\"Got updates:\"+updates.length);\n updates=removeItemsBeforeDate(updates,_dateFilter);\n copyProperties(_idsArr,updates);\n updates.sort(compareTimestamp);\n resolve(updates);\n }).catch(error => \n reject(error));\n }\n catch(Err){\n console.error(\"Error:\"+Err);\n reject(Err);\n }\n });\n}", "generateId(){\n let id = Math.floor((Math.random() * 40000) + 10000);\n let recGenObj = { recipeId: id , userId: this.state.user[0]._id };\n this.handleRecipeGen(recGenObj);\n }", "function nextId() {\r\n return currentId++;\r\n}", "function addIDandSelfLink(req, item){\n item.id = item[Datastore.KEY].id;\n item.self = \"https://\" + req.get(\"host\") + \"/ships/\" + item.id;\n return item;\n}", "function cb(id) {\n if (allIds.indexOf(id) === -1) allIds.push(id);\n }", "getIdGenerator() {\n let lastId = 0;\n return function() {\n lastId += 1;\n return lastId;\n };\n }", "async function sendReferenceKeyMalicious(id, Account) {\n let refKeyMalicious = crypto.RandomBytes(7);\n\n let receipt = await transactions.sendRefKey(Account, id, refKeyMalicious);\n\n return [receipt, refKeyMalicious];\n}", "returnInvalidAssociations() {\n return new Promise(\n\n async (resolve, reject) => {\n try {\n //query all associations.. page 2000 rows\n \n //for each association row - validate that from/to source actually exists\n //find that layerId fromSourceId, fromGlobalId, query Count and make sure it exists. \n //find the layerId of toSourceId, toGlobalId , query count make sure it exists \n //if doesn't exist add to invalid assocaition array. \n const invalidAssociations = [];\n //objectid >= ${offset} and objectid <= ${recordCount+offset}\n let c = 0;\n let offset = 0;\n let recordCount = 2000;\n while(true) {\n const result = await this.query(500001, `1=1`, undefined, undefined, [\"*\"], \"sde.DEFAULT\", offset, recordCount)\n console.log(`Processing ${recordCount} associations`)\n //for each assocaition check if its valid\n const bar = new ProgressBar(':bar', { total: result.features.length });\n for (let i = 0 ; i < result.features.length; i++){\n const associationRow = result.features[i]\n const isValid = await this.isAssocaitionValid( associationRow);\n if (!isValid){ \n const associationGuid = v(associationRow.attributes, \"globalid\");\n invalidAssociations.push({\n \"assocaitionGuid\":associationGuid\n })\n //console.log(`Discoved an invalid assocaition. ${associationGuid}`)\n //console.log(\"x\")\n }\n \n bar.tick();\n }\n \n\n //keep asking if this is true\n if (!result.exceededTransferLimit) break;\n offset+= recordCount;\n }\n \n resolve(invalidAssociations); \n }catch (ex) {\n reject(ex);\n }\n \n \n\n }\n )\n \n\n }", "function addid(worksetid) {\n //worksetid.forEach( x => worksetIds.add(x.toString()); );\n worksetIds.add(worksetid.toString());\n }", "function updateTaskID() {\n for (let i = 0; i < tasks.length; i++) {\n tasks[i].id = i;\n }\n}", "function fetchIngredient(input) {\n var url = ingredientUrl + input\n\n fetch(url)\n .then(function(response) {\n if (response.ok) {\n response.json().then(function(data) {\n console.log(data)\n data.drinks.forEach((drink, index) => {\n fetchId(drink.idDrink, index);\n });\n })\n }\n })\n}", "async runBatch(req, ids, change, options = {}) {\n let job;\n let notification;\n const total = ids.length;\n\n const results = {};\n const res = req.res;\n try {\n // sends a response with a jobId to the browser\n job = await self.start(options);\n\n self.setTotal(job, ids.length);\n // Runs after response is already sent\n run();\n\n // Trigger the \"in progress\" notification.\n notification = await self.triggerNotification(req, 'progress', {\n // It's only relevant to pass a job ID to the notification if\n // the notification will show progress. Without a total number we\n // can't show progress.\n jobId: total && job._id,\n ids,\n action: options.action\n });\n\n return {\n jobId: job._id\n };\n } catch (err) {\n self.apos.util.error(err);\n if (!job) {\n return res.status(500).send('error');\n }\n try {\n return await self.end(job, false);\n } catch (err) {\n // Not a lot we can do about this since we already\n // stopped talking to the user\n self.apos.util.error(err);\n }\n }\n async function run() {\n let good = false;\n try {\n for (const id of ids) {\n try {\n const result = await change(req, id);\n self.success(job);\n results[id] = result;\n } catch (err) {\n self.failure(job);\n }\n }\n good = true;\n } finally {\n await self.end(job, good, results);\n // Trigger the completed notification.\n await self.triggerNotification(req, 'completed', {\n dismiss: true\n });\n // Dismiss the progress notification. It will delay 4 seconds\n // because \"completed\" notification will dismiss in 5 and we want\n // to maintain the feeling of process order for users.\n await self.apos.notification.dismiss(req, notification.noteId, 4000);\n }\n }\n }", "async function outPutEmployeeQuery() {\n console.log('function called')\n try {\n console.log('function called 1')\n const id = await getIds; // <--- will stop code execution until `resolved` \n console.log('function called 2')\n const name = await getEmployeeName(id);\n console.log('function called 3')\n const final = await finishingTouch(name);\n console.log(final);\n } catch (error) {\n console.log(`exception :: ${error}`);\n }\n}", "function mapNextUniqId2() {\r\n window.setTimeout(mapNextUniqId3, CLICK_LOAD_DELAY);\r\n}", "function addIds(url, req) {\n req = JSON.parse(req);\n let current_id = 1;\n if (req.data instanceof Array) {\n for (let datum of req.data) {\n datum.id = current_id++;\n }\n } else {\n req.data.id = current_id++;\n }\n\n if (req.included) {\n for (let datum of req.included) {\n datum.id = current_id++;\n }\n }\n\n return req;\n}", "function delay2() {\nvar promises1 = w1BusMasters.map(function(w1BusMaster, key){\n return new Promise(function(resolve,reject) {\n //console.log('key ', key);\n var sensorsUids = getSensorsUidsArray.GetSensorsUidsArray(w1BusMaster);\n //console.log(sensorsUids ? sensorsUids.length : 'json_data is null or undefined');\n //console.log('sensorsUids ', sensorsUids);\n //if (sensorsUids !== \"undefined\" && sensorsUids !== []) {\n if (sensorsUids != []) {\n //console.log('sensorsUids ', sensorsUids);\n pinBus = delay(sensorsUids, w1BusMaster, key);\n //console.log('pinBus2 ', pinBus);\n };\n //};\n return resolve(pinBus);\n })\n})\nPromise.all(promises1).then(function(results1) {\n //console.log('results1', results1)\n})\nreturn pinBus;\n}", "static getByIdAll(_id) {\n return new Promise((resolve, reject) => {\n let chang = _id.toString();\n let id_uid = chang.split(',');\n console.log(\"hmm\", id_uid[0], id_uid[1]);\n models.postmodel.findAll({\n attributes: ['postedby', 'postedon', 'views', 'tag', 'title', 'content'],\n where: {id: id_uid[0]},\n include: [{model: models.user, attributes: ['firstname', 'lastname', 'email']}],\n })\n .then(vpst => {\n resolve(vpst);\n }, (error) => {\n\n reject(error);\n });\n });\n }", "async createHashToRelated(id, issuer) {\n // 1) Create a hash to related blank nodes map for storing hashes that\n // identify related blank nodes.\n const hashToRelated = new Map();\n\n // 2) Get a reference, quads, to the list of quads in the blank node to\n // quads map for the key identifier.\n const quads = this.blankNodeInfo.get(id).quads;\n\n // 3) For each quad in quads:\n let i = 0;\n for (const quad of quads) {\n // Note: batch hashing related blank node quads 100 at a time\n if (++i % 100 === 0) {\n await this._yield();\n }\n // 3.1) For each component in quad, if component is the subject, object,\n // and graph name and it is a blank node that is not identified by\n // identifier:\n // steps 3.1.1 and 3.1.2 occur in helpers:\n await Promise.all([this._addRelatedBlankNodeHash({\n quad,\n component: quad.subject,\n position: 's',\n id,\n issuer,\n hashToRelated\n }), this._addRelatedBlankNodeHash({\n quad,\n component: quad.object,\n position: 'o',\n id,\n issuer,\n hashToRelated\n }), this._addRelatedBlankNodeHash({\n quad,\n component: quad.graph,\n position: 'g',\n id,\n issuer,\n hashToRelated\n })]);\n }\n return hashToRelated;\n }", "async function requestId() {\n const res = await fetch(`http://pets-v2.dev-apis.com/pets?id=${id}`);\n const json = await res.json();\n setIds(json.pets);\n }", "getPersonId() {\n return this.#fetchAdvanced(this.#getPersonIdURL()).then((responseJSON) => {\n let personBOs = PersonBO.fromJSON(responseJSON);\n return new Promise(function (resolve) {\n resolve(personBOs);\n })\n })\n }", "findByIdLogin(idLogin) {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n //let cryptoHas = require('crypto');\r\n let id = this.utilsService.getObjectId(idLogin);\r\n console.log(id);\r\n let users = yield this.repository.find({\r\n loginId: id\r\n });\r\n console.log(users);\r\n return users;\r\n });\r\n }", "loadPatent(id) {\n const patents = this.state.patentsInstance;\n const requests = this.state.requestsInstance;\n const users = this.state.usersInstance;\n if (patents !== null && requests !== null && users !== null) {\n return new Promise((resolve, reject) => {\n let patent = { id };\n patents.getNumVersions.call(patent.id).then(numVersions => {\n patent['numVersions'] = numVersions.toNumber();\n patent['ipfsLocations'] = [];\n patent['timestamps'] = [];\n for (let j = 0; j < patent.numVersions; j++) {\n patents.getPatentLocation.call(patent.id, j).then(loc => {\n patent['ipfsLocations'].push(loc);\n });\n patents.getTimestamp.call(patent.id, j).then(timestamp => {\n patent['timestamps'].push(timestamp.toNumber());\n });\n }\n return patents.getMaxLicence.call(patent.id);\n }).then(licence => {\n patent['maxLicence'] = licence.toNumber();\n return patents.isDeleted.call(patent.id);\n }).then(deleted => {\n patent['deleted'] = deleted;\n return patents.getFolderHash.call(patent.id);\n }).then(folderID => {\n patent['folderID'] = folderID;\n return patents.getNumRequests.call(patent.id);\n }).then(numRequests => {\n patent['pendingRequesters'] = [];\n patent['rates'] = [];\n for (let j = 0; j < numRequests.toNumber(); j++) {\n patents.getBuyers.call(patent.id, j).then(userID => {\n requests.isPending.call(patent.id, userID).then(isPending => {\n if (isPending) {\n patent.pendingRequesters.push(userID);\n }\n });\n patents.getRate.call(patent.id, userID).then(rate => {\n if (rate > 0) {\n patent.rates.push(rate.toNumber())\n }\n });\n });\n }\n return patents.getPatentName.call(patent.id);\n }).then(name => {\n patent['name'] = name;\n const split = name.split('.');\n patent['fileExt'] = split[split.length - 1];\n return patents.getPrices.call(patent.id);\n }).then(prices => {\n patent['licencePrices'] = prices.map(price => price.toNumber());\n resolve(patent);\n }).catch(reject);\n });\n }\n }", "function insertVirtualMediaOnNodes(idrac_ips, image_path) {\n\treturn new Promise((resolve, reject) => {\n\t\tconsole.log(\"insertVirtualMediaOnNodes function called for \", idrac_ips); //debugging\n\t\tlet insertedCounter = 0;\n\n\t\ttry {\n\t\t\tidrac_ips.forEach(idrac_ip => {\n\t\t\t\t// checkRedfishSupport(idrac_ip)\n\t\t\t\t// .then(response => {\n\t\t\t\t// console.log(`checkRedfishSupport result for ${idrac_ip} is: ${response.message}`);\n\t\t\t\t// if (response.success) {\n\t\t\t\tcheckVirtualMediaCdStatus(idrac_ip)\n\t\t\t\t\t.then(response => {\n\t\t\t\t\t\tconsole.log(`checkVirtualMediaCdStatus result for ${idrac_ip} is inserted: ${response.message}`);\n\t\t\t\t\t\tif (response.message === \"true\") {\n\t\t\t\t\t\t\tejectVirtualMediaCD(idrac_ip)\n\t\t\t\t\t\t\t\t.then(response => {\n\t\t\t\t\t\t\t\t\tconsole.log(`ejectVirtualMediaCD result for ${idrac_ip} is: ${response.message}`);\n\t\t\t\t\t\t\t\t\tif (response.success) {\n\t\t\t\t\t\t\t\t\t\tinsertVirtualMediaCD(idrac_ip, image_path)\n\t\t\t\t\t\t\t\t\t\t\t.then(response => {\n\t\t\t\t\t\t\t\t\t\t\t\tconsole.log(`insertVirtualMediaCD result for ${idrac_ip} is: ${response.message}`);\n\t\t\t\t\t\t\t\t\t\t\t\tif (response.success) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t// deleteJobQueue(idrac_ip, \"CLEARALL\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t// .then(response => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t// console.log(`deleteJobQueue result for ${idrac_ip} is: ${response.message}`);\n\t\t\t\t\t\t\t\t\t\t\t\t\t// if (response.success) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsetNextOneTimeBootVirtualMediaDevice(idrac_ip)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.then(response => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole.log(`setNextOneTimeBootVirtualMediaDevice result for ${idrac_ip} is: ${response.message}`);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!response.success) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: response.message\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tinsertedCounter++;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (insertedCounter == idrac_ips.length) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (idrac_ips.length == 1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: `---\"${image_path}\" has been successfuly inserted on the selected node and set to boot from it.---`\n\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\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: `---\"${image_path}\" has been successfuly inserted on all selected nodes and set to boot from it.---`\n\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\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}) \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.catch(error => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole.log(`CATCH in setNextOneTimeBootVirtualMediaDevice: ${error.message}`);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: `CATCH in setNextOneTimeBootVirtualMediaDevice: ${error.message}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\t\t\t\t\t\t\t// })\n\t\t\t\t\t\t\t\t\t\t\t\t\t// .catch(error => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t// console.log(`CATCH in deleteJobQueue: ${error.message}`);\n\t\t\t\t\t\t\t\t\t\t\t\t\t// reject({\n\t\t\t\t\t\t\t\t\t\t\t\t\t// success: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\t// message: `CATCH in deleteJobQueue: ${error.message}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: response.message\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}) \n\t\t\t\t\t\t\t\t\t\t\t.catch(error => {\n\t\t\t\t\t\t\t\t\t\t\t\tconsole.log(`CATCH in insertVirtualMediaCD: ${error.message}`);\n\t\t\t\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: `CATCH in insertVirtualMediaCD: ${error.message}`\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tmessage: response.message\n\t\t\t\t\t\t\t\t\t\t});\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\t.catch(error => {\n\t\t\t\t\t\t\t\t\tconsole.log(`CATCH in ejectVirtualMediaCD: ${error.message}`);\n\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\tmessage: `CATCH in ejectVirtualMediaCD: ${error.message}`\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} else {\n\t\t\t\t\t\t\tinsertVirtualMediaCD(idrac_ip, image_path)\n\t\t\t\t\t\t\t\t.then(response => {\n\t\t\t\t\t\t\t\t\tconsole.log(`insertVirtualMediaCD result for ${idrac_ip} is: ${response.message}`);\n\t\t\t\t\t\t\t\t\tif (response.success) {\n\t\t\t\t\t\t\t\t\t\t// deleteJobQueue(idrac_ip, \"CLEARALL\")\n\t\t\t\t\t\t\t\t\t\t// .then(response => {\n\t\t\t\t\t\t\t\t\t\t// console.log(`deleteJobQueue result for ${idrac_ip} is: ${response.message}`);\n\t\t\t\t\t\t\t\t\t\t// if (response.success) {\n\t\t\t\t\t\t\t\t\t\tsetNextOneTimeBootVirtualMediaDevice(idrac_ip)\n\t\t\t\t\t\t\t\t\t\t\t.then(response => {\n\t\t\t\t\t\t\t\t\t\t\t\tconsole.log(`setNextOneTimeBootVirtualMediaDevice result for ${idrac_ip} is: ${response.message}`);\n\t\t\t\t\t\t\t\t\t\t\t\tif (!response.success) {\n\t\t\t\t\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: response.message\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\tinsertedCounter++;\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (insertedCounter == idrac_ips.length) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (idrac_ips.length == 1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: `---\"${image_path}\" has been successfuly inserted on the selected node and set to boot from it.---`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: `---\"${image_path}\" has been successfuly inserted on all selected nodes and set to boot from it.---`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t.catch(error => {\n\t\t\t\t\t\t\t\t\t\t\t\tconsole.log(`CATCH in setNextOneTimeBootVirtualMediaDevice: ${error.message}`);\n\t\t\t\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tmessage: `CATCH in setNextOneTimeBootVirtualMediaDevice: ${error.message}`\n\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\t\t\t\t// })\n\t\t\t\t\t\t\t\t\t\t// .catch(error => {\n\t\t\t\t\t\t\t\t\t\t// console.log(`CATCH in deleteJobQueue: ${error.message}`);\n\t\t\t\t\t\t\t\t\t\t// reject({\n\t\t\t\t\t\t\t\t\t\t// success: false,\n\t\t\t\t\t\t\t\t\t\t// message: `CATCH in deleteJobQueue: ${error.message}`\n\t\t\t\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t\t\t\t\t// });\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tmessage: response.message\n\t\t\t\t\t\t\t\t\t\t});\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\t.catch(error => {\n\t\t\t\t\t\t\t\t\tconsole.log(`CATCH in insertVirtualMediaOnNodes: ${error.message}`);\n\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\tmessage: `CATCH in insertVirtualMediaOnNodes: ${error.message}`\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\t.catch(error => {\n\t\t\t\t\t\t\t\t\tconsole.log(`CATCH in insertVirtualMediaCD: ${error.message}`);\n\t\t\t\t\t\t\t\t\treject({\n\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\tmessage: `CATCH in insertVirtualMediaCD: ${error.message}`\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}\n\t\t\t\t\t})\n\t\t\t\t\t.catch(error => {\n\t\t\t\t\t\tconsole.log(`CATCH in checkVirtualMediaCdStatus: ${error.message}`);\n\t\t\t\t\t\treject({\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\tmessage: `CATCH in checkVirtualMediaCdStatus: ${error.message}`\n\t\t\t\t\t\t});\n\t\t\t\t\t})\n\n\t\t\t\t// } else {\n\t\t\t\t// reject({\n\t\t\t\t// success: false,\n\t\t\t\t// message: `iDRAC version installed on ${idrac_ip} does not support this functionality via Redfish`\n\t\t\t\t// });\n\t\t\t\t// }\n\t\t\t\t// })\n\t\t\t\t// .catch(error => {\n\t\t\t\t// console.log(`CATCH in insertVirtualMediaCD: ${error.message}`);\n\t\t\t\t// reject({\n\t\t\t\t// success: false,\n\t\t\t\t// message: `CATCH in insertVirtualMediaCD: ${error.message}`\n\t\t\t\t// });\n\t\t\t\t// });\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconsole.log(`CATCH in insertVirtualMediaOnNodes: ${error.message}`);\n\t\t\treject({\n\t\t\t\tsuccess: false,\n\t\t\t\tmessage: `CATCH in insertVirtualMediaOnNodes: ${error.message}`\n\t\t\t});\n\t\t}\n\t});\n}", "async resolveBatchResults(results) {\n const messageIDs = results.reduce((acc, { associatedIDs }) => acc.concat(associatedIDs), []);\n const representations = await this.client.rest.messages.fetchMany(messageIDs);\n return Promise.all(representations.map(rep => this.add(rep)));\n }", "getReqId() {\n return new Promise((resolve, reject) => {\n // Generate an unique id\n try {\n const id = rs.generate({\n length: 32,\n charset: 'alphanumeric'\n });\n ;\n resolve(id);\n } catch (err) {\n reject(err);\n }\n });\n }", "async function getUsernameFromId(listOfUserIds) {\n var apiUrl = 'https://accounts.rec.net/account/bulk';\n\n return new Promise(function (resolve, reject) {\n var formData = new FormData();\n listOfUserIds.forEach(item => formData.append(\"id\", item));\n\n axios({\n method: 'post',\n url: apiUrl,\n data: formData,\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then(function (response) {\n // handle success\n resolve(response.data);\n })\n .catch(function (error) {\n // handle error\n console.log(error);\n reject(error);\n })\n .then(function () {\n // always executed\n });\n });\n}", "function sqPushUpdates(pushObject) {\n // DEFINE LOCAL VARIABLES\n var opsPromiseList = [];\n\n // NOTIFY PROGRESS\n console.log(\"sqPushUpdates got this notification:\"); \n console.log(pushObject);\n\n // DEFINE LOCAL VARIABLES\n\n // RETURN ASYNC WORK\n return new Promise(function sqPushUpdatesPromise(resolve, reject) {\n\n // NOTIFY PROGRESS\n console.log('sqPushUpdates: squareV1.retrievePayment');\n\n // DOWNLOAD SQUARE TRANSACTION\n squareV1.retrievePayment(pushObject.location_id, pushObject.entity_id)\n .then(function success(sqTx) {\n \n //var instanceIdPromise = ivdb.read.instanceId(s.created_at, s.tender[0].employee_id);\n //var sqTxToOpMapPromise = ivdb.\n\n // NOTIFY PROGRESS\n console.log('sqPushUpdates: ivdb.read.instanceId', sqTx);\n \n // AFTER THE TRANSACTION HAS BEEN OBTAINED COLLECT THE INVENTORY INSTANCES\n ivdb.read.instanceId(sqTx.created_at, sqTx.tender[0].employee_id).then(function success(instanceId) {\n\n // NOTIFY PROGRESS\n console.log('sqPushUpdates: instanceId', instanceId );\n\n // ONCE THE INSTANCE ID HAS BEEN IDENTIFIED, RECORDS CAN BE ADDED TO IT\n ivdb.map.txToOp(sqTx.itemizations)\n .then(function success(opsList) {\n // DEFINE LOCAL VARIABLES\n //var isVariable = ()\n\n // ITERATE OVER THE LIST OF OPERATIONS\n for(var i = 0; i < opsList.length; i++) {\n opsPromiseList.push(\n ivdb.run.entryOperation(opsList[i], instanceId, ivdb.data.formatDateLong(sqTx.created_at), i, (sqTx.tip_money.amount / (opsList.length)))\n );\n };\n\n // NOTIFY PROGRESS\n console.log('running ', opsPromiseList.length, \" operations\");\n\n // FINALLY RUN ALL THE PROMISES\n Promise.all(opsPromiseList)\n .then(function succes(s) {\n\n // NOTIFY PROGRESS\n console.log('sqPushUpdates: All operations run');\n\n resolve(s);\n \n }).catch(function error(e) {\n reject(e);\n });\n \n }).catch(function error(e) {\n reject(e);\n });\n\n }).catch(function error(e) {\n reject(e);\n });\n\n }).catch(function error(e) {\n\n // NOTIFY PROGRESS\n console.log('ERROR:');\n console.log(e);\n\n reject(e);\n\n });\n\n \n });\n}", "function createPromises (ids, callback) {\n let promiseArray = [];\n ids.forEach(function (id, index) {\n promiseArray.push(createNewPromise(callback, id, index));\n });\n return promiseArray;\n}", "regenerateIds(req, schema, doc) {\n for (const field of schema) {\n if (field.type === 'array') {\n for (const item of (doc[field.name] || [])) {\n item._originalId = item._id;\n item._id = self.apos.util.generateId();\n self.regenerateIds(req, field.schema, item);\n }\n } else if (field.type === 'object') {\n self.regenerateIds(req, field.schema, doc[field.name] || {});\n } else if (field.type === 'area') {\n if (doc[field.name]) {\n doc[field.name]._originalId = doc[field.name]._id;\n doc[field.name]._id = self.apos.util.generateId();\n for (const item of (doc[field.name].items || [])) {\n item._originalId = item._id;\n item._id = self.apos.util.generateId();\n const schema = self.apos.area.getWidgetManager(item.type).schema;\n self.regenerateIds(req, schema, item);\n }\n }\n }\n // We don't want to regenerate attachment ids. They correspond to\n // actual files, and the reference count will update automatically\n }\n }", "function createExistingIdentities() {\n\n}", "async function updateCardsInTrade () {\n const updateTrade = async ({ object: { id } }, change) => {\n const trade = await Trade.get(id);\n trade.yourOffer.forEach(({ id: cid, print_id: pid }) => {\n cardsInTrades.updatePrint(id, \"give\", cid, pid, change);\n });\n trade.parnerOffer.forEach(({ id: cid, print_id: pid }) => {\n cardsInTrades.updatePrint(id, \"receive\", cid, pid, change);\n });\n };\n\n onTradeChange(\n (initialTrades) => {\n Promise.all(initialTrades.map((trade) => updateTrade(trade, +1)))\n .then(cardsInTrades.ready);\n },\n (addedTrade) => {\n updateTrade(addedTrade, +1);\n },\n (removedTrade) => {\n updateTrade(removedTrade, -1);\n },\n );\n}", "xhrItems(ids, cb) {\n setTimeout(_.partial(cb, null, _.map(ids, (id) => {\n return {\n 'id': id,\n 'product': faker.commerce.productName(),\n 'brand': faker.company.companyName(),\n 'color': faker.commerce.color(),\n 'material': faker.commerce.productMaterial(),\n 'price': faker.commerce.price()\n }\n })), _.random(200, 500));\n }" ]
[ "0.63187206", "0.62814933", "0.6165819", "0.61442494", "0.6141721", "0.6042492", "0.59505856", "0.59123796", "0.5897462", "0.5817669", "0.57656187", "0.57368577", "0.57148826", "0.56886595", "0.5686155", "0.56849086", "0.5683023", "0.56461793", "0.56388587", "0.5590095", "0.5555175", "0.5552768", "0.5529135", "0.5492654", "0.546446", "0.5449807", "0.5443675", "0.543308", "0.54217476", "0.5376566", "0.53684604", "0.53271824", "0.5323598", "0.5313514", "0.5306643", "0.5295399", "0.52948976", "0.52853215", "0.5265925", "0.5261666", "0.5240803", "0.52354205", "0.5235013", "0.52155715", "0.52144396", "0.52023417", "0.51960623", "0.5172989", "0.51641417", "0.516242", "0.5152004", "0.51495105", "0.51469994", "0.51445794", "0.5143779", "0.513492", "0.51343924", "0.5132417", "0.51318264", "0.5129711", "0.51286185", "0.5119541", "0.5116332", "0.51152486", "0.51076317", "0.51058155", "0.5104992", "0.50965685", "0.50893", "0.50890905", "0.50881773", "0.50868297", "0.508671", "0.50846153", "0.5084441", "0.5080476", "0.50763816", "0.5075792", "0.50742984", "0.5069312", "0.5065858", "0.50568545", "0.50552225", "0.5053312", "0.50498956", "0.5046644", "0.5044859", "0.50425005", "0.5042139", "0.5037746", "0.5037193", "0.50357646", "0.5033679", "0.5031997", "0.5031596", "0.50293833", "0.50065035", "0.4997378", "0.49963003", "0.49952704" ]
0.5605028
19
Creates single linked resource
function createLinked(linkedModel, linkedResource){ return createResources(linkedModel, [linkedResource]) .then(function(resources){ return resources[0].id; }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function createAndLink(fromResource, useProperty, type, dataCallback) {\n RDFAUTHOR_START_FIX = \"linkAndCreate\";\n var serviceUri = urlBase + 'service/rdfauthorinit';\n\n // check if an resource is in editing mode\n if (typeof RDFAUTHOR_STATUS != 'undefined') {\n if(RDFAUTHOR_STATUS === 'active') {\n alert(\"Please finish all other editing actions before creating a new instance.\");\n return;\n }\n }\n\n // remove resource menus\n removeResourceMenus();\n\n loadRDFauthor(function() {\n $.getJSON(serviceUri, {\n mode: 'class',\n uri: type\n }, function(data) {\n if (data.hasOwnProperty('propertyOrder')) {\n var propertyOrder = data.propertyOrder;\n delete data.propertyOrder;\n }\n else {\n var propertyOrder = null;\n }\n // pass data through callback\n if (typeof dataCallback == 'function') {\n data = dataCallback(data);\n }\n var addPropertyValues = data['addPropertyValues'];\n var addOptionalPropertyValues = data['addOptionalPropertyValues'];\n RDFAUTHOR_DISPLAY_FIX = data['displayProperties'];\n RDFAUTHOR_DATATYPES_FIX_ADDITIONAL_DATA = data['additionalData'];\n delete data['addPropertyValues'];\n delete data['addOptionalPropertyValues'];\n delete data.additionalData;\n delete data.displayProperties;\n\n // get default resource uri for subjects in added statements (issue 673)\n // grab first object key\n for (var subjectUri in data) {break;};\n // add statements to RDFauthor\n var graphURI = selectedGraph.URI;\n populateRDFauthor(data, true, subjectUri, graphURI, 'class');\n RDFauthor.setOptions({\n saveButtonTitle: 'Create Resource',\n cancelButtonTitle: 'Cancel',\n title: ['createNewInstanceOf', type],\n autoParse: false,\n showPropertyButton: true,\n loadOwStylesheet: false,\n addPropertyValues: addPropertyValues,\n addOptionalPropertyValues: addOptionalPropertyValues,\n onSubmitSuccess: function (responseData) {\n newObjectSpec = resourceURL(responseData.changed);\n if (responseData && responseData.changed) {\n var objectUri = resourceURL(responseData.changed);\n var pos = objectUri.indexOf('=', objectUri);\n objectUri = objectUri.substring(pos+1,objectUri.length);\n $.ajax({\n type: \"POST\",\n url: urlBase + 'linkandcreate/linktriple',\n data: {subject: fromResource, predicate: useProperty, object: objectUri }\n });\n // HACK: reload whole page after 500 ms\n window.setTimeout(function () {\n window.location.href = window.location.href;\n }, 500);\n }\n },\n onCancel: function () {\n // everything fine\n }\n });\n\n var options = {};\n if (propertyOrder != null) {\n options.propertyOrder = propertyOrder;\n }\n options.workingMode = 'class';\n RDFauthor.start(null, options);\n })\n });\n}", "function resourceCreate(cb) {\n\n var resource = new Resource({\n //_projectId: [projects[0]],\n name: 'server',\n type: 'Facility',\n status: 'Available',\n deletedAt: null\n });\n\n resource.save(function (err) {\n if (err) {\n cb('resource', null);\n return\n }\n console.log('New Resource ' + resource);\n resources.push(resource);\n cb(null, resource);\n } );\n}", "function addResource(newResource){\n return db('resources')\n .insert(newResource, 'id')\n .then(id => {\n return getResourceById(id[0])\n })\n}", "function txCreateResource(name, slug, content) {\n\n var action = TX_API + \"/project/\" + TX_PROJECT_SLUG + \"/resources/\";\n\n var options = {\n uri: action,\n auth: TX_AUTH,\n header: { \"Content-Type\": \"application/json\" },\n json: {\n name: name,\n slug: slug,\n content: content,\n i18n_type: 'RESJSON'\n }\n };\n\n var deferred = q.defer();\n\n request.post(options, function (error, response, body) {\n if (!error && response.statusCode === 201) {\n deferred.resolve(body);\n } else {\n deferred.reject(body);\n }\n });\n return deferred.promise;\n }", "function createResource (data, maxAge, type) {\n return {\n body: data,\n headers: {\n 'Cache-Control': 'public, max-age=' + Math.floor(maxAge / 1000),\n 'ETag': etag(data)\n },\n type: type\n };\n}", "_handleRequestResourceCreate(options)\n {\n var resource = null;\n if (options.resourcetype)\n {\n resource = new Resource({project: options.project.get('url'), file: options.file, resource_type: options.resourcetype});\n }\n else\n {\n resource = new Resource({project: options.project.get('url'), file: options.file});\n }\n var jqXHR = resource.save({}, {success: (model) => this._handleCreateSuccess(model, this._collection)});\n Radio.channel('rodan-client-core').request(Events.REQUEST__TRANSFERMANAGER_MONITOR_UPLOAD, {request: jqXHR, file: options.file});\n }", "createResource(data, parent_id = null) {\n if (!data) {\n throw \"data is needed\";\n return;\n }\n this.parent_id = parent_id;\n var route = this.buildUrl();\n var promise_request = new Promise((resolve, reject) => {\n this._http.post(route, data)\n .then((data) => {\n resolve(this.created(data));\n })\n .catch((err) => {\n reject(err);\n });\n });\n return promise_request;\n }", "attachResource (resource) {\n if (typeof resource !== 'object' || resource === null ||\n typeof resource.close !== 'function') {\n throw new TypeError('The first argument must be a resource object')\n }\n\n this[kResources].add(resource)\n }", "function createTopicResource(url, title) {\r\n //\r\n var webpageTitle = cleanUpForJson(title);\r\n var webtopic = '{\"uri\":\"\",\"type_uri\":\"dm4.webbrowser.web_resource\",\"composite\":'\r\n + '{\"dm4.webbrowser.web_resource_description\":\"'+webpageTitle+'\",\"dm4.webbrowser.url\":\"'+url+'\"}}';\r\n // checks if topic with given url already exists\r\n getTopicByValueAndType('dm4.webbrowser.url', url, function(responseText) {\r\n //\r\n if (responseText != undefined) {\r\n // ### Notify user and load existing Bookmark, may wants to change title/name of URL \r\n if (lookmarker.statusLabel != undefined) lookmarker.statusLabel.value = lookmarker.statusdoubledURL;\r\n } else { // undefined => no topic like this known.. go on create it.\r\n sendTopicPost(webtopic, getResultingTopicId);\r\n }\r\n });\r\n}", "function create_link(self, kw, common)\n {\n let id = kw_get_str(kw, \"id\", kw_get_str(kw, \"name\", \"\"));\n\n /*\n * Check if link exists\n */\n let gobj_link = self.yuno.gobj_find_unique_gobj(id);\n if(gobj_link) {\n log_error(sprintf(\"%s: link already exists '%s'\", self.gobj_short_name(), id));\n return null;\n }\n\n // 'id' or 'name' can be use as all port names\n kw[\"source_port\"] = kw_get_dict_value(kw, \"source_port\", id);\n kw[\"target_port\"] = kw_get_dict_value(kw, \"target_port\", id);\n\n json_object_update_missing(kw, common);\n\n return self.yuno.gobj_create_unique(id, Ka_link, kw, self);\n }", "async create(resource) {\n try {\n return this._convertFrom(await this._model.create(resource));\n }\n catch (e) {\n this._handleError(e);\n }\n }", "function create_resource (form) {\n var theform = $(form);\n theform.checkValidity();\n var action_status = $('.action-status');\n action_status.text(\"Creating resource ...\");\n var inputs = theform.serializeArray();\n var params = {}\n for(var i in inputs){\n params[inputs[i].name] = inputs[i].value;\n }\n params.owner = current_ctx; \n params.picture = picture;\n params.calc_mode = model.time_based() ? calc_modes.time_based : calc_modes.quantity_based;\n params.calendar = model.calendar();\n function success() {\n action_status.text(\"Resource created successfully\").attr('class', 'status-success');\n setTimeout(function(){\n window.location = basepath + '/resources';\n }, 1000);\n };\n function error() {\n action_status.text(\"Error in creating resource\").attr('class', 'status-fail');\n };\n jsonrpc('resource.new', params, success, error);\n}", "function addLink() {\n SC.RunLoop.begin();\n Nodelink.store.createRecord(Nodelink.Link, { guid: 'node2', startNode: 'node1', endNode: 'node2' } );\n SC.RunLoop.end();\n}", "function create(fromKey, toKey, type){\n return new Promise(function (resolve, reject) {\n var PremiseCollection = Arango.getPremisLinkCollection();\n var datetime = Utils.getCreateDateForDb();\n PremiseCollection.save({\n \"_from\": fromKey,\n \"_to\": toKey,\n \"type\": type,\n \"creationDate\": datetime\n }).then((meta) => {\n resolve({\n \"_from\": fromKey,\n \"_to\": toKey,\n \"type\": type,\n \"creationDate\": datetime,\n \"_id\": meta._id,\n \"_key\": meta._key\n });\n }).catch((err) => {\n console.log('FAIL: premise link creation fail');\n reject(err);\n });\n });\n}", "async function saveResource(req, res) {\n let body = req.body;\n\n let resource = {\n name: body.name,\n description: body.description,\n status: body.status || true,\n }\n\n await Resource.create(resource)\n .then(async result => {\n saveBitacora('Resource', result.id, result.name, 'create', req.user.id);\n res.status(200).json({\n ok: true,\n message: 'Recurso creado con éxito',\n result\n });\n })\n .catch(err => {\n res.status(500).send({\n ok: false,\n message: 'Recurso no creado, ha ocurrido un error',\n error: err.parent.detail\n });\n });;\n}", "async createLink () {\n\t\tconst thing = this.codemark || this.review || this.codeError;\n\t\tconst type = (\n\t\t\t(this.codemark && 'c') ||\n\t\t\t(this.review && 'r') ||\n\t\t\t(this.codeError && 'e')\n\t\t);\n\t\tconst attr = (\n\t\t\t(this.codemark && 'codemarkId') ||\n\t\t\t(this.review && 'reviewId') ||\n\t\t\t(this.codeError && 'codeErrorId')\n\t\t);\n\t\tconst linkId = UUID().replace(/-/g, '');\n\t\tthis.url = this.makePermalink(linkId, this.isPublic, thing.teamId, type);\n\t\tconst hash = this.makeHash(thing, this.markers, this.isPublic, type);\n\n\t\t// upsert the link, which should be collision free\n\t\tconst update = {\n\t\t\t$set: {\n\t\t\t\tteamId: thing.teamId,\n\t\t\t\tmd5Hash: hash,\n\t\t\t\t[attr]: thing.id\n\t\t\t}\n\t\t};\n\n\t\tconst func = this.request.data.codemarkLinks.updateDirectWhenPersist ||\n\t\t\tthis.request.data.codemarkLinks.updateDirect;\t// allows for migration script\n\t\tawait func.call(\n\t\t\tthis.request.data.codemarkLinks,\n\t\t\t{ id: linkId },\n\t\t\tupdate,\n\t\t\t{ upsert: true }\n\t\t);\n\t}", "static create(displayName, intrinsicVal,desc){\n const nameArr=displayName.toLowerCase().split(\" \");\n const nameToUse=nameArr[nameArr.length-1];\n return new Resource (nameToUse,displayName,intrinsicVal,desc);\n }", "function addResc(resource){\n return db.insert(resource, '*').into('resources');\n}", "function create(req, res) {\n Recipe.create(req.body, function (err, recipe) {\n res.redirect('/recipes')\n })\n}", "function addRoomResource(room_name, ressource_name){\n\tdb.run(`insert into room_ressource (idRoom, idRessource)\n\tvalues((select idRoom from rooms where name = ?),\n\t(select idRessource from ressources where name = ?))`,\n\t[room_name, ressource_name]);\n}", "function makeUrl(protocol, host, resource, id) {\n return protocol + \"://\" + host + resource + id;\n}", "function create() {\n const id = uuid();\n props.history.push(`/${id}`);\n }", "async createLinkDoc (accountId) {\n const linkProofPromise = this.createLink(this.idw.id)\n\n const linkDoc = await this.ceramic.createDocument(\n 'account-link',\n { metadata: { owners: [accountId] } },\n { applyOnly: true }\n )\n const linkProof = await linkProofPromise\n await linkDoc.change({ content: linkProof })\n await this.ceramic.pin.add(linkDoc.id)\n await this.idx.set('cryptoAccountLinks', { [accountId]: linkDoc.id })\n }", "create() {\n const source = internal(this).source;\n const target = internal(this).target;\n // Make sure source and target both exist.\n source.create();\n target.create();\n // Add connection to the model.\n const model = internal(source).model;\n internal(model).connections.add(this);\n }", "function create(req, res) {\n req.model.userId = req.auth.userId\n //request to the model payload\n traumaTypesService.create(req.model)\n .then(id => {\n const responseModel = new responses.ItemResponse()\n responseModel.item = id\n res.status(201)\n .location(`${_apiPrefix}/${id}`)\n .json(responseModel)\n })\n .catch(err => {\n console.log(err)\n res.status(500).send(new responses.ErrorResponse(err))\n })\n}", "create(resource, requestOptions) {\n return this.request({ ...requestOptions,\n url: `${resource.resourceType}`,\n method: \"POST\",\n body: JSON.stringify(resource),\n headers: {\n // TODO: Do we need to alternate with \"application/json+fhir\"?\n \"content-type\": \"application/json\",\n ...(requestOptions || {}).headers\n }\n });\n }", "function addRessource(r){\n\tdb.run(`insert into ressources (name) values ('${r.name}')`);\n}", "static createLink(name, link) {\n return Helper_1.createEntry(name, true, `Object.assign(exports, require('${link}'));`);\n }", "function PHPJS_Resource (type, id, opener) { // Can reuse the following for other resources, just changing the instantiation\r\n // See http://php.net/manual/en/resource.php for types\r\n this.type = type;\r\n this.id = id;\r\n this.opener = opener;\r\n }", "function PHPJS_Resource (type, id, opener) { // Can reuse the following for other resources, just changing the instantiation\r\n // See http://php.net/manual/en/resource.php for types\r\n this.type = type;\r\n this.id = id;\r\n this.opener = opener;\r\n }", "function Resource()\r\n{\r\n\tthis.filename = null; //name of file without folder or path\r\n\tthis.fullpath = null; //contains the unique name as is to be used to fetch it by the resources manager\r\n\tthis.remotepath = null; //the string to fetch this resource in internet (local resources do not have this name)\r\n\tthis._data = null;\r\n\t//this.type = 0;\r\n}", "static insert(resource_obj, type) {\n\n try{\n type = type.toLowerCase();\n const parent_obj = {\"type\":type, \"title\": resource_obj.title, \"id\":0}; // parent resource obj fits this schema\n delete resource_obj.id; // make it fit for the child table\n delete resource_obj.title; // make it fit for the child table\n const parent_data = connection.query(`INSERT INTO resource VALUES( ${this.objectToQueryString(parent_obj)} )`); // Insert resource data (parent)\n resource_obj.resource_id = parent_data.insertId; // with the insert id of the resource table, reference the fk of the child data to the pk of the parent\n resource_obj.id = 0;\n connection.query(`INSERT INTO ${type} VALUES (${this.objectToQueryString(resource_obj)})`); // Insert into the child table the child data (book, magazine, music, movie)\n //const date = new Date(Date.now() + (1000 /*sec*/ * 60 /*min*/ * 60 /*hour*/ * 24 /*day*/ * 10)).toString();\n const resource_line_item = {\"id\":0, \"resource_id\": parent_data.insertId, \"user_id\": null, \"date_due\": ''}; // declare schema for the line item instance (this table represents the number of instances)\n connection.query(`INSERT INTO resource_line_item (id, resource_id, user_id, date_due) VALUES(0, ${resource_line_item.resource_id}, NULL, '${resource_line_item.date_due}')`);\n const resource = this.select(parent_data.insertId).results\n return {status: 0, message: 'Resource Added', results: resource};\n }\n catch(error){\n return{ status: 1, message: 'Error' +error, error}\n }\n }", "function create(uri) {\r\n return { uri: uri };\r\n }", "function create(uri) {\r\n return { uri: uri };\r\n }", "function create(uri) {\r\n return { uri: uri };\r\n }", "function create(uri) {\r\n return { uri: uri };\r\n }", "function create(uri) {\r\n return { uri: uri };\r\n }", "function create(uri) {\r\n return { uri: uri };\r\n }", "function create(uri) {\n return {\n uri: uri\n };\n }", "function create(uri) {\n return {\n uri: uri\n };\n }", "function create(uri) {\n return {\n uri: uri\n };\n }", "create(req, res) {\n\n\t}", "create () {}", "create () {}", "function create(uri) {\n return { uri: uri };\n }", "function create(req, res) {\n Note.create(req.body, function (err, note) {\n res.redirect('/recipes/:id')\n })\n}", "create() {}", "create() {}", "create(path, attrs) {\n return this.network.run`\n ${this.model}.find_by(uuid: '${this.information.uuid}').\n ${path}.\n create!(JSON.parse('${JSON.stringify(attrs)}'))\n `\n }", "addResource(resource) {\n this._resource = this._resource.merge(resource);\n }", "async function createOne (req, res) {\n const archive = new Archives({\n name : req.body.name,\n stat : \"archive\"\n })\n try {\n const newArchive = await archive.save()\n res.json(newArchive)\n } catch (err) {\n res.json({message : err.message})\n }\n}", "function createOne(req, res){\n Authors.create(req.body)\n .then(data => {\n console.log(\"got to controller-create\")\n res.json(data)})\n .catch(errs => res.json(errs))\n}", "save(resource, object) {\n const url = `${baseUrl}/${resource}/`\n return this.fetchFactory(url, \"POST\", object)\n }", "function createK8sNodeResource (name, grpcEndpoint, status) {\n const obj = {\n apiVersion: 'openebs.io/v1alpha1',\n kind: 'MayastorNode',\n metadata: defaultMeta(name),\n spec: { grpcEndpoint }\n };\n if (status) {\n obj.status = status;\n }\n return obj;\n}", "function createMWSResource(shells, onSuccess) {\n $.post(mongo.config.baseUrl, null,function (data, textStatus, jqXHR) {\n if (!data.res_id) {\n $.each(shells, function (i, shell) {\n shell.insertError('No res_id recieved! Shell disabled.');\n });\n } else {\n console.info('/mws/' + data.res_id, 'was created succssfully.');\n onSuccess(data);\n }\n }, 'json').fail(function (jqXHR, textStatus, errorThrown) {\n $.each(shells, function (i, shell) {\n shell.insertResponseLine('Failed to create resources on DB on server');\n console.error('AJAX request failed:', textStatus, errorThrown);\n });\n });\n }", "function resource(_id, _type, _paths) { // Queues a resource for download. Called it resource so it can be declared in the same way of a scene\n\tvar resi = {\n\t\tpaths: _paths, // Multiple paths, will try until one works\n\t\tpathToTry: 0, // Increments each time until a path works\n\t\ttype: _type, // image, audio, video\n\t\tdownloaded: false,\n\t\tfailed: false,\n\t\tdata: (_type == \"image\") ? new Image() :\n\t\t\t (_type == \"audio\") ? new Audio() :\n\t\t\t (console.log(_type + \" is not supported by the resource downloader.\")) ? false : false // To do: add video support\n\t};\n\tres[_id] = resi;\n\tresVars.totalResources++;\n\tresVars.resourcesLeftToDownload++;\n}", "shallowResource(resource, controller) {\n const resourceInstance = new Resource_1.RouteResource(resource, controller, this.matchers, true);\n const openedGroup = this.getRecentGroup();\n if (openedGroup) {\n openedGroup.routes.push(resourceInstance);\n }\n else {\n this.routes.push(resourceInstance);\n }\n return resourceInstance;\n }", "function Resource(model, resource_name, options) {\n this.model = model;\n this.options = {\n limit: 20,\n refs: null\n };\n this.many_path = \"/\" + resource_name;\n this.single_path = \"/\" + resource_name + \"/:_id\";\n _.merge(this.options, options);\n this.options.path = this.many_path;\n this.emitter = new EventEmitter();\n }", "static createHardLink(options) {\n FileSystem._wrapException(() => {\n return FileSystem._handleLink(() => {\n return fsx.linkSync(options.linkTargetPath, options.newLinkPath);\n }, Object.assign(Object.assign({}, options), { linkTargetMustExist: true }));\n });\n }", "function createResource(id_folder, folder, code) {\n\n if(!queryResource(1, 2, code, '', folder)) return false;\n\n var id_resource = ++d_resources.list_folders[id_folder].files_folder.numbers_items_url_youtube;\n jQuery.getJSON( \"https://noembed.com/embed?format=json&url=https://www.youtube.com/watch/?v=\"+code)\n .done(function (json) {\n jQuery('#folder_resources_'+id_folder).prepend(\n '<div id=\"resource_item_'+id_folder+'_'+id_resource+'\" class=\"col s12 m4\">' +\n '<div class=\"card small hoverable\" id=\"resource-list\">' +\n '<div class=\"card-image mix\">' +\n '<a class=\"portfolio-thumbnill\" target=\"_blank\" href=\"https://www.youtube.com/embed/'+code+'/?autoplay=1\">' +\n '<img src=\"https://i.ytimg.com/vi/'+code+'/hqdefault.jpg\" alt=\"\">' +\n '<i class=\"material-icons view-icon\">play_circle_outline</i>' +\n '</a>'+\n '</div>' +\n '<div class=\"card-content\">' +\n '<span class=\"card-title activator\" onclick=\"actionResource(\\'delete\\',\\''+id_folder+'\\',\\''+id_resource+'\\',\\''+code+'\\');\"><i class=\"material-icons right\">delete</i></span>' +\n '<p>'+json.title+'</p>' +\n '</div>' +\n '</div>' +\n '</div>'\n );\n });\n\n jQuery(\".portfolio-list\").lightGallery({\n selector: '.portfolio-thumbnill',\n download: false\n });\n\n return true;\n}", "createOne(req, res) {\n this.sendNotFound(req, res);\n }", "create(req, res) {\n Assembly.create(req.body)\n .then(Assembly => res.json(Assembly))\n .catch(err => res.status(400).json(err));\n }", "async function postResourceToDB(newResource) {\n try {\n const res = await axios.post(\"http://localhost:8000/newResource\", newResource);\n console.log(res.data);\n }\n catch(err) {\n console.log(\"error in post resource: \" + err);\n }\n }", "create(title, cost, description, thumbnail, image){\n let template = {\n \"title\": title,\n \"cost\": cost,\n //VERY BAD, USE Object.Id (mongoose)\n // \"id\": this.guid(),\n \"id\": Math.floor(1000 + Math.random() * 9000),\n \"description\": description,\n \"thumbnail\": thumbnail,\n \"image\": image\n }\n this.templates.push(template)\n this.saveTemplates((err, data) => {\n if (err){\n console.log(err)\n return\n }\n })\n return template\n }", "function createShortUrl(req, res, next) {\n\tif(!req.body.longUrl) {\n return res.status(400).send({\"status\": \"error\", \"message\": \"A long URL is required\"});\n }\n db.any('SELECT * FROM urls WHERE long_url = $1', [req.body.longUrl])\n .then(function (data) {\n if(data.length === 0) {\n \tvar hashids \t= new Hashids();\n \tvar response = {\n\t id: hashids.encode((new Date).getTime()),\n\t longUrl: req.body.longUrl\n \t}\n \tresponse.shortUrl = \"http://localhost:3000/\" + response.id;\n \t\n db.none('INSERT INTO urls(id, short_url, long_url) VALUES(${id}, ${shortUrl}, ${longUrl})', response)\n .then(function () {\n\t res.status(200)\n\t .json({\n\t status: 'success',\n data: response,\n\t message: 'Inserted one url'\n\t });\n\t })\n\t .catch(function (err) {\n\t return next(err);\n\t });\n\t\t} else {\n\t\t\tres.send(data[0]);\n\t\t}\n\t})\n\t.catch(function (err) {\n return next(err);\n });\n}", "function create() {\n\n}", "create(req, res) {\n PetsService.create(req.body)\n .then((result) =>\n res.status(201).location(`/api/v1/pet/${result.id}`).json(result)\n )\n .catch((error) => {\n res.status(500).json(error);\n });\n }", "create(req, res) {\n Item.create(req.body)\n .then((newItem) => {\n res.status(200).json(newItem);\n })\n .catch((error) => {\n res.status(500).json(error);\n });\n }", "async function addResource () {\n// const message2I = prompt(\"Ask a question/ or comment & we will get back to you\")\n Axios.post(\"/api/resources\", {\n // author: user.id,\n heading: myheading,\n catagory: mycatagory,\n subtitle: mysubtitle,\n body1: mybody1,\n body2: mybody2,\n rating: myrating,\n // link: mylink\n })\n .then(res => console.log(res))\n .then(alert(\"Saved Resource\"))\n .catch(err => alert(err));\n}", "function create(req, res, next) {\n var url = req.body.url;\n ShortUrl.build({ url: url }).save().complete(function(err,short) {\n if(!err) {\n var id = short.id;\n res.json({url: url, hash_code: hasher.encode(id), hits: short.hits });\n } else {\n next(err);\n }\n });\n}", "create(request, response) {\n console.log('insde create', request.body);\n Resttask.create(request.body)\n .then(resttask => response.json(resttask))\n .catch(error => response.json(error));\n }", "function Resource(name, type, inline, element) {\n this.name = name;\n this.type = type;\n this.inline = inline;\n this.element = element;\n}", "async create() {\n const { ctx, service } = this;\n const params = getParams(ctx, 'body');\n const res = await service.user.crud({\n type: 'createOne',\n data: params,\n });\n ctx.body = res;\n }", "create() {\n\t}", "function create(data) {\n return $http.post(baseEndpoint, data).then(function (response) {\n data.id = R.last(response.headers().location.split('/'));\n response.data = data;\n return response;\n });\n }", "function createReference(initialValues) {\n var referenceType = entityManager.metadataStore.getEntityType('Reference');\n // create a new reference entity\n var entity = entityManager.createEntity(referenceType, initialValues);\n entity.Type = 'SP.Data.Research_x0020_ReferencesListItem';\n entity['odata.type'] = 'SpResourceTracker.Models.Reference';\n return entity;\n }", "function addResource(config){ \r\n var expressApp = config.expressApp,\r\n dataModel = config.dataModel,\r\n resourceName = config.resourceName,\r\n resourceConfig = config.resourceConfig;\r\n \r\n for(var action in resourceConfig.actions){\r\n addResourceAction({\r\n action: resourceConfig.actions[action],\r\n apiConfig: resourceConfig,\r\n expressApp: expressApp,\r\n resourceFacade: dataModel[resourceName]\r\n });\r\n }\r\n}", "async createPermalink () {\n\t\tif (this.attributes.teamId) {\n\t\t\tthis.attributes.permalink = await new PermalinkCreator({\n\t\t\t\trequest: this.request,\n\t\t\t\tcodeError: this.attributes\n\t\t\t}).createPermalink();\n\t\t}\n\t}", "async function generateUrl() {\n try{\n const response = await instance.post(\"/create_url\", {\n url: longurl,\n });\n setNew(response.data);\n }catch(error){\n console.log(error)\n }\n \n }", "function CreateLink(editor) {\r\n\tthis.editor = editor;\r\n\tvar cfg = editor.config;\r\n\tvar self = this;\r\n\r\n editor.config.btnList.createlink[3] = function() { self.show(self._getSelectedAnchor()); }\r\n}", "create(argv) {\n const resourceRule = argv.strategy_resource ?\n argv.strategy_resource : \"./resource/never\";\n\n return require(resourceRule);\n }", "function callCreate(object){ object.create(); }", "add(title, url, description = \"\", template = \"STS\", language = 1033, inheritPermissions = true) {\r\n const props = {\r\n Description: description,\r\n Language: language,\r\n Title: title,\r\n Url: url,\r\n UseSamePermissionsAsParentSite: inheritPermissions,\r\n WebTemplate: template,\r\n };\r\n const postBody = jsS({\r\n \"parameters\": extend({\r\n \"__metadata\": { \"type\": \"SP.WebCreationInformation\" },\r\n }, props),\r\n });\r\n return this.clone(Webs_1, \"add\").postCore({ body: postBody }).then((data) => {\r\n return {\r\n data: data,\r\n web: new Web(odataUrlFrom(data).replace(/_api\\/web\\/?/i, \"\")),\r\n };\r\n });\r\n }", "function createPatient(requestData)\n{\n //var url = \"http://uclactive.westeurope.cloudapp.azure.com:8080/openmrs/ws/fhir/Patient\";\n var url = \"http://51.140.66.103:8080/openmrs/ws/fhir/Patient\";\n\n var options = {\n uri: url,\n method: 'POST',\n json: requestData,\n headers:{\n 'Authorization': 'Basic ' + new Buffer(\"*****:*****\").toString('base64')\n } \n };\n\n request(options, function (error, response, body) {\n if (!error && (response.statusCode == 200 || response.statusCode == 201)) {\n console.log(body.id) // Print the shortened url.\n } else {\n console.log(\"error: \" + error)\n console.log(\"response.statusCode: \" + response.statusCode)\n console.log(\"response.statusText: \" + response.statusText)\n }\n });\n}", "function createNodeResource (name, grpcEndpoint, status) {\n return new NodeResource(createK8sNodeResource(name, grpcEndpoint, status));\n}", "function createResourceWorker(fn) {\n\t\tvar strResource = createWorkerScript(fn.toString());\n\t\tvar resource = $URL.createObjectURL(new Blob([strResource], { type: 'text/javascript' }));\n\t\treturn resource;\n\t}", "function createPatient(requestData)\n{\n //var url = \"http://uclactiveserver.westeurope.cloudapp.azure.com:8080/openmrs/ws/fhir/Patient\";\n var url = \"http://51.140.66.103:8080/openmrs/ws/fhir/Patient\";\n\n var options = {\n uri: url,\n method: 'POST',\n json: requestData,\n headers:{\n 'Authorization': 'Basic ' + new Buffer(\"*****:*****\").toString('base64')\n } \n };\n\n request(options, function (error, response, body) {\n if (!error && (response.statusCode == 200 || response.statusCode == 201)) {\n console.log(body.id) // Print the shortened url.\n } else {\n console.log(\"error: \" + error)\n console.log(\"response.statusCode: \" + response.statusCode)\n console.log(\"response.statusText: \" + response.statusText)\n }\n });\n}", "async create (req, res) {\n throw new Error('create: Implementation Missing!')\n }", "allocate () {\n this.lastBorrowTime = Date.now()\n this.state = PooledResourceStateEnum.ALLOCATED\n }", "async function createThing() {\n const rootObjectGroup = await client.getRootObjectGroup();\n const thingPayload = {\n _name: 'SampleThing',\n _description: {\n en: 'Sample thing created with SAP Leonardo IoT SDK',\n },\n _thingType: [thingTypePayload.Name],\n _objectGroup: rootObjectGroup.objectGroupID,\n };\n\n const createThingResponse = await client.createThing(thingPayload, { resolveWithFullResponse: true });\n const thingId = createThingResponse.headers.location.split('\\'')[1];\n console.log(`Thing created: ${thingId}`);\n}", "create({ title, description }) {\n const id = uuidv4();\n\n const object = {\n id,\n title,\n description\n };\n\n this.data[id] = (object);\n return Promise.resolve(object);\n }", "function resource(title,id,description,tasks,start,end,complete) {\n\t\t\tthis.title = title;\n\t\t\tthis.id = id;\n\t\t\tthis.description = description;\n\t\t\tthis.tasks = tasks;\n\t\t\tthis.start = start;\n\t\t\tthis.end = end;\n\t\t\tthis.complete = complete;\n\t\t}", "async CreateAsset(ctx, id, laborname, firstname, lastname,birthdate, location, dateandtime, result ) {\r\n const exists = await this.AssetExists(ctx, id);\r\n if (exists) {\r\n throw new Error(`The asset ${id} already exists`);\r\n }\r\n\r\n \r\n\t\tlet testedPersonObject = new TestedPerson( id,firstname,lastname, birthdate\r\n\t\t\r\n\t\t ,laborname,location,dateandtime,result);\r\n\t\t\t\t\t\t\t\t\t\t\t\t \r\n\t\ttestedPersonObject.docType = 'testedPerson';\t\t\t\t\t\t\t\t\t\t \r\n\t\t\r\n await ctx.stub.putState(id, Buffer.from(JSON.stringify(testedPersonObject)));\r\n return JSON.stringify(testedPersonObject);\r\n }", "function createObject(e){\n\t\n\t// create random object data\n\tvar object={\n\t\tname: 'PeppaTest Object' + Math.floor(Math.random()*100),\n\t\tstatus: 'created',\n\t\tcost: 2.99\n\t};\n\t\n\t// Now Save It\n\tapi.Object.Create('PeppaTest',object,function(r){\n\t\tif(r.success){\n\t\t\talert('New Object persisted to server');\n\t\t}\n\t});\t\n\t\n}", "create({ body }, res) {\n let sponsor = {\n name: body.name,\n description: body.description,\n sponsorLinks: body.links,\n sponsorMedia: body.mediaObjs\n }\n saveImg(body.logo)\n .then(logo =>\n Sponsor.create({...sponsor, logo}, {include: [SponsorLink, SponsorMedia]})\n )\n .then((c)=>{res.json(c)});\n }", "getResource(internal_name) {\n if (IsString(internal_name, true)) {\n const resource = this.asset.resource.get(internal_name);\n return resource ? resource : {};\n }\n }", "function create(params) {\n var loan = new RequestLoan();\n loan.resource = params.resource;\n loan.user = params.user;\n return loan;\n}", "function createResource(asyncFn) {\n let status = \"pending\";\n let result;\n let promise = asyncFn().then(\n r => {\n status = \"success\";\n result = r;\n },\n e => {\n status = \"error\";\n result = e;\n }\n )\n return {\n read: () => {\n if (status === \"pending\") throw promise;\n if (status === \"error\") throw result;\n if (status === \"success\") return result;\n throw new Error(\"This should be impossible\");\n }\n }\n}", "function addIDandSelfLink(req, item){\n item.id = item[Datastore.KEY].id;\n item.self = \"https://\" + req.get(\"host\") + req.route.path + \"/\"+ item.id;\n return item;\n}", "function createEvent(eventData) {\n // First create resource that will be send to server.\n var resource = {\n 'summary': eventData.eventTitle,\n 'start': {\n 'dateTime': new Date(eventData.date + ' ' + eventData.startTime).toISOString()\n },\n 'end': {\n 'dateTime': new Date(eventData.date + ' ' + eventData.endTime).toISOString()\n },\n };\n // create the request\n var request = gapi.client.calendar.events.insert({\n 'calendarId': 'primary',\n 'resource': resource\n });\n\n // execute the request\n request.execute(function(resp) {\n var linkToEvent = 'Event created: <a href=\"' + resp.htmlLink + '\">link to event</a>';\n console.log(\"Inside linkToEvent ...\" + linkToEvent);\n document.getElementsByClassName('event-created')[0].innerHTML = linkToEvent;\n });\n}" ]
[ "0.7318703", "0.675712", "0.64981854", "0.6326865", "0.6103492", "0.59534866", "0.5906946", "0.588835", "0.58253855", "0.5800774", "0.57741034", "0.57535577", "0.5748674", "0.5725261", "0.5682321", "0.5679762", "0.56629163", "0.564455", "0.5627849", "0.55961746", "0.5590086", "0.5589121", "0.55847585", "0.5515673", "0.55095583", "0.54949975", "0.54813725", "0.54799956", "0.54768103", "0.54768103", "0.54679036", "0.54647857", "0.5463918", "0.5463918", "0.5450644", "0.5450644", "0.5450644", "0.5450644", "0.5441302", "0.5441302", "0.5441302", "0.5434253", "0.5433832", "0.5433832", "0.54197884", "0.54010695", "0.5397417", "0.5397417", "0.5391364", "0.53783005", "0.5371945", "0.5368822", "0.5348071", "0.53410083", "0.53339285", "0.5331724", "0.53280115", "0.5324311", "0.53141683", "0.53014266", "0.52870715", "0.52773696", "0.52755964", "0.5270527", "0.52652884", "0.52583647", "0.5253406", "0.5246553", "0.5234648", "0.52319604", "0.52309316", "0.52249324", "0.52124864", "0.5203791", "0.5196197", "0.5192487", "0.5192256", "0.5175895", "0.5173125", "0.51701343", "0.51682055", "0.5164989", "0.51638824", "0.5161444", "0.51548994", "0.51532435", "0.5149639", "0.5146953", "0.5146187", "0.5134388", "0.51342607", "0.5131115", "0.51291764", "0.51243937", "0.5123997", "0.51175874", "0.51163805", "0.5114263", "0.511137", "0.5110379" ]
0.702165
1
Get the related resources of an individual resource. Called if request.method is GET and no matching action was found
function getSubresources(req, res) { var id = req.params.id, key = req.params.key, originalFilter = req.query.filter ? _.cloneDeep(req.query.filter) : {}; zipkinTracer.scoped(() => { const traceId = zipkinTracer.createRootId(); req.zipkinTraceId = traceId; zipkinTracer.setId(traceId); zipkinTracer.recordServiceName('fortune-read-sub-resource'); zipkinTracer.recordRpc(req.method.toUpperCase()); zipkinTracer.recordBinary('fortune.resource', name); zipkinTracer.recordBinary('fortune.subresource', key); zipkinTracer.recordAnnotation(new Annotation.ServerRecv()); }); const localTracer = zipkin.makeLocalCallsWrapper(req, zipkinTracer); var projection = {}; var select = parseSelectProjection(req.query.fields, model.modelName); req.query.fortuneExtensions = [{}]; req.fortune.routeMetadata = _.extend({}, req.fortune.routeMetadata, { type: ROUTE_TYPES.getSubresources, resource: collection, subResourcePath: key }); if (select){ projection = { select: select }; } if (!_.isUndefined(req.query.limit)){ projection.limit = parseInt(req.query.limit,10); } if(id){ //Reset query.filter to value applied to primary resource req.query.filter = {}; req.query.filter.id = id; } localTracer('before-read-hooks-primary', () => beforeReadHook({}, req, res)) .then(function(){ // get a resource by ID return localTracer('reading-database-primary', () => { zipkinTracer.recordBinary('fortune.mongo_query', zipkin.safeStringify(req.query.filter)); zipkinTracer.recordBinary('fortune.mongo_projection', zipkin.safeStringify(projection)); return adapter.find(model, req.query.filter, projection) }); }, function(err){ sendError(req, res, 500, err); }) // run after read hook .then(function(resource) { return localTracer('after-read-hooks-primary', () => afterReadHook(resource, req, res)); }, function(error) { sendError(req, res, 404, error); }) // change context to resource .then(function(resource) { var ids, relatedModel; try { ids = resource.links[key]; if (_.isUndefined(ids)) { ids = []; } ids = _.isArray(ids) ? ids : [ids]; relatedModel = _this._schema[name][key]; relatedModel = _.isArray(relatedModel) ? relatedModel[0] : relatedModel; relatedModel = _.isPlainObject(relatedModel) ? relatedModel.ref : relatedModel; if (key && key.length > 0 && !relatedModel) { return sendError(req, res, 404); } } catch(error) { return sendError(req, res, 404, error); } var findPromise; if (_.size(ids) > 0) { //Reset req.query.filter to original value discarding changes applied for parent resource req.query.filter = originalFilter; req.query.filter.id = {$in: ids}; //run before read hook findPromise = localTracer('before-read-hooks-secondary', () => beforeReadHook(relatedModel, {}, req, res)) .then(function(){ // find related resources return localTracer('readin-database-secondary', () => adapter.findMany(relatedModel, req.query.filter, _.isNumber(projection.limit) ? projection.limit : undefined)); }, function(err){ sendError(req, res, 500, err); }); } else { var deferred = RSVP.defer(); deferred.resolve([]); findPromise = deferred.promise; } // do after transforms findPromise.then(function(resources) { return localTracer('after-read-hooks-secondary', () => { return RSVP.all(resources.map(function (resource) { return afterReadHook(relatedModel, resource, req, res); })); }); }, function(error) { sendError(req, res, 500, error); }) // send the response .then(function(resources) { var body = {}; body[inflect.pluralize(relatedModel)] = resources; sendResponse(req, res, 200, body); }, function(error) { sendError(req, res, 403, error); }); }, function(error) { sendError(req, res, 403, error); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getRelated() {}", "function get(req, res, next) {\n const prop = pluralize.singular(req.params.resource);\n req.query[`${prop}${opts.foreignKeySuffix}`] = req.params.id;\n req.url = `/${req.params.nested}`;\n next();\n } // Rewrite URL (/:resource/:id/:nested -> /:nested) and request body", "function get(req, res, next) {\n const prop = toProp(req.params.resource)\n req.query[prop] = toId(req.params.id)\n req.url = `/${req.params.nested}`\n next()\n }", "fetch () {\n this._makeRequest('GET', resources);\n }", "function getAction(resourceName, actionName, method){\n\t//get all actions for resource\n\treturn this._actions[resourceName] &&\n\t\tthis._actions[resourceName][actionName];\n}", "function relatedResourcesWidget() {\n\t\tvar $this = $(this);\n\t\tvar resource = $this.data();\n\t\tvar dataSource = resource.source;\n\t\t// URL of service\n\t\tvar template = resource.template;\n\t\t// Template to use\n\t\tvar $parent = $this.parent();\n\n\t\t// Get data\n\t\t$.ajax({\n\t\t\ttype: 'GET',\n\t\t\turl: dataSource,\n\t\t\tcache: true,\n\t\t\tdataType: 'json',\n\t\t\tsuccess: function relatedResourcesRequestSuccess(json) {\n\t\t\t\tvar data = json.Resources;\n\t\t\t\tvar dataL = data.length;\n\t\t\t\tvar i;\n\n\t\t\t\tfor(i = 0; i < dataL; i++) {\n\t\t\t\t\tbuildContent(data[i], $this, template);\n\t\t\t\t}\n\n\t\t\t\tif(dataL === 0) {\n\t\t\t\t\t$parent.remove();\n\t\t\t\t}\n\t\t\t},\n\t\t\tcomplete: function relatedResourcesRequestComplete() {\n\t\t\t\tlimitText();\n\n\t\t\t\t// Use the AMD module if available\n\t\t\t\tif (dynamicRatingsModule) {\n\t\t\t\t\tdynamicRatingsModule.dynamicRatings();\n\t\t\t\t} else {\n\t\t\t\t\twindow.dynamicRatings();\n\t\t\t\t}\n\n\t\t\t\t// run again to fix rail height if necessary\n\t\t\t\tif (podHeightsModule) {\n\t\t\t\t\tpodHeightsModule.fixPodHeights();\n\t\t\t\t} else {\n\t\t\t\t\twindow.fixPodHeights();\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function relatedResourcesRequestError() {\n\t\t\t\t$parent.remove();\n\t\t\t}\n\t\t});\n\t}", "get relatedItems() {\r\n return RelatedItemManagerImpl.FromUrl(this.toUrl());\r\n }", "get resources() {\n return this.resource ? [this.resource] : [];\n }", "getRelatedData(qParams) {\n return this.request.get('/entry-related-data', qParams);\n }", "loadRelated(params) {\n return this.request.get('entry-related-data', params);\n }", "function userGet(req, res, next) {\n res.send(req.currentResources);\n}", "loadRelated(qParams) {\n return this.request.get('entry-related-data', qParams);\n }", "function getQuery(req, res, next) {\n var resourceName = req.params.resource;\n var query = data.get(resourceName);\n\n if (!query) {\n \tnext({ // 404 if the request does not map to a registered query\n statusCode: 404,\n message: \"Unable to create a query for \" + resourceName\n });\n } else {\n query(req.query, _callback(res, next));\n }\n}", "get related () {\n\t\treturn this._related;\n\t}", "function getAction(resourceId,actionId) {\n return $http({\n url: baseUrl + '/show/' + resourceId + '/' + actionId,\n method: 'GET'\n }).then(function(res){\n return res;\n }).catch(function(err){\n throw err;\n });\n }", "function getObjects(req, res, next) {\n var location = req.param(\"location\");\n var type = req.param(\"type\");\n objectService.getObjects(location, type, (error, response) => {\n if (response == null) {\n ResponseHandler(404, response, res);\n return;\n }\n ResponseHandler(error, response, res);\n });\n}", "getResources(options) {\n\n options = options || {};\n\n if (options.populate) {\n return SUtils.getResources(this.project.getPopulated(options));\n } else {\n return SUtils.getResources(this.project.get());\n }\n }", "function updateResources(data) {\n var traitsPaged = _.get(\n _.find(data.traits || [], function(trt) {\n return trt.paged\n }),\n 'paged.queryParameters'\n )\n if (traitsPaged) {\n _.forEach(data.resources || [], function(resource) {\n _.forEach(resource.methods || [], function(method) {\n if ((method.is || []).includes('paged')) {\n method.queryParameters = _.extend(\n method.queryParameters || {},\n traitsPaged\n )\n }\n })\n })\n }\n return data\n}", "get relatedAction () {\n\t\treturn this._relatedAction;\n\t}", "findResource(id, params = {}, parent_id = null) {\n if (!id) {\n throw \"ID is needed\";\n return;\n }\n this.parent_id = parent_id;\n var route = this.buildUrl(id);\n var resource_promise = new Promise((resolve, reject) => {\n this._http.get(route, {\n params\n })\n .then((response) => {\n resolve(this.found(response));\n })\n .catch((err) => {\n reject(err);\n });\n });\n\n return resource_promise;\n }", "function isResource(request) {\n return request.url.match(/\\/imgs\\/.*$/) && request.method === 'GET';\n}", "getResource(params = {}, parent_id = null) {\n this.parent_id = parent_id\n var route = this.buildUrl();\n var promise_request = new Promise((resolve, reject) => {\n this._http.get(route, {\n params\n })\n .then((response) => {\n resolve(this.fetched(response));\n })\n .catch(error => {\n reject(error);\n })\n });\n\n return promise_request\n }", "function get( options ) {\n return ( request, reply ) => {\n\n let _handler = ( request, options ) => {\n\n debug( 'get' );\n\n return new Promise( done => {\n\n options.getCriteria( request, done )\n\n } ).then(criteria=> {\n\n let Model = request.server.getModel( options.model );\n\n return Model.find( criteria ).then( models => {\n\n return models;\n });\n })\n };\n\n let _reply = ( reply, response ) => {\n\n reply( response );\n\n };\n\n return _do( _handler, _reply, request, reply, options, 'get' )\n\n }\n}", "async getReferences(req, res) {\n var applicationId;\n if (!req.query || !req.query.applicationId) {\n return res\n .status(400)\n .send({ error: \"applicationId param was not provided with request.\" });\n }\n ({ applicationId } = req.query);\n const matchedReferences = await References.findOne({\n applicationId,\n userId: req.user._id,\n });\n if (matchedReferences) {\n return res.status(200).send(matchedReferences);\n } else {\n return res.status(404).send({\n error:\n \"references for given application and user combination not found.\",\n });\n }\n }", "async function getResource(identifier) {\n let res = await db.query('SELECT * FROM resources WHERE id = ?', [identifier])\n if (res.length > 0) return res[0]\n res = await db.query('SELECT * FROM resources WHERE reference = ?', [identifier])\n if (res.length > 0) return res[0]\n return null\n }", "function getObjectsResolved(req, res, next) {\n var userid = req.param(\"userid\");\n objectService.getObjectsResolved(userid, (error, response) => {\n if (response == null) {\n ResponseHandler(404, response, res);\n return;\n }\n ResponseHandler(error, response, res);\n });\n}", "function getObjectsOwnedByUser(req, res, next) {\n var userid = req.param(\"userid\");\n objectService.getObjectsOwnedByUser(userid, (error, response) => {\n if (response == null) {\n ResponseHandler(404, response, res);\n return;\n }\n ResponseHandler(error, response, res);\n });\n}", "function getProfessionals(req, res) {\n if (DEBUG_TRACE_LEVEL >= 1) {\n console.log('**** FUNCTION professionals.getProfessionals ****');\n }\n\n if (DEBUG_TRACE_LEVEL >= 2) {\n console.log('req.query.id: ', req.query.id);\n }\n\n if (typeof req.query.id !== 'undefined') {\n if (DEBUG_TRACE_LEVEL >= 1) {\n console.log(\"1.getProfessionals.professionalId is defined: \", req.query.id)\n }\n getProfessionalById(req, res);\n } else {\n if (DEBUG_TRACE_LEVEL >= 1) {\n console.log(\"2.getProfessionals.professionalId is undefined: \", req.query.id)\n }\n getProfessionalsByQuery(req, res);\n }\n}", "getApplicationSetRelatedResources(variables) {\n return client.query({\n query: Query.getApplicationSetRelatedResources,\n variables\n })\n }", "async function getResources(req, res) {\n await Resource.findAll()\n .then(resources => {\n if (resources.length === 0) {\n return res.status(200).json({\n ok: false,\n message: 'No hay recursos registrados',\n });\n } else {\n res.status(200).json({\n ok: true,\n message: 'correcto',\n resources\n });\n }\n })\n .catch(err => {\n console.log(err);\n res.status(500).json({\n ok: false,\n message: 'Ha ocurrido un error',\n error: err.message\n });\n });\n}", "function getObjectsByUser(req, res, next) {\n var userid = req.param(\"userid\");\n objectService.getObjectsByUser(userid, (error, response) => {\n if (response == null) {\n ResponseHandler(404, response, res);\n return;\n }\n ResponseHandler(error, response, res);\n });\n}", "getResources (portalOpts) {\n const urlPath = `/portals/self/resources?f=json`;\n return this.request(urlPath, null, portalOpts);\n }", "function getMyRoutes() {\r\n\r\n // Get and return all runs in database\r\n $.ajax({\r\n url: \"/api/getMyRoutes/\" + user.userId,\r\n method: \"GET\"\r\n })\r\n .then(function (response) {\r\n displayMyRoutes(response);\r\n });\r\n}", "relations(request, reply) {\n if (!this.options.relations || !this.options.relations[request.params.relation]) {\n return reply(Boom.notFound());\n }\n\n const join = {};\n join[request.params.relation] = true;\n\n this.Model.get(request.params[this.options.primaryKey]).getJoin(join).run().then((doc) => {\n reply(doc);\n });\n }", "getAll(request, response, next) {\n this.model.find({}, (err, data) => {\n if (err) {\n return next(err);\n }\n response.json(data);\n });\n }", "function handlGetReferences(req, res, filter) {\n async.waterfall([\n req.repo.getReferences.bind(req.repo, git.Reference.Type.All),\n function (refNames, cb) {\n if (filter) {\n refNames = _.filter(refNames, filter);\n }\n // convert reference names to references\n async.map(refNames, refNameToJSON.bind(req.repo), cb);\n }\n ], function (err, refs) {\n if (err) {\n res.status(500).json({ error: err.toString() });\n } else {\n res.status(200).json(refs);\n }\n });\n}", "all(parent, includeChildren) {\n\t\treturn this.$http.get(`${this.path()}${includeChildren ? \"?include_children\" : \"\"}`, {\n\t\t\tparams: {\n\t\t\t\tparent\n\t\t\t},\n\t\t\tcache: includeChildren ? false : this.cache\n\t\t}).then(response => response.data);\n\t}", "async function getAccessForAll(resourceUrl, actorType) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : internal_defaultFetchOptions;\n if (actorType === \"agent\") {\n return getAgentAccessAll$3(resourceUrl, options);\n }\n if (actorType === \"group\") {\n return getGroupAccessAll(resourceUrl, options);\n }\n return null;\n}", "getDaStuffs(){\n axios.get(`/api/pages/${this.props.user.id}`).then(response => {\n this.props.getPages(response.data);\n })\n axios\n .get(`/api/blogs/${this.props.user.id}`)\n .then(response => {\n this.props.getBlogs(response.data);\n })\n .catch(console.log())\n }", "function Resource(model, resource_name, options) {\n this.model = model;\n this.options = {\n limit: 20,\n refs: null\n };\n this.many_path = \"/\" + resource_name;\n this.single_path = \"/\" + resource_name + \"/:_id\";\n _.merge(this.options, options);\n this.options.path = this.many_path;\n this.emitter = new EventEmitter();\n }", "function resFilter(resourceKey) {\n return resource.get(resourceKey);\n }", "function isResource(req, res, next) {\n let uri = req._parsedOriginalUrl.path;\n if (uri.includes('/api')){\n uri = uri.substring(4);\n }\n if (uri.includes('?')){\n uri = uri.substring(0, uri.indexOf(\"?\"));\n }\n uri = uri.substring(1);\n uri = uri.substring(0, uri.indexOf('/'));\n // let table = uri.substring(0, uri.length - 1);\n let table = uri;\n let id = Number(req.params.id);\n client.query(`SELECT id FROM ${table} WHERE id = '${id}'`, function(error, results) {\n // error will be an Error if one occurred during the query\n // results will contain the results of the query\n // fields will contain information about the returned results fields (if any)\n if (error) {\n throw error;\n }\n if (results.rowCount === 0){\n res.render('404');\n }\n else {\n next();\n }\n });\n}", "function isResource(req, res, next) {\n let uri = req._parsedOriginalUrl.path;\n if (uri.includes('/api')){\n uri = uri.substring(4);\n }\n if (uri.includes('?')){\n uri = uri.substring(0, uri.indexOf(\"?\"));\n }\n uri = uri.substring(1);\n uri = uri.substring(0, uri.indexOf('/'));\n // let table = uri.substring(0, uri.length - 1);\n let table = uri;\n let id = Number(req.params.id);\n client.query(`SELECT id FROM ${table} WHERE id = '${id}'`, function(error, results) {\n // error will be an Error if one occurred during the query\n // results will contain the results of the query\n // fields will contain information about the returned results fields (if any)\n if (error) {\n throw error;\n }\n if (results.rowCount === 0){\n res.render('404');\n }\n else {\n next();\n }\n });\n}", "function get(req, res) {\n\tif(req.params.id === '0') { // respond with a new resident model\n\t\tauth.allowsAdd(req.decoded.id, 'residents') // is authorized to add ?\n\t\t\t.then(granted => res.json(new Resident()))\n\t\t\t.catch(errorToNotify);\n\t} else { // respond with fetched re model\n\t\tResident\n\t\t\t.forge( {id: req.params.id} )\n\t\t\t.fetch()\n\t\t\t.then(doAuth) // is authorized to view?\n\t\t\t.then(model => res.json(model))\n\t\t\t.catch(errorToNotify);\n\t}\n\tfunction doAuth(model) {\n\t\tlogger.debug('/api/residents >> get()...');\n\t\treturn auth.allowsView(req.decoded.id, 'residents', model);\n\t}\n\tfunction errorToNotify(err) {\n\t\tlogger.error(err)\n\t\treturn res.status(500).json({error: true, data: {message: err.message}});\n\t}\n}", "getQuestion(req, res) {\n // console.log(\"get question\");\n Question.findById(req.params.id,\n (err, ques) => {\n if (err) {\n // res.status(500).send();\n res.json({\n status: 500,\n error: err\n });\n }\n else {\n res.json({\n status: 200,\n question: ques\n });\n }\n });\n\n // const question = questions.filter(q => (q.id === parseInt(req.params.id)));\n // if (question.length > 1) return res.status(500).send();\n // if (question.length === 0) return res.status(404).send();\n // res.send(question[0]);\n }", "function getMyExercises(){\n var request = $http({\n method: \"get\",\n url: \"/myActivities\",\n params: {\n action: \"get\"\n }\n\n\n });\n\n return( request.then( handleSuccess, handleError ) );\n }", "function getOne(req, res, next) {\n req.url = `/${req.params.nested}/${req.params.nestedId}`\n next()\n }", "get resources() {\n return [this.resource];\n }", "function loadJourneyRelatedBehaviourData()\n\t\t{\n\t\t\tvar objRequest = {\n\t\t\t\t\tacrq: 'load-journey-related-behaviours',\n\t\t\t\t\tjourney_id: $scope.objJourney.id\n\t\t\t};\n\t\t\t\n\t\t\t$scope.objJourneyRelatedBehaviours = Array();\n\t\t\tvar $p = JourneysPageService.get(objRequest, \n\t\t\t\tfunction success(response) {\n\t\t\t\t\tlogToConsole(response);\n\t\t\t\t\t//check for errors\n\t\t\t\t\tif (typeof response.error != 'undefined' && response.error == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tdoErrorAlert('Unable to load Journey Related Behaviours', '<p>Request failed with response: ' + response.response + '</p>');\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}//end if\n\t\t\t\t\t\n\t\t\t\t\tangular.forEach(response.objData, function (objBehaviour, i) {\n\t\t\t\t\t\t$scope.objJourneyRelatedBehaviours.push(objBehaviour);\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\t//trigger build journey diagram function\n\t\t\t\t\tloadJourneyFlowDiagram();\n\t\t\t\t},\n\t\t\t\tfunction error(errorResponse) {\n\t\t\t\t\tlogToConsole(errorResponse);\n\t\t\t\t\tdoErrorAlert('Unable to complete request', '<p>An unknown error has occurred. Please try again.</p>');\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\t$scope.loadJourneyBehavioursProgress.addPromise($p);\n\t\t}//end function", "async get() {\r\n let params = {\r\n where: this.getWheres(),\r\n include: this.getIncludes(),\r\n order: this.getOrders(),\r\n group: this.getGroup()\r\n };\r\n\r\n if (!_.isArray(this.getAttributes()) && this.getAttributes().length > 0) {\r\n params = _.assign(params, { attributes: this.getAttributes() });\r\n }\r\n let model = this.Models();\r\n if (this.getScopes().length > 0) {\r\n _.forEach(this.getScopes(), scope => {\r\n model = model.scope(scope);\r\n });\r\n }\r\n const result = await model.findAll(params);\r\n\r\n return result;\r\n }", "async fetch () {\n\t\tif (this.notFound.length === 0) {\n\t\t\treturn;\t// got 'em all from the cache ... yeehaw\n\t\t}\n\t\telse if (this.notFound.length === 1) {\n\t\t\t// single ID fetch is more efficient\n\t\t\treturn await this.fetchOne();\n\t\t}\n\t\telse {\n\t\t\treturn await this.fetchMany();\n\t\t}\n\t}", "__allResourcesReturned () {\n const ps = Array.from(this._resourceLoans.values())\n .map((loan) => loan.promise)\n .map(reflector)\n return this._Promise.all(ps)\n }", "function getResources() {\n return $http({\n method: 'get',\n headers: { 'Content-Type': 'application/json' },\n url: 'https://mywell-server.vessels.tech' + '/api/resources?filter=%7B%22fields%22%3A%7B%22image%22%3Afalse%7D%7D'\n }).then(function (response) {\n //cache the response\n $localstorage.setObject('getResourcesCache', response);\n return response;\n }).catch(function (err) {\n //Rollback to previous request if exists\n var cached = $localstorage.getObject('getResourcesCache');\n if (!angular.isNullOrUndefined(cached)) {\n return cached;\n }\n\n return Promise.reject(err);\n });\n }", "get (request, response) {\n // Compare the get request url to all valid requests.\n if (request.url === '/') {\n // If the root url / index was requested call index function.\n this.index(request, response);\n } else if (request.url === '/highscore') {\n // If the highscore page was requested call the highscore get function.\n this.highscoreGet(request, response);\n } else {\n // If the request did not match any of the above default to index.\n this.index(request, response);\n }\n }", "getRelatedMovie(movies) {\n // It Display Related Movie When User Search For Movie\n this.displayRelatedMovie(movies)\n }", "getRelatedRecords(record) {\n return [];\n }", "getRelatedRecords(record) {\n return [];\n }", "getResources(widget) {\n return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {\n if (IsObject(widget.resource, true)) {\n const success = yield this.resource.setCollection(widget.resource);\n if (success) {\n this.resource.getCollection(widget.resource);\n return resolve(true);\n }\n else {\n resolve(false);\n }\n }\n else {\n resolve(false);\n }\n }));\n }", "function getAllJournals(req, res, next) {\n\tJournals.findAll({ \n\t\twhere: {\n\t\t\tuserID: req.params.id\n\t\t}\n\t})\n .then(found => res.json(found))\n .catch(err=>next(err));\n}", "async function getResourceById(req, res) {\n let id = req.params.id;\n await Resource.findOne({ where: { id } })\n .then(resource => {\n if (resource === null) {\n return res.status(200).json({\n ok: false,\n message: 'No existe un recurso con ese id asociado',\n });\n } else {\n res.status(200).json({\n ok: true,\n message: 'correcto',\n resource\n });\n }\n })\n .catch(err => {\n res.status(500).json({\n ok: false,\n message: 'Ha ocurrido un error',\n error: err.message\n });\n });\n}", "getWithQuery(queryParams, options) {\n options = this.setQueryEntityActionOptions(options);\n const action = this.createEntityAction(EntityOp.QUERY_MANY, queryParams, options);\n this.dispatch(action);\n return this.getResponseData$(options.correlationId).pipe(\n // Use the returned entity ids to get the entities from the collection\n // as they might be different from the entities returned from the server\n // because of unsaved changes (deletes or updates).\n withLatestFrom(this.entityCollection$), map(([entities, collection]) => entities.reduce((acc, e) => {\n const entity = collection.entities[this.selectId(e)];\n if (entity) {\n acc.push(entity); // only return an entity found in the collection\n }\n return acc;\n }, [])), shareReplay(1));\n }", "_doRelatedRequest(store, snapshot, relatedSnapshots, relationship, url) {\n return this.ajax(url, 'PATCH', {\n data: store.serializerFor('preprint').serialize(snapshot),\n isBulk: false\n });\n }", "async _get({ href }) {\n let request = this._requests.get(href);\n if (!request) {\n const action = new SirenAction({ href });\n request = this.submit({ action }).finally(() => this._requests.delete(href));\n this._requests.set(href, request);\n }\n return request;\n }", "getAll(resource) {\n const url = `${baseUrl}/${resource}/`\n return this.fetchFactory(url)\n }", "function apiHandler(req, reply) {\n\n var rb = new RepresentationBuilder(settings.relsUrl);\n var resource = rb.create({}, req.url);\n\n // grab the routing table and iterate\n var routes = req.server.table();\n for (var i = 0; i < routes.length; i++) {\n var route = routes[i];\n\n // :\\\n var halConfig = route.settings.app && route.settings.app.hal;\n\n if (halConfig && halConfig.apiRel) {\n var rel = halConfig.apiRel;\n var href = routes[i].path;\n\n // grab query options\n if (halConfig.query) {\n href += halConfig.query;\n }\n\n // check if link is templated\n var link = new hal.Link(rb.resolve(rel), href);\n if (/{.*}/.test(href)) {\n link.templated = true;\n }\n\n // todo process validations for query parameters\n resource.link(link);\n }\n }\n\n // handle any curies\n rb.addCuries(resource);\n reply(resource).type('application/hal+json');\n }", "function getRequests (req, res) {\r\n\tconsole.log ('GET /requests');\r\n\tRequest.find(null, 'name _id', function(err, requests) {\r\n\t\tif(err) {\r\n\t\t\tres.status(500).send({ message : 'Error while retrieving the requests list'});\r\n\t } else { \r\n\t \tif(!requests) { \r\n\t \t\tres.status(404).send({ message : 'Error there are no requests stored in the DB'});\r\n\t \t} else {\r\n\t\t\t\tres.status(200).jsonp(requests);\r\n\t \t}\r\n\t }\t\r\n\t});\r\n}", "bindResources(props) {\n const page = props.params.page ? Number.parseInt(props.params.page) : 1\n this.setState({ page });\n const query = {\n filter: {\n limit: this.state.perPage,\n skip: this.state.perPage * (page - 1),\n include: ['roles']\n }\n }\n // # retrieve all the posts from the Post Store\n this.retrieveAll(this.store, { query });\n }", "function passThroughAuthorizedResources(request) {\n var resource = this;\n return new RSVP.Promise(function (resolve, reject) {\n checkUserAndToken(resource.links.owner, request)\n .then(function () {\n resource.good = true;\n resolve(resource);\n }, function () { resolve(void 0); } );\n });\n }", "function apiGet(request, response, next) {\r\n Person\r\n .findById(fetchID(request))\r\n .then(person => {\r\n if (person) {\r\n response.json(person.toJSON())\r\n } else {\r\n makeResponse(response, 404)\r\n }\r\n })\r\n .catch(error => next(error))\r\n}", "getAll(req, res, next) {\n let userId = req.query.user_id ? req.query.user_id : null;\n let query = {};\n\n if (userId) {\n query = {\n [Op.or]: [{ fromId: userId }, { toId: userId }]\n };\n }\n\n ActivitiesService.getAll(query)\n .then(function (activities) {\n res.status(200).json(activities);\n }).catch(function (error) {\n });\n }", "get() {\n return (req, res) => {\n User.findOne({ _id: req.params.accountId }, {}, (err, user) => {\n if (err) {\n res.status(500).send(err);\n } else if (user == null) {\n res.status(404).send(\"User Not found\")\n } else {\n\n Profile.findOne({ _id: user.profileId }, {}, (err, profile) => {\n if (err) {\n res.status(500).send(err);\n } else if (profile == null) {\n res.status(404).send(\"User Not found\")\n } else {\n\n Education.find({ profileId: profile._id }, {}, (err, education) => {\n if (err) {\n res.status(500).send(err);\n }\n\n Experience.find({ profileId: profile._id }, {}, (err, expirience) => {\n if (err) {\n res.status(500).send(err);\n }\n\n Occupation.find({ profileId: profile._id }, {}, (err, occupation) => {\n if (err) {\n res.status(500).send(err);\n }\n\n ProfileSkillAssociation.find({ profileId: profile._id }, {}, (err, skill) => {\n if (err) {\n res.status(500).send(err);\n }\n\n let included = [];\n included.push({\n type: \"Profile\",\n id: profile._id,\n attributes: profile,\n relationships: {\n skills: {\n data: skill.map(s => {\n return {\n type: \"Skill\",\n id: s._id\n };\n })\n },\n occupations: {\n data: occupation.map(o => {\n return {\n type: \"Occupation\",\n id: o._id\n };\n })\n },\n education: {\n data: education.map(e => {\n return {\n type: \"Education\",\n id: e._id\n };\n })\n },\n experience: {\n data: expirience.map(e => {\n return {\n type: \"Expirience\",\n id: e._id\n };\n })\n }\n }\n });\n\n included = included.concat(skill);\n included = included.concat(occupation);\n included = included.concat(education);\n included = included.concat(expirience);\n\n res.json({\n data: {\n id: user._id,\n type: \"User\",\n attributes: user,\n relationships: {\n profile: {\n data: {\n id: profile._id,\n type: \"Profile\"\n }\n }\n }\n },\n included: included\n });\n });\n });\n });\n });\n }\n });\n }\n });\n };\n }", "function get(request, response) {\n var userToShow = request.userQueried.detailPolicies();\n response.status(200).json(userToShow);\n}", "function getAllResourceKids(){\r\n var resource_kids = [];\r\n //is a multi-viewer page collections\r\n $('.resource-container-level').find('.other-resource').each(function (){\r\n var resource_kid = $(this).attr('id');\r\n resource_kid = resource_kid.replace('identifier-', '');\r\n resource_kids.push( resource_kid );\r\n });\r\n //is a search page add to collections\r\n if( resource_kids.length == 0 ){\r\n resource_kids = JSON.parse($('#selected-resource-ids').html());\r\n }\r\n //if still no resources, then stop.\r\n if( resource_kids.length == 0 ){\r\n throw new Error(\"There are no resources selected.\");\r\n }\r\n return resource_kids;\r\n }", "function getTask(req, res, next) {\r\n\r\n log.info('getTask was called for: ', owner);\r\n Task.find({\r\n owner: owner\r\n }, function(err, data) {\r\n if (err) {\r\n req.log.warn(err, 'get: unable to read %s', owner);\r\n next(err);\r\n return;\r\n }\r\n\r\n res.json(data);\r\n });\r\n\r\n return next();\r\n}", "function fetchResources() {\n fetch('/api/resources')\n .then(response => response.json())\n .then(resources => {\n console.log(resources);\n for (x = 0; x < resources.length; x++) {\n buildResources(resources[x], category[x])\n }\n })\n}", "getThoughtById({ params }, res) {\n Thought.findOne({ _id: params.id })\n //also want to return users when GET\n .populate({\n path: 'users',\n select: '-__v'\n })\n .select('-__v')\n .then(dbThoughtData => {\n if (!dbThoughtData) {\n res.status(404).json({ message: 'No thought found with this id!' });\n return;\n }\n res.json(dbThoughtData);\n })\n .catch(err => {\n console.log(err);\n res.status(400).json(err);\n });\n }", "static async getQueryEndpoint(ctxt, input, context, info) {\n\n this.logger.debug(`get (id: ${input.id})`);\n\n const fieldsWithoutTypeName = GraphQLFields(info, {}, { excludedFields: ['__typename'] });\n const topLevelFields = fieldsWithoutTypeName ? Object.keys(fieldsWithoutTypeName) : [];\n let eagerResolves = null;\n\n if(this.relationFieldNames && this.relationFieldNames.length && fieldsWithoutTypeName) {\n eagerResolves = this._getEagerFieldsForQuery(topLevelFields);\n }\n\n const [object, user] = await Promise.all([\n this.find(input.id, eagerResolves),\n this.resolveUserForContext(context)\n ]);\n\n if(!object) {\n return new NotFoundError(\"Instance not found.\");\n }\n\n const [aclTargets, isOwner] = this.userToAclTargets(user, object);\n\n if(this.aclSet) {\n\n const accessMatch = this.aclSet.applyRules(aclTargets, AclActions.Access, object);\n this._debugAclMatching(user, aclTargets, isOwner, AclActions.Access, accessMatch, `query-get`);\n if(!accessMatch.allow) {\n throw new AuthorizationError(\"You do not have access to this object.\");\n }\n\n if(!this.restrictionsApplyToUser(accessMatch.allowedRestrictions, isOwner)) {\n throw new AuthorizationError(\"You do not have access to this object.\");\n }\n }\n\n this.addModelInstanceToGraphQLContext(context, object, this);\n\n return object.copyAllowedFieldsAsObject(aclTargets, topLevelFields);\n }", "async function get(req, res) {\n const book = req.query\n try {\n\n if(book.id){\n return res.send(await Book.find({_id: book.id}))\n }\n //Searches mongodb for books\n else{\n return res.send(await Book.find())\n }\n\n\n } catch (err) {\n return res.status(400).send({ error: `Could not get book(s): ${err}` })\n }\n}", "getAll(req, res) {\n // Blank .find param gets all\n Player.find({})\n .then(Players => res.json(Players))\n .catch(err => res.status(400).json(err))\n }", "getRelatedItems(identifier) {\n var uniqueIdentifier = identifier || 'InformationM'; \n \n let url = \"https://be-api.us.archive.org/mds/v1/get_related/all/\" + uniqueIdentifier;\n\n return fetch(url)\n .then(function(response) {\n return response.json();\n })\n .then(function(data) {\n return data.hits.hits;\n });\n }", "get relatedFields() {\r\n return new SharePointQueryable(this, \"getRelatedFields\");\r\n }", "function GetUserRecipes( req, res ) {\n \t\n \trecipeModel.userRecipe.find( { userID: req.params._id }, function( err, userRecipes ) {\n\t\tif ( err ) {\n\t\t\tres.send( err );\n\t\t} else {\n\t\t\tres.send( userRecipes );\n\t\t}\n\t})\n\n}", "function getObject(req, res, next) {\n var objectid = req.param(\"objectid\");\n objectService.getObject(objectid, (error, response) => {\n if (response == null) {\n ResponseHandler(404, response, res);\n return;\n }\n ResponseHandler(error, response, res);\n });\n}", "get(uri, action) {\n\n this.route('GET', uri, action);\n }", "function getCars(req, res) {\n return Car.find({}).exec()\n .then(respondWithResult(res))\n .catch(handleError(res));\n}", "getAll(req, res){\n console.log(\"getAll method executed\");\n\n //if you pass in no arguments, it finds everything\n Joke.find()\n .then( (jokes) => {\n res.json(jokes);\n })\n .catch( (err) => {\n res.json(err);\n })\n }", "function getQuestions(req, res) {\n\tvar queryParams = {\n\t\tuser_id: req.user.id\n\t};\n return questionsService.query(queryParams).then(function (questions) {\n res.json(questions);\n });\n}", "static async get(request, reply) {\n\n // Only authenticated Admins can see collections that are not enabled\n let isAdmin = request.auth.credentials && request.auth.credentials.scope && request.auth.credentials.scope.indexOf('admin') !== -1;\n let enabled = !isAdmin;\n\n return reply({items: await Collection.find({\n tags: request.query.tags ? request.query.tags.split(',') : null\n }, enabled)});\n }", "findRequestAll(qParams) {\n return this.request.get('requests', qParams);\n }", "function retrievePosts(req, res, next){\n courseService.retrievePosts(req.params.id, req.user.sub).then(x => {\n res.json(x);\n })\n}", "findAll() {\n var token = localStorage[\"token\"];\n return Ember.$.getJSON(this.host + \"/api/user/requests\", {token: token});\n }", "getListManagement(req, res) {\n Management.findAll({\n where: {\n 'ManagementType': req.params.id\n }\n }).then(function(Management) {\n if (Management) {\n res.json(Management);\n } else {\n res.send(401, \"Management not found\");\n }\n }, function(error) {\n res.send(\"Management not found\");\n });\n }", "function getQuestions() {\n $http\n .get(CONFIG.API_BSE_URL + 'resources/ '+ $stateParams.id + '/questions')\n .success(function(response) {\n $scope.questions = response.data.questions;\n });\n }", "getAll(req, res) {\n // Blank .find param gets all\n Assembly.find({})\n .then(Assemblies => res.json(Assemblies))\n .catch(err => res.status(400).json(err))\n }", "function request(resource, page, extraParams){\n //default value of 1 if page is undefined\n page = page ? page : 1;\n\n var deferred = $q.defer();\n var FINAL_URL = BASE_URL+ resource + '?api_key=' + API_KEY + '&page=' + page;\n //add any extra params added\n if ( extraParams ) {\n extraParams.forEach(function(param){\n //make sure the param has key and value properties\n if(param.key && param.value){\n FINAL_URL += '&'+param.key+'='+param.value ;\n }\n });\n }\n $http.get(FINAL_URL)\n .then(\n //success function\n function(response){\n //return the actually resource (e.g. movies), so that the caller can use it right away\n //if has results (array of something), return it, otherwise return data (single data)\n deferred.resolve(response.data.results ? response.data.results : response.data);\n },\n\n //error function\n function(error){\n //propagate the error to the caller\n deferred.reject(error);\n });\n return deferred.promise;\n }", "loadWithQuery(queryParams, options) {\n options = this.setQueryEntityActionOptions(options);\n const action = this.createEntityAction(EntityOp.QUERY_MANY, queryParams, options);\n this.dispatch(action);\n return this.getResponseData$(options.correlationId).pipe(shareReplay(1));\n }", "function getResource(resource = getCurrentHash(), method = 'GET', data = null) {\n\t\t\n if (resource.trim() === '') {\n window.location.hash = apiRoot;\n window.location.reload();\n\t\t\tresource = apiRoot;\n }\n\n // Adding '/' to the resource if missing\n if (resource.substring(0, 1) !== '/') {\n resource = '/' + resource;\n }\n\n let url = apiU + resource;\n\t\t\n\t\tif( method === 'DELETE' ){\n\t\t\tif (resource.substring(0, 1) == '/') {\n\t\t\t\tresource = resource.substring(1);\n\t\t\t}\n\t\t\turl = resource;\n\t\t}\n\t\t\n\t\tif( method === 'PUT' ){\t\t\n\t\t\t\n\t\t\tif (resource.substr(resource.length - 2) == '//') {\n\t\t\t\tresource = resource.substring(0, resource.length - 1);\n\t\t\t}\n\t\t\tif (resource.substring(0, 1) == '/') {\n\t\t\t\tresource = resource.substring(1);\n\t\t\t}\n\t\t\turl = resource;\n\t\t\tconsole.log(url)\n\t\t}\n\t\t\n //history.replaceState(null, null, '#!' + resource);\n\n $.ajax({\n contentType: data !== null ? PLAINJSON : null,\n data: data,\n timeout: xhrTimeout,\n type: method,\n url: url,\n })\n .done(renderData)\n .fail(handleAjaxError)\n\t\t\n }", "function getMyBooks(req, res, next) {\r\n //\r\n var owner = req.user ? req.user.email : null\r\n if(owner) {\r\n BookModel.find({ owner: owner }, function(err, mybooks) {\r\n if(err) throw err\r\n // mybooks will be 0 length array if no values found\r\n res.status(200).json({\r\n data: {\r\n items: mybooks\r\n }\r\n })\r\n })\r\n }\r\n}", "findAll(qParams) {\n return this.request.get('', qParams);\n }", "findAll(qParams) {\n return this.request.get('', qParams);\n }" ]
[ "0.63456845", "0.6028967", "0.569128", "0.5680128", "0.5517527", "0.53564864", "0.53275687", "0.5288383", "0.5283731", "0.5280788", "0.5202523", "0.51622283", "0.51279396", "0.5089165", "0.50607973", "0.5022023", "0.50104743", "0.5009311", "0.49712893", "0.49617997", "0.49356735", "0.4908557", "0.48938587", "0.48896465", "0.4879241", "0.4874028", "0.484315", "0.48427138", "0.48415914", "0.48311156", "0.48089147", "0.48034698", "0.4792707", "0.4789591", "0.4788919", "0.4786929", "0.47827327", "0.47478783", "0.4741237", "0.47398552", "0.47363013", "0.47324562", "0.47324562", "0.4721261", "0.47081503", "0.47062945", "0.4698589", "0.46962172", "0.46932086", "0.46916577", "0.4691189", "0.46794423", "0.4670273", "0.46600062", "0.4645835", "0.4642788", "0.4642788", "0.4634655", "0.46328285", "0.4624495", "0.46197033", "0.46131185", "0.46109614", "0.4602901", "0.4599918", "0.45954084", "0.45917425", "0.4589976", "0.45858794", "0.45782396", "0.45771068", "0.45752913", "0.45603895", "0.45599797", "0.4553363", "0.455304", "0.4548735", "0.45384467", "0.4536451", "0.45295268", "0.45279473", "0.45275828", "0.4525958", "0.45230973", "0.45186475", "0.4508744", "0.45035002", "0.45034078", "0.44945532", "0.44935727", "0.44690356", "0.44673583", "0.4466426", "0.44491905", "0.4447176", "0.44455302", "0.44425836", "0.44419393", "0.44409057", "0.44409057" ]
0.5462412
5
Refactoring options: 1. Make it yield parts of `body` rather than operate on it directly
function appendLinked(linkpath, body, resources, schema, inclusions, req, res) { // build of tree of paths to fetch and maybe include var includePaths = buildPathsTree(inclusions); var _this = this; var fetchedIds = {}; body.linked = {}; return fetchChildren(linkpath, includePaths, resources, schema).then(function() { return body; }); function fetchChildren(linkpath, config, resources, schema) { return RSVP.all(_.map(_.keys(config), function(key) { if(key === "__includeInBody") return null; var type = getTypeOfRef(schema, key), ids = _.difference(linkedIds(resources, key, schema), fetchedIds[type]); //only wanna cache ids for resources that are going to be present in the body if(config[key].__includeInBody){ fetchedIds[type] = _.union(fetchedIds[type] || [], ids); } return getLinked.call(_this, ids, type, req, res).then(function(result) { var relation = _.isArray(schema[key]) ? schema[key][0] : schema[key]; if(relation && relation.external){ var pluralisedRef = inflect.pluralize(relation.ref || key); body.linked[pluralisedRef] = "external"; body.links[linkpath + "." + key] = {type: pluralisedRef}; } if (result && result.resources) { if (config[key].__includeInBody) { body.linked[result.type] = body.linked[result.type] || []; body.linked[result.type] = body.linked[result.type].concat(result.resources); body.links[linkpath + "." + key] = {type: result.type}; } return fetchChildren(linkpath + "." + key, config[key], result.resources, _this._schema[inflect.singularize(result.type)]); }else if (result && result.type){ if (config[key].__includeInBody){ body.linked[result.type] = body.linked[result.type] || []; body.links[linkpath + '.' + key] = {type: result.type} } } }); })); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function bodyContentGenerator(_route) {\n if (_route[0] == 'isHomePage') {\n var isActive =['class=\"active\"','',''];\n } else if (_route[0] == 'isExplorer') {\n apiGetUgly('https://api.blockcypher.com/v1/btc/main', 'actualBlockHeight');\n prettyApiGet('https://api.blockcypher.com/v1/btc/main', 'infos');\n prettyApiGet('https://btc.blockr.io/api/v1/coin/info', 'blockchainInfos');\n } else if (_route[0] == 'isBlog') {\n var isActive = ['','','class=\"active\"'];\n } else {\n return false;\n }\n}", "get body() { return this._body; }", "function body_nest(body) {\r\n\tvar new_body;\r\n\tvar body_part;\r\n\r\n\tnew_body = body.split(/>/g);\r\n\tconsole.log(new_body[0]);\r\n\t\r\n\treturn new_body[max_score(new_body, score_function)];\r\n}", "function Body(props) {\n return <props.content options={props.options} />;\n}", "static get BODY() {\n return 2;\n }", "body(){\n const options = { \n parse_mode : this.parseMode,\n reply_markup: {} \n }\n const base = {\n owner: this.owner,\n type : this.type,\n destroy: this.destroy\n }\n\n if(this.type != \"$delete\") base['message'] = this.message\n if(this.keyboard != null)\n options.reply_markup['keyboard'] = this.keyboard\n\n if(this.inlineKeyboard != null )\n options.reply_markup['inline_keyboard'] = this.inlineKeyboard\n\n return {\n ...base,\n options\n }\n\n \n }", "function processReplacements(body)\n{\n //make links clickable\n body = linkify(body);\n\n //add smileys\n body = smilify(body);\n\n return body;\n}", "get body() {\n assert(!this.bodyUsed);\n assert(isReadableNodeStream(this._body)); // Not implemented: conversion of ArrayBuffer etc to stream\n this.bodyUsed = true;\n return this._body;\n }", "body(value) {\n if (value === 'static-text' || value === 'parsed-text' || value === 'html') {\n this.tag.body = value;\n } else {\n throw new Error('Invalid value for \"body\". Allowed: \"static-text\", \"parsed-text\" or \"html\"');\n }\n }", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream__default['default'])) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream__default['default'])) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream__default['default'])) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream__default['default'])) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof stream__WEBPACK_IMPORTED_MODULE_0___default.a)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof stream__WEBPACK_IMPORTED_MODULE_0__)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function create_content (body) {\n var meta = create_meta_info(body.meta_title, body.meta_description, body.meta_sort);\n return meta + body.content;\n }", "function consumeBody() {\n var _this4 = this;\n\n if (this[INTERNALS].disturbed) {\n return Body.Promise.reject(new TypeError('body used already for: ' + this.url));\n }\n\n this[INTERNALS].disturbed = true;\n\n if (this[INTERNALS].error) {\n return Body.Promise.reject(this[INTERNALS].error);\n }\n\n // body is null\n if (this.body === null) {\n return Body.Promise.resolve(Buffer.alloc(0));\n }\n\n // body is string\n if (typeof this.body === 'string') {\n return Body.Promise.resolve(Buffer.from(this.body));\n }\n\n // body is blob\n if (this.body instanceof _blob2.default) {\n return Body.Promise.resolve(this.body[_blob.BUFFER]);\n }\n\n // body is buffer\n if (Buffer.isBuffer(this.body)) {\n return Body.Promise.resolve(this.body);\n }\n\n // body is buffer\n if (Object.prototype.toString.call(this.body) === '[object ArrayBuffer]') {\n return Body.Promise.resolve(Buffer.from(this.body));\n }\n\n // istanbul ignore if: should never happen\n if (!(this.body instanceof Stream)) {\n return Body.Promise.resolve(Buffer.alloc(0));\n }\n\n // body is stream\n // get ready to actually consume the body\n var accum = [];\n var accumBytes = 0;\n var abort = false;\n\n return new Body.Promise(function (resolve, reject) {\n var resTimeout = void 0;\n\n // allow timeout on slow response body\n if (_this4.timeout) {\n resTimeout = setTimeout(function () {\n abort = true;\n reject(new _fetchError2.default('Response timeout while trying to fetch ' + _this4.url + ' (over ' + _this4.timeout + 'ms)', 'body-timeout'));\n }, _this4.timeout);\n }\n\n // handle stream error, such as incorrect content-encoding\n _this4.body.on('error', function (err) {\n reject(new _fetchError2.default('Invalid response body while trying to fetch ' + _this4.url + ': ' + err.message, 'system', err));\n });\n\n _this4.body.on('data', function (chunk) {\n if (abort || chunk === null) {\n return;\n }\n\n if (_this4.size && accumBytes + chunk.length > _this4.size) {\n abort = true;\n reject(new _fetchError2.default('content size at ' + _this4.url + ' over limit: ' + _this4.size, 'max-size'));\n return;\n }\n\n accumBytes += chunk.length;\n accum.push(chunk);\n });\n\n _this4.body.on('end', function () {\n if (abort) {\n return;\n }\n\n clearTimeout(resTimeout);\n\n try {\n resolve(Buffer.concat(accum));\n } catch (err) {\n // handle streams that have accumulated too much data (issue #414)\n reject(new _fetchError2.default('Could not create Buffer from response body for ' + _this4.url + ': ' + err.message, 'system', err));\n }\n });\n });\n}", "function Body() { Entity.apply(this, arguments); }", "writeBody(streamWriter, body) {\n let bodyItemsCount = body.length - 1;\n let bodyItem = undefined;\n for (let i = 0; i <= bodyItemsCount; i++) {\n bodyItem = body[i];\n if (bodyItem.hasOwnProperty('inlines')) {\n let isLastPara = (bodyItem === this.lastPara) ? true : false;\n this.writeParagraph(streamWriter, bodyItem, isLastPara);\n }\n else {\n this.writeTable(streamWriter, bodyItem);\n }\n }\n }", "getBody() {\n return this.body;\n }", "function consumeBody() {\n var _this4 = this;\n\n if (this[INTERNALS].disturbed) {\n return Body.Promise.reject(new TypeError(\"body used already for: \".concat(this.url)));\n }\n\n this[INTERNALS].disturbed = true;\n\n if (this[INTERNALS].error) {\n return Body.Promise.reject(this[INTERNALS].error);\n }\n\n var body = this.body; // body is null\n\n if (body === null) {\n return Body.Promise.resolve(Buffer.alloc(0));\n } // body is blob\n\n\n if (isBlob(body)) {\n body = body.stream();\n } // body is buffer\n\n\n if (Buffer.isBuffer(body)) {\n return Body.Promise.resolve(body);\n } // istanbul ignore if: should never happen\n\n\n if (!(body instanceof stream__WEBPACK_IMPORTED_MODULE_3__)) {\n return Body.Promise.resolve(Buffer.alloc(0));\n } // body is stream\n // get ready to actually consume the body\n\n\n var accum = [];\n var accumBytes = 0;\n var abort = false;\n return new Body.Promise(function (resolve, reject) {\n var resTimeout; // allow timeout on slow response body\n\n if (_this4.timeout) {\n resTimeout = setTimeout(function () {\n abort = true;\n reject(new FetchError(\"Response timeout while trying to fetch \".concat(_this4.url, \" (over \").concat(_this4.timeout, \"ms)\"), 'body-timeout'));\n }, _this4.timeout);\n } // handle stream errors\n\n\n body.on('error', function (err) {\n if (err.name === 'AbortError') {\n // if the request was aborted, reject with this Error\n abort = true;\n reject(err);\n } else {\n // other errors, such as incorrect content-encoding\n reject(new FetchError(\"Invalid response body while trying to fetch \".concat(_this4.url, \": \").concat(err.message), 'system', err));\n }\n });\n body.on('data', function (chunk) {\n if (abort || chunk === null) {\n return;\n }\n\n if (_this4.size && accumBytes + chunk.length > _this4.size) {\n abort = true;\n reject(new FetchError(\"content size at \".concat(_this4.url, \" over limit: \").concat(_this4.size), 'max-size'));\n return;\n }\n\n accumBytes += chunk.length;\n accum.push(chunk);\n });\n body.on('end', function () {\n if (abort) {\n return;\n }\n\n clearTimeout(resTimeout);\n\n try {\n resolve(Buffer.concat(accum, accumBytes));\n } catch (err) {\n // handle streams that have accumulated too much data (issue #414)\n reject(new FetchError(\"Could not create Buffer from response body for \".concat(_this4.url, \": \").concat(err.message), 'system', err));\n }\n });\n });\n}", "constructor(body) {\n this.body = body;\n }", "function renderPageForBots() {\n\n /* Fill the body content with either a blog-index, post or page. */\n if (gsConfig.blogIndexIsActive()) {\n\n /* use the sitemap instead of the blog index */\n var gsSitemap = new Sitemap(gsConfig);\n PrettyMarkdownTextToHTML(gsSitemap.links(), gs_body_id);\n\n } else if (gsConfig.postIsActive()) {\n /* If a post was found in the url query. */\n MarkdownFileToBody(gs_post_path+'/'+gsConfig.requested_page);\n\n /* render previous and next links */\n var gsPagination = new PageNav(gsConfig);\n gsPagination.genPostNavListTags();\n\n } else {\n /* The active page needs to correspond to a file at this point so \n * that the getter can download it. The getter should be post aware.*/\n MarkdownFileToBody(gsConfig.requested_page); \n }\n\n /* render the simple sitemap */\n if (gsConfig.sitemapIsActive()) {\n var gsSitemap = new Sitemap(gsConfig);\n PrettyMarkdownTextToHTML(gsSitemap.links(), gs_body_id);\n }\n\n /* Fill the body content with either a blog-index, post or page. */\n /* fill in the navbar */\n var gsNav = new Nav(gsConfig);\n \n}", "function pre(context) {\n const { request, content } = context;\n const { document } = content;\n const $ = jquery(document.defaultView);\n\n // Expose the html & body attributes so they can be used in the HTL\n [document.documentElement, document.body].forEach((el) => {\n el.attributesMap = [...el.attributes].reduce((map, attr) => {\n map[attr.name] = attr.value;\n return map;\n }, {});\n });\n\n let $sections = $(document.body).children('div');\n\n // first section has a starting image: add title class and wrap all subsequent items inside a div\n $sections\n .first()\n .has('p:first-child>img')\n .addClass('title')\n .find(':nth-child(1n+2)')\n .wrapAll('<div class=\"header\"></div>');\n\n // sections consisting of only one image\n $sections\n .filter('[data-hlx-types~=\"has-only-image\"]')\n .not('.title')\n .addClass('image');\n\n // sections without image and title class gets a default class\n $sections\n .not('.image')\n .not('.title')\n .addClass('default');\n\n // if there are no sections wrap everything in a default div\n // with appropriate class names from meta\n if ($sections.length === 0) {\n const div = $('<div>').addClass('default');\n if (context.content.meta && context.content.meta.class) {\n context.content.meta.class.split(',').forEach((c) => {\n div.addClass(c.trim());\n });\n }\n $(document.body).children().wrapAll(div);\n $sections = $(document.body).children('div');\n }\n\n // ensure content.data is present\n content.data = content.data || {};\n\n // extract metadata\n const { meta = {} } = content;\n // description: text from paragraphs with 10 or more words\n let match = false;\n const desc = $sections\n .find('p')\n .map(function exractWords() {\n if (match) {\n // already found paragraph for description\n return null;\n }\n const words = $(this).text().trim().split(/\\s+/);\n if (words.length < 10) {\n // skip paragraphs with less than 10 words\n return null;\n }\n match = true;\n return words;\n })\n .toArray();\n meta.description = `${desc.slice(0, 25).join(' ')}${desc.length > 25 ? ' ...' : ''}`;\n meta.url = getAbsoluteUrl(request.headers, request.url);\n meta.imageUrl = getAbsoluteUrl(request.headers, content.image || '/default-meta-image.png');\n}", "function loaded(error, response, body) {\n // Check for errors\n if (!error && response.statusCode == 200) {\n // The raw HTML is in body\n res.send(body);\n } else {\n res.send(response);\n }\n }", "get body() {\n let element = this.childOne(Body);\n if (!element) {\n element = this.createElement(Body);\n element && this.appendChild(element);\n }\n return element;\n }", "* process () {\n let body = _.get(this.context, 'request.body');\n\n if (!body) {\n throw new FormValidationError('No request body available to process');\n }\n\n yield this.setValues(body);\n yield this.validate();\n yield this.runHook('postValidation');\n }", "function _hydrateAndRenderBodyTemplate() {\n const reverse = new Reverse();\n const template = new Template(\n reverse.templateName, \n reverse.parentBlock,\n reverse.data, \n );\n\n const render = new RenderLocalTemplate();\n render.render(template);\n}", "function consumeBody$1() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS$3].disturbed) {\n\t\treturn Body$1.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS$3].disturbed = true;\n\n\tif (this[INTERNALS$3].error) {\n\t\treturn Body$1.Promise.reject(this[INTERNALS$3].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body$1.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob$1(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body$1.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body$1.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body$1.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError$1(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError$1(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError$1(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError$1(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}", "function blocksToBody(blocks, entityMap) {\n return blocks.map(b => {\n if (b.text && b.text.length > 0) {\n if (b.entityRanges.length > 0) {\n for (const range of b.entityRanges.reverse()) {\n let i = range.offset + range.length;\n const entity = entityMap[range.key];\n if (entity.type === 'IMAGE') {\n const insert = `[${entity.data.alt || 'image'}](${entity.data.src})`;\n b.text = b.text.slice(0, i) + insert + b.text.slice(i);\n adjustRanges(b.inlineStyleRanges, i, insert);\n continue;\n }\n if (entity.type === 'LINK' || entity.data.type === 'youtube') {\n const insert2 = `](${entity.data.url})`;\n b.text = b.text.slice(0, i) + insert2 + b.text.slice(i);\n adjustRanges(b.inlineStyleRanges, i, insert2);\n i -= range.length;\n const insert1 = `[`;\n b.text = b.text.slice(0, i) + insert1 + b.text.slice(i);\n adjustRanges(b.inlineStyleRanges, i, insert1);\n continue;\n }\n if (entity.data.id) {\n const urls = threadUrls[entity.data.id.split('?')[0]];\n if (entity.data.entity === 'thread' && urls) {\n const insert = urls.discourse || urls.spectrum;\n b.text = b.text.slice(0, i) + insert + b.text.slice(i);\n adjustRanges(b.inlineStyleRanges, i, insert);\n continue;\n }\n }\n console.error('unsupported entity!', entity);\n }\n }\n // Looks like: \"inlineStyleRanges\":[{\"offset\":63,\"length\":37,\"style\":\"CODE\"},{\"offset\":112,\"length\":16,\"style\":\"CODE\"}]\n for (const range of (b.inlineStyleRanges || []).reverse()) {\n let i = range.offset + range.length;\n switch (range.style) {\n case 'CODE':\n b.text = b.text.slice(0, i) + '```' + b.text.slice(i);\n i -= range.length;\n b.text = b.text.slice(0, i) + '```' + b.text.slice(i);\n break;\n case 'ITALIC':\n b.text = b.text.slice(0, i) + '*' + b.text.slice(i);\n i -= range.length;\n b.text = b.text.slice(0, i) + '*' + b.text.slice(i);\n break;\n case 'BOLD':\n b.text = b.text.slice(0, i) + '**' + b.text.slice(i);\n i -= range.length;\n b.text = b.text.slice(0, i) + '**' + b.text.slice(i);\n break;\n default:\n console.error('unknown style range', range);\n }\n }\n switch (b.type) {\n case 'unstyled':\n break;\n case 'atomic':\n b.text = b.text.replace(/^ /, '');;\n break;\n case 'blockquote':\n b.text = '> ' + b.text;\n break;\n case 'ordered-list-item':\n b.text = '1. ' + b.text;\n break;\n case 'unordered-list-item':\n b.text = '- ' + b.text;\n break;\n case 'code-block':\n b.text = b.text.replace(/^(<code>)?/, '```\\n').replace(/(<\\/code>)?$/, '\\n```');\n break;\n case 'header-one':\n b.text = '# ' + b.text;\n break;\n case 'header-two':\n b.text = '## ' + b.text;\n break;\n case 'header-three':\n b.text = '### ' + b.text;\n break;\n case 'header-four':\n b.text = '#### ' + b.text;\n break;\n case 'header-five':\n b.text = '##### ' + b.text;\n break;\n default:\n console.error('unknown text block type:', b.type, b);\n }\n return b.text.replace(/\\\"/g, '\\'').replace(/\\\\/g, '\\\\\\\\');\n }\n console.error('unsupported block!', b);\n return '';\n }).join('\\n\\n');\n}", "function processEmailBodies() {\r\n\t$(\".ii.gt.adP.adO:visible\").each(function(bodyIndex, element) {\r\n\t\t$emailBody = $(this);\r\n\t\t\r\n\t\tif (!$emailBody.attr(\"searchedForDates\")) {\r\n\t\r\n\t\t\t$emailBody.attr(\"searchedForDates\", \"true\");\r\n\t\r\n\t\t\tvar MAX_EMAIL_BODIES_TO_PROCESS = 20;\r\n\t\t\tif (bodyIndex < MAX_EMAIL_BODIES_TO_PROCESS) {\r\n\t\t\t\t//console.log(\"EMAILBODY: \" + $emailBody.html());\r\n\t\t\t\t\r\n\t\t\t\t//console.log(\"START PROCESSING\")\r\n\t\t\t\t\r\n\t\t\t\t//processNode($emailBody, response.pageDetails.title, response.pageDetails.description);\r\n\t\r\n\t\t\t\t//var $ellipsis = $emailBody.find(\".yj6qo.ajU\");\r\n\t\t\t\t\r\n\t\t\t\t// encapsulated because of async sendMessage above\r\n\t\t\t\tprocessEmailBody($emailBody);\r\n\t\t\t\t\r\n\t\t\t\t/*\r\n\t\t\t\tvar text = $emailBody.html();\r\n\t\t\t\t\r\n\t\t\t\tif (!DateTimeHighlighter.init) {\r\n\t\t\t\t\tDateTimeHighlighter();\r\n\t\t\t\t}\r\n\t\t\t\tvar highlightedHTML = DateTimeHighlighter.highlight( text, function(myDateRegex) {\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar title = $(\".hP:visible\").first().text();\r\n\t\t\t\t\tvar description = $(\".ii.gt:visible\").html();\r\n\t\t\t\t\tvar content = prepContentForCreateEvent(title, description, response.tab.url);\r\n\t\t\t\t\ttitle = content.title;\r\n\t\t\t\t\tdescription = content.description;\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar generateActionParams = {title:title, description:description, startTime:myDateRegex.startTime, allDay:myDateRegex.allDay};\r\n\t\t\t\r\n\t\t\t\t\tif (myDateRegex.endTime) {\r\n\t\t\t\t\t\tgenerateActionParams.endTime = myDateRegex.endTime;\r\n\t\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\t\tvar actionLinkObj = generateActionLink(\"TEMPLATE\", generateActionParams);\r\n\t\t\t\t\tvar tagStart = '<a target=\"_blank\" title=\"Add to Google Calendar\" href=\"' + actionLinkObj.url + \"?\" + actionLinkObj.data + '\">';\r\n\t\t\t\t\tvar tagEnd = '</a>';\r\n\t\t\t\r\n\t\t\t\t\tconsole.log( myDateRegex.match + \" \" + myDateRegex.pattern + \" _ \" + myDateRegex.startTime + \"__\" + myDateRegex.endTime);\r\n\t\t\t\t\treturn tagStart + myDateRegex.match + tagEnd;\r\n\t\t\t\t});\r\n\t\t\t\t\r\n\t\t\t\tif (highlightedHTML != text) {\r\n\t\t\t\t\t$emailBody.html( highlightedHTML );\r\n\t\t\t\t\t$emailBody.find(\".yj6qo.ajU\").replaceWith($ellipsis);\r\n\t\t\t\t}\r\n\t\t\t\t*/\r\n\t\r\n\t\t\t\t//console.log(\"FINISHED PROCESSING\")\r\n\t\t\t} else {\r\n\t\t\t\tconsole.warn(\"too many email bodies, skipping processEmailBody!\");\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}", "function _clone(instance) {\n var p1, p2;\n var body = instance.body; // don't allow cloning a used body\n\n if (instance.bodyUsed) {\n throw new Error('cannot clone body after it is used');\n } // check that body is a stream and not form-data object\n // note: we can't clone the form-data object without having it as a dependency\n\n\n if (body instanceof stream__WEBPACK_IMPORTED_MODULE_3__ && typeof body.getBoundary !== 'function') {\n // tee instance body\n p1 = new PassThrough();\n p2 = new PassThrough();\n body.pipe(p1);\n body.pipe(p2); // set instance body to teed body and return the other teed body\n\n instance[INTERNALS].body = p1;\n body = p2;\n }\n\n return body;\n}", "function requestBody(fragment, context) {\n const body = fragment.body;\n if (!body) return;\n return (typeof body === 'function') ? body(context) : body;\n}", "static BodyParser(req, res, next)\n {\n // TODO? check if text is empty vs. undefined '/check_score' should have empty text field\n if (!req.body || !req.body.text)\n {\n SendResponseMessage(\n res,\n 'Failed to parse request: no body',\n { in_channel: false, markdown: false}\n );\n\n // Do not continue to handle the request any further\n return;\n }\n\n try\n {\n req.slack = {\n input: Slack.ParseMessage(req.body.text)\n }\n next();\n }\n catch (error)\n {\n SendResponseMessage(\n res,\n `Failed to parse request: ${error.message}`\n );\n\n // Do not continue to handle the request any further\n return;\n }\n }", "function render() {\n for (let i = 0; i < storedCreatedObj.length; i++) {\n storedCreatedObj[i].render_for_body();\n }\n storedCreatedObj[0].render_for_head();\n storedCreatedObj[0].render_for_foot();\n}", "getContentBlog(callback){\n let me = this,\n cfg = me.cfg,\n url = cfg.blogUrl,\n options = {\n url:url,\n headers:me.headers\n },\n request = me.request,\n cheerio = me.cheerio,\n log = me.log,\n blogPosts = []\n request(options,(err,res,body)=>{\n log(res.headers)\n let $ = cheerio.load(body)\n var posts = $('.date-posts')\n // log(posts.length)\n // this.inspectPost(posts.eq(0).html())\n for(let i = 0 ; i < posts.length; i++){\n blogPosts.push(this.inspectPost(posts.eq(i).html()))\n }\n // blogPosts.forEach(p => {\n // log(p.postTitle)\n // log(p.postLink)\n // log(p.postContent)\n // })\n callback(blogPosts)\n })\n }", "makeBody(){\n\n\t\t// an object for mail\n\t\tlet mail;\n\t\tmail = new mailComposer({\n\t\t\tto: this.to,\n\t\t\ttext: this.body,\n\t\t\tsubject: this.sub,\n\t\t\ttextEncoding: \"base64\"\n\t\t});\n\t\t//Compiles and encodes the mail.\n\t\tmail.compile().build((err, msg) => {\n\t\t\tif (err){\n\t\t\t\treturn console.log('Error compiling email ' + error);\n\t\t\t} \n\t\t\tconst encodedMessage = Buffer.from(msg)\n\t\t\t .toString('base64')\n\t\t\t .replace(/\\+/g, '-')\n\t\t\t .replace(/\\//g, '_')\n\t\t\t .replace(/=+$/, '');\n\t\t\t\n\t\t\t// task is user specified\n\t\t\tif(this.task === 'send'){\n\t\t\t\t// console.log('sending')\n\t\t\t\tthis.sendMail(encodedMessage);\n\t\t\t}\n\t\t\tthis.saveDraft(encodedMessage);\n\t\t});\n\t}", "function clone$1(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough$2();\n\t\tp2 = new PassThrough$2();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS$3].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "genBody()\n {\n\n return{editSearches:Object.values(this.state.searches),\n unstructuredDataSearches:Object.values(this.state.unstructuredDataSearches),\n structuredDataSearches:Object.values(this.state.structuredDataSearches) }\n\n\n }", "function pageGenerator() {\n var route = routing();\n\n var body = \n `<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>` +\n `<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"></script>`;\n\n document.getElementsByTagName('body')[0].innerHTML += body;\n\n // Récupérer les objet du DOM existant déjà pour les retirer\n var elmt = document.getElementById('navBlock');\n \n while (elmt.firstChild) {\n elmt.removeChild(elmt.firstChild);\n }\n \n navBlockGenerator(route);\n\n\n var elmt = document.getElementById('bodyContent');\n while (elmt.firstChild) {\n elmt.removeChild(elmt.firstChild);\n }\n\n bodyElementsGenerator(route);\n\n bodyContentGenerator(route);\n \n\n var elmt = document.getElementById('footerBlock');\n while (elmt.firstChild) {\n elmt.removeChild(elmt.firstChild);\n }\n\n footerBlockGenerator(route);\n}", "function bodyEvaluator(writer) {\n var newCtx = extendContext(ctx);\n newCtx[name] = bodyEvaluator;\n for ( var i = 1; i < plen; i++ ) {\n newCtx[params[i]] = arguments[i];\n }\n return statements(newCtx, writer);\n }", "async function consumeBody(data) {\n\tif (data[INTERNALS].disturbed) {\n\t\tthrow new TypeError(`body used already for: ${data.url}`);\n\t}\n\n\tdata[INTERNALS].disturbed = true;\n\n\tif (data[INTERNALS].error) {\n\t\tthrow data[INTERNALS].error;\n\t}\n\n\tlet {body} = data;\n\n\t// Body is null\n\tif (body === null) {\n\t\treturn Buffer.alloc(0);\n\t}\n\n\t// Body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// Body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn body;\n\t}\n\n\t/* c8 ignore next 3 */\n\tif (!(body instanceof Stream)) {\n\t\treturn Buffer.alloc(0);\n\t}\n\n\t// Body is stream\n\t// get ready to actually consume the body\n\tconst accum = [];\n\tlet accumBytes = 0;\n\n\ttry {\n\t\tfor await (const chunk of body) {\n\t\t\tif (data.size > 0 && accumBytes + chunk.length > data.size) {\n\t\t\t\tconst err = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size');\n\t\t\t\tbody.destroy(err);\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof FetchBaseError) {\n\t\t\tthrow error;\n\t\t} else {\n\t\t\t// Other errors, such as incorrect content-encoding\n\t\t\tthrow new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error);\n\t\t}\n\t}\n\n\tif (body.readableEnded === true || body._readableState.ended === true) {\n\t\ttry {\n\t\t\tif (accum.every(c => typeof c === 'string')) {\n\t\t\t\treturn Buffer.from(accum.join(''));\n\t\t\t}\n\n\t\t\treturn Buffer.concat(accum, accumBytes);\n\t\t} catch (error) {\n\t\t\tthrow new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error);\n\t\t}\n\t} else {\n\t\tthrow new FetchError(`Premature close of server response while trying to fetch ${data.url}`);\n\t}\n}", "addBody(body) {\n Must(this.body === undefined);\n Must(body);\n this.body = body;\n }", "function clone$1(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream__default['default'] && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "setupBody(senderId, response, meta) {\n throw new Error('setupBody - not implemented');\n }", "get body() {\n return this.querySelector('body');\n }", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof stream__WEBPACK_IMPORTED_MODULE_0___default.a && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function getManagingBodies(){\n\n\tvar select = squel.select().from(config.table);\n\n\tselect.field(\"managing_body\").distinct();\n\n\tvar sqlQuery = select.toString();\n\n\treturn db.queryp(sqlQuery);\n\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof stream__WEBPACK_IMPORTED_MODULE_0__ && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "makeBody(objectParams) {\n return objectParams;\n }", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}", "function clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream__default['default'] && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}" ]
[ "0.59942055", "0.5750982", "0.57046455", "0.5624097", "0.55721575", "0.55424577", "0.5439902", "0.54165685", "0.5377422", "0.53667736", "0.53667736", "0.53667736", "0.53667736", "0.5365766", "0.5352186", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5348839", "0.5335448", "0.53302926", "0.5317735", "0.531456", "0.5314245", "0.5285073", "0.5279359", "0.52322406", "0.5199675", "0.5190106", "0.51735115", "0.5170656", "0.5164471", "0.51414067", "0.51094925", "0.5095521", "0.5078925", "0.50760627", "0.5073388", "0.50556153", "0.5049543", "0.5041969", "0.503866", "0.50328165", "0.50324243", "0.5001775", "0.50009155", "0.5000418", "0.49998495", "0.499974", "0.49844727", "0.49792138", "0.4978488", "0.49629503", "0.49544096", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.49492034", "0.494647" ]
0.0
-1
Define a function to print the player's current time
function showProgress () { var current = $('.js-player').prop('currentTime'); $('progress').prop("value", current); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function output_time() { // output the current time\r\n\ttime.value = player_data.current_time;\r\n}", "function printTime(){\n var currentTime = new Date();\n var time = currentTime.getHours() + \":\" + currentTime.getMinutes() + \":\" + currentTime.getSeconds();\n return time;\n}", "function tellTime() {\n var now = new Date(); \n document.write(\"Current time: \"+ now);\n }", "function printTime(){\n\tvar d = new Date();\n\tvar hours = d.getHours();\n\tvar mins = d.getMinutes();\n\tvar secs = d.getSeconds();\n\tdocument.body.innerHTML = hours + \":\" + mins + \":\" + secs;\n}", "function printTime() {\r\nvar d = new Date();\r\nvar hours = d.getHours();\r\nvar mins = d.getMinutes();\r\nvar secs = d.getSeconds();\r\ndocument.body.innerHTML = hours+\":\"+mins+\":\"+secs;\r\n}", "function printTime()\n\t{\n\t\tvar time = getTime();\n\n\t\t// Print time\n\t\ttaskline.obj.time_timeday.innerHTML = time.hour + ':' + time.min;\n\t}", "function printTime() {\n var d = new Date();\n var hours = d.getHours();\n var mins = d.getMinutes();\n var secs = d.getSeconds();\n document.body.innerHTML = hours+\":\"+mins+\":\"+secs;\n}", "function printTime() {\n var d = new Date();\n var hours = d.getHours();\n var mins = d.getMinutes();\n var secs = d.getSeconds();\n document.body.innerHTML = hours+\":\"+mins+\":\"+secs;\n}", "function printTime() {\r\n var d = new Date(); \r\n var hours = d.getHours(); \r\n var mins = d.getMinutes(); \r\n var secs = d.getSeconds(); \r\n document.body.innerHTML = \r\nhours+\":\"+mins+\":\"+secs; \r\n}", "function currentTime() {\r\n let time = new Date();\r\n let h = time.getHours();\r\n let m = time.getMinutes();\r\n let s = time.getSeconds();\r\n if (m < 10) m = \"0\" + m;\r\n if (s < 10) s = \"0\" + s;\r\n document.getElementById('currentTime').innerHTML = h + \":\" + m + \":\" + s;\r\n}", "function showCurrentTime(time) {\n document.querySelector(\".time p\").textContent = currentTime(time);\n}", "function getTime() {\n\tOutput('<span>It\\'s the 21st century man! Get a SmartWatch</span></br>');\n}", "function showTime() {\n console.log(\"Time is:\", new Date().toISOString(), \"(UTC)\");\n}", "function displayTime() {\n var today = new Date();\n \n //gathers information about current hour, min and sec. \n //Add zero at the head if it is a single digit number.\n var currentHour = addZero(today.getHours());\n var currentMin = addZero(today.getMinutes());\n var currentSec = addZero(today.getSeconds());\n \n // for formatting the display.\n hourElement.innerHTML = currentHour + \":\";\n minElement.innerHTML = currentMin + \":\";\n secElement.innerHTML = currentSec;\n }", "function printTime() {\r\n var d = new Date();\r\n var year = d.getFullYear();\r\n var month = d.getMonth();\r\n var day = d.getDate();\r\n var hours = d.getHours();\r\n var mins = d.getMinutes();\r\n var secs = d.getSeconds();\r\n document.body.div.main.innerHTML =\r\n \"Current date and time is: \" +\r\n day +\r\n \"/\" +\r\n month +\r\n \"/\" +\r\n year +\r\n \" \" +\r\n hours +\r\n \":\" +\r\n mins +\r\n \":\" +\r\n secs;\r\n}", "function getTime() {\n\tvar today = new Date();\n\tseperator();\n\tOutput('<span>>time:<span><br>');\n\tOutput('<span>' + today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + \":\" + today.getMinutes() + \":\" + today.getSeconds() + '</span></br>');\n}", "function printTime(){\n\tvar now = new Date();\n\tvar hours = now.getHours();\n\tvar mins = now.getMinutes();\n\tvar seconds = now.getSeconds();\n\tvar amPm=\"\";\n\tif(hours>12) {\n\t\thours=hours-12;\n\t\tamPm = \"PM\";\n\t}else {\n\t\tamPm=\"AM\";\n\t}\n\tif (hours<10) hours=\"0\"+hours;\n\tif (mins<10) mins=\"0\"+mins;\n\tif (seconds<10) seconds=\"0\"+seconds;\n\tvar time=document.getElementById(\"time\");\n\ttime.innerHTML= \"\"+hours+\":\"+mins+\":\"+seconds+\" \"+amPm;\n}", "function currentTime() {\n var timeNow = moment().format('h:mm a')\n $(\"#currentTime\").text(timeNow)\n }", "function showTime() {\n\t\ttry {\n\t\t\tvar hours = time.getUTCHours();\n\t\t\tvar minutes = time.getUTCMinutes();\n\t\t\tvar seconds = time.getUTCSeconds();\n\t\n\t\t\t// build the human-readable format\n\t\t\tvar timeValue = \"\" + ((hours > 12) ? hours - 12 : hours);\n\t\t\ttimeValue += ((minutes < 10) ? \":0\" : \":\") + minutes;\n\t\t\ttimeValue += ((seconds < 10) ? \":0\" : \":\") + seconds;\n\t\t\ttimeValue += (hours >= 12) ? \" pm\" : \" am\";\n\t\n\t\t\tvar clockElement;\n\t\t\tif ((piratequesting.sidebar) && (clockElement = sidebar.contentDocument.getElementById('servertime'))) {\n\t\t\t\tclockElement.setAttribute(\"value\", timeValue);\n\t\t\t}\n\t\t} \n\t\tcatch (e) {\n\t\t\tdumpError(e);\n\t\t}\t\n\t}", "function currentTime () {\n return new Date().toLocaleTimeString()\n}", "function displayTime() {\n //Calculate the number of minutes and seconds based on the current time\n var min = Math.floor(currentTime / 60);\n var sec = Math.floor(currentTime % 60);\n \n //Add a 0 to the front of the second when appropriate\n if (sec < 10) {\n sec = \"0\" + sec;\n }\n \n $(\"#time-text\").text(min + \":\" + sec);\n }", "function print_time() {\n //console.clear();\n console.log(\"local_time : \", Date.now());\n console.log(\"server_time : \", api.get_time());\n console.log(\"delta_time : \", Date.now() - api.get_time());\n console.log(\"\");\n }", "function displayTime() {\n let time = new Date();\n document.getElementById(\"timeNow\").innerHTML = time;\n}", "function print(txt) {\n document.getElementById(\"time-display\").innerHTML = txt;\n }", "function printTime () {\n var current = $('.js-player').prop('currentTime');\n console.debug('Current time: ' + current);\n $('progress').attr('value', current)\n\n if (current >= 30) {\n $('.js-player').trigger('pause');\n $('.btn-play').removeClass('playing');\n $('.btn-play').addClass('disabled');\n $('progress').attr('value', 0);\n } \n }", "function displayTime() {\n var time = new Date().toLocaleTimeString();\n document.querySelector('#display').textContent = time;\n}", "function updateTimerDisplay() {\n // Update current time text display.\n //$('#current-time').text(formatTime(player.getCurrentTime()))\n //$('#duration').text(formatTime(player.getDuration()))\n}", "function displayCurrentTime() {\n var currentDate = new Date();\n console.log(formatCurrentTime(currentDate));\n}", "function showCurrentTime(player,span) { \n //var span=document.getElementById(spanId);\n span.innerHTML = secondsToTimeText(player.getCurrentTime()); \n}", "function displayCurrentTime() {\n\tsetInterval(function(){\n\t\t$('#current-time').html(moment().format('hh:mm A'))\n\t }, 1000);\n\t}", "function currentTime() { //returns current time in \"[HH:MM] \" 24hr format (string)\n var d = new Date();\n return '['+d.toTimeString().substr(0,5)+'] ';\n}", "function time(whatTime) {\n\n\tconsole.log(\"I'ts around \" + Math.round(whatTime) + \" of morning\");\n}", "function displayTime() {\n var str = \"\";\n\t//What this does is pretty straight forward:\n\t//Grab a Date object\n var currentTime = new Date()\n\t//Extract hours, minutes and seconds out of it\n var hours = currentTime.getHours()\n var minutes = currentTime.getMinutes()\n var seconds = currentTime.getSeconds()\n\t//If we have less than 10 minutes on the clock, prefix it with a zero to have a \n\t//handy dandy standard format\n if (minutes < 10) {\n minutes = \"0\" + minutes\n }\n\t//Same for seconds\n if (seconds < 10) {\n seconds = \"0\" + seconds\n }\n\t//It uses A.M. and P.M. Time format for the hours, so we need to add this\n str += hours + \":\" + minutes + \":\" + seconds + \" \";\n if(hours > 11){\n str += \"PM\"\n } else {\n str += \"AM\"\n }\n\t//and aaawwaaaaayyyyy we go!\n return str+\"\";\n}", "function getCurrentTime(){\n\t//get timestamp and format it\n\t\tvar date = new Date();\n\t\tvar hours = date.getHours()\n\t\tvar ampm = (hours >= 12) ? \"PM\" : \"AM\";\n\t\thours = hours% 12||12;\n\t\tvar minutes =date.getMinutes();\n\t\tminutes = (minutes <10) ? \"0\" + minutes:minutes;\n\t\treturn \"(\" + hours + \":\" + minutes + ampm + \")\";\n}", "function currentTime() {\r\n var date = new Date();\r\n year = date.getFullYear();\r\n month = date.getMonth();\r\n month = month + 1;\r\n day = date.getDate();\r\n hours = date.getHours();\r\n minutes = date.getMinutes();\r\n\r\n var ampm = hours >= 12 ? 'PM' : 'AM';\r\n hours = hours % 12;\r\n hours = hours ? hours : 12; // the hour '0' should be '12'\r\n minutes = minutes < 10 ? '0' + minutes : minutes;\r\n var strTime = hours + ':' + minutes + ' ' + ampm;\r\n\r\n document.write(month + \"/\" + day + \"/\" + year + \" - \" + strTime);\r\n}", "function currentTime(){\n var getHour = moment().format('HH');\n var getMin = moment().format('mm');\n var getMonth = moment().format('MMMM');\n var getDay = moment().format('Do');\n var getYear = moment().format('YYYY');\n $('.month').text(getMonth);\n $('.day').text(getDay);\n $('.year').text(getYear);\n $('.hours').text(getHour);\n $('.min').text(getMin);\n }", "function showTime() {\n let today = new Date(),\n hour = today.getHours(),\n min = today.getMinutes(),\n seconds = today.getSeconds();\n\n //Set AM or PM\n const amOrPm = hour >= 12 ? \"PM\" : \"AM\";\n\n //Format to 12 hours\n hour = hour % 12 || 12;\n console.log(time);\n //Outputting time\n time.innerHTML = `${hour} <span>:</span> ${min} <span>:</span> ${seconds}`;\n\n setTimeout(showTime, 1000);\n}", "function updateTimerDisplay(){\n // Update current time text display.\n $('#current-time').text(formatTime(player.getCurrentTime() ));\n $('#duration').text(formatTime( player.getDuration() ));\n}", "function timeDigtal(){\r\n\tvar currentTime = new Date();\r\n\tvar hours = currentTime.getHours();\r\n\tvar minutes = currentTime.getMinutes();\r\n\tvar seconds = currentTime.getSeconds();\r\n document.getElementById(\"digtime\").innerHTML=\"<b>TIME IS: \" + hours + \":\" + minutes + \" \" + \":\" + seconds + \" \" + \"</b>\";\r\n}", "function currentTime() {\n let current = moment().format(\"HH:mm:ss A\");\n $(\"#clock\").html(\"<i class='far fa-clock'></i> \" + current);\n setTimeout(currentTime, 1000);\n }", "function currentTime() {\n var current = moment().format('LT');\n $(\"#current-time\").html(current);\n setTimeout(currentTime, 1000);\n }", "function time() {\r\nvar d = new Date();\r\ndocument.getElementById(\"tx\").innerHTML = d.toLocaleTimeString();\r\n document.getElementById(\"ti\").innerHTML = d.toLocaleDateString();\r\n}", "function displayTime() {\n var str = \"\";\n\n var currentTime = new Date()\n var hours = currentTime.getHours()\n var minutes = currentTime.getMinutes()\n var seconds = currentTime.getSeconds()\n\n if (minutes < 10) {\n minutes = \"0\" + minutes\n }\n if (seconds < 10) {\n seconds = \"0\" + seconds\n }\n str += hours + \":\" + minutes + \":\" + seconds + \" \";\n if(hours > 11){\n str += \"PM\"\n } else {\n str += \"AM\"\n }\n return str;\n}", "print(){\r\n console.log(this.hours + 'h' + this.minutes);\r\n }", "function currentTime() {\n const today = new Date();\n let hours = today.getHours();\n let mins = today.getMinutes();\n let ampm = \"am\";\n\n if (hours >= 12) {\n ampm = \"pm\";\n }\n if (mins < 10) {\n mins = '0' + mins;\n }\n hours = hours % 12;\n let time = hours + \":\" + mins + ampm;\n return time;\n}", "function currentTimeString(){\n\treturn new Date().toLocaleString(\"en-US\",{hour:\"numeric\",minute:\"numeric\",hour12:true,second:\"numeric\"});\n}", "function time() {\r\n var data = new Date();\r\n var ora = addZero( data.getHours() );\r\n var minuti = addZero( data.getMinutes() );\r\n return orario = ora + ':' + minuti;\r\n }", "function getTime(){\n let currentDate = new Date();\n let time = currentDate.toLocaleTimeString();\n $(\".currentTime\").html(time);\n}", "function currentTime(type,showSeconds) {\r\n\tvar d = new Date();\r\n\tvar curr_hour = d.getHours();\r\n\tif (curr_hour < 10) curr_hour = '0'+curr_hour;\r\n\tvar curr_min = d.getMinutes();\r\n\tif (curr_min < 10) curr_min = '0'+curr_min;\r\n\tvar curr_sec = d.getSeconds();\r\n\tif (curr_sec < 10) curr_sec = '0'+curr_sec;\r\n\tif (type=='m') return curr_min;\r\n\telse if (type=='h') return curr_hour;\r\n\telse if (type=='s') return curr_sec;\r\n\telse return curr_hour+':'+curr_min+(showSeconds ? ':'+curr_sec : '');\r\n}", "function displayDateAndTime() {\n return new Date();\n}", "function currentTime(){\n let now = new Date();\n\n const hh = String(now.getHours()).padStart(2, '0');\n const mm = String(now.getMinutes()).padStart(2, '0');\n\n now = hh + ':' + mm;\n\n return now; \n}", "function currentTime() {\n\tvar d = new Date();\n var x = document.getElementById(\"demo\");\n var h = addZero(d.getHours());\n var m = addZero(d.getMinutes());\n var current = h+\":\"+m;\n return current;\t\n}", "function getTime() {\r\n var currentTime = new Date();\r\n var hours = currentTime.getHours();\r\n var minutes = currentTime.getMinutes();\r\n if (minutes < 10) {\r\n minutes = \"0\" + minutes;\r\n }\r\n return hours + \":\" + minutes;\r\n}", "function updateTime() {\n\n}", "function updateTimerDisplay(){\n // Update current time text display.\n $('#current-time').text(formatTime( player.getCurrentTime() ));\n $('#duration').text(formatTime( player.getDuration() ));\n }", "function printDate()\n\t{\n\t\tvar time = getTime();\n\n\t\t// Print time\n\t\ttaskline.obj.time_date.innerHTML = time.day + '.' + time.monthNameShort + ' ' + time.year;\n\t}", "function time(){\n var curr_time = new Date().toTimeString();\n var curr_day = new Date().getDay();\n var curr_month = new Date().getMonth();\n var curr_year = new Date().getFullYear();\n var curr_date = curr_day+\"/\"+\" \"+curr_month+\"/\"+\" \"+curr_year;\n document.write(\"Current Date =\"+\" \"+curr_date+\"<br>\");\n document.write(\"Current Time =\"+\" \"+curr_time);\n}", "function displayCurrentTime() {\n setInterval(function(){\n $('#current-time').html(moment().format('HH:mm'))\n }, 1000);\n }", "function showTime(){\r\n\tvar p = document.getElementById(\"clock\");\r\n\tvar time = new Date();\r\n\t\r\n\t// This will ensure that the minute value displays as two digits\r\n\tvar min = time.getMinutes();\r\n\tif(min < 10){\r\n\t\tmin = \"0\" + min\r\n\t}\r\n\t\r\n\t// This will ensure that the second value displays as two digits\r\n\tvar sec = time.getSeconds();\r\n\tif(sec < 10){\r\n\t\tsec = \"0\" + sec;\r\n\t}\r\n\t\r\n\t// This will update the 'clock' p element with a String representing the time\r\n\tp.innerHTML = getCurrentDate() + \" \" + time.getHours() + \":\" + min + \" \" + sec + \"<br />\";\r\n}", "function Update () {\n\tvar time = Mathf.Round(GameObject.Find(\"Global Game Controller\").GetComponent.<GameController>().timer);\n\ttext.text = \"Time: \" + time;\t\n}", "function getCurrentTIME() {\n\t\t\tvar player_time = Processing.getInstanceById('raced');\n\t\t\t\t$('#jquery_jplayer_1').bind($.jPlayer.event.timeupdate, function(event) { // Adding a listener to report the time play began\n\t\t\t\t\tvar jstime = event.jPlayer.status.currentTime;\n\t\t\t\t\tvar percentduration = event.jPlayer.status.currentPercentAbsolute;\t\n\t\t\t\t\t\t\tplayer_time.timecurrent(jstime);\n\t\t\t\t\t\t\tplayer_time.timepercent(percentduration);\n\t\t\t\t});\n\t\t\t}", "function getCurrentTime(){\n return '[' + moment.format(\"HH:mm\") + '] ';\n}", "function dateTime() {\n var dateTime = new Date();\n document.write(\"Current Date\", \" \" , dateTime , \"<br>\");\n }", "function currentTime(){\n var date = new Date().getDate();\n var month = new Date().getMonth() + 1;\n var year = new Date().getFullYear();\n var hours = new Date().getHours();\n var min = new Date().getMinutes();\n var sec = new Date().getSeconds();\n\n return month + '/' + date + '/' + year \n + ' ' + hours + ':' + min + ':' + sec;\n\n\n\n }", "function showTime() {\n\n var d = new Date();\n\n if (d.getMinutes().length < 2) {\n currTime = monthNames[d.getMonth()] + '.' + d.getDate() + '.' + d.getFullYear() + ' | ' + d.getHours() + ':0' + d.getMinutes();\n } else {\n currTime = monthNames[d.getMonth()] + '.' + d.getDate() + '.' + d.getFullYear() + ' | ' + d.getHours() + ':' + d.getMinutes();\n }\n\n $('.time').html(currTime);\n }", "function printTimedisplay (hours, minutes, seconds, milliseconds) {\n maintimeDisplay.innerHTML = hours + ':' + minutes + ':' + seconds;\n millisecondDisplay.innerHTML = '.' + milliseconds;\n}", "function showTime() {\r\n // stocam in variabila time un string cu ora curenta obtinut din libraria moment.js\r\n const time = moment().format(\"HH:mm:ss\");\r\n // orice e in elementul clockContainer va fi rescris.\r\n clockContainer.innerHTML = time;\r\n // trimitem functia ca parametru in metoda requestAnimationFrame de pe obiectul window.\r\n window.requestAnimationFrame(showTime);\r\n}", "function timeNow(){\n var now = moment().format('HH:mm')\n $(\"#current-time\").text(now)\n}", "function get_time() {\n return Date.now();\n}", "function time() {\n\t// storing the variable of the Date() function to call on to get hours, minutes, seconds\n\tvar current = new Date()\n\t// Storing the variables of hours, minutes, seconds\n\tvar currentHour = current.getHours()\n\tvar currentMinutes = current.getMinutes()\n\tvar currentSeconds = current.getSeconds()\n\t// changing the hours to to standard time instead of military time\n\tif(currentHour > 12) {\n\t\t// removing 12 hours from clock to make standard time\n\t\tcurrentHour = currentHour - 12\n\t}\n\t// at hour 00 in military aka midnight\n\tif(currentHour == 0) {\n\t\t// adding 12 hours so the clock reads 12 instead of 00\n\t\tcurrentHour = currentHour + 12\n\t}\n\tminutes = addZero(currentMinutes)\n\tseconds = addZero(currentSeconds)\n\t// adding the information to the div in my html\n\tdocument.getElementById(\"time\").textContent =\"Time: \" + currentHour + \":\" + minutes + \":\" + seconds\n\t// making the fuction time run every second\n\tsetTimeout(function() {\n\t\ttime()\n\t\t// 1000 milliseconds = 1 second\n\t}, 1000)\n}", "function getTime() {\n const date = new Date();\n const minutes = date.getMinutes();\n const hours = date.getHours();\n\n clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours} : ${\n minutes < 10 ? `0${minutes}` : minutes\n }`;\n}", "function updateTime() {\r\n const date = new Date();\r\n const hour = formatTime(date.getHours());\r\n const minutes = formatTime(date.getMinutes());\r\n const seconds = formatTime(date.getSeconds());\r\n\r\n display.innerText=`${hour} : ${minutes} : ${seconds}`\r\n}", "function showTime() {\n // get the time\n let tdy = new Date();\n let hrs = tdy.getHours();\n let min = tdy.getMinutes();\n let sec = tdy.getSeconds();\n\n // display AM or PM\n const amPm = hrs > 12 ? \"PM\" : \"AM\";\n\n // set 12 hr format\n hrs = hrs % 12 || 12;\n\n // add Zero in min and sec\n function addZero(e) {\n return (parseInt(e, 10) < 10 ? \"0\" : \"\") + e;\n }\n time.innerHTML = `${hrs}<span>:</span>${addZero(min)}<span>:</span>${addZero(sec)}<span> </span>${amPm}`;\n setTimeout(showTime, 1000);\n}", "function updateTime() {\n let m = String(new Date().getMinutes());\n let h = String(new Date().getHours());\n if (h.length == 1) {\n h = \"0\" + h;\n }\n if (m.length == 1) {\n m = \"0\" + m;\n }\n var time = h + \":\" + m;\n document.getElementById(\"time\").innerHTML = time;\n}", "function currentTime() {\r\n let date = new Date();\r\n let hh = date.getHours();\r\n let mm = date.getMinutes();\r\n let ss = date.getSeconds();\r\n let session = \"AM\";\r\n\r\n if (hh == 0) {\r\n hh = 12;\r\n }\r\n\r\n if (hh > 12) {\r\n hh = hh - 12;\r\n session = \"PM\";\r\n }\r\n\r\n hh = (hh < 10) ? \"0\" + hh : hh;\r\n mm = (mm < 10) ? \"0\" + mm : mm;\r\n ss = (ss < 10) ? \"0\" + ss : ss;\r\n\r\n let time = hh + \":\" + mm + \":\" + ss + \":\" + session;\r\n\r\n\r\n document.getElementById(\"clock\").innerHTML = time;\r\n let yogi = setInterval(() => {\r\n currentTime();\r\n {\r\n currentTime()\r\n }\r\n }, 1000)\r\n}", "showTime(time) {\n const current = new Date(time.time);\n\n const currentMonth = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"][current.getMonth()];\n const currentDay = current.getDate();\n const currentYear = current.getFullYear();\n\n const curTime = ui.formatTime(current);\n\n\n this.sunrise.innerHTML = ui.formatTime(new Date(time.sunrise));\n this.sunset.innerHTML = ui.formatTime(new Date(time.sunset));\n this.currentTime.innerHTML = `${curTime}, ${currentMonth} ${currentDay}, ${currentYear}`;\n }", "function printTimeInWords() {\n var msg;\n if (minNow === 0) {\n return '<span class=\"its\">It\\'s</span><br>' + '<span class=\"hour\">' + setHours() + '</span><br>' + ' <span class=\"min\">o\\'clock</span>.';\n } \n else if (minNow === 30) {\n return '<span class=\"its\">It\\'s</span> <br> <span class=\"min\">half past</span> <br>' + '<span class=\"hour\">' + setHours() + '</span>' + '.';\n }\n else {\n\t \n msg = '<span class=\"its\">It\\'s</span> <br >' + '<span class=\"min\">' + setMinutes() + '</span>' + '<span class=\"pos\">' + setPos() + '</span> <br>' + '<span class=\"hour\">' + setHours() + '</span>' + '.';\n return msg;\n }\n}", "function showDateTime() {\n let currentDateTime = new Date();\n let hours =\n currentDateTime.getHours() < 10\n ? \"0\" + currentDateTime.getHours()\n : currentDateTime.getHours();\n\n let mins =\n currentDateTime.getMinutes() < 10\n ? \"0\" + currentDateTime.getMinutes()\n : currentDateTime.getMinutes();\n let secs =\n currentDateTime.getSeconds() < 10\n ? \"0\" + currentDateTime.getSeconds()\n : currentDateTime.getSeconds();\n\n dateTime.innerHTML = hours + \":\" + mins + \":\" + secs;\n}", "function showTime(format24 = Storage.loadFormat24()){\r\n let today = new Date(),\r\n hour = today.getHours(),\r\n min = today.getMinutes(),\r\n sec = today.getSeconds();\r\n \r\n let amPm = hour >= 12 ? 'PM' : 'AM';\r\n \r\n //add zeros\r\n hour = addZero(hour)\r\n min = addZero(min)\r\n sec = addZero(sec)\r\n\r\n //12hr format\r\n if(format24 === \"false\"){\r\n hour = hour % 12 || 12\r\n }else{\r\n }\r\n \r\n if(Storage.loadClock() === \"currentTime\"){\r\n time.innerHTML = `${hour}<span>:</span>${min}<span>:</span>${sec} ${format24 === \"true\" ? '' : amPm}`; \r\n }\r\n \r\n const refresh = function (){\r\n showTime()\r\n } \r\n\r\n setTimeout(refresh, 100)\r\n }", "function time() {\n var date = new Date();\n var hours = date.getHours();\n var minutes = date.getMinutes();\n if (minutes < 10) {\n minutes = \"0\" + minutes;\n }\n var time = hours + \":\" + minutes\n return time;\n}", "function printTime() {\n $(\"#currentDay\").text(todaysDate);\n }", "function updateClock() {\n let date = new Date();\n let curr = pad(date.getHours(), 2) + \":\" + pad(date.getMinutes(), 2);\n document.getElementById(\"currentTime\")\n .innerText = curr;\n}", "function displayCurrentTime()\r\n\t{\r\n\t\t//display current playback time in minutes and seconds - MinutesMinutes:SecondsSeconds\r\n\t\tlet minutes = Math.floor ( myVideo.currentTime / 60 ); //divides the current playback time by 60 & uses Math.floor to round the real number into an integer (whole number)\r\n\t\tlet seconds = Math.floor ( myVideo.currentTime % 60 ); //gets the remainder of the currentTime of the video and thus will represent the seconds - uses Math.floor to round the real number into an integer (whole number)\r\n\t\t\r\n\t\t//if statements; outcome differs depending on conditions\r\n\t\tif ( minutes < 10 )\r\n\t\t{\r\n\t\t\tminutes = \"0\" + minutes; //current time is less than 10 minutes: a zero is in front e.g. \"01:00\", instead of \"1:00\"\r\n\t\t} //end if statement\r\n\t\t\r\n\t\tif ( seconds < 10 )\r\n\t\t{\r\n\t\t\tseconds = \"0\" + seconds; //current time is less than 10 seconds: a zero is in front e.g. \"00:09\", instead of \"00:9\"\r\n\t\t} //end if statement\r\n\t\tcurrentTimeDisplay.setAttribute ( \"value\", ( minutes + \":\" + seconds) ); //sets value for currentTimeDisplay to the minutes and seconds of the current playback time\r\n\t}", "function updateCurrentTime() {\n $('#current_time').html(formatTime(getCurrentTime()));\n}", "function displayDateTime() {\n $(\"#currentDay\").text(\"Today is: \" + moment().format(\"dddd, MMMM Do YYYY\"));\n $(\"#currentTime\").text(\"Time is now: \" + moment().format(\"h:mm:ss A\"));\n }", "function clock()\r\n{\r\n\tvar today=new Date();\r\n\tvar h=today.getHours();\r\n\tvar m=today.getMinutes();\r\n\tvar s=today.getSeconds();\r\n\t// add a zero in front of numbers<10\r\n\tm=checkTime(m);\r\n\ts=checkTime(s);\r\n\t\r\n\t$(\"#menu-hour\").html(h+\":\"+m+\":\"+s);\r\n}", "function current_time() {\n var hh = today.getHours()\n var mm = today.getMinutes()\n\n if (mm < 10) {\n mm = \"0\" + mm\n }\n\n if (hh >= 12) {\n hh = hh % 12\n return (hh + \":\" + mm + \"pm\")\n } else {\n return (hh + \":\" + mm + \"am\")\n }\n}", "function updatetime() {\n time.innerHTML = new Date;\n \n}", "function getCurrentTimeString() {\n const date = new Date();\n return date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();\n}", "function displayTime() {\n\t\t// Get the current time.\n\t var now = new Date();\n\t var h = now.getHours() > 12 ? now.getHours() % 12 : now.getHours();\n\t var m = now.getMinutes();\n\t var s = now.getSeconds();\n\n\t // Create a formatted string for the time.\n\t var timeString = (h < 10 ? \"\" : \"\") + now.toLocaleTimeString();\n\n\t // Set the time label's value to the time string.\n\t document.getElementById(\"current-time\").innerHTML = timeString;\n\t\t\n\t\t\n\t\t// Draw the clock using SVG\n\t\tfunction svgClock() {\n\t\t\t// Get current time.. again\n\t\t\tvar now = new Date();\n\t\t\tvar h, m, s;\n\t\t\th = 30 * ((now.getHours() % 12) + now.getMinutes() / 60);\n\t\t\tm = 6 * now.getMinutes();\n\t\t\ts = 6 * now.getSeconds();\n\n\t\t\t// Find pointers of the clock, rotate\n\t\t\tdocument.getElementById('h_pointer').setAttribute('transform', 'rotate(' + h + ', 50, 50)');\n\t\t\tdocument.getElementById('m_pointer').setAttribute('transform', 'rotate(' + m + ', 50, 50)'); \n\t\t\tdocument.getElementById('s_pointer').setAttribute('transform', 'rotate(' + s + ', 50, 50)');\n\t\t\t\n\t\t\t// Loop every second\n\t\t\tsetTimeout(svgClock, 1000);\n\t\t}\n\t svgClock();\n\t}", "function GetTime() {\n window.setTimeout( \"GetTime()\", 1000 );\n LiveTime = new Date()\n $(\"time\").innerHTML=LiveTime;\n }", "function showTime() {\n var date = new Date();\n var h = date.getHours();\n var m = date.getMinutes();\n var s = date.getSeconds();\n var session = \"AM\";\n\n // if (h == 0) {\n // h = 12;\n // }\n\n if (h > 12) {\n h = h - 12;\n session = \"PM\";\n }\n\n h = h < 10 ? \"0\" + h : h;\n m = m < 10 ? \"0\" + m : m;\n s = s < 10 ? \"0\" + s : s;\n\n var time = h + \":\" + m + \":\" + s + \"\" + session;\n document.getElementById(\"time\").innerHTML = time;\n // document.getElementById(\"time\").textContent = time;\n\n setTimeout(showTime, 1000);\n}", "function getTimeString() \n{\n var current_date = new Date();\n return current_date.getHours() + \":\" + current_date.getMinutes();\n}", "function timeNow() {\n var d = new Date(),\n h = (d.getHours()<10?'0':'') + d.getHours(),\n m = (d.getMinutes()<10?'0':'') + d.getMinutes(),\n s = (d.getSeconds()<10?'0':'') + d.getSeconds();\n return h + ':' + m + ':' + s;\n }", "_onTimeupdate () {\n this.emit('timeupdate', this.getCurrentTime())\n }", "_onTimeupdate () {\n this.emit('timeupdate', this.getCurrentTime())\n }", "function displayTime() {\n var rightNow = moment().format('MMM DD, YYYY [at] hh:mm:ss a');\n timeDisplayEl.text(rightNow);\n}", "function currentTime() {\n var now = new Date();\n var offset = now.getTimezoneOffset();\n var actual = now - offset;\n var str_date = new Date(actual).toLocaleDateString();\n var str_time = new Date(actual).toLocaleTimeString();\n return str_date + ' ' + str_time;\n}", "function wishGuest( name, time){\n console.log(`good ${time} ${name} have fun.`);\n}", "function getCurrentTime() {\n var currentTime = editor.player.prop(\"currentTime\");\n currentTime = isNaN(currentTime) ? 0 : currentTime.toFixed(4);\n return parseFloat(currentTime);\n}", "function GetCurrentTime() {\n var date = new Date();\n var hours = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();\n var am_pm = date.getHours() >= 12 ? \"PM\" : \"AM\";\n hours = hours < 10 ? \"0\" + hours : hours;\n var minutes = date.getMinutes() < 10 ? \"0\" + date.getMinutes() : date.getMinutes();\n var seconds = date.getSeconds() < 10 ? \"0\" + date.getSeconds() : date.getSeconds();\n return hours + \":\" + minutes + \":\" + seconds + \" \" + am_pm;\n}" ]
[ "0.7804829", "0.77773476", "0.76876307", "0.76045966", "0.7603456", "0.7533893", "0.7506032", "0.7506032", "0.74689245", "0.7463391", "0.7459716", "0.7335616", "0.73169553", "0.73098105", "0.73080784", "0.7302703", "0.7288477", "0.7274046", "0.71828634", "0.7170896", "0.71656483", "0.71560955", "0.7067125", "0.70504135", "0.7028832", "0.70173424", "0.7010214", "0.70063704", "0.6964637", "0.69581515", "0.6952769", "0.692644", "0.69228274", "0.69095886", "0.69008774", "0.68880415", "0.6881401", "0.68765503", "0.6875522", "0.68754816", "0.6861649", "0.68580496", "0.6857523", "0.6831722", "0.6798327", "0.6787282", "0.67810994", "0.6778035", "0.6775316", "0.6773086", "0.6767772", "0.6763961", "0.67546767", "0.6736755", "0.67360055", "0.6735994", "0.6722152", "0.67190856", "0.6712427", "0.66915476", "0.6687438", "0.6683831", "0.6662839", "0.6658504", "0.66579777", "0.664885", "0.6647027", "0.664561", "0.6640348", "0.6637622", "0.6634379", "0.66327554", "0.6632136", "0.6627658", "0.6621044", "0.6615956", "0.6602097", "0.6600916", "0.65942293", "0.65925205", "0.65869826", "0.65798277", "0.65788907", "0.65551674", "0.6553575", "0.6553147", "0.65523154", "0.65448105", "0.6525506", "0.652267", "0.65219015", "0.65199316", "0.6516112", "0.65148216", "0.6511575", "0.6511575", "0.65096617", "0.6503563", "0.64972246", "0.6496774", "0.6483806" ]
0.0
-1
Add a constructor in the SearchBar Component
constructor(props) { super(props); this.state = { term: ' ', location: ' ', sortBy: 'best_match' }; //bind methods in the constructor this.handleTermChange = this.handleTermChange.bind(this); this.handleLocationChange = this.handleLocationChange.bind(this); this.handleSearch = this.handleSearch.bind(this); //Create an Object with keys and values that conform to what the API expects to reecieve this.sortByOptions = { 'Best Match': 'best_match', 'Highest Rated': 'rating', 'Most Reviewed': 'review_count' }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "constructor(props) { // always called when class initated\n super(props); // super calls parent method on parent class (Component)\n\n this.state = { term: '' }; // state - plain JS obj, initialised by defining a property.\n // component level state (SearchBar) \n }", "constructor(props){ //constructor function called by default when SearchBar initiates\n super(props); //super calls parent method\n\n this.state = { term: 'Enter your search'}; //create new state object - term is value updated in search bar\n }", "constructor(props) {\n super(props);\n\n // value of input will be mapped to this.state.term\n this.state = { term: '' };\n\n // searchbar (this) has a func called onInputChange -> bind that func to this and then replace it w/ bound instance of the func\n this.onInputChange = this.onInputChange.bind(this);\n // ^ necessary cuz we're passing a callback that has a reference to 'this'\n this.onFormSubmit = this.onFormSubmit.bind(this);\n }", "constructor(props) {\n super(props); // this calls the constructor on the parent class Component\n\n // state is an object available to all classes, only inside the constructor do we change state this way\n this.state = { term: '' }; // we are recording the state of the search term on initialisation\n }", "constructor(props) {\n\t\tsuper(props);\n\n\t\t//Adding state - taking input from search bar and updating 'term' value.\n\t\tthis.state = {term: ''};\n\t}", "AddSearchProvider() {}", "constructor(props){\n super(props);\n //Sets the term displayed in the search bar on page load\n this.state = { term: ''};\n }", "constructor() {\n super();\n this.searchField = document.querySelector(\".type-search\");\n }", "constructor(props) {\n\t\tsuper(props);\n\t\tthis.state = {\n\t\t\tsearchInput: '',\n\t\t\tsearchResult: [],\n\t\t\tresultShow: false\n\t\t};\n\t\tthis.handleUpdate = this.handleUpdate.bind(this);\n\t\tthis.searchMovie = this.searchMovie.bind(this);\n\t\tthis.onBlur = this.onBlur.bind(this); \n\t\tthis.focusOnSearch = this.focusOnSearch.bind(this);\n\t}", "constructor()\r\n\t {\r\n\t super();\r\n\r\n\t this.submitHandler=this.submitHandler.bind(this);/*Will bind submitHandler to the SearchBarComponent component*/\r\n\t }", "constructor(props){\n super(props); //Calls parent method. \n this.state = {term:''};//initialises state. New object. term will be our search term property.\n }", "constructor(props) {\n\t\tsuper(props);\n\n\t\t// We also set our initial state inside the constructor.\n\t\t// In this case, we're just setting the state of 'term'\n\t\t// to an empty string. We'll alter this state once the \n\t\t// user types something in the search field.\n\t\tthis.state = { term: \"\" };\n\t}", "constructor(){\n super()\n this.state = {\n searchText: \"\"\n }\n }", "constructor(props){\n super(props);\n this.state={\n searchTerm:''\n }\n }", "constructor() { \n \n SearchResults.initialize(this);\n }", "constructor() {\n this.addSearchHTML();\n\n this.openButton = $('.js-search-trigger');\n this.closeButton = $('.search-overlay__close');\n this.searchOverlay = $('.search-overlay');\n this.searchField = $('#search-term');\n this.isOpen = false;\n this.typingTimer;\n this.resultsDiv = $('#search-overlay__result');\n this.previousValue;\n this.isSpinVisible = false;\n \n this.events();\n }", "constructor() {\n super(SearchEngine);\n }", "constructor(props) {\n super(props);\n\n // This is how we initialize \"state\" in a classe based component. Only\n // class-based component have state. When we create state, we always\n // say this.state and assign it to a new object. The object we pass\n // will have properties that we want to record on the state. We name\n // this particular property term because it is short for \"search term\", \n // which will be the value that we want to update when the search bar changes.\n // Only inside our constructor function, can we set state in this fashion.\n // Everywhere else in our code, we will have to use \"this.setState({})\", \n // where inside the object, we change the properties\n this.state = { term: \"\" };\n }", "constructor(props) {\n super(props);\n this.state = {term: ''};\n }", "constructor() {\n super();\n this.state = {\n data: [],\n filtered_data: [],\n showResults: false\n }\n this.search = this.search.bind(this);\n }", "constructor(props) {\n // The 'constructor' function that all js classes have,\n // is the first and only function called automatically,\n // whenever a new instance of the class is created.\n // And is reserved for initializing variables, state etc. for our class\n\n super(props);\n // with 'super' we call the parent method defined on the parent class\n\n //Initialize state:\n this.state = { term: '' };\n // whenever the user updates the search input, 'term' is the property that will record the change on\n // so we will update this.state.term to be the value of the input\n\n // !! IMPORTANT\n // this is the ONLY PLACE IN OUR APP where we will define the state value in this way, with '=' operator\n // when we will UPDATE the state, we will use 'setState' method !\n }", "constructor(props) {\n super(props)\n\n this.state = {\n filter: {},\n showFilterDialog: false\n }\n this._closeFilter = ::this._closeFilter\n this._onFilterClick = ::this._onFilterClick\n this._onFilterUpdated = ::this._onFilterUpdated\n this._onWorkshopClick = ::this._onWorkshopClick\n }", "constructor(props) {\n\t\tsuper(props);\n\n\t\t//how you instantiate state in a React component (only time we treat state like this!)\n\t\tthis.state = {term: ''};\n\t}", "constructor(props) {\n super(props);\n\n\t/*\n\tsets initial state of search bar. \n\tterm will refer to the search term located in the search input. \n\tlocation will refer to the location to search near from the location input.\n\tsortBy will represent the selected sortign option to use.\n\t\n\tthe first two keys should be set to empty strings (''). \n\tthe last key should be set to 'best_match'. this completes the constructor.\n\t*/\n this.state = {\n term: '',\n location: '',\n sortBy: 'best_match'\n };\n\n\t//bindings to methods.\n this.handleTermChange = this.handleTermChange.bind(this);\n this.handleLocationChange = this.handleLocationChange.bind(this);\n this.handleSearch = this.handleSearch.bind(this);\n \n\n this.sortByOptions = {\n 'Best Match': 'best_match',\n 'Highest Rated': 'rating',\n 'Most Reviewed': 'review_count'\n };\n }", "constructor(props) {\n super(props);\n this.state = {\n filterDropdownVisible: false,\n data: this.props.links,\n searchText: '',\n filtered: false,\n };\n }", "constructor(props) {\n super(props);\n\n this.savedFields = this.initFields();\n this.savedFields['title'] = '%';\n this.state.mode = 'search';\n this.state.fields = this.getSavedFields();\n this.state.editable = true;\n }", "constructor(props) {\n // call parent method from component\n super(props);\n // initialize state. this.state will contain properties we want to hold\n this.state = {term: ''};\n }", "constructor(props) {\n super(props);\n\n this.state = {\n searchKey: \"\",\n userKey: \"\",\n results: [],\n error: \"\",\n };\n\n this.searchInputChange = this.searchInputChange.bind(this);\n this.searchInputBlur = this.searchInputBlur.bind(this);\n this.setContentNameLocal = this.setContentNameLocal.bind(this);\n }", "constructor() {\n super();\n this.state = {\n showingSearch: false,\n ls: [{}],\n searching: false,\n };\n }", "constructor(props){\n\t\tsuper (props);\n\t\t this.state = {\n\t\t\t filter: modelInstance.getFilter(),\n\t\t\t isOpen: false,\n\t\t };\n\t}", "constructor (props) {\n super(props);\n //this.state = is only ever used inside of the constructor this.setState is used outside of constructor to manipulate state.\n this.state = {term:''};\n }", "constructor (props) {\n //it is mandatory to use super\n super(props); \n // this.state = {\n // list: list\n // }; \n //ES6 SUgar --- we can use a shorthand to initialize properties in a Object - since the property and the variable has the same name\n\n this.state = {\n list,\n //define the initial state for the query\n query: '',\n }; \n //the callback function is bound to the internal static component\n //binding and defining the method\n this.onSearch = this.onSearch.bind(this); \n\n }", "constructor() {\n /**\n * Search form name\n * @type {String}\n */\n this.searchForm = 'searchForm';\n\n /**\n * Search text\n * @type {String}\n */\n this.searchText = '';\n }", "constructor() {\n super();\n this.state = {\n showingSearch: false,\n searchTerm: '',\n searchResults: {items: [], total: 0}\n };\n }", "constructor(props){\n\t\tsuper(props);\n\t\tthis.state = { term:'' };\n\t\tthis.onInputChange = this.onInputChange.bind(this);\n\t}", "constructor(props) {\n // calling parent method\n super(props);\n\n // self.state update properties as state changes\n this.state = {term:''}\n }", "constructor(props) {\n super(props);\n this.state = {\n movie: ''\n };\n this.renderSearch = this.renderSearch.bind(this);\n this.handleMovieSubmit = this.handleMovieSubmit.bind(this);\n }", "onActionClickSearchBar() {\n this.search(this.state.search)\n }", "constructor(props){\n // the super method below allows us to call the constructor of the parent class of this class\n super(props);\n \n // the state here is where we hold properties that we want to record in this component \n this.state = {\n term: ''\n }\n }", "constructor(props) {\n\n //use methods from parent\n super(props);\n\n this.state = { term: '' }\n }", "constructor(props) {\n\t\tsuper(props);\n\n\t\t// 'CREATE' the state (only do this in the constructor)\n\t\t// ie. Only do 'this.state =' in constructor methods\n\t\tthis.state = {\n\t\t\tterm: ''\n\t\t};\n\t}", "constructor(props){\n super(props)\n this.state = {\n searchContent:true,\n loading: false,\n loader:false,\n searchText: '',\n response:''\n }\n }", "constructor(props){\r\n\t\tsuper(props);\r\n\t\tthis.loadmoreColor = new Animated.Value(0);\r\n\t\tthis.loadmoreScale = new Animated.Value(0);\r\n\t\tthis.state = {\r\n\t\t\tdimensions:Dimensions.get('window'),\r\n\t\t\tdata:{\r\n\t\t\t\tcategory:this.props.searchCategory,\r\n\t\t\t\tkanal:this.props.searchKanal,\r\n\t\t\t\tprovince:this.props.searchProvince,\r\n\t\t\t\ttext:this.props.searchText,\r\n\t\t\t\ttype:this.props.searchType,\r\n\t\t\t},\r\n\t\t\tsearchComp:<Spinner/>,\r\n\t\t\tsearchPage:0,\r\n\t\t\tsearchData:[],\r\n\t\t\tScrollView:this.refs.ScrollView,\r\n\t\t}\r\n\t}", "constructor(props) {\n \tsuper(props);\n\n \tthis.state = { term: '' }; //only class based components have state (not functional components)\n }", "constructor() {\n super();\n this.searchCleared = this.searchCleared.bind(this);\n this.searchChanged = this.searchChanged.bind(this);\n this.sortingChanged = this.sortingChanged.bind(this);\n }", "constructor(props) {\n super(props);\n this.state = {\n status: \"LISTENING\",\n searchDataCol: []\n };\n this.initSearch = this.initSearch.bind(this);\n this.getSearchedItem = this.getSearchedItem.bind(this);\n this.nullifyState = this.nullifyState.bind(this);\n }", "constructor(props) {\n // super() is the constructor function on Component class\n super(props);\n // we set state to be a JS object with any properties we want to record (eg: 'term' will be our yt searchterm)\n // This is the only time we will set the state in this way! The rest of the time we use this.setState()\n this.state = { term: '' };\n }", "constructor() {\n this.addSearchHTML();\n this.resultsDiv = document.querySelector(\"#search-overlay__results\");\n this.openButton = document.querySelectorAll(\".js-search-trigger\");\n this.closeButton = document.querySelector(\".search-overlay__close\");\n this.searchOverlay = document.querySelector(\".search-overlay\");\n this.searchField = document.querySelector(\"#search-term\");\n this.isOverlayOpen = false;\n this.isSpinnerVisible = false;\n this.previousValue;\n this.typingTimer;\n this.events();\n }", "constructor() {\n super();\n //since it has state it is called a smart component, they tend to have class syntax\n this.state = {\n robots: [],\n searchfield: ''\n }\n }", "constructor(props){\n super(props);\n this.state = { videoData:[], selectedVideo:null };\n\n //this.searchBarText('america');\n\n }", "initSearch() {\n this.search.init();\n\n if (this.visible) {\n this.closeSearch();\n } else {\n this.openSearch();\n }\n }", "function SearchPanel() {\n Component.call(this, 'form');\n\n var $element = $(this.element);\n var $input = $('<input type=\"search\" placeholder=\"Input a text...\">');\n var $button = $('<button type=\"submit\">Search</button>');\n\n $element.submit(function(event){\n event.preventDefault();\n var query = $input.val();\n if (query && _callback) _callback(query);\n }.bind(this));\n \n $element.append([$input, $button]);\n \n var _callback;\n this.onSearch = function (callback) {\n _callback = callback;\n };\n}", "constructor(props) {\n\n super(props);\n\n this.state = { term: ''};\n }", "constructor(props) {\n // Call the constructor defined on the parent\n super(props);\n\n // This is the ONLY PLACE WHERE we set state like this: this.state.term = 'bli'. Always use this.setState()!!\n // but you can reference using this.state.term\n this.state = { term: '' }\n }", "constructor(props) {\n // super calls parent method\n super(props);\n this.state = { term: \"\" };\n }", "createSearch() {\n\t\t\tconst {searchTerms} = this.state;\n\t \tif (searchTerms) {\n\t \t\tconst terms = searchTerms\n\t \t\tthis.setState({\n\t \t\t\tsearchTerms: ''\n\t \t\t})\n\t \t\tthis.props.sendSearchToParent(terms);\n\t \t}\n\t \t}", "constructor(search, nthParent, cssFilter, hrefFilter, hashFilter, location, conditionCallback) {\n super()\n this.search = search\n this.nthParent = parseInt(nthParent) || 1\n this.cssFilter = typeof cssFilter === 'string' ? cssFilter : ''\n this.hrefFilter = typeof hrefFilter === 'string' ? hrefFilter : ''\n this.hashFilter = typeof hashFilter === 'string' ? hashFilter : ''\n this.location = location\n this.conditionCallback = typeof conditionCallback === 'function' ? conditionCallback : function () { return true }\n }", "render(){\n\t\t// every class must have a render method \n\t\treturn(\n\t\t\t<div className=\"search-bar\">\n\t\t \t\t<input \n\t\t \t\t\tvalue = {this.state.term} // this turns into controlled component\n\t\t \t\t\tonChange={(event) => this.onInputChange(event.target.value)} />\n\t\t \t</div>\n\t\t );\n\t}", "constructor(props){\n // super props sets this.props to the constructor\n super(props);\n\n // setting up state\n this.state = {\n results: null,\n searchKey: '',\n searchTerm: DEFAULT_QUERY,\n isLoading: false,\n }\n\n // bind the functions to this (app component)\n this.removeItem = this.removeItem.bind(this);\n this.searchValue = this.searchValue.bind(this);\n this.fetchTopStories = this.fetchTopStories.bind(this);\n this.setTopStories = this.setTopStories.bind(this);\n this.onSubmit = this.onSubmit.bind(this);\n }", "constructor(props) {\n super(props)\n\n this.state = { term: '' }\n }", "constructor(props) {\n super(props);\n\n this.state = { term: \"\" };\n }", "constructor(props) {\n super(props);\n this.state = {term: ''};\n\n //Whenever you use this.functionName on react, you should bind the method here to \"this\", otherwise it wont know the correct context\n this.onInputChange = this.onInputChange.bind(this);\n }", "constructor(props){\n super(props);\n this.state={term:''};\n}", "constructor(props) {\n\t\tsuper(props);\n\t\tthis.state = {\n\t\t\t//UI option/toggles\n\t\t\tdisplayFacets : this.props.collectionConfig.facets ? true : false,\n\t\t\tgraphType : null,\n\t\t\tisSearching : false,\n\n\t\t\tquery : this.props.query,\n\n\t\t\t//query OUTPUT\n currentCollectionHits: this.getCollectionHits(this.props.collectionConfig),\n aggregations : {}\n\n }\n this.CLASS_PREFIX = 'qb';\n\t}", "constructor(props) {\n super(props)\n this.state = {\n uri: root_dom_element.getAttribute(\"data-api-uri\"),\n search_delay: 1000,\n search_querystring:\n \"query=any,contains,[TERM]&tab=Everything&search_scope=MyInstitution\",\n search_timer: null,\n search_uri: root_dom_element.getAttribute(\"data-api-uri\"),\n search_iframe_key: Math.random(),\n search_term: \"\",\n keyboardVisible: true,\n layoutName: \"default\"\n }\n }", "constructor(props) {\n // This super(props) line lets us access our parents properties as props.\n super(props);\n\n this.state = {\n searchTerm: \"\",\n starYear: \"\",\n endYear: \"\",\n results:[],\n Saved: []\n };\n\n this.setTerm = this.setTerm.bind(this);\n this.setStartYear = this.setStartYear.bind(this);\n this.setEndYear = this.setEndYear.bind(this);\n this.getClick = this.getClick.bind(this);\n }", "constructor(){\n super(); // By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods:\n this.state = {\n doppelgangers: [],\n searchfield: ''\n }\n }", "function SearchPanel() {\n Component.call(this, 'form');\n //Llamamos al componente ubicado en (web-components....)\n //Pasando el this(obligatorio para el call) y form que llegará \n //al componente como tag\n // var input = document.createElement('input');\n // input.type = 'search';\n // input.placeholder = 'Input a text...';\n // var button = document.createElement('button');\n // button.type = 'submit';\n // button.innerHTML = 'Search';\n var $form = $(this.element);\n\n var $input = $('<input type=\"search\" placeholder=\"Input a text...\"></a>');\n var $button = $('<button type=\"submit\">Search</button>');\n\n //Añadimos a SearchPanel.form.appendChild(input)\n $form.append($input);\n $form.append($button);\n\n //Declara una variable interna llamada callback\n var _callback;\n\n this.element.addEventListener('submit', function (event) {\n //Para que no te redirija a otro sitio\n event.preventDefault();\n\n var query = $input.val();\n\n if (query && _callback) _callback(query);\n //Bind hace referencia a su scope. En este caso a SearchPanel \n }.bind(this));\n\n //El this hace referencia al que hace la llamada ya que en este caso hay dos search(dos buscadores)\n this.onSearch = function (callback) {\n _callback = callback;\n };\n}", "constructor(props) {\n super(props)\n\n this.state = { term: '' }; // only time you use this syntax to set value of state! otherwise, use setState()\n }", "constructor(props){ \n // init stuff \n super(props); // <- 5.4 get parent method \n // 6.1 only inside of the constructor function do we change our state like this by just saying like this this.state = {term:'xxx'}\n // \"this.state\" 係 syntax\n this.state = {term:''}; //<- 5.5 when user update search input, 'term' property we want to update\n // state exists on class based components, 'this.state' <- 送嘅\n\n }", "constructor(props){\r\n //super used to call parent class\r\n super(props);\r\n\r\n this.state = { term: ''};\r\n }", "constructor(props) {\n super(props);\n // set empty array to state\n this.state = {\n search: '',\n data: [],\n \n isLoading: true,\n isListEmpty: false\n };\n }", "function SearchLight(props) { return <SearchInput initText={ props.initText } appTheme={ props.appTheme } onSubmit={ props.onSubmit } onDismiss={ props.onDismiss }/> }", "constructor(props) {\n\n // \"super\" calls the parent method in parent class \"Component\". \n super(props);\n\n // We initialise 'state' by creating a new object and assigning it to this.state. The object we pass contains\n // properties (e.g term ) that we want to record on the state. In this case, we want to record the 'term' \n // property on 'state'. 'term' aka 'search term'. Whenever the user updates the input, this is the property that \n // would be updated. The only time we manually change state is when it's in the constructor. \n // this.state.term is set to an empty string. \n // The initial state is an empty string. \n this.state = {term: ''};\n }", "function SearchControl (config) {\r\n\t\tSearchControl.superclass.constructor.apply(this, arguments);\r\n\t}", "function SearchBar(props){\n return(\n <SearchContainer>\n <SearchBox onChange={props.onChange} placeholder=\"Search for artist\"></SearchBox>\n {/* <SearchButton>\n <SearchIcon/>\n </SearchButton> */}\n </SearchContainer>\n )\n}", "render() {\r\n\r\n\t\t\r\n\t\treturn (\r\n\t\t\t<div class={style.searchBar}>\r\n\t\t\t\t<input type=\"text\" onKeyPress={this.props.onKeyPressed} placeholder=\"Search For A City\" />\r\n\t\t\t</div>\r\n\t\t);\r\n\t}", "function setUpSearch() {\n const $search = jQuery(\".users-search\");\n const usersSearch = new UsersSearch($search);\n}", "function searchBar() {\n const search = document.createElement('input');\n search.setAttribute('data-id-search', '');\n search.id = 'search';\n search.placeholder = 'Search Seddit';\n search.type = 'search';\n return search;\n}", "AutocompleteAdapter() {}", "function initSearchBox(options) {\n // Invoke auto complete for search box\n var searchOptions = {\n data: options,\n list: {\n maxNumberOfElments: 0,\n match: {enabled: true},\n onChooseEvent: function () {\n searchChooseItem();\n }\n }\n };\n searchInput.easyAutocomplete(searchOptions);\n\n // Start searching when typing in search box\n searchInput.on(\"input\", function (e) {\n e.preventDefault();\n searchChooseItem();\n });\n }", "constructor(props){\n super(props);\n\n this.state = { term: '' };\n }", "function SearchService() {\n\n // ensure that the q is shared across the whole app\n this.q = '';\n}", "constructor(props) {\n super(props);\n\n this.state = {\n contacts: [],\n filterText: '',\n sortContactValue: 'ascending',\n loading: true\n }\n }", "constructor(props) {\n super(props); // inherit parent component props\n\n // only in constructor we can initiate (set) state like this!!!\n this.state = {\n term: ''\n };\n }", "constructor(props){\n //it is the first and the only function called automatically, whenever a new instance was created\n super(props);\n this.state = { term: ''}; //initialize the state by create a new object, and assign it to this.state.\n }", "constructor() {\n this.addSearchHTML(); //Js is synchronous, so must call this function first\n this.resultsDiv = $(\"#search-overlay__results\");\n this.openButton = $(\".js-search-trigger\");\n this.closeButton = $(\".search-overlay__close\");\n this.searchOverlay = $(\".search-overlay\"); \n this.searchField = $(\"#search-term\");\n this.isOverlayOpen = false;\n this.isSpinnerVisible = false;\n this.typingTimer; //call to reset timer\n this.previousValue;\n this.events();\n }", "constructor(props){\n super(props); // inherit props and react methods\n this.state = {\n displayList: this.props.movies,\n query: ''\n };\n //function binding goes here\n this.handleSearch = this.handleSearch.bind(this)\n }", "get searchBarConfig() {\n return {\n searchFields: this.constants.searchFieldNames,\n filter: {show: true, options: this.filterOptions},\n };\n }", "constructor(props) {\n\n super(props);\n\n // initialize state object in constructor\n\n this.state = { term: '' };\n }", "constructor(props) {\n super(props);\n this.searchEmployee = this.searchEmployee.bind(this)\n this.state = {employeesData: employees, query: \"s\"};\n }", "construct(inSearchRequest : ISOClaimSearchRequest, inExposure : Exposure) {\n super(inSearchRequest, inExposure)\n }", "constructor() {\n \t/*\n this.name = \"Jane\";\n this.eyeColor = \"green\";\n this.head = {};\n this.brain = {}; */\n\t/* This part makes the live search window, which was moved from footer.php.\n\t if web browser disables JavaScript, search window should not be displayed.\n\t this is the reason why it should be displayed by 'Search.js' file.\n\t It should be in the first line of constructor, since other function will work\n\t only after searh live window exists. */\n this.addSearchHTML();\n\n this.resultsDiv = $(\"#search-overlay__results\");\n this.openButton = $(\".js-search-trigger\");\n this.closeButton = $(\".search-overlay__close\");\n\tthis.searchOverlay = $(\".search-overlay\");\n\t// search-term is the ID of <input> HTML element\n this.searchField = $(\"#search-term\");\n\tthis.events();\n\t// this property will be used for openOverlay and closeOverlay methods.\n this.isOverlayOpen = false;\n this.isSpinnerVisible = false;\n\tthis.previousValue;\n\t/* this is used to keep from reset the timer of keyboard. whenever user press\n\t the keyboard in search window */\n this.typingTimer;\n }", "constructor(){\n super(); //Use this to allow states to be used in the application\n\n this.state = {\n celebs: [\n //from ComponentDidMount(), users are adde here\n //and (this.state.celebs) renders it to the page\n ],\n searchField:''\n\n\n };\n\n }", "constructor(props) {\n super(props);\n\n this.state = {term: ''}; // object contains the properties that we want to record on the state\n // let's record the value of our input on the state\n }", "constructor(props) {\n\t\t// rmb we extend React.Component; Component has its own constructor function\n\t\t// when we define a method that is already defined on the parent class which is Component, we can call that parent method on the parent class by calling super\n\t\t// thus super is calling the parent method\n\t\tsuper(props)\n\t\t// whenever we use state, we initialize it by creating a new object and assigning it to this.state\n\t\t// the object we pass will also contain properties that we want to record on the state\n\t\t// eg, below we want to record the property 'term' on state; this is the property that we want to record our change on for the search bar\n\t\t// what we want is that as the user starts typing on the input, we want to update this.state.term to not be an empty string but to be the value of the input\n\t\tthis.state = { term: ''}\n\t}\n\t.\n\t.\n\t.", "function createSearchBox() {\r\n\t\t$(\".page-header\").append(searchBox);\r\n\t\t$(searchBox).addClass('student-search')\r\n\t\t$(searchBox).append(input);\r\n\t\t$(searchBox).append(button);\r\n\t\tbutton.textContent = \"Search\";\r\n\t}", "search() {\n this.trigger('search', {\n element: this.searchBar,\n query: this.searchBar.value\n });\n }", "constructor(props) {\n super(props);\n this.state = {\n query: ''\n }\n }", "render() {\n return (React.createElement(\"div\", { className: \"jp-extensionmanager-search-bar\" },\n React.createElement(InputGroup, { className: \"jp-extensionmanager-search-wrapper\", type: \"text\", placeholder: this.props.placeholder, onChange: this.handleChange, value: this.state.value, rightIcon: \"search\", disabled: this.props.disabled })));\n }", "constructor(props) {\n super(props);\n this.state = {\n books: [],\n searchedBooks: [],\n showSearchPage: false,\n loadShelvesSpinner: {\n currentlyReading: true,\n wantToRead: true,\n read: true,\n searchPage: false\n },\n showSearchMessage: false,\n movingBook: false\n }\n\n //Using Debounce Mechanism to Delay execution of API search request as user types for 1000 ms (1sec); hence, improving performance\n this.handleInputChangeThrottled = _.debounce(this.handleBookSearch, 1000);\n }" ]
[ "0.757572", "0.72776276", "0.7120856", "0.70949227", "0.70257163", "0.7003477", "0.7001607", "0.6918931", "0.68518233", "0.68232673", "0.68171465", "0.68098783", "0.6807952", "0.6799482", "0.6736351", "0.6728042", "0.6696609", "0.669564", "0.6683961", "0.6658316", "0.6648982", "0.6632578", "0.66282433", "0.66019857", "0.6582598", "0.6558359", "0.655471", "0.6543101", "0.65351427", "0.65215087", "0.6519944", "0.6488705", "0.64761686", "0.64713764", "0.6470509", "0.64497375", "0.64484596", "0.6441437", "0.63911444", "0.63859314", "0.63793683", "0.63768774", "0.637431", "0.6368273", "0.63649213", "0.63478386", "0.6346111", "0.63443756", "0.63121575", "0.6300333", "0.6291234", "0.62772864", "0.6273556", "0.62720656", "0.6271271", "0.62669563", "0.6262585", "0.6259358", "0.62589854", "0.62507474", "0.62429357", "0.6241215", "0.62379324", "0.6237278", "0.6235455", "0.6225014", "0.62234896", "0.62060946", "0.62046355", "0.61676383", "0.61652", "0.61591727", "0.6158307", "0.6157976", "0.6157759", "0.61342597", "0.6122814", "0.61004114", "0.60993814", "0.60967255", "0.60892713", "0.60818326", "0.6078547", "0.6052277", "0.6048896", "0.60363954", "0.6035824", "0.60343343", "0.6023584", "0.59998596", "0.5999286", "0.5995672", "0.599247", "0.59909105", "0.5980556", "0.5979035", "0.59745646", "0.59644854", "0.5955419", "0.5947572", "0.5936484" ]
0.0
-1
Add a method that returns the current CSS class of the sort Options
getSortByClass(sortByOption) { if (this.state.sortBy === sortByOption) { return 'active'; } else { return ''; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "sortClass(){\n return {\n 'sort-btn': true,\n 'sort-asc icon-down': this.column.sort === 'asc',\n 'sort-desc icon-up': this.column.sort === 'desc'\n };\n }", "getSortByClass(sortByOption) {\n if (this.state.sortBy === sortByOption) {\n return 'active';\n } else {\n return '';\n }\n }", "function sortClassToAdd(SortOrder){ \r\n \tvar classtoAdd = \"\"\r\n if(SortOrder == 0){\r\n classtoAdd = \"headerSortUp\";\r\n } else { \r\n classtoAdd = \"headerSortDown\";\r\n }\r\n\t\treturn (classtoAdd);\r\n\t}", "getSortByClass(sortByOption) {\n\t /*\n\t check if the state value of sortBy is equal to the provided sortByOptions. \n\t if it is, return 'active', otherwise return an empty string ('')\n\t */\n if (this.state.sortBy === sortByOption) {\n return 'active';\n }\n return '';\n }", "function updateSortCSS() {\n\n var sortButtons = jQuery('.flex-item');\n\n sortButtons.each(function() {\n\n if ( jQuery(this).attr('data-is-selected') == 'true') {\n jQuery(this).css({\n 'backgroundColor': 'black',\n 'color': 'white'\n });\n } else {\n jQuery(this).css({\n 'backgroundColor': 'white',\n 'color': 'black'\n });\n }\n });\n\n return;\n}", "function getSorter(){\n return $(\".active\").attr(\"sortAttr\");\n }", "get overrideSorting() {}", "function resortClass(idx){\n arrayBlock.children[idx].className ='sorted-element'\n}", "function getHeaderClass(table, column) {\n\n // Default class\n var cls = column.cls || '';\n // Sortable\n cls += column.sortable === false ? '' : 'sortable';\n\n if (table.view && table.view.sort && (table.view.sort[column.name] || table.view.sort[column.sort])) {\n cls += ' sorted-' + (table.view.sort[column.sort] || table.view.sort[column.name]);\n } else {\n // Leave as is\n }\n return cls;\n\n}", "function _fnSortingClasses(oSettings) {\n\t\t\tvar i, iLen, j, jLen, iFound;\n\t\t\tvar aaSort, sClass;\n\t\t\tvar iColumns = oSettings.aoColumns.length;\n\t\t\tvar oClasses = oSettings.oClasses;\n\n\t\t\tfor (i = 0; i < iColumns; i++) {\n\t\t\t\tif (oSettings.aoColumns[i].bSortable) {\n\t\t\t\t\t$(oSettings.aoColumns[i].nTh).removeClass(\n\t\t\t\t\t\t\toClasses.sSortAsc + \" \" + oClasses.sSortDesc + \" \"\n\t\t\t\t\t\t\t\t\t+ oSettings.aoColumns[i].sSortingClass);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (oSettings.aaSortingFixed !== null) {\n\t\t\t\taaSort = oSettings.aaSortingFixed.concat(oSettings.aaSorting);\n\t\t\t} else {\n\t\t\t\taaSort = oSettings.aaSorting.slice();\n\t\t\t}\n\n\t\t\t/* Apply the required classes to the header */\n\t\t\tfor (i = 0; i < oSettings.aoColumns.length; i++) {\n\t\t\t\tif (oSettings.aoColumns[i].bSortable) {\n\t\t\t\t\tsClass = oSettings.aoColumns[i].sSortingClass;\n\t\t\t\t\tiFound = -1;\n\t\t\t\t\tfor (j = 0; j < aaSort.length; j++) {\n\t\t\t\t\t\tif (aaSort[j][0] == i) {\n\t\t\t\t\t\t\tsClass = (aaSort[j][1] == \"asc\") ? oClasses.sSortAsc\n\t\t\t\t\t\t\t\t\t: oClasses.sSortDesc;\n\t\t\t\t\t\t\tiFound = j;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$(oSettings.aoColumns[i].nTh).addClass(sClass);\n\n\t\t\t\t\tif (oSettings.bJUI) {\n\t\t\t\t\t\t/* jQuery UI uses extra markup */\n\t\t\t\t\t\tvar jqSpan = $(\"span\", oSettings.aoColumns[i].nTh);\n\t\t\t\t\t\tjqSpan.removeClass(oClasses.sSortJUIAsc + \" \"\n\t\t\t\t\t\t\t\t+ oClasses.sSortJUIDesc + \" \"\n\t\t\t\t\t\t\t\t+ oClasses.sSortJUI + \" \"\n\t\t\t\t\t\t\t\t+ oClasses.sSortJUIAscAllowed + \" \"\n\t\t\t\t\t\t\t\t+ oClasses.sSortJUIDescAllowed);\n\n\t\t\t\t\t\tvar sSpanClass;\n\t\t\t\t\t\tif (iFound == -1) {\n\t\t\t\t\t\t\tsSpanClass = oSettings.aoColumns[i].sSortingClassJUI;\n\t\t\t\t\t\t} else if (aaSort[iFound][1] == \"asc\") {\n\t\t\t\t\t\t\tsSpanClass = oClasses.sSortJUIAsc;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsSpanClass = oClasses.sSortJUIDesc;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tjqSpan.addClass(sSpanClass);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t/*\n\t\t\t\t\t * No sorting on this column, so add the base class. This\n\t\t\t\t\t * will have been assigned by _fnAddColumn\n\t\t\t\t\t */\n\t\t\t\t\t$(oSettings.aoColumns[i].nTh).addClass(\n\t\t\t\t\t\t\toSettings.aoColumns[i].sSortingClass);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Apply the required classes to the table body Note that this is\n\t\t\t * given as a feature switch since it can significantly slow down a\n\t\t\t * sort on large data sets (adding and removing of classes is always\n\t\t\t * slow at the best of times..) Further to this, note that this code\n\t\t\t * is admitadly fairly ugly. It could be made a lot simpiler using\n\t\t\t * jQuery selectors and add/removeClass, but that is significantly\n\t\t\t * slower (on the order of 5 times slower) - hence the direct DOM\n\t\t\t * manipulation here.\n\t\t\t */\n\t\t\tsClass = oClasses.sSortColumn;\n\n\t\t\tif (oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses) {\n\t\t\t\tvar nTds = _fnGetTdNodes(oSettings);\n\n\t\t\t\t/* Remove the old classes */\n\t\t\t\tif (nTds.length >= iColumns) {\n\t\t\t\t\tfor (i = 0; i < iColumns; i++) {\n\t\t\t\t\t\tif (nTds[i].className.indexOf(sClass + \"1\") != -1) {\n\t\t\t\t\t\t\tfor (j = 0, jLen = (nTds.length / iColumns); j < jLen; j++) {\n\t\t\t\t\t\t\t\tnTds[(iColumns * j) + i].className = $\n\t\t\t\t\t\t\t\t\t\t.trim(nTds[(iColumns * j) + i].className\n\t\t\t\t\t\t\t\t\t\t\t\t.replace(sClass + \"1\", \"\"));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (nTds[i].className.indexOf(sClass + \"2\") != -1) {\n\t\t\t\t\t\t\tfor (j = 0, jLen = (nTds.length / iColumns); j < jLen; j++) {\n\t\t\t\t\t\t\t\tnTds[(iColumns * j) + i].className = $\n\t\t\t\t\t\t\t\t\t\t.trim(nTds[(iColumns * j) + i].className\n\t\t\t\t\t\t\t\t\t\t\t\t.replace(sClass + \"2\", \"\"));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (nTds[i].className.indexOf(sClass + \"3\") != -1) {\n\t\t\t\t\t\t\tfor (j = 0, jLen = (nTds.length / iColumns); j < jLen; j++) {\n\t\t\t\t\t\t\t\tnTds[(iColumns * j) + i].className = $\n\t\t\t\t\t\t\t\t\t\t.trim(nTds[(iColumns * j) + i].className\n\t\t\t\t\t\t\t\t\t\t\t\t.replace(\" \" + sClass + \"3\", \"\"));\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}\n\n\t\t\t\t/* Add the new classes to the table */\n\t\t\t\tvar iClass = 1, iTargetCol;\n\t\t\t\tfor (i = 0; i < aaSort.length; i++) {\n\t\t\t\t\tiTargetCol = parseInt(aaSort[i][0], 10);\n\t\t\t\t\tfor (j = 0, jLen = (nTds.length / iColumns); j < jLen; j++) {\n\t\t\t\t\t\tnTds[(iColumns * j) + iTargetCol].className += \" \"\n\t\t\t\t\t\t\t\t+ sClass + iClass;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (iClass < 3) {\n\t\t\t\t\t\tiClass++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function orderClassBy(e) {\n var prevOrderBy = orderBy;\n\n // remove active class from all columns\n for(var i = 0; i < orderByItems.length; i++) {\n orderByItems[i].classList.remove('active-ASC');\n orderByItems[i].classList.remove('active-DESC');\n }\n\n orderBy = e.target.dataset.orderBy;\n\n // toggle ASC | DESC if column clicked is same as previous click\n if(prevOrderBy == orderBy) {\n if(ascOrDesc == 'DESC') {\n ascOrDesc = 'ASC';\n } else {\n ascOrDesc = 'DESC';\n }\n // make ASC if column clicked is different from previous click\n } else {\n ascOrDesc = 'ASC';\n }\n\n // add active class to clicked column\n e.target.classList.add('active-'+ascOrDesc);\n\n console.log('ordering by...' + orderBy, ascOrDesc);\n\n updateBatchList();\n}", "function _fnSortingClasses( oSettings )\n\t\t{\n\t\t\tvar i, iLen, j, jLen, iFound;\n\t\t\tvar aaSort, sClass;\n\t\t\tvar iColumns = oSettings.aoColumns.length;\n\t\t\tvar oClasses = oSettings.oClasses;\n\t\t\t\n\t\t\tfor ( i=0 ; i<iColumns ; i++ )\n\t\t\t{\n\t\t\t\tif ( oSettings.aoColumns[i].bSortable )\n\t\t\t\t{\n\t\t\t\t\t$(oSettings.aoColumns[i].nTh).removeClass( oClasses.sSortAsc +\" \"+ oClasses.sSortDesc +\n\t\t\t\t \t\t\" \"+ oSettings.aoColumns[i].sSortingClass );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif ( oSettings.aaSortingFixed !== null )\n\t\t\t{\n\t\t\t\taaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\taaSort = oSettings.aaSorting.slice();\n\t\t\t}\n\t\t\t\n\t\t\t/* Apply the required classes to the header */\n\t\t\tfor ( i=0 ; i<oSettings.aoColumns.length ; i++ )\n\t\t\t{\n\t\t\t\tif ( oSettings.aoColumns[i].bSortable )\n\t\t\t\t{\n\t\t\t\t\tsClass = oSettings.aoColumns[i].sSortingClass;\n\t\t\t\t\tiFound = -1;\n\t\t\t\t\tfor ( j=0 ; j<aaSort.length ; j++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( aaSort[j][0] == i )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsClass = ( aaSort[j][1] == \"asc\" ) ?\n\t\t\t\t\t\t\t\toClasses.sSortAsc : oClasses.sSortDesc;\n\t\t\t\t\t\t\tiFound = j;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$(oSettings.aoColumns[i].nTh).addClass( sClass );\n\t\t\t\t\t\n\t\t\t\t\tif ( oSettings.bJUI )\n\t\t\t\t\t{\n\t\t\t\t\t\t/* jQuery UI uses extra markup */\n\t\t\t\t\t\tvar jqSpan = $(\"span\", oSettings.aoColumns[i].nTh);\n\t\t\t\t\t\tjqSpan.removeClass(oClasses.sSortJUIAsc +\" \"+ oClasses.sSortJUIDesc +\" \"+ \n\t\t\t\t\t\t\toClasses.sSortJUI +\" \"+ oClasses.sSortJUIAscAllowed +\" \"+ oClasses.sSortJUIDescAllowed );\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar sSpanClass;\n\t\t\t\t\t\tif ( iFound == -1 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t \tsSpanClass = oSettings.aoColumns[i].sSortingClassJUI;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if ( aaSort[iFound][1] == \"asc\" )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsSpanClass = oClasses.sSortJUIAsc;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsSpanClass = oClasses.sSortJUIDesc;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tjqSpan.addClass( sSpanClass );\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/* No sorting on this column, so add the base class. This will have been assigned by\n\t\t\t\t\t * _fnAddColumn\n\t\t\t\t\t */\n\t\t\t\t\t$(oSettings.aoColumns[i].nTh).addClass( oSettings.aoColumns[i].sSortingClass );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t/* \n\t\t\t * Apply the required classes to the table body\n\t\t\t * Note that this is given as a feature switch since it can significantly slow down a sort\n\t\t\t * on large data sets (adding and removing of classes is always slow at the best of times..)\n\t\t\t * Further to this, note that this code is admitadly fairly ugly. It could be made a lot \n\t\t\t * simpiler using jQuery selectors and add/removeClass, but that is significantly slower\n\t\t\t * (on the order of 5 times slower) - hence the direct DOM manipulation here.\n\t\t\t */\n\t\t\tsClass = oClasses.sSortColumn;\n\t\t\t\n\t\t\tif ( oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses )\n\t\t\t{\n\t\t\t\tvar nTds = _fnGetTdNodes( oSettings );\n\t\t\t\t\n\t\t\t\t/* Remove the old classes */\n\t\t\t\tif ( nTds.length >= iColumns )\n\t\t\t\t{\n\t\t\t\t\tfor ( i=0 ; i<iColumns ; i++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( nTds[i].className.indexOf(sClass+\"1\") != -1 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnTds[(iColumns*j)+i].className = \n\t\t\t\t\t\t\t\t\t$.trim( nTds[(iColumns*j)+i].className.replace( sClass+\"1\", \"\" ) );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if ( nTds[i].className.indexOf(sClass+\"2\") != -1 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnTds[(iColumns*j)+i].className = \n\t\t\t\t\t\t\t\t\t$.trim( nTds[(iColumns*j)+i].className.replace( sClass+\"2\", \"\" ) );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if ( nTds[i].className.indexOf(sClass+\"3\") != -1 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnTds[(iColumns*j)+i].className = \n\t\t\t\t\t\t\t\t\t$.trim( nTds[(iColumns*j)+i].className.replace( \" \"+sClass+\"3\", \"\" ) );\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}\n\t\t\t\t\n\t\t\t\t/* Add the new classes to the table */\n\t\t\t\tvar iClass = 1, iTargetCol;\n\t\t\t\tfor ( i=0 ; i<aaSort.length ; i++ )\n\t\t\t\t{\n\t\t\t\t\tiTargetCol = parseInt( aaSort[i][0], 10 );\n\t\t\t\t\tfor ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tnTds[(iColumns*j)+iTargetCol].className += \" \"+sClass+iClass;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif ( iClass < 3 )\n\t\t\t\t\t{\n\t\t\t\t\t\tiClass++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function sortby(picked) {\n // Based on what we picked, style spans and trigger sorting functions \n if (picked==1){$('#by-date').removeClass('sort-selected');$('#by-cat').addClass('sort-selected');catsort();}\n if (picked==0){$('#by-cat').removeClass('sort-selected');$('#by-date').addClass('sort-selected');datesort();}\n}", "function sortby(picked) {\n // Based on what we picked, style spans and trigger sorting functions \n if (picked==1){$('#by-date').removeClass('sort-selected');$('#by-cat').addClass('sort-selected');catsort();}\n if (picked==0){$('#by-cat').removeClass('sort-selected');$('#by-date').addClass('sort-selected');datesort();}\n}", "showSortArrow() {\n // Remove existing active arrows first.\n const active = document.querySelector('.marot-arrow-active');\n if (active) {\n active.classList.remove('marot-arrow-active');\n }\n // Highlight the appropriate arrow for the sorting field.\n const className = this.sortReverse ? 'marot-arrow-down' : 'marot-arrow-up';\n const arrow = document.querySelector(\n `#marot-${this.sortByField}-th .${className}`);\n if (arrow) {\n arrow.classList.add('marot-arrow-active');\n }\n }", "function setActiveSortClass(fieldName, reverse) {\n const activeSortLink = document.querySelector(\n `.headCell__link[data-fieldName=${fieldName}]`\n );\n const oldSortLink = document.querySelector(\".headCell__link.active\");\n const direction = reverse ? \"asc\" : \"desc\";\n\n // Remove previous active classes\n if (oldSortLink) {\n oldSortLink.classList.remove(\"active\", \"asc\", \"desc\");\n }\n // Set active css class\n activeSortLink.classList.add(\"active\", direction);\n}", "getSortOptions () {\n return [\n {value: 0, label: 'Price - Low to High'},\n {value: 1, label: 'Price - High to Low'},\n {value: 2, label: 'Distance - Close to Far'},\n {value: 3, label: 'Recomended'}\n ];\n }", "function _fnSortingClasses( oSettings )\n\t\t{\n\t\t\tvar i;\n\t\t\tvar aaSort;\n\t\t\tvar iColumns = oSettings.aoColumns.length;\n\t\t\tfor ( i=0 ; i<iColumns ; i++ )\n\t\t\t{\n\t\t\t\t$(oSettings.aoColumns[i].nTh).removeClass( \"sorting_asc sorting_desc sorting\" );\n\t\t\t}\n\t\t\t\n\t\t\tif ( oSettings.aaSortingFixed !== null )\n\t\t\t{\n\t\t\t\taaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\taaSort = oSettings.aaSorting.slice();\n\t\t\t}\n\t\t\t\n\t\t\t/* Apply the required classes to the header */\n\t\t\tfor ( i=0 ; i<oSettings.aoColumns.length ; i++ )\n\t\t\t{\n\t\t\t\tif ( oSettings.aoColumns[i].bSortable && oSettings.aoColumns[i].bVisible )\n\t\t\t\t{\n\t\t\t\t\tvar sClass = \"sorting\";\n\t\t\t\t\tfor ( var j=0 ; j<aaSort.length ; j++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( aaSort[j][0] == i )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsClass = ( aaSort[j][1] == \"asc\" ) ?\n\t\t\t\t\t\t\t\t\"sorting_asc\" : \"sorting_desc\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$(oSettings.aoColumns[i].nTh).addClass( sClass );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t/* \n\t\t\t * Apply the required classes to the table body\n\t\t\t * Note that this is given as a feature switch since it can significantly slow down a sort\n\t\t\t * on large data sets (adding and removing of classes is always slow at the best of times..)\n\t\t\t */\n\t\t\tif ( oSettings.oFeatures.bSortClasses )\n\t\t\t{\n\t\t\t\tvar nTrs = _fnGetTrNodes( oSettings );\n\t\t\t\t$('td', nTrs).removeClass( 'sorting_1 sorting_2 sorting_3' );\n\t\t\t\t\n\t\t\t\tvar iClass = 1;\n\t\t\t\tfor ( i=0 ; i<aaSort.length ; i++ )\n\t\t\t\t{\n\t\t\t\t\tvar iVis = _fnColumnIndexToVisible(oSettings, aaSort[i][0]);\n\t\t\t\t\tif ( iVis !== null )\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Limit the number of classes to three */\n\t\t\t\t\t\tif ( iClass <= 2 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$('td:eq('+iVis+')', nTrs).addClass( 'sorting_'+iClass );\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$('td:eq('+iVis+')', nTrs).addClass( 'sorting_3' );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tiClass++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "cellClass(){\n var cls = {\n 'sortable': this.column.sortable,\n 'resizable': this.column.resizable\n };\n\n if(this.column.heaerClassName){\n cls[this.column.headerClassName] = true;\n }\n\n return cls;\n }", "function setIcon(element, asc) {\n $(\"th\").each(function(index) {\n $(this).removeClass(\"sorting\");\n $(this).removeClass(\"asc\");\n $(this).removeClass(\"desc\");\n });\n element.addClass(\"sorting\");\n if (asc) element.addClass(\"asc\");\n else element.addClass(\"desc\");\n }", "getSortFunction() {\n var low_to_high = function (a, b) {return a.duration - b.duration};\n var high_to_low = function (a, b) {return b.duration - a.duration};\n if(this.state.selected_sort === 'High To Low'){\n return high_to_low\n }\n else if(this.state.selected_sort === 'Low To High'){\n return low_to_high\n }\n else {\n return null\n }\n }", "renderSortByOptions() {\n return Object.keys(this.sortByOptions).map(sortByOption => {\n let sortByOptionValue=this.sortByOptions[sortByOption];\n return ( <li className={this.getSortByClass(sortByOptionValue)} key={sortByOptionValue} onClick={this.handleSortByChange.bind(this, sortByOptionValue)} >{sortByOption}</li> );\n });\n }", "function toggleCurrentArrayElementClass(index){\n if(arrayBlock.children[index].className === 'default'){\n arrayBlock.children[index].className = 'sorted-element'\n }else{\n arrayBlock.children[index].className = 'default'\n}\n}", "_configureColumnClassCss (value, obj){\n if (obj.checkbox && obj.$group) {\n return 'rowGroupHeaderSelect';\n }\n if (obj.checkbox && !obj.$group) {\n return 'rowSelect';\n }\n if (!obj.checkbox && obj.$group) {\n return 'rowGroupHeader';\n }\n return \"\";\n }", "repeaterOnSort() {\n }", "getCurrentClassOptions(currentClass) {\n var options = [];\n var remainingClasses = this.remainingClasses.slice();\n remainingClasses.push(currentClass);\n remainingClasses.sort();\n for (let i = 0; i < remainingClasses.length; i++) {\n if (remainingClasses[i] === currentClass) {\n options.push(\n <option value={remainingClasses[i]} key={i}>\n {remainingClasses[i]}\n </option>\n );\n } else {\n options.push(\n <option value={remainingClasses[i]} key={i}>\n {remainingClasses[i]}\n </option>\n );\n }\n }\n return options;\n }", "get sortingOrder() {}", "function sortFromOption(){\n // console.log(\"sortFromOption\");\n getSortMethod(nowArray);\n pageNumber = 1;\n changeDisplayAmount(displayType,1);\n}", "function toogleSort(){\r\n\t\tif(settings.sort_type=='desc'){\r\n\t\t\tsettings.sort_type='asc';\r\n\t\t }else{\r\n\t\t\t settings.sort_type='desc';\r\n\t\t }\r\n\t}", "_optionClasses() {\n //show/hide classes\n\n const show_ticks = this.ui.show_ticks;\n const show_value = this.ui.show_value;\n const show_value_when_drag_play = this.ui.show_value_when_drag_play;\n const axis_aligned = this.ui.axis_aligned;\n const show_play = (this.ui.show_button) && (this.model.time.playable);\n\n this.xAxis.labelerOptions({\n scaleType: \"time\",\n removeAllLabels: !show_ticks,\n limitMaxTickNumber: 3,\n showOuter: false,\n toolMargin: {\n left: 10,\n right: 10,\n top: 0,\n bottom: 30\n },\n fitIntoScale: \"optimistic\"\n });\n\n this.element.classed(class_hide_play, !show_play);\n this.element.classed(class_playing, this.model.time.playing);\n this.element.classed(class_show_value, show_value);\n this.element.classed(class_show_value_when_drag_play, show_value_when_drag_play);\n this.element.classed(class_axis_aligned, axis_aligned);\n }", "function sortMethodList(type) {\n var methods = vm.allClasses[vm.selectedClass.key].methods;\n switch (type) {\n case constants.sortMessage.default:\n vm.sortMessage = constants.sortMessage.default;\n ref.once(\"value\", handleDataUpdate);\n break;\n case constants.sortMessage.a:\n vm.sortMessage = constants.sortMessage.a;\n vm.allClasses[vm.selectedClass.key].methods = helperFactory.sortList(methods, constants.sortMessage.a);\n break;\n case constants.sortMessage.d:\n vm.sortMessage = constants.sortMessage.d;\n vm.allClasses[vm.selectedClass.key].methods = helperFactory.sortList(methods, constants.sortMessage.d);\n break;\n default:\n break;\n }\n }", "get sort() { return this._sort; }", "get sort() { return this._sort; }", "get sort() { return this._sort; }", "getSortableOptions () {\n\n return {\n ...this.sortableOptions,\n ...{\n\n ghostClass : this.sortableGhostClass,\n chosenClass : this.sortableChosenClass,\n dragClass : this.sortableDragClass,\n animation : this.sortableAnimation,\n disabled : this.mode === 'view',\n group : this.enableMoveBlocksBetweenRows ? 'vgd' : undefined,\n filter : '.no-drag',\n preventOnFilter: true,\n onUpdate : this.onUpdate,\n onRemove : this.onRemove,\n onAdd : this.onAdd,\n\n // Chrome has a hover bug https://github.com/SortableJS/Sortable/issues/232\n onStart: this.onStart,\n onEnd : this.onEnd\n\n }\n };\n\n }", "function updateSortIcon() {\n // Remove previous downward sort icon, if it exists\n if (document.querySelector(\"th i.fa-sort-down\")) {\n document.querySelector(\"th i.fa-sort-down\").classList.remove(\"fa-sort-down\");\n }\n\n // Remove previous upward sort icon, if it exists\n if (document.querySelector(\"th i.fa-sort-up\")) {\n document.querySelector(\"th i.fa-sort-up\").classList.remove(\"fa-sort-up\");\n }\n\n // Add sort icon with correct direction to new heading\n if (dbState.sortDirection == 1) {\n headings[dbState.sortColIndex].querySelectorAll(\"i\")[1].classList.add(\"fa-sort-down\");\n\n } else {\n headings[dbState.sortColIndex].querySelectorAll(\"i\")[1].classList.add(\"fa-sort-up\");\n }\n}", "function _fakeSort() {\n var resultsEls = $( '.all-results .search-result-full' ).get();\n var sortOn = this.attributes[\"sort-trigger\"].value;\n\n // toggle the classes\n $( '.search-results-order .selected' ).removeClass('selected');\n $( this ).addClass('selected');\n\n // change our parent sort val\n $( '.search-step-3' ).attr('sort', sortOn);\n\n $( resultsEls.reverse() ).each(function() {\n $(this).detach().appendTo('.all-results');\n });\n }", "function renderSortOptions(col, status, colname) {\n str = \"\";\n if (status == -1) {\n\n if (col == \"ccode\" || col == \"class\" || col == \"credits\" || col == \"start_period\" || col == \"end_period\" || col == \"study_program\" || col == \"tallocated\") {\n str += \"<span onclick='myTable.toggleSortStatus(\\\"\" + col + \"\\\",0)'>\" + colname + \"</span>\";\n } else {\n str += \"<span onclick='myTable.toggleSortStatus(\\\"\" + col + \"\\\",0)'>\" + colname + \"</span>\";\n }\n } else {\n if (col == \"ccode\" || col == \"cname\" || col == \"class\" || col == \"credits\" || col == \"start_period\" || col == \"end_period\" || col == \"study_program\" || col == \"tallocated\") {\n if (status == 0) {\n str += \"<div onclick='myTable.toggleSortStatus(\\\"\" + col + \"\\\",1)'>\" + colname + \"&#x25b4;</div>\";\n } else {\n str += \"<div onclick='myTable.toggleSortStatus(\\\"\" + col + \"\\\",0)'>\" + colname + \"&#x25be;</div>\";\n }\n } else {\n if (status == 0) {\n str += \"<div onclick='myTable.toggleSortStatus(\\\"\" + col + \"\\\",1)'>\" + colname + \"&#x25b4;</div>\";\n } else {\n str += \"<div onclick='myTable.toggleSortStatus(\\\"\" + col + \"\\\",0)'>\" + colname + \"&#x25be;</div>\";\n }\n }\n }\n\n return str;\n}", "sortBy() {\n // YOUR CODE HERE\n }", "function sorting($event) {\n //get all thead td \n var tds = $($($event.currentTarget).parents('thead')).find('td');\n\n //check sorting or desc \n if ($($event.currentTarget).hasClass(\"sorting\") == true || $($event.currentTarget).hasClass(\"sorting_desc\") == true) {\n\n $(tds).attr(\"class\", \"sorting\"); // add sorting class to every td in thead\n $(tds[0]).attr(\"class\", \"\"); //remove class sorting from action coloumn \n $(tds[1]).attr(\"class\", \"\"); //remove class sorting from action coloumn \n\n $($event.currentTarget).attr(\"class\", \"sorting_asc\"); //add asc class in current tag\n\n vmab120.sortExp = $($event.currentTarget).attr(\"data-colname\") + \" asc\"; //update soring column in sorting exp\n\n } else {\n\n $(tds).attr(\"class\", \"sorting\"); // add sorting class to every td in thead\n $(tds[0]).attr(\"class\", \"\"); //remove class sorting from action coloumn \n $(tds[1]).attr(\"class\", \"\"); //remove class sorting from action coloumn \n\n $($event.currentTarget).attr(\"class\", \"sorting_desc\"); //add asc class in current tag\n vmab120.sortExp = $($event.currentTarget).attr(\"data-colname\") + \" desc\"; //update soring column in sorting exp\n }\n\n getab120();\n }", "getOrderBy() {}", "function getCompareFunction( styles ) {\n\t\t\t\t\tvar order = CKEDITOR.tools.array.map( styles, function( item ) {\n\t\t\t\t\t\treturn item.selector;\n\t\t\t\t\t} );\n\n\t\t\t\t\treturn function( style1, style2 ) {\n\t\t\t\t\t\tvar value1 = isClassSelector( style1.selector ) ? 1 : 0,\n\t\t\t\t\t\t\tvalue2 = isClassSelector( style2.selector ) ? 1 : 0,\n\t\t\t\t\t\t\tresult = value2 - value1;\n\n\t\t\t\t\t\t// If the selectors have same specificity, the latter one should\n\t\t\t\t\t\t// have higher priority (goes first).\n\t\t\t\t\t\treturn result !== 0 ? result :\n\t\t\t\t\t\t\torder.indexOf( style2.selector ) - order.indexOf( style1.selector );\n\t\t\t\t\t};\n\t\t\t\t}", "function datesort() {\n $('.categories, .categories li').css('display','none');\n $('.recent').css('display','block');\n $('.fas').removeClass('fa-caret-down, fa-caret-right').addClass('fa-caret-right');\n}", "get isSorting() {\r\n return this.i.cf;\r\n }", "function sorting($event) {\n //get all thead td \n var tds = $($($event.currentTarget).parents('thead')).find('td');\n\n //check sorting or desc \n if ($($event.currentTarget).hasClass(\"sorting\") == true || $($event.currentTarget).hasClass(\"sorting_desc\") == true) {\n\n $(tds).attr(\"class\", \"sorting\"); // add sorting class to every td in thead\n $(tds[0]).attr(\"class\", \"\"); //remove class sorting from action coloumn \n $(tds[1]).attr(\"class\", \"\"); //remove class sorting from action coloumn \n\n $($event.currentTarget).attr(\"class\", \"sorting_asc\"); //add asc class in current tag\n\n vmab041.sortExp = $($event.currentTarget).attr(\"data-colname\") + \" asc\"; //update soring column in sorting exp\n\n } else {\n\n $(tds).attr(\"class\", \"sorting\"); // add sorting class to every td in thead\n $(tds[0]).attr(\"class\", \"\"); //remove class sorting from action coloumn \n $(tds[1]).attr(\"class\", \"\"); //remove class sorting from action coloumn \n\n $($event.currentTarget).attr(\"class\", \"sorting_desc\"); //add asc class in current tag\n vmab041.sortExp = $($event.currentTarget).attr(\"data-colname\") + \" desc\"; //update soring column in sorting exp\n }\n\n getab041();\n }", "getSortTools(direction = null, cellProps) {\n const { computedSortable, renderSortTool: render } = this.getProps();\n return renderSortTool({ sortable: computedSortable, direction, renderSortTool: render }, cellProps);\n }", "function sortBy(categories) {\n    var sortIt = $(this).attr(\"data-sortby\"); \n    sortObjArray(Employees.entries, sortIt); \n    \n    $(\".btn.active\").removeClass(\"active\");\n    $(this).addClass(\"active\");\n}", "function getSortMethod(aimArray){\n // to got sort option\n var sortMethod=$(\"#sortByPrice\").find(\"option:selected\").text();\n\n if(sortMethod==\"Price: low-high\"){\n orderLowtoHigh(aimArray);\n }else if(sortMethod==\"Price: high-low\"){\n orderHightoLow(aimArray);\n }\n}", "function onSortChanged() {\n\n //Update the style values\n Object.keys($scope.sort)\n .forEach(updateValue);\n\n function updateValue(name) {\n var val = $scope.sort[name],\n field,\n desc;\n switch (val) {\n case true:\n field = name;\n desc = '';\n $scope.style.sort[name] = iconDown;\n break;\n case false:\n field = name;\n field += ' desc';\n $scope.style.sort[name] = iconUp;\n break;\n default:\n $scope.style.sort[name] = '';\n break;\n }\n\n if (field) {\n $scope.sortValue = field;\n }\n }\n }", "function selectionSetSorted(){\n setClass(nodes[selectionSmallest], 2, \"Default\");\n setClass(nodes[selectionCurrent], 2, \"Sorted\"); //sets the current node to \"sorted\" color\n addStep(\"Current Node \" + (selectionCurrent + 1) + \" is now sorted.\");\n sortedSwitchStep++;\n}", "function addOrder(){\n\tvar dirSort = document.getElementById('dirSort');\n\tif(dirSort.value=='asc'){\n\t\t$('#dirSort').val('desc');\n\t}else{\n\t\t$('#dirSort').val('asc');\n\t}\n\t\n\tvar dirSort = document.getElementById('dirSort');\n\t$('#date').css(\"font-weight\",\"bold\");\n\tif(dirSort.value=='asc'){\n\t\t$('#date i').removeClass(\"icon-up-dir\");\n\t\t$('#date i').addClass(\"icon-down-dir\");\n\t\t\n\t}\n\telse{\n\t\t$('#date i').removeClass(\"icon-down-dir\");\n\t\t$('#date i').addClass(\"icon-up-dir\");\n\t\t\n\t}\n\tproposalMessageFormBody();\n\t//messageFormBody();\n}", "function getSortMethod(columnName)\r\n{\r\n function compareNumericalDesc(x,y) { return y-x; }\r\n function compareNumericalAsc(x,y) { return x-y; }\r\n function compareString(x,y) { return (x==y) ? 0 : (y<x) ? 1 : -1; }\r\n \r\n function preprocessUsingHash(hash) { return function(cellText) { return hash[cellText]; }; }\r\n function integerize(cellText) { return parseInt(cellText, 10); }\r\n function uppercase(cellText) { return cellText.toUpperCase(); }\r\n\r\n var hashes = \r\n {\r\n \"Sev\" : { \"blo\":7, \"cri\":6, \"maj\":5, \"nor\":4, \"min\":3, \"tri\":2, \"enh\":1 }, // BMO's sane order\r\n \"Status\" : { \"UNCO\":7, \"NEW\":6, \"ASSI\":5, \"REOP\":4, \"RESO\":3, \"VERI\":2, \"CLOS\":1 }, // BMO's sane order\r\n \"Resolution\": { \"\":7, \"FIXE\":6, \"INVA\":5, \"WONT\":4, \"DUPL\":3, \"WORK\":2, \"MOVE\":1 } // BMO's weird order\r\n };\r\n\r\n\r\n switch(columnName) {\r\n\r\n case \"Sev\":\r\n case \"Status\":\r\n case \"Resolution\":\r\n return { preprocess: preprocessUsingHash(hashes[columnName]), compare: compareNumericalDesc };\r\n\r\n case \"Votes\":\r\n // bugs with the most votes first\r\n return { preprocess: integerize, compare: compareNumericalDesc };\r\n \r\n case \"ID\":\r\n // oldest bugs first\r\n return { preprocess: integerize, compare: compareNumericalAsc };\r\n\r\n default:\r\n // case-insensitive, alphabetical\r\n return { preprocess: uppercase, compare: compareString};\r\n\r\n }\r\n\r\n //also dates! maybe skip those, because the server has more information about dates than it gives us?\r\n}", "addClassModifier (iconClassName, options) {\n const classModifiers = {\n '--fav': this.isFavorite,\n '--visited': this.hasBeenVisited,\n '--new': this.isPromotion\n }\n\n const checkModifier = (className) => {\n return classModifiers[className](options)\n }\n\n const modifier = Object.keys(classModifiers).find(checkModifier)\n return modifier ? iconClassName + modifier : ''\n }", "set overrideSorting(value) {}", "static ASC(){\n return \"ASC\";\n }", "_updateColumnCssClassName() {\n this._columnCssClassName = [`cdk-column-${this.cssClassFriendlyName}`];\n }", "get sortOrder()\n\t{\n\t\treturn true;\n\t}", "function sortDates() {\n sortUsingNestedDate($('#projectIndexBig'), \"span\", $(\"button.btnSortDate\").data(\"sortKey\"));\n\n //ADDING UNDERLINE CLASSES\n if ($(\"#name\").hasClass(\"underline\")) {\n $(\"#name\").removeClass(\"underline\");\n $(\"#date\").addClass(\"underline\");\n } else {\n $(\"#date\").addClass(\"underline\");\n }\n }", "getVoteCountSortControl(field, order) {\n const isActive = field === \"voteCount\";\n return (\n <div>\n {isActive ? <label>Vote count {this.getEnabledIcon()}</label> : <label>Vote count</label>}\n <div className=\"dropdown\">\n <button className=\"btn btn-default dropdown-toggle\" type=\"button\" id=\"dropdownVoteCount\"\n data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"true\">\n {order === \"asc\" ? \"Ascending \" : \"Descending \"}<span className=\"caret\"> </span>\n </button>\n <ul className=\"dropdown-menu\" aria-labelledby=\"dropdownVoteCount\">\n <li>\n <div onClick={this.orderByVoteCount(true).bind(this)}>\n <h5 className=\"inline-default margin-left-sm\">Ascending</h5>\n {field === 'voteCount' && order === \"asc\" ?\n (<span className=\"margin-left-sm glyphicon glyphicon-ok\"> </span>) : null}\n </div>\n </li>\n <li>\n <div onClick={this.orderByVoteCount(false).bind(this)}>\n <h5 className=\"inline-default margin-left-sm\">Descending</h5>\n {field === 'voteCount' && order === \"desc\" ?\n (<span className=\"margin-left-sm glyphicon glyphicon-ok\"> </span>) : null}\n </div>\n </li>\n </ul>\n </div>\n </div>);\n }", "function setSort(clickedSort, direction) {\n document.querySelectorAll(\".sort-dropdown button\").forEach((knap) => {\n knap.classList.remove(\"selected\");\n });\n clickedSort.classList.add(\"selected\");\n\n currentSort = clickedSort.dataset.sort;\n sortDirection = direction;\n console.log(currentSort, sortDirection);\n buildList();\n}", "function reverseStyleSelected() {\n if (instanceOfMainClass.getSelectegCategory() !== '') {\n document.getElementById(instanceOfMainClass.getSelectegCategory()).classList.remove('category-main-chosen');\n }\n}", "function _addClassesOption(options, classes) {classes.forEach(function(cls){_addClassOption(options, cls)})}", "function getOrderOptions() {\n const sort = sortOptions[vm.activeSort] || vm.activeSort\n\n if (Array.isArray(sort)) {\n return sort.map(s => {\n const isReverse = s.startsWith('-')\n const str = isReverse ? s.substring(1) : s\n\n return `${isReverse ? '-' : ''}scores.${vm.sT}.${str}`\n })\n }\n\n return `scores.${vm.sT}.${sort}`\n }", "getIconClass(i) {\n switch (i) {\n case 0:\n return \"fas fa-sort\";\n case 1:\n return \"fas fa-sort-alpha-down\";\n case 2:\n return \"fas fa-sort-alpha-up\";\n case 3:\n return \"fas fa-sort-numeric-down\";\n case 6:\n return \"fas fa-sort-numeric-up\";\n default:\n return \"fas\";\n }\n }", "changeSorting() {\n this.currentlySelectedOrder =\n (this.currentlySelectedColumn === this.columnName) ? !this.currentlySelectedOrder : false;\n this.currentlySelectedColumn = this.columnName;\n }", "syncHeaderSortState() {\n const me = this,\n sorterMap = {};\n\n if (!me.grid.isConfiguring) {\n let storeSorters = me.store.sorters,\n sorterCount = storeSorters.length,\n classList = new DomClassList(),\n sorter;\n\n // Key sorters object by field name so we can find them.\n for (let sortIndex = 0; sortIndex < sorterCount; sortIndex++) {\n const sorter = storeSorters[sortIndex];\n if (sorter.field) {\n sorterMap[sorter.field] = {\n ascending: sorter.ascending,\n sortIndex: sortIndex + 1\n };\n }\n }\n\n // Sync the sortable, sorted, and sortIndex state of each leaf header element\n for (const leafColumn of me.grid.columns.bottomColumns) {\n const leafHeader = leafColumn.element;\n\n if (leafHeader) {\n // TimeAxisColumn in Scheduler has no textWrapper, since it has custom rendering,\n // but since it cannot be sorted by anyway lets just ignore it\n const dataset = leafColumn.textWrapper && leafColumn.textWrapper.dataset;\n\n // data-sortIndex is 1-based, and only set if there is > 1 sorter.\n // iOS Safari throws a JS error if the requested delete property is not present.\n dataset && dataset.sortIndex && delete dataset.sortIndex;\n\n classList.value = leafHeader.classList;\n\n if (leafColumn.sortable !== false) {\n classList.add(me.sortableCls);\n sorter = sorterMap[leafColumn.field];\n if (sorter) {\n if (sorterCount > 1 && dataset) {\n dataset.sortIndex = sorter.sortIndex;\n }\n classList.add(me.sortedCls);\n if (sorter.ascending) {\n classList.add(me.sortedAscCls);\n classList.remove(me.sortedDescCls);\n } else {\n classList.add(me.sortedDescCls);\n classList.remove(me.sortedAscCls);\n }\n } else {\n classList.remove(me.sortedCls);\n // Not optimal, but easiest way to make sure sort feature does not remove needed classes.\n // Better solution would be to use different names for sorting and grouping\n if (!classList['b-group']) {\n classList.remove(me.sortedAscCls);\n classList.remove(me.sortedDescCls);\n }\n }\n } else {\n classList.remove(me.sortableCls);\n }\n\n // Update the element's classList\n DomHelper.syncClassList(leafHeader, classList);\n }\n }\n }\n }", "function sortSelectCallback() {\n let sortType = $(this).val();\n setStatus(\"sortType\", sortType);\n\n console.log(\"sort clicked\");\n\n //TODO: Can we do this without referencing sg namespace?\n sg.cardContainer.sortCards(orderCodes[sortType]);\n }", "sort(sort) {\n this.options.sort = sort;\n return this;\n }", "syncHeaderSortState() {\n const me = this,\n sorterMap = {};\n\n if (!me.grid.isConfiguring) {\n const storeSorters = me.store.sorters,\n sorterCount = storeSorters.length,\n classList = new DomClassList();\n let sorter; // Key sorters object by field name so we can find them.\n\n for (let sortIndex = 0; sortIndex < sorterCount; sortIndex++) {\n const sorter = storeSorters[sortIndex];\n\n if (sorter.field) {\n sorterMap[sorter.field] = {\n ascending: sorter.ascending,\n sortIndex: sortIndex + 1\n };\n }\n } // Sync the sortable, sorted, and sortIndex state of each leaf header element\n\n for (const leafColumn of me.grid.columns.bottomColumns) {\n const leafHeader = leafColumn.element;\n\n if (leafHeader) {\n // TimeAxisColumn in Scheduler has no textWrapper, since it has custom rendering,\n // but since it cannot be sorted by anyway lets just ignore it\n const dataset = leafColumn.textWrapper && leafColumn.textWrapper.dataset; // data-sortIndex is 1-based, and only set if there is > 1 sorter.\n // iOS Safari throws a JS error if the requested delete property is not present.\n\n dataset && dataset.sortIndex && delete dataset.sortIndex;\n classList.value = leafHeader.classList;\n\n if (leafColumn.sortable !== false) {\n classList.add(me.sortableCls);\n sorter = sorterMap[leafColumn.field];\n\n if (sorter) {\n if (sorterCount > 1 && dataset) {\n dataset.sortIndex = sorter.sortIndex;\n }\n\n classList.add(me.sortedCls);\n\n if (sorter.ascending) {\n classList.add(me.sortedAscCls);\n classList.remove(me.sortedDescCls);\n } else {\n classList.add(me.sortedDescCls);\n classList.remove(me.sortedAscCls);\n }\n } else {\n classList.remove(me.sortedCls); // Not optimal, but easiest way to make sure sort feature does not remove needed classes.\n // Better solution would be to use different names for sorting and grouping\n\n if (!classList['b-group']) {\n classList.remove(me.sortedAscCls);\n classList.remove(me.sortedDescCls);\n }\n }\n } else {\n classList.remove(me.sortableCls);\n } // Update the element's classList\n\n DomHelper.syncClassList(leafHeader, classList);\n }\n }\n }\n }", "function getMyListSortByOptions() {\n\t\tvar html = '';\n\t\thtml += '<option value=\"country\">Country</option>';\n\t\thtml += '<option value=\"city\">City</option>';\n\t\thtml += '<option value=\"repository\">Repository</option>';\n\t\thtml += '<option value=\"hmmlProjectNumber\">HMML Project Number</option>';\n\t\t\n\t\treturn html;\n\t}", "orderIcon () {\n var {order} = this.props;\n\n if (order === 'descending') {\n return 'fa fa-sort-amount-desc';\n } else {\n return 'fa fa-sort-amount-asc';\n }\n }", "sortOnClick (e) {\n if (!e.target.className.includes('sortButton')) return\n this.setState({ sortActive: !this.state.sortActive })\n }", "get tileClass() {\n const TILE_WRAPPER_SELECTED_CLASS = 'tile-wrapper selected';\n const TILE_WRAPPER_UNSELECTED_CLASS ='tile-wrapper';\n if(this.selectedBoatId){\n return TILE_WRAPPER_SELECTED_CLASS;\n }\n return TILE_WRAPPER_UNSELECTED_CLASS;\n }", "function getDirection(options){\n if(options && options.dir == \"rtl\"){\n arrow_class = 'arrow-left'\n }else{\n arrow_class = 'arrow-right'\n }\n return arrow_class;\n}", "Sort() {\n\n }", "function setOrderingUI () {\n\t\t$('.glyphicon').on('click', function () {\n\t\t\tvar clickedDom = this;\n\t\t\t// Iterating through all the elemets under the glyphicon class\n\t\t\t$('.glyphicon').each(function() {\n\t\t\t\tvar currentItem = $(this);\n\t\t\t\t// When the concerened elemnet is the element that is clicked\n\t\t\t\tif (clickedDom === this) {\n\t\t\t\t\tcurrentItem.hasClass('active') ?\n\t\t\t\t\t\tcurrentItem.toggleClass('glyphicon-chevron-up glyphicon-chevron-down') :\n\t\t\t\t\t\t\tcurrentItem.toggleClass('active');\n\n\t\t\t\t\tstorageKey = this.id;\n\t\t\t\t\torder = currentItem.hasClass('glyphicon-chevron-up') ? 'ascending' : 'descending';\n\t\t\t\t\thandleDataToggling();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcurrentItem.removeClass('active glyphicon-chevron-up')\n\t\t\t\t\t\t.addClass('glyphicon-chevron-down');\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}", "function sort_overview_class(){\r\r\n\t\r\r\n\tvar click_num = $('#class_click_num').val();\r\r\n\t\r\r\n\tif(click_num == 0 || click_num == 2){\r\r\n\t\t\r\r\n\t\t$('#class_click_num').val(1);\r\r\n\t\t\r\r\n\t}else if(click_num == 1){\r\r\n\t\t\r\r\n\t\t$('#class_click_num').val(2);\r\r\n\t\t\r\r\n\t}\r\r\n\t\r\r\n\tfilter = {\r\r\n\t\t\r\r\n\t\tclass_of: $('#get_year').val(),\r\r\n\t\t\r\r\n\t\tsort_by_class: $('#class_click_num').val()\r\r\n\t\t\r\r\n\t};\r\r\n\t\r\r\n\tload_overview_student();\r\r\n\t\r\r\n}", "sort(column) {\n this.sortColumn = column.header;\n switch (this.sortClass) {\n case 'descending':\n this.sortClass = 'ascending';\n this.criteria.order = '-' + column.field;\n break;\n\n default:\n this.sortClass = 'descending';\n this.criteria.order = column.field;\n break;\n }\n\n return this.updateData();\n }", "function Sort() {}", "sort() {\n if (this.sortOrder === 'asc') {\n this.set('sortOrder', 'desc');\n\n } else if (this.sortOrder === '') {\n this.set('sortOrder', 'asc');\n\n } else {\n this.set('sortOrder', '');\n\n }\n }", "function sort_ite_class(){\r\r\n\t\r\r\n\tvar click_num = $('#class_click_num').val();\r\r\n\t\r\r\n\tif(click_num == 0 || click_num == 2){\r\r\n\t\t\r\r\n\t\t$('#class_click_num').val(1);\r\r\n\t\t\r\r\n\t}else if(click_num == 1){\r\r\n\t\t\r\r\n\t\t$('#class_click_num').val(2);\r\r\n\t\t\r\r\n\t}\r\r\n\t\r\r\n\tfilter = {\r\r\n\t\t\r\r\n\t\tclass_of: $('#get_year').val(),\r\r\n\t\t\r\r\n\t\tsort_by_class: $('#class_click_num').val()\r\r\n\t\t\r\r\n\t};\r\r\n\t\r\r\n\tload_ite_student();\r\r\n\t\r\r\n}", "_sortButtonColoring(button){\n\t\t// \n\t\tfor(var i = 0; i< this.buttons.length; i++){\n\t\t\tif(this.buttons[i][0] != button && this.buttons[i].attr('class') == 'button-blue'){\n\t\t\t\tthis._alterButton(this.buttons[i], \"button-blue\", \"button-normal\");\n\t\t\t//clciked button\t\n\t\t\t}else if(this.buttons[i][0] == button ){\n\t\t\t\tif(this.buttons[i].attr('class') == 'button-blue'){\n\t\t\t\t\tthis._alterButton(this.buttons[i], 'button-blue','button-normal');\n\t\t\t\t \tthis.clicked_button.className = 'button-normal';\n\t\t\t\t}else{\n\t\t\t\t\tthis._alterButton(this.buttons[i], 'button-normal','button-blue');\n\t\t\t\t\tthis.clicked_button.className = 'button-blue';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}", "function addOrder() {\n\tvar dirSort = document.getElementById('dirSort');\n\tif (dirSort.value == 'asc') {\n\t\t$('#dirSort').val('desc');\n\t} else {\n\t\t$('#dirSort').val('asc');\n\t}\n\n\tvar dirSort = document.getElementById('dirSort');\n\t$('#date').css(\"font-weight\", \"bold\");\n\tif (dirSort.value == 'asc') {\n\t\t$('#date i').removeClass(\"icon-up-dir\");\n\t\t$('#date i').addClass(\"icon-down-dir\");\n\n\t} else {\n\t\t$('#date i').removeClass(\"icon-down-dir\");\n\t\t$('#date i').addClass(\"icon-up-dir\");\n\n\t}\n\n\tmessageFormBody();\n}", "pullRequestClass(){\n var pullRequestClassName\n if (this.props.data.merged == true) {\n pullRequestClassName = \"merged\";\n } else {\n pullRequestClassName = this.props.data.state;\n }\n return pullRequestClassName;\n }", "function manageExportSorts() {\n\n var disabledOptions = [];\n\n for (var i = 0; i < sortBys.length; i++) {\n var sortByVal = $(\"#\" + sortBys[i]).val();\n var sortByVal2 = document.getElementById(sortBys[i]);\n var value = sortByVal2.options[sortByVal2.selectedIndex].value;\n if (sortByVal !== \"\") {\n $('.' + sortByVal).prop(\"disabled\", \"true\");\n $(\".\" + sortByVal).css(\"background-color\", \"#e6e6e6\");\n if (disabledOptions.indexOf(sortByVal) === -1) {\n disabledOptions[disabledOptions.length] = value;\n }\n }\n else {\n for (var j = 0; j < optionClasses.length; j++) {\n if (disabledOptions.indexOf(optionClasses[j]) == -1) {\n $(\".\" + optionClasses[j]).removeAttr(\"disabled\");\n $(\".\" + optionClasses[j]).css(\"background-color\", \"white\");\n }\n }\n }\n }\n}", "function setClassList(){\n\t\tlet cldd=$(\"<select />\").attr('id','cl-hdr').append($(\"<option />\").text('Class List').val('null'))\n\t\tlet classInfo=JSON.parse(localStorage.getItem('__Class-Info'))||{}\n\t\t\n\t\tfor (let [code, name] of Object.entries(classInfo)) {\n\t\t\tcldd.append($(\"<option />\").text(name).val(code))\n\t\t}\n\t\n\t\tcldd.append($(\"<option />\").text('──────────').val('').attr('disabled','disabled'))\n\t\t.append($(\"<option />\").text('Add').val('+').attr('title','Add `named` class... NB - only use if LocalStorage variables are permitted'))\n\t\treturn cldd\n\t}", "getSortFunction(query, options) {\n var search = this.prepareSearch(query, options);\n return this._getSortFunction(search);\n }", "function refreshSortPriorities() {\n\tfor (filterId in Filters) {\n\t\tvar f = Filters[filterId];\n\n\t\tif (f.Priority > 0) {\n\t\t\t$(\"#\" + f.Column.OrderButtonName).text(f.Priority);\n\t\t}\n\t}\n}", "function cssClass(className) {\n return \"json-formatter-\" + className;\n }", "function changeSortDirection(clickedSortButton, direction) {\n document.querySelectorAll(\".sort-dropdown button\").forEach((knap) => {\n knap.dataset.sortDirection = \"asc\";\n });\n\n document.querySelector(\".sort-heading p\").textContent = \"\";\n\n if (currentSort === \"firstName\") {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: First Name`;\n } else if (currentSort === \"lastName\") {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: Last Name`;\n } else if (currentSort === \"isMemberOfInqSquad\") {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: Inquisitorial`;\n } else if (currentSort === \"isPrefect\") {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: Prefects`;\n } else {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: ${currentSort}`;\n }\n\n if (direction === \"asc\") {\n clickedSortButton.dataset.sortDirection = \"desc\";\n document.querySelector(\".sort-heading i\").classList = \"arrow up\";\n } else {\n clickedSortButton.dataset.sortDirection = \"asc\";\n document.querySelector(\".sort-heading i\").classList = \"arrow down\";\n }\n}", "sortChange() {\n let choice = this.selector.value;\n switch(choice) {\n case \"1\":\n return this.sortAlpha();\n case \"2\":\n return this.sortAlpha(true);\n case \"3\":\n return this.sortDonation();\n case \"4\":\n return this.sortDonation(true);\n }\n }", "_updateColumnCssClassName() {\n super._updateColumnCssClassName();\n this._columnCssClassName.push(`mat-column-${this.cssClassFriendlyName}`);\n }", "_updateColumnCssClassName() {\n super._updateColumnCssClassName();\n this._columnCssClassName.push(`mat-column-${this.cssClassFriendlyName}`);\n }", "menuSort(sort) {\r\n const sortMethods = ['Sort by Company Name', 'Sort by Views', 'Sort by Rating']\r\n return sortMethods.map((name) => (\r\n <MenuItem\r\n name={name}\r\n insetChildren={true}\r\n checked={sort && sort.indexOf(name) > -1}\r\n value={name}\r\n primaryText={name}\r\n />\r\n ));\r\n }", "get sortingLayerName() {}", "function sortByDistanceAndRenderHTML() {\n\tdocument.getElementById(\"sort__distance\").classList.add('sort__button--active');\n\tdocument.getElementById(\"sort__price\").classList.remove('sort__button--active');\n\n\tcoffeeShops.sort(function(a,b) {\n\t\treturn a.distance - b.distance;\n\t});\n\n\tdocument.getElementById(\"coffee-shops-list\").innerHTML = \"\";\n\tcoffeeShops.forEach(function(shop){\n\t\taddCoffeeShopToList(shop);\n\t});\n}", "sort() {\n let time = 0;\n this.toggleSortButton(time);\n\n switch (this.state.currSelection) {\n case MERGESORT:\n time = this.mergeSort();\n break;\n case QUICKSORT:\n time = this.quickSort();\n break;\n case HEAPSORT:\n time = this.heapSort();\n break;\n case BUBBLESORT:\n time = this.bubbleSort();\n break;\n default:\n break;\n }\n\n this.toggleSortButton(time);\n }", "function changeSortingTypeOfListingHeaders(target)\n{\n\t$('table.listing, table.listingDis, table.small_table', $('#'+target)).not('.sortingTypeVerified').each(function()\n\t{\t\n\t\tvar table = this;\n\t\tvar rowLen = $('tr', this).length;\n\t\tif(rowLen < 20 && rowLen > 2) \n\t\t{\n\t\t\t$('tr:first th', this).each(function()\n\t\t\t{\n\t\t\t\t//check class asc or desc if exists return no need to continue \n\t\t\t\tif($('a', this).length <= 0)\n\t\t\t\t\treturn;\n\t\t\t\tvar anchorHref = $('a', this).attr('href');\t\n\t\t\t\tif(anchorHref.indexOf('direction:desc') > 0)\n\t\t\t\t\treturn;\n\t\t\t\tvar colIndex = $(this).index();\n\t\t\t\tvar cells = [], sortedCells = [];\n\t\t\t\t$('tr td:nth-child('+(colIndex + 1)+')', table).each(function() {\n\t\t\t\t\tvar colText = $(this).text();\n\t\t\t\t\tcells.push(colText); // save column text into an array\n\t\t\t\t\tsortedCells.push(colText);\n\t\t\t\t});\n\t\t\t\tsortedCells.sort(function(a,b) { // do case insensitive sort\n\t\t\t\t\tvar a = a.toLowerCase(), b = b.toLowerCase();\n\t\t\t\t\tif( a == b) return 0; if( a > b) return 1; return -1;\n\t\t\t\t});\n\t\t\t\tif(arraysEqual(cells, sortedCells)) { //check defalut column text with manual sorted text\n\t\t\t\t\t//if it is equal make it desc order\n\t\t\t\t\tanchorHref = anchorHref.replace(\"direction:asc\",\"direction:desc\"); \n\t\t\t\t\t$('a', this).attr('href', anchorHref);\n\t\t\t\t}\t\t\t\n\t\t\t});\n\t\t}\n\t\t$(this).addClass('sortingTypeVerified');// add verified class to avoid the same process again on next ajax call\n\t});\t\n}", "tableHeaderOrderIcons(columnName){\n if(this.$route.query.type !== undefined){\n if(this.$route.query.type == 'desc' && this.$route.query.order == columnName){\n return 'fa fa-long-arrow-up';\n }\n }\n return 'fa fa-long-arrow-down';\n }", "function columnOrderClick() {\n $(divHeader).on(\"click\", function() {\n clearInterval(colorsIntervalId);\n clearInterval(sortIntervalId);\n let newClass=$(this).attr('class');\n if (newClass===orderClass) orderAsc=!orderAsc;\n orderClass=newClass;\n reorderRows=true;\n sortRunning=true;\n colorsRunning=false;\n sort();\n sortSetInterval();\n colors();\n });\n}" ]
[ "0.7296139", "0.7126677", "0.68716156", "0.6587146", "0.65364623", "0.6504597", "0.6308812", "0.6235036", "0.6223046", "0.59736294", "0.5956998", "0.5898191", "0.5890625", "0.5890625", "0.588406", "0.58394873", "0.5834518", "0.5797572", "0.5758416", "0.5710294", "0.57089", "0.564265", "0.5634301", "0.56309783", "0.56198657", "0.56137353", "0.55892324", "0.5587258", "0.5506573", "0.5497372", "0.5495295", "0.5488098", "0.5488098", "0.5488098", "0.5482559", "0.5480834", "0.54801875", "0.54484206", "0.544007", "0.54172385", "0.54148674", "0.538153", "0.53760964", "0.53669405", "0.5362557", "0.53594214", "0.5347379", "0.53384876", "0.5337657", "0.5330773", "0.5327674", "0.5313384", "0.5306527", "0.52940065", "0.5293764", "0.52869374", "0.52822536", "0.5277687", "0.5253673", "0.52461964", "0.52260166", "0.5217636", "0.5203531", "0.52026343", "0.52014166", "0.5194969", "0.51924837", "0.519221", "0.51836896", "0.5168666", "0.5164993", "0.5152647", "0.5152552", "0.51487476", "0.5145493", "0.5141844", "0.513256", "0.51245034", "0.51232004", "0.51096714", "0.510964", "0.5104005", "0.5102451", "0.50899297", "0.5086296", "0.5082551", "0.5077477", "0.5073869", "0.5072742", "0.5051989", "0.5032546", "0.50280666", "0.50280666", "0.502774", "0.5017724", "0.50106335", "0.5002111", "0.49983203", "0.49959126", "0.4994377" ]
0.70470965
2
Add a method that sets the state of a sorting option
handleSortByChange(sortByOption) { this.setState({sortBy: sortByOption}); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "set overrideSorting(value) {}", "changeSorting() {\n this.currentlySelectedOrder =\n (this.currentlySelectedColumn === this.columnName) ? !this.currentlySelectedOrder : false;\n this.currentlySelectedColumn = this.columnName;\n }", "handleSortByChange(sortByOption) {\n this.setState({ sortBy: sortByOption});\n }", "_onChangeSortParams(sortBy, typeOfSorting) {\n this.setState({ onSorting: true, sortPrams: { sortBy, typeOfSorting } });\n }", "set sortingOrder(value) {}", "sort() {\n if (this.sortOrder === 'asc') {\n this.set('sortOrder', 'desc');\n\n } else if (this.sortOrder === '') {\n this.set('sortOrder', 'asc');\n\n } else {\n this.set('sortOrder', '');\n\n }\n }", "setSort(sort) {\n this.setState({\n sort\n });\n }", "'click .sort-by-priority'(event, instance) {\n instance.state.set('sortBy', 'priority');\n }", "function sortFromOption(){\n // console.log(\"sortFromOption\");\n getSortMethod(nowArray);\n pageNumber = 1;\n changeDisplayAmount(displayType,1);\n}", "handleSort() {\n this.state.sort === true\n ? this.setState({ sort: false })\n : this.setState({ sort: true });\n }", "changeSort(newSort)\n {\n if (this.state.selectedSort==newSort)\n {\n this.setState({sortDirection:this.state.sortDirection?0:1},this.sendSortData);\n return;\n }\n\n this.setState({selectedSort:newSort},this.sendSortData);\n }", "get overrideSorting() {}", "function setSort(x) { //these 3 functions are connected to the event of the buttons\n sortby = x;\n updateDoctorsList(); //they then invoke updatedoctorslist, that is meant to access the doctors on the server with the current criteria, the fetch..\n}", "storeSortMethod(method) {\n // If the method is not valid\n if (!method.target.value) return;\n // Otherwise, set the state as the actual sorting method\n let sort = method.target.value;\n this.setState({ sort_method: sort });\n }", "triggerSort() {\n const logPrefix = 'SortingFilterController.changeOrderBy()\\t';\n\n if (_.isEmpty(this.filterSortingList)) {\n this.$log.warn(logPrefix + 'please define field \"entityListName\"');\n return;\n } else if (_.isEmpty(this.filterSortingField)) {\n this.$log.warn(logPrefix + 'please define field \"field\"');\n return;\n } else if (_.isUndefined(this.tableCell.tableManager.baseData)) {\n this.$log.warn(logPrefix + 'please sorting base data');\n return;\n }\n\n //TODO: read this data from the state service.\n //const sortingOptions = this.tableCell.tableManager.baseData.sorting;\n\n // Entity list or field name has changed -> reset sort order.\n if (this.sorting.entityList !== this.filterSortingList || this.sorting.field !== this.filterSortingField) {\n this.sorting.order = '';\n }\n\n let sortingType = this.filterSortingType;\n if (_.isEmpty(sortingType)) {\n sortingType = 'string';\n }\n\n let options = this.filterSortingOptions;\n if (_.isUndefined(options) || _.isPlainObject(options) === false) {\n options = {};\n }\n\n this.sorting.fnc = sortingType;\n this.sorting.entityList = this.filterSortingList;\n this.sorting.field = this.filterSortingField;\n this.sorting.options = options;\n\n // Swap the sorting order e.g. to start on a numerical sorting column with the largest value.\n if (options.swapOrder) {\n this.sorting.order = (this.sorting.order === 'desc' ? 'asc' : 'desc');\n } else {\n this.sorting.order = (this.sorting.order === 'asc' ? 'desc' : 'asc');\n }\n\n // Update class attribute onto this filter's table cell element.\n if (this.sorting.order === 'asc') {\n this.tableCell.$element\n .removeClass('desc')\n .addClass('asc');\n } else {\n this.tableCell.$element\n .removeClass('asc')\n .addClass('desc');\n }\n\n // Sort list by defined sort parameters\n this.tableCell.tableManager.baseData.data = SortUtils.sortArrayOfLists(\n this.tableCell.tableManager.baseData.data,\n this.sorting.fnc,\n this.sorting.entityList,\n this.sorting.field,\n this.sorting.order,\n this.sorting.options\n );\n\n // Trigger a view update to display the new (sorted) data.\n this.tableCell.tableManager.updateView();\n }", "function setSort(clickedSort, direction) {\n document.querySelectorAll(\".sort-dropdown button\").forEach((knap) => {\n knap.classList.remove(\"selected\");\n });\n clickedSort.classList.add(\"selected\");\n\n currentSort = clickedSort.dataset.sort;\n sortDirection = direction;\n console.log(currentSort, sortDirection);\n buildList();\n}", "sort (type) {\n this.setState({\n sortType: type\n });\n }", "setSortType(type) {\n this.sortType = type;\n }", "onSortSelect(event) {\n this.setState(\n {\n sortOrder: event\n }\n )\n }", "function setSortOrder() {\n\tif (sortOrder == \"high to low\") {\n\t\tsortOrder = \"low to high\";\n\t} else {\n\t\tsortOrder = \"high to low\";\n\t}\n}", "sortChange() {\n let choice = this.selector.value;\n switch(choice) {\n case \"1\":\n return this.sortAlpha();\n case \"2\":\n return this.sortAlpha(true);\n case \"3\":\n return this.sortDonation();\n case \"4\":\n return this.sortDonation(true);\n }\n }", "sort() {\n let time = 0;\n this.toggleSortButton(time);\n\n switch (this.state.currSelection) {\n case MERGESORT:\n time = this.mergeSort();\n break;\n case QUICKSORT:\n time = this.quickSort();\n break;\n case HEAPSORT:\n time = this.heapSort();\n break;\n case BUBBLESORT:\n time = this.bubbleSort();\n break;\n default:\n break;\n }\n\n this.toggleSortButton(time);\n }", "function bindSort(obj, sortByID, sortOrderID, actionTypeID, fnCallback) {\r\n\r\n\r\n var sortby = ($(obj).attr(\"sortby\"));\r\n var previouseSortBy = $(\"#\" + sortByID).val();\r\n var sortOrder = $(\"#\" + sortOrderID).val();\r\n\r\n if (sortby == previouseSortBy) {\r\n if (sortOrder == '0') {\r\n $(\"#\" + sortOrderID).val(\"1\");\r\n $(obj).addClass(\"desc\");\r\n }\r\n else {\r\n $(\"#\" + sortOrderID).val(\"0\");\r\n $(obj).addClass(\"asc\");\r\n }\r\n $(\"#\" + sortByID).val(sortby);\r\n }\r\n else {\r\n $(\"#\" + sortOrderID).val(\"1\");\r\n $(\"#\" + sortByID).val(sortby);\r\n }\r\n $(\"#\" + actionTypeID).val(\"sortList\");\r\n //$(\"#currentPage\").val(\"1\");\r\n fnCallback();\r\n\r\n}", "function selectSort() {\n const clickedSort = this;\n const direction = this.dataset.sortDirection;\n setSort(clickedSort, direction);\n\n const clickedSortButton = this;\n changeSortDirection(clickedSortButton, direction);\n}", "_changeSortMode(e) {\n if (this.sortColumn === e.detail.columnNumber && this.sortMode === \"asc\") {\n this.sortMode = \"desc\";\n } else if (\n this.sortColumn === e.detail.columnNumber &&\n this.sortMode === \"desc\"\n ) {\n this.sortMode = \"none\";\n } else {\n this.sortMode = \"asc\";\n this.sortColumn = e.detail.columnNumber;\n }\n e.detail.setSortMode(this.sortMode);\n this.sortData(this.sortMode, e.detail.columnNumber);\n }", "sort(sort) {\n this.options.sort = sort;\n return this;\n }", "function toogleSort(){\r\n\t\tif(settings.sort_type=='desc'){\r\n\t\t\tsettings.sort_type='asc';\r\n\t\t }else{\r\n\t\t\t settings.sort_type='desc';\r\n\t\t }\r\n\t}", "onChange(setTo) {\n\t\tthis.props.sortBy(setTo);\n\t}", "'click .sort-by-date'(event, instance) {\n instance.state.set('sortBy','date');\n }", "handleSort(columnName){\n if (this.state.order === \"ascending\"){\n this.setState({...this.state, order: \"descending\"});\n }\n else if (this.state.order === \"descending\"){\n this.setState({...this.state, order: \"ascending\"});\n }\n }", "sort(predicate) {\n if (this._multiple && this.selected) {\n this._selected.sort(predicate);\n }\n }", "function onSortValueChanged() {\n $scope.options.filter = { sort: $scope.sortValue };\n }", "function initializeSortingState() {\n let datasetFields = Object.values(classNameToKeyMap);\n datasetFields.forEach(function(field) {\n ascendingOrder[field] = false;\n });\n}", "finishedSortingHandler(){\n this.setState({ arraySorting : false })\n }", "getSortOptions () {\n return [\n {value: 0, label: 'Price - Low to High'},\n {value: 1, label: 'Price - High to Low'},\n {value: 2, label: 'Distance - Close to Far'},\n {value: 3, label: 'Recomended'}\n ];\n }", "function sortComplete(){\n isSorting = false\n updateMenu()\n}", "sort(sortable) {\n if (this.active != sortable.id) {\n this.active = sortable.id;\n this.direction = sortable.start ? sortable.start : this.start;\n }\n else {\n this.direction = this.getNextSortDirection(sortable);\n }\n this.sortChange.emit({ active: this.active, direction: this.direction });\n }", "sort(sortable) {\n if (this.active != sortable.id) {\n this.active = sortable.id;\n this.direction = sortable.start ? sortable.start : this.start;\n }\n else {\n this.direction = this.getNextSortDirection(sortable);\n }\n this.sortChange.emit({ active: this.active, direction: this.direction });\n }", "_sortValues() {\n if (this.multiple) {\n const options = this.options.toArray();\n this._selectionModel.sort((a, b) => {\n return this.sortComparator ? this.sortComparator(a, b, options) :\n options.indexOf(a) - options.indexOf(b);\n });\n this.stateChanges.next();\n }\n }", "onSortChange() {\n const {\n state: { sortDirection, listItem },\n } = this;\n\n const newSortDirection =\n SORT_DIRECTION.ASC === sortDirection\n ? SORT_DIRECTION.DESC\n : SORT_DIRECTION.ASC;\n\n const sortedList = sortList(newSortDirection, listItem);\n this.setState({\n sortDirection: newSortDirection,\n listItem: sortedList,\n });\n }", "onSorted(){\n if(this.column.sortable){\n this.column.sort = NextSortDirection(this.sortType, this.column.sort);\n\n this.onSort({\n column: this.column\n });\n }\n }", "function setSort(objName) {\n vm.predicate = objName;\n vm.reverse = !vm.reverse;\n }", "function sortby(picked) {\n // Based on what we picked, style spans and trigger sorting functions \n if (picked==1){$('#by-date').removeClass('sort-selected');$('#by-cat').addClass('sort-selected');catsort();}\n if (picked==0){$('#by-cat').removeClass('sort-selected');$('#by-date').addClass('sort-selected');datesort();}\n}", "function sortby(picked) {\n // Based on what we picked, style spans and trigger sorting functions \n if (picked==1){$('#by-date').removeClass('sort-selected');$('#by-cat').addClass('sort-selected');catsort();}\n if (picked==0){$('#by-cat').removeClass('sort-selected');$('#by-date').addClass('sort-selected');datesort();}\n}", "function saveSortParams(event) {\n var table = jQuery(event.target);\n var selected = table.find(\".headerSortDown\");\n var direction = \"down\";\n if (selected.length == 0) {\n\tselected = table.find(\".headerSortUp\");\n\tdirection = \"up\";\n }\n\n selected = jQuery.trim(selected.text());\n jQuery.post(\"/filter/set_single_task_filter\", {\n \tname : \"sort\",\n \tvalue : (selected + \"_\" + direction)\n });\n}", "sortButtonEvent(){\n this.setState({ arraySorted: true, arraySorting: true, drawerOpen: false });\n }", "repeaterOnSort() {\n }", "updateSortColumn(columnIndex) {\n this.setState(\n {\n sortColumnIndex: columnIndex,\n ascendingOrder: this.state.sortColumnIndex === columnIndex ? !this.state.ascendingOrder : true\n },\n () => this.immediateFilterAndSort()\n )\n }", "resetSortState() {\n this.props.dispatch(couponsActions.toggleSort(false, 4, 'Recommended'));\n this.props.dispatch(couponsActions.setSortResults([]));\n }", "get sort() { return this._sort; }", "get sort() { return this._sort; }", "get sort() { return this._sort; }", "function _selectSortItemOnViewSettingDialog() {\n\t\tvar oSelectedSortItem = {}, isDescending;\n\t\t//TODO: Unify ascending/descending\n\t\tif (oSelectedRepresentation.orderby && oSelectedRepresentation.orderby.length && oSelectedRepresentation.orderby[0].descending !== undefined) {\n\t\t\tisDescending = oSelectedRepresentation.orderby[0].descending;\n\t\t} else if (oSelectedRepresentation.orderby && oSelectedRepresentation.orderby.length) {\n\t\t\tisDescending = !oSelectedRepresentation.orderby[0].ascending;\n\t\t}\n\t\tif (oSelectedRepresentation.orderby && oSelectedRepresentation.orderby.length > 1) { //More than one sorting criterium in config\n\t\t\toSelectedSortItem = undefined;\n\t\t} else if(oSelectedRepresentation.orderby && oSelectedRepresentation.orderby.length == 1) { //One sorting criterium in config\n\t\t\toSelectedSortItem = oSelectedRepresentation.orderby[0].property;\n\t\t} else {\n\t\t\toSelectedSortItem = undefined; //No sorting criterium in config\n\t\t\tisDescending = false;\n\t\t}\n\t\toViewSettingDialog.setSortDescending(isDescending);\n\t\toViewSettingDialog.setSelectedSortItem(oSelectedSortItem);\n\t}", "changeSort(sort, sortAscending) {\n\t\tthis.fetchExternalData(\n\t\t\t\tthis.state.filter, \n\t\t\t\tthis.state.currentPage, \n\t\t\t\tthis.state.externalResultsPerPage,\n\t\t\t\tsort,\n\t\t\t\tsortAscending);\n }", "function onSortChanged() {\n\n //Update the style values\n Object.keys($scope.sort)\n .forEach(updateValue);\n\n function updateValue(name) {\n var val = $scope.sort[name],\n field,\n desc;\n switch (val) {\n case true:\n field = name;\n desc = '';\n $scope.style.sort[name] = iconDown;\n break;\n case false:\n field = name;\n field += ' desc';\n $scope.style.sort[name] = iconUp;\n break;\n default:\n $scope.style.sort[name] = '';\n break;\n }\n\n if (field) {\n $scope.sortValue = field;\n }\n }\n }", "setSortBy(sort_by) {\n // set sort_by radio to stored value, un-check other options.\n const sortByOptions = ['best_match', 'rating', 'review_count', 'distance'];\n sortByOptions.forEach(id => {\n if (sort_by === id) $(`#${id}`).prop('checked', true);\n else $(`#${id}`).prop('checked', false);\n });\n }", "sortBy() {\n // YOUR CODE HERE\n }", "function list_set_sort(col)\n {\n if (settings.sort_col != col) {\n settings.sort_col = col;\n $('#notessortmenu a').removeClass('selected').filter('.by-' + col).addClass('selected');\n rcmail.save_pref({ name: 'kolab_notes_sort_col', value: col });\n\n // re-sort table in DOM\n $(noteslist.tbody).children().sortElements(function(la, lb){\n var a_id = String(la.id).replace(/^rcmrow/, ''),\n b_id = String(lb.id).replace(/^rcmrow/, ''),\n a = notesdata[a_id],\n b = notesdata[b_id];\n\n if (!a || !b) {\n return 0;\n }\n else if (settings.sort_col == 'title') {\n return String(a.title).toLowerCase() > String(b.title).toLowerCase() ? 1 : -1;\n }\n else {\n return b.changed_ - a.changed_;\n }\n });\n }\n }", "sort(predicate) {\n if (this._multiple && this.selected) {\n this._selected.sort(predicate);\n }\n }", "sort(predicate) {\n if (this._multiple && this.selected) {\n this._selected.sort(predicate);\n }\n }", "changeSortingVariable(value, bool) {\n\t\t\tconst order = bool !== undefined\n\t\t\t\t? bool :\n\t\t\t\t(this.sortingVariable === value ? !this.orderArray[value] : true);\n\t\t\tthis.$set(this.orderArray, value, order);\n\t\t\tthis.sortingVariable = value;\n\t\t}", "function sortButtonClick() {\n\tvar id = $(this).attr(\"data-col\");\n\t// console.log('id discovered was'+ id);\n\n\tvar f = Filters[id];\n\n\tswitch (f.Direction) {\n\t\tcase SortOptions.None:\n\t\t\tf.Direction = SortOptions.Ascending;\n\t\t\tf.Priority = getMaxPriority() + 1;\n\t\t\tbreak;\n\n\t\tcase SortOptions.Ascending:\n\t\t\tFilters[id].Direction = SortOptions.Descending;\n\t\t\tbreak;\n\n\t\tcase SortOptions.Descending:\n\t\t\tFilters[id].Direction = SortOptions.None;\n\t\t\tremoveOrderPriorityById(id);\n\t\t\tbreak;\n\t}\n\n\tsetButtonsFromFilters(f);\n\trefreshSortPriorities();\n\tResort();\n\tsetGrid(globData);\n}", "onSortChange(newSortSettings) {\n const comments = this.filterAndSort(this.state.comments,\n newSortSettings.comparator,\n this.state.commentFilter.filterFn);\n\n this.setState({\n comments: comments,\n sortSettings: newSortSettings\n });\n }", "function setSortAndSave(e, rowID){\n setSort(e, rowID);\n saveSort();\n}", "function sortingOptions() {\n var doOrderBy = document.getElementById(\"chkOrderBy\").checked;\n if (doOrderBy !== null && doOrderBy === true) {\n document.getElementById(\"cmboFields\").disabled = false;\n document.getElementById(\"comboOrderByMode\").disabled = false;\n }\n else {\n document.getElementById(\"cmboFields\").disabled = true;\n document.getElementById(\"comboOrderByMode\").disabled = true;\n }\n}", "function Sorter() {\n\tthis.column = 0; \t\t\t// keep track of sort column\n\tthis.order = 'ascending'; // keep track of sort order \n}", "sortClass(){\n return {\n 'sort-btn': true,\n 'sort-asc icon-down': this.column.sort === 'asc',\n 'sort-desc icon-up': this.column.sort === 'desc'\n };\n }", "function sortSelectCallback() {\n let sortType = $(this).val();\n setStatus(\"sortType\", sortType);\n\n console.log(\"sort clicked\");\n\n //TODO: Can we do this without referencing sg namespace?\n sg.cardContainer.sortCards(orderCodes[sortType]);\n }", "function supports_sort_by(sort) {\n $('input[name=\"supports_sort_by\"]').val(sort);\n $('.table-supports').DataTable().ajax.reload();\n $('input[name=\"supports_sort_by\"]').val('');\n}", "processSortItemsByStatus() {\n // IF WE ARE CURRENTLY INCREASING BY STATUS SWITCH TO DECREASING\n console.log(this.state.currentItemSortCriteria);\n let sortTransaction;\n if (this.isCurrentItemSortCriteria(ItemSortCriteria.SORT_BY_STATUS_INCREASING)) {\n // this.sortTasks(ItemSortCriteria.SORT_BY_STATUS_DECREASING);\n sortTransaction = new ItemSort_Transaction(this.sortTasks, \n this.state.currentItemSortCriteria,\n ItemSortCriteria.SORT_BY_STATUS_DECREASING);\n this.props.updateJsTPS(sortTransaction); \n }\n // ALL OTHER CASES SORT BY INCREASING\n else {\n // this.sortTasks(ItemSortCriteria.SORT_BY_STATUS_INCREASING);\n sortTransaction = new ItemSort_Transaction(this.sortTasks.bind(this), \n this.state.currentItemSortCriteria,\n ItemSortCriteria.SORT_BY_STATUS_INCREASING);\n this.props.updateJsTPS(sortTransaction); \n }\n this.setState({listToEdit: this.state.listToEdit});\n console.log(this.state.currentItemSortCriteria);\n }", "function enableSortingBtn(){\n document.querySelector(\".bubbleSort\").disabled = false;\n document.querySelector(\".insertionSort\").disabled = false;\n document.querySelector(\".mergeSort\").disabled = false;\n document.querySelector(\".quickSort\").disabled = false;\n document.querySelector(\".selectionSort\").disabled = false;\n}", "function changeSort(columnName) {\n for (let item of sortList) {\n\n if (item.name === columnName) {\n\n /* Set new sort */\n if (item.sort === undefined) {\n item.sort = true;\n } else {\n item.sort = !item.sort;\n }\n\n if (item.sort) {\n item.element.innerText = item.name + \" ▼\";\n } else {\n item.element.innerText = item.name + \" ▲\";\n }\n\n } else {\n /* Reset sort in all another field */\n item.sort = undefined;\n item.element.innerText = item.name + \" ▼▲\";\n }\n }\n\n filter();\n}", "function toggleSort(sortBy, sortvalue, sortdir, sortlabel) {\n if (sortdir) {\n var obj = _.find(sortBy, function (obj) {\n return obj.column == sortvalue;\n });\n\n if (obj) {\n obj.direction = sortdir;\n }\n else {\n sortBy.push({column: sortvalue, direction: sortdir, label: sortlabel});\n }\n }\n else {\n var index = 0;\n var obj = _.find(sortBy, function (obj) {\n return obj.column == sortvalue || ++index == sortBy.length && (index = -1);\t\t// see http://stackoverflow.com/a/8065397\n });\n\n if (obj) {\n sortBy.splice(index, 1);\n }\n }\n\n return sortBy;\n }", "resetSorting() {\n this.sortBy = undefined;\n this.sortDir = 0;\n }", "set sortIndex(value) {\n this._namedArgs.sort = \"index\";\n }", "_sortedByChanged(sorted) {\n const headerColumns = this.shadowRoot.querySelectorAll('.th');\n this._resetOldSorting();\n headerColumns.forEach((el) => {\n if (el.getAttribute('sortable') === sorted) {\n el.setAttribute('sorted', '');\n this.set('sortDirection', 'ASC');\n }\n });\n }", "function selectionSetSorted(){\n setClass(nodes[selectionSmallest], 2, \"Default\");\n setClass(nodes[selectionCurrent], 2, \"Sorted\"); //sets the current node to \"sorted\" color\n addStep(\"Current Node \" + (selectionCurrent + 1) + \" is now sorted.\");\n sortedSwitchStep++;\n}", "_handleTap(e) {\n const sortField = e.path[0].getAttribute('sortable');\n if (e.path[0].classList.contains('th') && sortField) {\n if (this.sorted === sortField) {\n this.set('sortDirection', this.sortDirection === 'ASC' ? 'DESC' : 'ASC');\n } else {\n this._resetOldSorting();\n this.set('sorted', sortField);\n }\n }\n }", "getSortableOptions () {\n\n return {\n ...this.sortableOptions,\n ...{\n\n ghostClass : this.sortableGhostClass,\n chosenClass : this.sortableChosenClass,\n dragClass : this.sortableDragClass,\n animation : this.sortableAnimation,\n disabled : this.mode === 'view',\n group : this.enableMoveBlocksBetweenRows ? 'vgd' : undefined,\n filter : '.no-drag',\n preventOnFilter: true,\n onUpdate : this.onUpdate,\n onRemove : this.onRemove,\n onAdd : this.onAdd,\n\n // Chrome has a hover bug https://github.com/SortableJS/Sortable/issues/232\n onStart: this.onStart,\n onEnd : this.onEnd\n\n }\n };\n\n }", "function changeSort(e) {\n console.log(\"value changed\");\n createPage();\n}", "setOrderBy(order) {\n this.orderBy = order;\n }", "sendSortData()\n {\n this.props.sortStat(this.state.selectedSort,this.state.sortDirection,this.state.selectedUpgrade);\n }", "function sortChanged(){\n\tconst url2 = url+`&q=${name.val()}&t=${type.val()}&color=${color.val()}&s=${sort.val()}`;\n\tloadData(url2, displayData);\n}", "function changeSortDirection(clickedSortButton, direction) {\n document.querySelectorAll(\".sort-dropdown button\").forEach((knap) => {\n knap.dataset.sortDirection = \"asc\";\n });\n\n document.querySelector(\".sort-heading p\").textContent = \"\";\n\n if (currentSort === \"firstName\") {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: First Name`;\n } else if (currentSort === \"lastName\") {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: Last Name`;\n } else if (currentSort === \"isMemberOfInqSquad\") {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: Inquisitorial`;\n } else if (currentSort === \"isPrefect\") {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: Prefects`;\n } else {\n document.querySelector(\".sort-heading p\").textContent = `Sort by: ${currentSort}`;\n }\n\n if (direction === \"asc\") {\n clickedSortButton.dataset.sortDirection = \"desc\";\n document.querySelector(\".sort-heading i\").classList = \"arrow up\";\n } else {\n clickedSortButton.dataset.sortDirection = \"asc\";\n document.querySelector(\".sort-heading i\").classList = \"arrow down\";\n }\n}", "get isSorting() {\r\n return this.i.cf;\r\n }", "handleSort(e) {\n let sortName = e.currentTarget.dataset.name;\n console.log(sortName);\n this.setState({\n sortOrder: (this.state.sortBy === sortName) ?\n ((this.state.sortOrder === \"descending\") ? \"ascending\" : \"descending\") : \"ascending\",\n sortBy: sortName\n }, () => {\n this.getSortData(this.state.processedData);\n });\n }", "changeIsAscending() {\n this.setState({\n isAscending: !this.state.isAscending\n })\n }", "function onSort() {\n\tvar items = {};\n\titems[ this.options.sortIdKey ] = this.sorTable.sortId;\n\titems[ this.options.sortAscKey ] = this.sorTable.sortAsc;\n\tchrome.storage.local.set( items );\n}", "function findSort(){\n if(!started){\n startSort();\n }\n\n if(done)\n return;\n\n randomizeButton.disabled = true;\n\n let decision = sortSelector.value;\n switch(decision){\n case \"Selection\":\n selectionSort();\n break;\n case \"Quick\":\n quicksort();\n break;\n case \"Bubble\":\n bubblesort();\n break;\n case \"Insertion\":\n insertionSort();\n break;\n case \"Merge\":\n mergeSort();\n break;\n case \"Heap\":\n heapSort();\n break;\n case \"Bogo\":\n bogoSort();\n break;\n }\n\n \n}", "sortData(type) {\n\n // CREATE A NEW ARRAY FROM STATE\n let array = this.state.masterData\n\n // CALL HELPER METHOD TO SORT ARRAY\n let sortedArray = SortHelper(this.state.descending, type, array)\n\n // SET SORT TYPE, USED IN SORTORDER FUNCTION\n this.setState({sortType: type})\n\n // RETURN SET STATE WITH A CALL BACK TO TRIGGER DATA MAP\n return this.setState({sortedData: sortedArray})\n\n }", "function resort(){\n if(scope.sorting && scope.sorting.obj){\n var sortKey = scope.sorting.obj.field;\n sorter(sortKey,scope.sorting.direction);\n }\n }", "function resort(){\n if(scope.sorting && scope.sorting.obj){\n var sortKey = scope.sorting.obj.field;\n sorter(sortKey,scope.sorting.direction);\n }\n }", "updateSortBy(event) {\n const data = Object.assign({}, this.state)\n //because you are changing the selection of jobs, makes sense that you restarting from page 1\n const activePage = 1;\n data['activePage'] = activePage\n data[event.target.name] = event.target.value\n this.setState({\n sortBy: data \n })\n this.loadNewData(data); \n }", "onSortChange(sortName, sortOrder) {\r\n this.setState({ toggleUpdate: !this.state.toggleUpdate });\r\n $('.dynamicsparkline').sparkline('html');\r\n }", "_sortFilters() {\n this.$filterSelects.each(function() {\n const $select = $(this);\n const $toSort = $select.find('option');\n const sortingFunction = sortingFunctions[$select.data('filters-type')];\n\n if (sortingFunction) {\n $toSort.sort((a, b) => {\n return sortingFunction($(a).val(), $(b).val());\n });\n }\n });\n }", "Sort() {\n\n }", "function sortAlt(sfield)\n {\n document.designateDEForm.sortColumn.value = sfield;\n submitDesignate(\"sortAlt\");\n }", "function _fakeSort() {\n var resultsEls = $( '.all-results .search-result-full' ).get();\n var sortOn = this.attributes[\"sort-trigger\"].value;\n\n // toggle the classes\n $( '.search-results-order .selected' ).removeClass('selected');\n $( this ).addClass('selected');\n\n // change our parent sort val\n $( '.search-step-3' ).attr('sort', sortOn);\n\n $( resultsEls.reverse() ).each(function() {\n $(this).detach().appendTo('.all-results');\n });\n }", "setSortByName() {\n this.setSort(SortbyContainer.SORT_BY_NAME);\n }" ]
[ "0.73853576", "0.72529536", "0.7155989", "0.7048791", "0.7037462", "0.700547", "0.7001464", "0.69612354", "0.69599247", "0.6922674", "0.69113153", "0.68882793", "0.68489474", "0.6830895", "0.6820062", "0.67407084", "0.6676105", "0.66645443", "0.6663364", "0.6654602", "0.6618105", "0.65897036", "0.6575971", "0.653625", "0.6519676", "0.6480564", "0.6478133", "0.6469135", "0.6453803", "0.64245284", "0.63954204", "0.6393988", "0.63911635", "0.6386958", "0.63585085", "0.6355496", "0.6344755", "0.6344755", "0.63428473", "0.6339815", "0.63384724", "0.6330463", "0.63191116", "0.63191116", "0.6308533", "0.62945145", "0.62812287", "0.626167", "0.62604266", "0.62558776", "0.62558776", "0.62558776", "0.6245918", "0.6240016", "0.6201044", "0.62005055", "0.61940837", "0.61897856", "0.6172045", "0.6172045", "0.6170801", "0.61621183", "0.6143318", "0.6130735", "0.6117406", "0.6100546", "0.6095639", "0.6089363", "0.60843134", "0.60838777", "0.6081087", "0.6075948", "0.60739756", "0.60557866", "0.60520697", "0.60387725", "0.60362995", "0.6022518", "0.60201365", "0.60054123", "0.60001653", "0.59978217", "0.5990648", "0.5985105", "0.59808636", "0.5971585", "0.596699", "0.59665126", "0.59659857", "0.59463274", "0.59446603", "0.59446603", "0.59445655", "0.59434533", "0.59367496", "0.5918712", "0.5906949", "0.5890084", "0.58801645" ]
0.69886655
8
Add two methods to handle changes in two input elements, Terms and Location
handleTermChange(event){ this.setState({term: event.target.value}); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onInputChangeTerms(terms_search) {\n console.log(\"onInputChangeTerms: \" + terms_search);\n let filters = this.props.filters;\n filters.terms_search = terms_search;\n filters.do_terms_search = true;\n this.props.setFilter( filters );\n }", "function termsGetDefinition()\r\n{\r\n terms = document.getElementsByClassName(\"simp-text-term\");\r\n\r\n for (var t = 0, len = terms.length; t < len; t++) {\r\n terms[t].setAttribute(\"id\", \"st\"+t);\r\n }\r\n\r\n for (var t = 0, len = terms.length; t < len; t++) {\r\n termToChange = document.getElementById(terms[t].id);\r\n changeTooltip(termToChange);\r\n }\r\n}", "function update() {\n var q = input.value\n var l = lang.value\n\n // clean main\n while(main.firstChild) { main.removeChild(main.firstChild); }\n\n // if we look for terms related to one we know\n if (q.startsWith('related:') && data[defaultLang].hasOwnProperty(q.substring(8).trim())) {\n var related = data[defaultLang][q.substring(8).trim()].related\n for (var id in data[defaultLang]) {\n if (related.indexOf(id) !== -1) {\n insert(id, l)\n }\n }\n } else { // standard search\n for (var id in data[defaultLang]) {\n if (match(q, l, id)) {\n insert(id, l)\n }\n }\n }\n\n activateRelated()\n}", "function elementSelectedLocation(){\r\n\tvar choice = document.form.location1.value;\r\n\tif(choice == \"Any\"){\r\n\t\tlocation1 = \"<Var>Location</Var>\" + \"\\n \";\r\n\t\tenglishLocation = \"any location\";\r\n\t}\r\n\telse {\r\n\t\tlocation1 = \"<Ind>\" + choice + \"</Ind>\" + \"\\n \";\r\n\t\tenglishLocation = choice;\r\n\t}\r\n\tcreateRuleML();\r\n}", "function onChangeTax1()\n{\n\tvar value = $(\"#taxType1\").val();\n\t// Set variables in completer objects for taxName1 and taxName2\n\t$(\"#taxName1\").data(\"ui-autocomplete\").options.params.type = value;\n\t$(\"#taxName2\").data(\"ui-autocomplete\").options.params.parType = value;\n\t// Reset taxName1 value\n\t$(\"#taxName1\").val(\"\");\n\t// Adjust visibility of fields according to selected type\n\tif (value === -1) { // no selection\n\t\t$(\"#tax2\").hide();\n\t\t$(\"#tax3\").hide();\n\t\t$(\"#taxName1\").prop(\"disabled\",true);\n\t\t$(\"#taxName2\").val(\"\");\n\t\t$(\"#taxName2\").prop(\"disabled\",true);\n\t\t$(\"#taxName3\").val(\"\");\n\t\t$(\"#taxName3\").prop(\"disabled\",true);\n\t}\n\telse if (value === 0) { // Species\n\t\t$(\"#tax2\").hide();\n\t\t$(\"#tax3\").hide();\n\t\t$(\"#taxName1\").prop(\"disabled\",false);\n\t\t$(\"#taxName2\").prop(\"disabled\",true);\n\t\t$(\"#taxName3\").val(\"\");\n\t\t$(\"#taxName3\").prop(\"disabled\",true);\n\t}\n\telse {\n\t\t$(\"#tax2\").show();\n\t\t$(\"#taxName1\").prop(\"disabled\",false);\n\t\tsetOptions($(\"#taxType1\"),$(\"#taxType2\"),value);\n\t}\n}", "function form_postSourcing(type, name)\n{\n if (name == 'entity') { // Client field has changed\n hasClientAgreedToTerms();\n }\n}", "function onChangeTax2()\n{\n\tvar value = $(\"#taxType2\").val();\n\t// Set variables in completer objects for taxName2 and taxName3\n\t$(\"#taxName2\").data(\"ui-autocomplete\").options.params.type = value;\n\t$(\"#taxName3\").data(\"ui-autocomplete\").options.params.parType = value;\n\t// Reset value in taxName2\n\t$(\"#taxName2\").val(\"\");\n\t// Set visibility of taxName3 according to selection\n\tif (value === \"-1\") { // no selection\n\t\t$(\"#tax3\").hide();\n\t\t$(\"#taxName2\").prop(\"disabled\",true);\n\t}\n\telse if (value === \"0\") { // Species\n\t\t$(\"#tax3\").hide();\n\t\t$(\"#taxName2\").prop(\"disabled\",false);\n\t}\n\telse {\n\t\t$(\"#tax3\").show();\n\t\t$(\"#taxName2\").prop(\"disabled\",false);\n\t\tsetOptions($(\"#taxType2\"),$(\"#taxType3\"),value);\n\t}\n}", "handleAddTerm() {\n const {\n terms,\n newTerm,\n newModder,\n } = this.state;\n\n if (newTerm && newModder) {\n terms.push([newTerm, newModder]);\n this.setState({\n terms,\n newTerm: '',\n newModder: '',\n });\n }\n }", "handleTerm(event){\r\n let wantedValue = event.target.value;\r\n this.handleTermChange(wantedValue);\r\n}", "function setTerms(terms) {\n $(\"#results ul.type li.result.default\").each(function () {\n $(this).data({\"terms\" : terms });\n $(this).find(\"span.terms\").html(highlight(terms, terms));\n });\n}", "onInputChange(term) { //\"on/handle\" + \"tagName\" + \"Change\"\n this.setState({term});\n this.props.onSearchTermChange(term);\n }", "onInputChange(term) {\n let results = this.parseString(term)\n this.setState({term});\n this.props.onSearchTermChange(results[1],results[0]);\n }", "function checkTerms(event) {\n if (!elTerm.checked) {\n elTermHint.innerHTML = 'You must agree to the terms.';\n event.preventDefault();\n }\n}", "onPlaceChanged() {\n let place = this.autocomplete.getPlace();\n\n if (!place.geometry) {\n // User entered the name of a Place that was not suggested and\n // pressed the Enter key, or the Place Details request failed.\n this.$emit('no-results-found', place, this.id);\n return;\n }\n\n if (place.address_components !== undefined) {\n // return returnData object and PlaceResult object\n this.$emit('placechanged', this.formatResult(place), place, this.id);\n\n // update autocompleteText then emit change event\n this.autocompleteText = document.getElementById(this.id).value\n this.onChange()\n }\n }", "function validateInput(ont_id,ont_term_list,table_id,new_data,export_data)\n{\n //if no data is input produce an alert\n if (ont_term_list.length==0){\n alert(\"Paste some data in the input box!\");\n return;\n }\n \n //get the list of ontologies using the ontology id\n ontologies=document.getElementById(ont_id)\n \n //get only the selected ontologies and convert to PL/SQL formatted text\n selected_ont=get_selected(ontologies)\n \n //if no ontology is selected produce an alert\n if (selected_ont==''){\n alert(\"Select at least one Ontology!\")\n return;\n }\n\n //take the pasted terms from user and convert those terms to an array\n ont_term_array=convert_terms_to_array(ont_term_list);\n \n //save this original list of terms from the user into an array\n original_ont_term_array=ont_term_array;\n \n //create an array to store the terms from the input boxes as they are being\n //modified\n updated_unique_terms=new Array();\n \n //if this is the first call to this function, create a unique list of terms\n //build the input boxes\n if (new_data == 'True')\n {\n //original_ont_term_array=new Array();\n original_unique_terms=new Array();\n \n //remove old input boxes, so the user can re-use the app over and over\n clear_inputs(table_id)\n \n //generate unique list and input boxes \n unique_ont_array=write_input_boxes(ont_term_array,table_id);\n \n //store unique ontology terms for later use\n original_unique_terms=unique_ont_array;\n updated_unique_terms=unique_ont_array;\n }\n //If this is not the first call, retrieve values from input boxes\n else\n {\n //get the values from the input boxes\n unique_ont_array=get_inputs(unique_ont_array);\n updated_unique_terms=unique_ont_array;\n }\n \n //check if browser can perform xmlhttp\n xmlhttp=GetXmlHttpObject()\n if (xmlhttp==null){\n alert (\"Your browser does not support XML HTTP Request\");\n return;\n }\n /*\n var url=\"ontology_validate.psp\";\n url=url+\"?ont_id=\"+selected_ont+\"&ont_terms=\"+unique_ont_array;\n url=url+\"&sid=\"+Math.random();\n xmlhttp.onreadystatechange=function()\n {\n if (xmlhttp.readyState==4)\n {\n //since the response from the PL/SQL is a string using the \"#' \n //delimitor, so we need to split and write them to the table\n validity=xmlhttp.responseText.split('#')\n for (var i=0; i<validity.length;i++){\n //determine if an input value is valid and write 'Invalid' or a \n //checkbox accordingly\n if (validity[i]=='Valid' || validity[i]=='Valid\\n'){\n document.getElementById('validtxtbox'+(i)).innerHTML='&#10003;';\n document.getElementById('validtxtbox'+(i)).style.color=\"green\"; \n }else if (validity[i]=='Invalid' || validity[i]=='Invalid\\n'){\n document.getElementById('validtxtbox'+(i)).innerHTML=validity[i];\n document.getElementById('validtxtbox'+(i)).style.color=\"red\";\n }\n }\n }\n }\n //perform a GET \n xmlhttp.open(\"GET\",url,true);\n xmlhttp.send(null)\n */\n //If the data is supposed to be exported, write the data to the new window\n if (export_data=='True'){\n write_data_to_new_window(original_ont_term_array,original_unique_terms,updated_unique_terms);\n }\n}", "termChanged({currentTarget: t }) { this.setState({term: t.value}) }", "onSuggestChange(event, o) {\n switch(o.method) {\n // this is necessary for the input to show each letter as its typed\n case 'type':\n this.setState({\n value: o.newValue\n });\n break;\n // one of the suggests was selected\n case 'click':\n let creatures = this.creatures;\n creatures.push({id: o.newValue.id, name: o.newValue.name});\n this.props.setModuleEditingPiece({creatures: creatures});\n // clear the input\n this.setState({\n value: ''\n });\n break;\n }\n }", "function linkGeoFormEvents() {\r\n\r\n $('geoOkButton').addEventListener('click', insertGeoFormOk, true);\r\n\r\n $('geoCancelButton').addEventListener('click', insertGeoFormCancel, true);\r\n\r\n $('insertGeoLocation').addEventListener('keyup', checkOkActivation, true);\r\n\r\n $('ShowRichEditor').addEventListener('mousedown', insertGeoFormCancel, true);\r\n\r\n $('htmlbar').addEventListener('mousedown', insertGeoFormCancel, true);\r\n\r\n}", "function onChangeGeo2()\n{\n\tvar value = $(\"#geoType2\").val();\n\t// Set completer variable for the corresponding name field\n\t$(\"#geoName2\").data(\"ui-autocomplete\").options.params.type = value;\n\t// Set completer variable for the name field in the next level\n\t$(\"#geoName3\").data(\"ui-autocomplete\").options.params.parType = value;\n\t$(\"#geoName2\").val(\"\");\n\tif (value === -1) { // no selection\n\t\t$(\"#geo3\").hide();\n\t\t$(\"#geoName2\").prop(\"disabled\",true);\n\t}\n\telse if (value === 0) { // layer\n\t\t$(\"#geo3\").hide();\n\t\t$(\"#geoName2\").prop(\"disabled\",false);\n\t}\n\telse { // all other\n\t\t$('#geo3').show();\n\t\t$(\"#geoName2\").prop(\"disabled\",false);\n\t\tsetOptions($(\"#geoType1\"),$(\"#geoType3\"),value);\n\t}\n}", "function updateValue() {\n const mainInput = document.getElementById('main-input');\n let mainOutput = document.getElementById('main-output');\n let finalKeywords = \"\";\n let keywordsArray = [];\n\n\n keywordsArray = mainInput.value.split('\\n');\n\n // Remove blank keywords\n\tlet lowerKeywordsArray = keywordsArray.filter(function (el) {\n return el != \"\";\n });\n\n lowerKeywordsArray.toLocaleString().toLowerCase().split(','); \n lowerKeywordsArray.forEach(textUpdater);\n \n function textUpdater(item) {\n if (broadCheckedValue === 1) {\n finalKeywords += item + \"\\n\";\n\n } if (modifiedCheckedValue === 1) {\n finalKeywords += item.replace(/(^|\\s+)/g, \"$1+\") + \"\\n\";\n\n } if (phraseCheckedValue === 1) {\n finalKeywords += '\"' + item + '\"' + \"\\n\";\n \n } if (exactCheckedValue === 1) {\n finalKeywords += '[' + item + ']' + \"\\n\";\n }\n \n let outputWords = finalKeywords.toString().toLowerCase();\n mainOutput.value = outputWords;\n }\n }", "termChanged(e) { this.setState({term: e.currentTarget.value}) }", "function locationChange(region)\n{\n \n let locationEle=document.getElementById('locationChange')\n let loc;\n locationEle.innerHTML=null;\n if(region==\"ncr\")\n {\n loc='National Capital Region (NCR)'\n locationEle.textContent='Movies In National Capital Region (NCR)'\n }\n else\n {\n loc=region\n locationEle.textContent=`Movies In ${region}`\n }\n let about=`<div>\n <article>\n <h4>Enjoy Online Ticket Booking for Movies in ${loc} With BookMyShow</h4>\n <p>If you are planning for <strong>movie ticket bookings</strong> for the latest movies in ${loc}, dont look any further. Now it is easy to get on with <strong>online ticket\n booking</strong> with BookMyShow. Your one-stop solution for movies to watch\n this weekend. Everyone enjoys watching their favorite movies on the big screen, and the excitement\n of watching it with friends is unparalleled. If you have been eagerly waiting for a movie that you\n can watch with your friends and family,\n now you know where to get the tickets from. When you watch a film ina cinema theatre, you get to\n watch it on a massive screen with surround-sound, and that enhances your movie-watching experience.\n Thus, allowing you to be a part\n of the actual movie. Get to know about <strong>all movies</strong> and <strong> trailers</strong> to\n watch here. Also, know <strong>how to book movie tickets.</strong></p>\n </article>\n <article>\n <h4>Latest Movies To Watch in ${loc} With Family And Friends</h4>\n <p>Each year the cinema worid is enlightened with the latest movie trailers, increasing the excitement\n among everyone. This year, just like the previous year, you have been waiting for some of the\n biggest <strong>Bollywood movies</strong> to be released\n with the biggest star cast. Enjoy your tavourite movie, not just with your friends, but in a cinema\n hall ${loc} that will be filled with like-minded people. Be a part of\n everyone's reaction. Dates are already announced,\n and all you need to do is book the tickets for the preferred date so that you dont end up missing\n the first-day first show! Dont worry we have the list of <strong> near you</strong> and\n <strong>movie showtimes</strong>.</p>\n </article>\n <article>\n <h4>Upcoming Hollywood Movies That You Can't Miss</h4>\n <p>Have you checked out the latest movie reviews of some of the best Hollywood movies ? If so, we bet\n you would want to watch them all in the nearest movie theatre! The Hollywood movies running in\n cinemas now are already making the\n audience want for more, and with the new releases happening in the coming months, we recommend\n booking the tickets now in ${loc}. Check out all the latest movie trailers\n here!</p>\n </article>\n <article>\n <h4>Exciting Tollywood Movies To Book Tickets For</h4>\n <p>Just like Bollywood and Hollywood movies, Tollywood seems to have a few good movie showtimes as well.\n You can plan for movies to watch this Friday with these Tollywood movies because the star cast is\n superb, and the storylines of\n these movies have already started making news. Don't miss any upcoming movies.</p>\n </article>\n <article>\n <h4>The Joy Of Movie Tickets Bookings with Just a Few Clicks</h4>\n <p>Grab on your popcorn because there are many movies to watch today in ${loc}.\n If you want to save some money, don't miss out on our movie offers and discounts. Check out the\n movies running in cinemas time,\n and call all your friends to enjoy the best movie-watching experience together. There are many big\n releases in the pipeline, and it is expected that these movies will have the perfect casting and\n direction. Get ready for upcoming movies in\n theatres.</p>\n </article>\n <article>\n <p>Dont wait anymore and book your movie tickets from BookMyShow today at the best price! Your access to\n your favourite movie in ${loc} is only a click away!</p>\n </article>\n <article id=\"privacy\">\n <h4>Privacy Note</h4>\n <p>By using www.bookmyshow.com(our website), you are Tuly accepting the Privacy Policy avalable at\n https://bookmyshow.com/privacy governing your access to Bookmyshow and provision of services by\n Bookmyshow to you. IT you do\n not accept terms mentioned in the Privacy Policy, you must not share any of your personal\n information and immediately exit Bookmyshow.</p>\n </article>\n</div>`\nlet aboutEle=document.getElementById('about')\naboutEle.innerHTML=about\n\n}", "function Terms(term, def) {\n\tthis.term = [term];\n\tthis.definition = def;\n}", "function toggleTerms() {\n\ttoggleAnalyserPanel('terms');\n}", "handleFormLocAutoComplete(searchText) {\r\n this.setState({location: searchText});\r\n this.handleLocationAutoComplete(searchText);\r\n this.handleLocationAutoCompleteSelect(searchText);\r\n }", "function handleTagSearch() {\n const newValues = document.getElementById('search_input').value\n setNewTagOption(newValues)\n console.log('newValues: ', newValues)\n }", "onChangeAddrB(newAddressInB)\n{\n // If the new value of B is EXACT SAME of the value of the suggestion then\n // it has a street or a full address EXACT as the suggestion has\n if (newAddressInB === this.state.addressInSuggestedB)\n {\n this.isFullAddressInB = this.isFullAddressInSuggestedB;\n this.isAtLeastStreetInB = this.isAtLeastStreetInSuggestedB;\n }\n else\n // If the new value of B EXACTLY starts with the one from the suggestion and IF\n // the suggestion contains at least street then we can be sure that B contains\n // at least streeat\n if (newAddressInB.startsWith(this.state.addressInSuggestedB) && this.isAtLeastStreetInSuggestedB)\n {\n this.isAtLeastStreetInB = true;\n }\n else\n // Same thing is above if B starts EXACTLY with the recent real string gotten from the server\n if (newAddressInB.startsWith(this.recentStreetNameInSuggestedB))\n {\n this.isAtLeastStreetInB = true;\n }\n else\n // Otherwise we don't believe that B contains anything meaningful like a street and a full\n // address\n {\n this.isFullAddressInB = false;\n this.isAtLeastStreetInB = false;\n }\n\n // Use entered space as a request for auto completion\n // Note: check if that's really entered space and not just space at the end of the\n // string because of the backspace usage :-)\n if (this.state.addressInB &&\n newAddressInB.length > this.state.addressInB.length &&\n newAddressInB.endsWith(' '))\n {\n this.autocompleteB();\n }\n\n // Synchronize put in text and the state\n this.setState(\n {\n addressInB: newAddressInB\n }\n )\n\n\n\n // If street name is already there then search for a house\n // Note: newAddressInB can contain not necessarily a bare sreet name it also\n // can contain something beyond - but that's OK - we want to autocomplete it to the house\n // Note: it will not change the B field - change only the suggestion\n if (this.isAtLeastStreetInB && this.isAtLeastStreetInSuggestedB)\n this.findHouse(newAddressInB);\n // If street name is not already there then search for a street\n else\n {\n fetch(\"http://185.241.194.113:1234/geo/find_street?s=\" + newAddressInB)\n .then(response => response.json())\n .then(responseJson => {\n // Found a street - save it the the suggestion (it's just a street, not a full address)\n this.setState(\n {\n addressInSuggestedB: responseJson[0][1],\n }\n )\n this.isAtLeastStreetInSuggestedB = true; // Street name is there\n this.isFullAddressInSuggestedB = false; // Full address is not (TODO: handle POI! They will always have a full address)\n this.recentStreetNameInSuggestedB = responseJson[0][1];\n })\n}\n}", "function updateInputTabs(el, caretPos, suggestions) {\n\tsuggestions = suggestions.split(\"\\n\");\n\tif (suggestions[0].trim() == '') suggestions.shift();\n\t\n\tif (!suggestions.length) {\n\t\tshowTipFor(el, caretPos, [\"No path matches found\"], true);\t// nothing matched, show error\n\t\tsetCaretPos(el, caretPos);\n\t} else if (suggestions.length == 1) {\n\t\tselectCompletionValue(el, caretPos, suggestions[0]);\t\t// only 1 thing matched, inject it at cursor\n\t} else {\n\t\tshowTipFor(el, caretPos, suggestions);\t\t\t\t\t\t// multiple things matched, allow clicking them to choose\n\t\tsetCaretPos(el, caretPos);\n\t}\n}", "function updateDescriptions() {\n\t\tvar inputs = document.getElementsByTagName('input');\n\t\tfor (var i = 0; i < inputs.length; i++) {\n\t\t\tvar input = inputs[i];\n\t\t\tif(input.type.toLowerCase() == 'text') {\n\t\t\t\tvar id = input.id;\n\t\t\t\tvar segment = getSegmentById(id);\n\t\t\t\tif (isNull(segment)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tsegment.description = input.value;\n\t\t\t}\n\t\t}\n\t}", "function onChangeGeo1()\n{\n\tvar value = $(\"#geoType1\").val();\n\t// Set the completer variable for the corresponding name field to the geo type value\n\t$(\"#geoName1\").data(\"ui-autocomplete\").options.params.type = value;\n\t// Set the completer variable 'parent type' for the name field in the next level to the geo type value\n\t$(\"#geoName2\").data(\"ui-autocomplete\").options.params.parType = value;\n\t$(\"#geoName1\").val(\"\");\n\t// Set visibility of fields according to selection\n\tif (value === \"-1\") { // no selection\n\t\t$(\"#geo2\").hide();\n\t\t$(\"#geo3\").hide();\n\t\t$(\"#geoName1\").prop(\"disabled\",true);\n\t\t$(\"#geoName2\").val(\"\");\n\t\t$(\"#geoName2\").prop(\"disabled\",true);\n\t\t$(\"#geoName3\").val(\"\");\n\t\t$(\"#geoName3\").prop(\"disabled\",true);\n\t}\n\telse if (value === \"0\") { // layer\n\t\t$(\"#geo2\").hide();\n\t\t$(\"#geo3\").hide();\n\t\t$(\"#geoName1\").prop(\"disabled\",false);\n\t\t$(\"#geoName2\").prop(\"disabled\",true);\n\t\t$(\"#geoName3\").val(\"\");\n\t\t$(\"#geoName3\").prop(\"disabled\",true);\n\t}\n\telse { // all other\n\t\t$(\"#geo2\").show();\n\t\t$(\"#geoName1\").prop(\"disabled\",false);\n\t\tsetOptions($(\"#geoType1\"),$(\"#geoType2\"),value);\n\t}\n}", "function onRegFieldUpdate(fieldEdited) {\n var fieldId = fieldEdited.id;\n var fieldContent = fieldEdited.text;\n switch (fieldId) {\n case \"regFirstNameInput\":\n //D007: Adding code to capitalize first character for fieldContent and fieldContent\n //volunteerRegObject.firstname = fieldContent;\n volunteerRegObject.firstName = fieldContent.charAt(0).toUpperCase() + fieldContent.slice(1);\n //End of D007\n break;\n case \"regLastNameInput\":\n //D007: Adding code to capitalize first character for fieldContent and fieldContent\n //volunteerRegObject.lastname = fieldContent;\n volunteerRegObject.lastName = fieldContent.charAt(0).toUpperCase() + fieldContent.slice(1);\n //End of D007\n break;\n case \"regUsernameInput\":\n volunteerRegObject.username = fieldContent;\n break;\n case \"regPasswordInput\":\n volunteerRegObject.password = fieldContent;\n break;\n case \"regReenterPasswordInput\":\n volunteerRegObject.reenteredPassword = fieldContent;\n break;\n case \"regWorkDetailsInput\":\n volunteerRegObject.workDetails = fieldContent;\n break;\n case \"regAboutMeInput\":\n volunteerRegObject.aboutMe = fieldContent;\n break;\n case \"regCompanyInput\":\n //Start of D012\n volunteerRegObject.companyName = fieldEdited.selectedKey;\n if (volunteerRegObject.companyName === \"Select\" || volunteerRegObject.companyName === null || volunteerRegObject.companyName === \"\") {\n volunteerRegObject.companyName = \"\";\n }\n //End of D012\n break;\n case \"regRoleInput\":\n volunteerRegObject.role = fieldContent;\n break;\n case \"regBusinessUnitInput\":\n volunteerRegObject.businessUnit = fieldContent;\n break;\n case \"regStateInput\":\n volunteerRegObject.state = fieldEdited.selectedKey;\n if (volunteerRegObject.state === \"Select\" || volunteerRegObject.state === null || volunteerRegObject.state === \"\") {\n volunteerRegObject.state = \"\";\n }\n break;\n case \"regAddressInput\":\n volunteerRegObject.address = fieldContent;\n break;\n case \"regCityInput\":\n volunteerRegObject.city = fieldContent;\n break;\n case \"regContactNumberInput\":\n volunteerRegObject.contactNumber = fieldContent;\n break;\n case \"regEmailAddressInput\":\n volunteerRegObject.emailAddress = fieldContent;\n break;\n default:\n break;\n }\n}", "function teeee(entry,type) {\n //document.getElementById(\"CompleteSym\").innerHTML = entry.innerText;\n if (type > 0) {\n searchLocus.value = entry.innerText;\n getParalog();\n } else if (type == 0) {\n searchSym.value = entry.innerText;\n getParalog(1);\n }\n}", "onClickHandlerTerms(id, type, name, event=null) {\n event ? event.preventDefault() : null;\n console.log(\"FilterMain: onClickHandlerSearch: type: \" + type + \" name: \" + name);\n let filters = this.props.filters;\n filters.terms_search = name;\n switch(type) {\n case \"RESOURCE\":\n filters.resource_filter = id ;\n break;\n case \"GROUP\":\n filters.group_filter = id;\n break;\n case \"UNIT\":\n filters.unit_filter = id;\n break;\n default:\n }\n filters.do_time_search = true;\n filters.next_day_search = 0;\n filters.previous_day = null;\n this.props.setFilter( filters );\n }", "function onLeaveTax1()\n{\n\tvar value = $(\"#taxName1\").val();\n\t// Set parentValue parameter in completer for taxName2\n\t$(\"#taxName2\").data(\"ui-autocomplete\").options.params.parValue = value;\n}", "function updateOffsetConditions(index, elt){\n var bucket = []; \n var i =0;\n $(this).children().each(function(){bucket[i]=this.value; i++;});\n if (!(bucket instanceof Array)) {\n bucket = [bucket];\n }\n currentQA = $('[name$=\"type-interaction\"]:checked:[value=\"question-answer\"],[name$=\"type-interaction\"]:checked:[value=\"question-answer-keyword\"]').parent().parent();\n //Adding present interaction if not already there\n for (var i=0; i<currentQA.length; i++) {\n var interactionId = $(currentQA[i]).children('[name$=\"interaction-id\"]').val();\n bucket.splice(bucket.indexOf(interactionId), 1);\n if ($(this).children(\"[value='\"+interactionId+\"']\").length==0)\n $(this).append(\"<option class='ui-dform-option' value='\"+\n interactionId+\"'>\"+\n $(currentQA[i]).find('[name$=\"content\"]').val()+\"</option>\")\n else\n $(this).children(\"[value='\"+interactionId+\"']\").text($(currentQA[i]).find('[name$=\"content\"]').val());\n } \n //Removing deleted interactions\n for (var i=0; i<bucket.length; i++) {\n //Do not delete the default choice\n if (bucket[i]==0) {\n continue\n }\n $(this).children(\"[value='\"+bucket[i]+\"']\").remove();\n defaultOptions = window.app['offset-condition-interaction-idOptions']\n defaultOptions.splice(defaultOptions.indexOf(bucket[i]),1);\n }\n}", "function setFinishSearchHandler(){\n\tvar selectBar2 = document.getElementById(\"triType\");\n\tvar button = document.getElementById(\"finish-search\");\n\tbutton.onclick = function(){\n\t\tif (_checkedTerms.length == 0){\n\t\t\treturn;\n\t\t}\n\t\tshowLoader()\n\t\t$(\"#results\").hide();\n\t\n\t\tvar checkedString = \"Your Intermediary Terms: \";\n\t\tvar csvName = \"\";\n\t\tfor (var i=0; i< _checkedTerms.length; i++){\n\t\t\tcheckedString += _checkedTerms[i] + \", \";\n\t\t\tcsvName += \"_\" + _checkedTerms[i];\n\t\t}\n\t\tcheckedString += \"<br>Your Final Term Type: \" + selectBar2.value;\n\t\t$(\"#selections\").html(checkedString);\n\t\tgetFinalTerms(_checkedTerms, selectBar2.value, csvName);\n\t};\n}", "function editSearchTerm(e){\r\n setSearch(e.target.value);\r\n }", "function updateInputs() {\r\n Inputang.setAttribute('value', Inputang.value);\r\n Inputvel.setAttribute('value', Inputvel.value);\r\n }", "function triangleSearch(){\n\tif (input.value == \"\") return;\n\t\t\n\t$(displayText).text(\"\");\n\t$(\"#selections\").text(\"\");\n\t$(\"#results\").hide();\n\t$(\"#show-subterms\").hide();\n\tshowLoader();\n\t$(\"#path-subresults\").hide();\n\n\tvar termA = termBank.getSynonym(input.value);\n\tvar type = selectBar.value;\n\t\n\t_withSubterms = subtermsCheckbox.checked;\n\tif(_withSubterms){\n\t\tqueryNeo4j(getMentionsWithSubtermsPayload(termA, type), triangleSearchOnSuccess);\n\t}else{\n\t\tqueryNeo4j(getMentionsPayload(termA, type), triangleSearchOnSuccess);\n\t}\t\n}", "handleTermChange(event) {\n this.setState({ term: event.target.value });\n }", "function enterButtonClicked()\n{\n\tvar madlibInputs = document.getElementsByClassName(\"madlib-input\");\n\tvar entryLex = new RiLexicon();\n\tvar entryWord, entryWordPOS;\n\n\tconsole.log(madlibInputs.length);\n\n\t//check for empty cases; if all are filled, show madlib results\n\tfor(var i = 0; i < madlibInputs.length; i++)\n\t{\n\n\t\tconsole.log(madlibInputs[i].value);\n\n\t\tentryWord = new RiString(madlibInputs[i].value);\n\n\t\tfor(var p = 0; p < ptMadlibs.length; p++)\n\t\t{\n\t\t\tconsole.log('checking POS equiv');\n\t\t\tif (entryWord.get('pos') === ptMadlibs[p][0])\n\t\t\t{\n\t\t\t\tentryWordPOS = ptMadlibs[p][1];\n\t\t\t}\n\t\t}\n\n\t\tconsole.log(entryWordPOS);\n\n\t\t//check for blank case\n\t\tif (madlibInputs[i].value === \"\") \n\t\t{\n\n\t\t\talert(\"Please enter a word into each box please!\");\n\t\t\tarrWordsEntered = [];\n\t\t\tbreak;\n\n\t\t}\n\n\t\t//check for wrong POS case\n\t\telse if (entryWordPOS !== arrPOSReplaced[i])\n\t\t{\n\t\t\tconsole.log('word POS: ' + entryWord.get('pos') + ' POS of word replaced: ' + arrPOSReplaced[i]);\n\t\t\talert(\"The part of speech for Box \" + (i+1) + \" doesn't quite match. Enter another word please.\");\n\t\t\tarrWordsEntered = [];\n\t\t\tbreak;\n\n\t\t}\n\n\t\t//add entered word to storage array\n\t\telse\n\t\t{\n\t\t\tarrWordsEntered.push(madlibInputs[i].value);\n\t\t}\n\n\t} //end for loop\n\n\t// verify that arrWordsEntered isn't empty and move to building the new passage\n\n\tif(arrWordsEntered.length > 0)\n\t{\n\t\tcreateModifiedPassage();\n\n\t\tchangeTheDOM();\n\t}\n\n}", "updateTags() {\n // Clear previous tags\n let parent = document.getElementById('tag-container');\n this.clearChildNodes(parent);\n\n let {area, comparisonAreas} = this.selected;\n\n // Create tag for focused country\n this.createTag(area.country, true);\n\n // Create tag for each comparison area\n for (let i = 0; i < comparisonAreas.length; i++) {\n this.createTag(comparisonAreas[i], false);\n }\n }", "function doneTyping (event) {\n\t\t\t\treo_update_properties( r , $(event.target).siblings().html() , $(event.target).val() );\n\t\t\t\tconsole.log( $(event.target).siblings().html() );\n\t\t\t}", "function addSuggestionToArray(ev) {\n\n var newSuggestion = inputElement.value;\n\n if(newSuggestion !== '' || newSuggestion !== undefined) {\n\n var isExisting = suggestionIsExisting(newSuggestion);\n\n var isUndefinedText = false;\n if(newSuggestion === 'undefined' || newSuggestion === ''){\n isUndefinedText = true;\n }\n\n\n if(!isExisting && !isUndefinedText){\n initialSuggestions.push(newSuggestion);\n\n traverseSuggestionsArray();\n\n inputElement.value = '';\n }\n\n } else{\n //do nothing\n }\n\n hideAllLiElements();\n inputElement.value = '';\n //console.toLocaleString(newSuggestion);\n }", "handleTermChange(value){\r\n this.setState({term: value});\r\n}", "onInputChange(term) {\r\n //set the value of the bar to what we type\r\n this.setState({term});\r\n //send onsearch our current term state\r\n this.props.onSearchTermChange(term);\r\n }", "function bindTextBoxesToMap(originTextBox, destinationTextBox) \n{\n // Route preview changes whenever the user finished editing the\n // seat pickup and dropoff textboxes\n $(originTextBox).change(previewRoute);\n $(destinationTextBox).change(previewRoute);\n}", "_changeSecondarySkills(evt) {\n var newState = this._mergeWithCurrentState({\n secondarySkills: evt.target.value\n });\n\n this._emitChange(newState);\n}", "function write_data_to_new_window(original_ont_term_array, original_unique_terms, updated_unique_terms){\n\n //Determine that all terms are valid\n for (var i=0;i<original_unique_terms.length;i++){\n if (original_unique_terms[i]!=''){\n validity=document.getElementById('validtxtbox'+(i)).innerHTML\n if ( validity=='' || validity=='Click Input Box...'){\n alert('You need choose valid terms!');\n return;\n }else if (validity=='Invalid' || validity=='Invalid\\n'){\n alert('You have invalid terms!');\n return;\n }\n }\n }\n \n //generate a new array with update terms based on the valid input boxes\n output_array=new Array();\n //using length-1 since we appended an empty element to the list in the\n //convert_terms_to_array function.\n for (var j=0;j<original_ont_term_array.length-1;j++){\n for (var k=0;k<original_unique_terms.length;k++){\n if (original_ont_term_array[j]==original_unique_terms[k]){\n output_array.push(updated_unique_terms[k]);\n }\n }\n if(original_ont_term_array[j]=='' && j!=0){\n output_array.push(output_array[j-1]);\n }else if(original_ont_term_array[j]=='' && j==0){\n output_array.push('n/a');\n }\n }\n \n //write the array to the new window\n writeConsole(output_array.join('<br>'));\n}", "function checkInput(subject, type) {\n var correct = true;\n var selected;\n var input;\n var citedData = {};\n \n if (subject == \"document\") {\n\n if ($('#selectedTextArea').attr('class') == 'hide') {\n // nessuna selezione di testo\n input = $('#docInput').val();\n selected = false;\n\n if (input == \"\") {\n Materialize.toast(\"insert something\", 2000);\n return false;\n }\n } else {\n // testo selezionato\n input = $('#selectedText').html();\n selected = true;\n }\n\n switch (type) {\n case \"hasAuthor\":\n correct = checkAuthor(input)\n break\n case \"hasPublicationYear\":\n correct = checkYear(input);\n break;\n case \"hasTitle\":\n correct = true;\n break;\n case \"hasURL\":\n correct = checkURL(input);\n break;\n case \"hasDOI\":\n correct = checkDOI(input);\n break;\n\n }\n } else if (subject == \"fragment\") {\n if ($('#selectedTextArea').attr('class') == 'hide')\n return false;\n else\n selected = true;\n\n switch (type) {\n case \"hasComment\": {\n input = $('#inputComment').val();\n correct = checkComment(input);\n break;\n }\n case \"denotesRhetoric\": {\n input = $('input[name=\"rhetoricalChoice\"]:checked').val()\n correct = checkRhetorical(input);\n break;\n }\n case \"cites\": {\n citedData.author = parseInput($(\"#inputCitedAuthor\").val());\n citedData.year = $(\"#inputCitedYear\").val();\n citedData.title = parseInput($(\"#inputCitedTitle\").val()); \n citedData.DOI = $(\"#inputCitedDOI\").val();\n \n input = citedData.URL = parseInput($(\"#inputCitedURL\").val());\n\n \n correct = checkCitation(citedData);\n\n break;\n }\n }\n }\n if (correct == true)\n saveAnnotation(subject, type, selected, parseInput(input), citedData);\n}", "function OAndOuKarModification(field, CH1, CH2)\r\n{\r\n\tif (document.selection) \r\n\t{\r\n\t\tfield.focus();\r\n\t\tsel = document.selection.createRange();\r\n\t\tif (field.value.length >= 1)\r\n\t\t\tsel.moveStart('character', -1); \r\n\t\tif(sel.text.charAt(0) == 'ে')\r\n\t\t\tsel.text = CH1;\r\n\t\telse\r\n\t\t\tsel.text = sel.text.charAt(0) + CH2;\r\n\t\tsel.collapse(true);\r\n\t\tsel.select();\r\n\t}\r\n\telse if (field.selectionStart || field.selectionStart == 0)\r\n\t{\r\n\t\tvar startPos = field.selectionStart-1;\r\n\t\tvar endPos = field.selectionEnd;\r\n\t\tvar scrollTop = field.scrollTop;\r\n\t\tvar CH;\r\n\t\tstartPos = (startPos == -1 ? field.value.length : startPos );\r\n\t\tif(field.value.substring(startPos, startPos+1) == \"ে\")\r\n\t\t\tCH = CH1;\r\n\t\telse\r\n\t\t{\r\n\t\t\tstartPos=startPos+1;\r\n\t\t\tCH = CH2;\r\n\t\t}\r\n\t\tfield.value = field.value.substring(0, startPos)\r\n\t\t\t+ CH\r\n\t\t\t+ field.value.substring(endPos, field.value.length);\r\n\t\tfield.focus();\r\n\t\tfield.selectionStart = startPos + CH.length;\r\n\t\tfield.selectionEnd = startPos + CH.length;\r\n\t\tfield.scrollTop = scrollTop;\r\n\t}\r\n\r\n}", "onInputChange(term){\n\t\tthis.setState( {term} );\n\t\tthis.props.onSearchTermChange(term);\n\t}", "function setup_word_info() {\n $(\"#output_table\").change(function() {\n is_word_info_as_table=true;\n display_word_info_as_table()\n });\n\n $(\"#output_histogram\").change(function() {\n is_word_info_as_table=false;\n display_word_info_as_histogram()\n });\n}", "updateSearch() {\n let searchTerms = [this.state.menus[0].active, this.state.menus[1].active];\n this.setState({\n searchTerms: searchTerms\n })\n }", "function handleEditTermFormSubmission(event) {\n event.preventDefault();\n props.onEditTerm();\n const propertiesToUpdate = {\n name: event.target.name.value,\n body: event.target.body.value\n }\n return firestore.update({ collection: 'terms', doc: term.id}, propertiesToUpdate);\n }", "setValues(searchTerms, operator) {\n if (searchTerms) {\n let sliderValues = [];\n // get the slider values, if it's a string with the \"..\", we'll do the split else we'll use the array of search terms\n if (typeof searchTerms === 'string' || (Array.isArray(searchTerms) && typeof searchTerms[0] === 'string') && searchTerms[0].indexOf('..') > 0) {\n sliderValues = (typeof searchTerms === 'string') ? [searchTerms] : searchTerms[0].split('..');\n }\n else if (Array.isArray(searchTerms)) {\n sliderValues = searchTerms;\n }\n if (Array.isArray(sliderValues) && sliderValues.length === 2) {\n this.$filterElm.slider('values', sliderValues);\n if (!this.filterParams.hideSliderNumbers) {\n this.renderSliderValues(sliderValues[0], sliderValues[1]);\n }\n }\n }\n // set the operator when defined\n this.operator = operator || this.defaultOperator;\n }", "setValues(searchTerms, operator) {\n if (searchTerms) {\n let sliderValues = [];\n // get the slider values, if it's a string with the \"..\", we'll do the split else we'll use the array of search terms\n if (typeof searchTerms === 'string' || (Array.isArray(searchTerms) && typeof searchTerms[0] === 'string') && searchTerms[0].indexOf('..') > 0) {\n sliderValues = (typeof searchTerms === 'string') ? [searchTerms] : searchTerms[0].split('..');\n }\n else if (Array.isArray(searchTerms)) {\n sliderValues = searchTerms;\n }\n if (Array.isArray(sliderValues) && sliderValues.length === 2) {\n this.$filterElm.slider('values', sliderValues);\n if (!this.filterParams.hideSliderNumbers) {\n this.renderSliderValues(sliderValues[0], sliderValues[1]);\n }\n }\n }\n // set the operator when defined\n this.operator = operator || this.defaultOperator;\n }", "function typeSelectorChanged()\r\n{\r\n var type = document.getElementsByClassName(name_typeSelector)[0].value;\r\n \r\n \r\n // reset rating stars in the search box\r\n resetRatingStars(document.getElementsByClassName(name_ratingSelector)[0]);\r\n \r\n if (type == 'name') {\r\n showSearchBar();\r\n hideSuburbSelector();\r\n hideRatingSelector();\r\n \r\n } else if (type == 'suburb') {\r\n showSuburbSelector();\r\n hideRatingSelector();\r\n hideSearchBar();\r\n \r\n } else if (type == 'rating') {\r\n showRatingSelector();\r\n hideSuburbSelector();\r\n hideSearchBar();\r\n \r\n } else if (type == 'location') {\r\n showSearchBar();\r\n hideSuburbSelector();\r\n hideRatingSelector();\r\n getLocation();\r\n }\r\n}", "function editsuggest(element) {\n //attribute is on the input\n let editid = $(element).attr('data-editid');\n let editlistid = \"editlist\" + editid;\n let editlistselector = '#' + editlistid;\n //get the links\n console.log('did we change editbar?');\n //clear original datalist\n $(editlistselector).html(\"\");\n //get current search value\n let cursearch = $(element).val()\n //use \"badtitle' function from articlecreate file to check chars\"\n if (badtitle(cursearch) || cursearch.length > 50) {\n $('div#editing input.editAddLink').css(\"border\", \"solid 2px\");\n $('div#editing input.editAddLink').css('border-color', 'red');\n } else {\n $('div#editing input.editAddLink').css(\"border\", \"none\");\n $('div#editing input.editAddLink').css('border-color', 'white');\n search($(element), $(editlistselector)) ;\n }\n }", "function addTaxonParam() {\n //Get the text field value\n var txTaxon = document.getElementById('taxonId');\n var text = txTaxon.value;\n var txRange = document.getElementById('taxonTypeId');\n\tvar rangeId = parseInt(txRange.value)+1;\n //Validate special characters (' or \")\n if((text.match(\"\\\"\") == \"\\\"\") || (text.match(\"'\") == \"'\") || (text.match(\"<\") == \"<\") || (text.match(\"/\") == \"/\")){\n alert(invalidChar);\n return;\n }\n //Validate null values\n if(text==null||text==''){\n alert(specifyTaxonE);\n txTaxon.value = '';\n return\n }\n //Validate repeated values\n var aux_exist = document.getElementById(text);\n if(aux_exist!=null){\n alert(alreadyAddedE);\n txTaxon.value = '';\n return;\n }\n //Add the search criteria\n var taxonlist = document.getElementById('taxParameters');\n var newdiv = document.createElement('div');\n newdiv.setAttribute(\"id\",text+\"~\"+rangeId); //Taxon~range\n newdiv.innerHTML =\n \"<a class=\\\"criteria\\\" href=\\\"javascript:\\\" onclick=\\\"removeTaxonParamElement(\\'\"+text+\"~\"+rangeId+\"\\')\\\">\"+text+\"</a>\";\n taxonlist.appendChild(newdiv);\n txTaxon.value = '';\n}", "function assignValues(cityValue, latValue, lngValue) {\n city = cityValue;\n lat = latValue;\n lng = lngValue; \n document.getElementById(\"location-text\").value=city;\n}", "onInputChange(term) {\n\t\tthis.setState({term});\n\t\tthis.props.onSearchTermChange(term);\n\t}", "function onPlaceChanged(){\n\n\tvar place= autocomplete.getPlace();\n\n\t// var to get latitude and longitude of city to map using google maps API\n\tloc= new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng());\n\n\t// variable to store city,state and country for yelp matching\n\tcityName = place.formatted_address;\n\n\t//Empty previous list and markers\n\tplaceArray([]);\n\tmarker([]);\n\n\t// set heading based on place \n\t$('#heading').html(\"Restaurants around \" + place.name);\n\n\t// if place found zoom to place else ask user to enter a valid city\n\tif (place.geometry) {\n\t\tmap.panTo(place.geometry.location);\n\t\tif (screen.width < 600) {\n\t\t\tmap.setZoom(12);\n\t\t} else {\n \t\tmap.setZoom(15);\n \t}\n\n \t//hide citysearch input field\n\t\t$('.csearch').toggleClass(\"hidden\");\n\n\t\t//perform location search\n \tsearch();\n \t\n \tvar check = $('.menu').hasClass('closed');\n \tif (screen.width > 600 && check) {\n \t\ttoggleMenu();\n \t}\n\t} else {\n\t\talert(\"Enter a valid city\");\n\t\tgetCityInput();\n\t}\n}", "function searchUpdated(term) {\n setsearch(term);\n }", "function locationSelectedInInput(div, val) {\n var intValue = parseInt(val);\n if (!isNaN(intValue)) {\n // Change the location control requests the location's geometry to place on the map.\n $.getJSON(indiciaData.read.url + 'index.php/services/data/location?parent_id=' + val + '&orderby=name' +\n '&mode=json&view=detail&auth_token=' + indiciaData.read.auth_token + '&nonce=' + indiciaData.read.nonce + \"&callback=?\", function(data) {\n // Sort into numeric section order.\n data.sort(function(a, b) {\n var aCode = a.code.replace(/^S/g, '');\n var bCode = b.code.replace(/^S/g, '');\n return parseInt(aCode, 10) - parseInt(bCode, 10);\n });\n indiciaData.subsites = data;\n $('#subsites').val(JSON.stringify(data));\n indiciaData.mapdiv.removeAllFeatures(indiciaData.mapdiv.map.editLayer, 'section');\n $.each(data, function(idx, subsite) {\n var geomwkt = subsite.boundary_geom || data[0].centroid_geom;\n var parser = new OpenLayers.Format.WKT();\n var feature = parser.read(geomwkt);\n indiciaData.siteChanged = true;\n feature.attributes.type = 'section';\n if (indiciaData.mapdiv.indiciaProjection.projCode!==indiciaData.mapdiv.map.projection.projCode){\n geomwkt = feature.geometry.transform(div.indiciaProjection, indiciaData.mapdiv.map.projection).toString();\n }\n indiciaData.mapdiv.map.editLayer.addFeatures([feature]);\n });\n indiciaData.mapdiv.map.zoomToExtent(indiciaData.mapdiv.map.editLayer.getDataExtent());\n });\n }\n }", "static setCity(e) {\n e.preventDefault();\n city = locationInput.value;\n document.querySelector(\".location\").innerText = city;\n UI.updateUI();\n }", "onInputChange(term) {\n\t\t// It will take that search term (a string) and set the \n\t\t// component's state 'term' equal to the search term.\n\t\tthis.setState({ term: term });\n\n\t\t// On the second line of this method, we're running the method\n\t\t// 'onSearchTermChange' (which was passed in from index.js via\n\t\t// the props. Note that 'onSearchTermChange' is the throttled/\n\t\t// debounced version of the runSearch method in index.js.\n\t\t// We're passing in a value (a new search term) by grabbing\n\t\t// the state 'term', which is equal to the most recent search\n\t\t// term.\n\t\tthis.props.onSearchTermChange(this.state.term);\n\t}", "function elementChange(yourLs, element) {\n\tif (element.value.length > 0) {\n\t\t// Try to find element in waypoint list\n\t\tviaNr = element.parentNode.attributes['waypointnr'].value;\n\t\twait_image = jQuery(\".via_image\", element.parentNode);\n\t\tmessage_div = jQuery(\".via_message\", element.parentNode);\n\t\tyourLs.selectWaypoint(viaNr);\n\n\t\twait_image.css(\"visibility\", \"visible\");\n\t\t// Choose between Namefinder or Nominatim\n\t\t//Yours.NamefinderLookup( Yours.lookupMethod.nameToCoord, jQuery.trim(element.value), MyFirstWayPoint, map, myCallback);\n\t\tYours.NominatimLookup( Yours.lookupMethod.nameToCoord, jQuery.trim(element.value), yourLs.Selected, map, myCallback);\n\t}\n}", "function applyNeumeDataChanges(){\n var type = document.getElementById(\"type\").value;\n \n if(type && type != \"none\"){\n currentNeume.type = type;\n }\n \n document.getElementById(\"meiOutput\").value = createMEIOutput();\n document.getElementById(\"input\").innerHTML = neumeDataChangeForm();\n createSVGOutput();\n}", "function doSelectTerm() {\n var e = document.getElementById(\"inp1\");\n var selIndex = e.options[e.selectedIndex].value;\n Selected(selIndex, 'inp1');\n e = document.getElementById(\"inp6\");\n selIndex = e.options[e.selectedIndex].value;\n Selected(selIndex, 'inp6');\n}", "function validateTerms(fields, data, errors) {\n if (!data[\"accepte\"].checked) {\n errors.push(\"Vous devez être en accord avec les termes de la license.\");\n }\n}", "function updateValues(propertyInput,valueInput){\t\r\n\tremoveOptions(valueInput);\r\n\t\r\n\tswitch(propertyInput.value){\r\n\t\tcase \"Protection vs Elites\":\r\n\t\t\tvalueInputsOne(valueInput);\r\n\t\t\tbreak;\r\n\t\tcase \"Skill Haste\":\r\n\t\t\tvalueInputsTwo(valueInput);\r\n\t\t\tbreak;\r\n\t\tcase \"Pistol Damage\":\r\n\t\t\tvalueInputsThree(valueInput);\r\n\t\t\tbreak;\r\n\t\tcase \"Armor (additional)\":\r\n\t\t\tvalueInputsFour(valueInput);\r\n\t\t\tbreak;\r\n default:\r\n text = \"N/A\";\r\n\t}\t\r\n}", "onInputChange(event){\r\n this.setState({\r\n term: event.target.value\r\n });\r\n }", "function OnAccuracyVisit_Change( e , type )\r\n{\r\n Alloy.Globals.AeDESModeSectionEight[\"ACCURACY_VISIT\"] = e.id ;\r\n // If the selected item is not \"Other\" the OtherName will be set to empty\r\n if( e.id != 7 )\r\n {\r\n $.widgetAppTextFieldAeDESModeFormsSectionEightOther.set_text_value( \"\" ) ;\r\n Alloy.Globals.AeDESModeSectionEight[\"OTHER\"] = \"\" ;\r\n }\r\n}", "function placeChangedHandler() {\n var place = autocomplete.getPlace();\n if (!place.geometry) {\n // User entered the name of a Place that was not suggested and\n // pressed the Enter key, or the Place Details request failed.\n program.showMessage(\"\", \"Staðsetning finnst ekki, reyndu aftur\");\n } \n else {\n program.addAllInfo(place);\n }\n }", "function _reuseOldInput($step) {\n\t\t\tif($step.given_answer) {\n\t\t\t\tswitch($step.type) {\n\t\t\t\t\tcase 'single_choice':\n\t\t\t\t\t\t$(\".single-choice-button\").each(function(k) {\n\t\t\t\t\t\t\tif($step.given_answer == $(this).data('value')) {\n\t\t\t\t\t\t\t\t$(this).find('i').fadeIn(200);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'multiple_choice':\n\t\t\t\t\t\t$(\".fancy-checkbox\").each(function(k) {\n\t\t\t\t\t\t\tvar $button = $(this).find(\"button\");\n\t\t\t\t\t\t\tif($step.given_answer.indexOf($button.data('value')) != -1) {\n\t\t\t\t\t\t\t\tCheckboxBeautifier.selectButton($button);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'form':\n\t\t\t\t\t\t$(\"input\").each(function(index) {\n\t\t\t\t\t\t\tif($step.given_answer[index]) {\n\t\t\t\t\t\t\t\t$(this).val($step.given_answer[index]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'multiple_image_choice':\n\t\t\t\t\t\tvar $konut_choices = wizard.find('.multiple-image-choice');\n\t\t\t\t\t\t$konut_choices.each(function(index) {\n\t\t\t\t\t\t\tif($step.given_answer.indexOf($(this).data('slug')) != -1) {\n\t\t\t\t\t\t\t\tvar $temp = $(this);\n\t\t\t\t\t\t\t\t$temp.isAvailable = true;\n\t\t\t\t\t\t\t\t_selectElement('multiple_image_choice', $temp);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'textarea':\n\t\t\t\t\t\twizard.find(\"textarea\").val($step.given_answer);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function locationsTabModifications() {\n\t//Create a global variable for the XML, no need to read it million of times\n\txmlDoc = loadXML(\"../uploaded_files/HVD/requestLinkLogic.xml\");\n\t\n\t//console.log(\"function locationsTabModifications\");\n\n\t//Each DIV has it's own variables and listener, so no conflict should happen.\n\t$(\".EXLSublocation\").each(function() {\n\t\t//need to find which AVA is open to items table, in case users came from loc tab in brief results\n\t\tif ($(this).find(\".EXLLocationTable\").length > 0) {\t\t\t\n\t\t\t//Modify all the Items in this single Holding record\n\t\t\tmodifyItems();\t\n\t\t}\t\t\t\n\n\t\t//Put a listener on the Sublibrary DIV which contains the Request options to catch when it is populated, or more items are added\n\t\t$(this).on(\"DOMSubtreeModified propertychange\", handleDomChanges);\n\t});\n\n\t\n\t//If full display, let Locations tab extend like Details tab.\n\tif ((RegExp(\"display.do\").test(window.location.href)) || (RegExp(\"dlDisplay.do\").test(window.location.href)))\n\t\t$(\".EXLLocationListContainer\").css(\"height\", \"auto\");\n\n\t//Add a spinning wheel for loading locations for any arrows that appear on the Locations tabs\n\t$(\".EXLLocationsIcon\").click(handleLocationIconClick);\n\n\t//If it is a single location, perform all changes immediately before attaching a listener\n\t//20150107 CB added libInfoLink for library info links\n\tlibInfoLink();\n\t\n\t//20150819 CB displaying more holdings info instead of hidden behind lightbox\t\n\tholdingsandlightbox();\t\n\n\t//Add note to Show More items that it is loading; this will disappear when items load b/c Primo already hides that row after items load\n\t/*$(\".EXLLocationViewAllLink\").click(function() {\n\t\t$(this).append('&nbsp;Loading...');\n\t});\t\t*/\n\n\t//Alon B: Adding BorrowDirect at the bottom of Locations tab\n\tborrowDirect();\t\n\n\t//Alon B: Adding Expand All feature\n\taddExpandAll();\n}", "onInput (e) {\n this.setState({\n term: e.target.value\n });\n }", "function addSearchTextChangedListener() {\n\tdocument.getElementById(\"id_input_search_district\").addEventListener(\n\t\t\t\"input\", populateDistricts, false);\n\tdocument.getElementById(\"id_input_search_deleted_district\")\n\t\t\t.addEventListener(\"input\", populateTrashedDistricts, false);\n}", "function changeFormMethod() {\n //values setters\n document.getElementById('checkAll').checked = true;\n // document.getElementById('searchBox').value = \"Random Word\";\n\n // document.getElementById('searchBox').setParameter('required','required');\n\n //execution\n document.getElementById('searchForm').action=\"simplesearch\";/*random result*//*lateri will change the action*/\n}", "changeLocation(newLocation) {\n this.locationEl.text(newLocation);\n }", "function updateResponses() {\n\tvar responseForm = rightPane.querySelector('form[id=\"response-form\"]');\n\tvar name = responseForm.querySelector('input[type=\"text\"]');\n\tvar response = responseForm.querySelector('textarea[type=\"text\"]');\n\tif(name.value && response.value) {\n\t\tappendResponseToResponseList(name.value, response.value);\n\t\texpandQuestion();\n\t}\n }", "function cityType (e){\n}", "function searchApartment() {\n // opzioni per ricerca\n var searchOptions = {\n key: 'LXS830AiWeCA3ogV5iiftuD8GgwteTOE',\n language: 'it-IT',\n limit: 5\n };\n // opzione autocomplete\n var autocompleteOptions = {\n key: 'LXS830AiWeCA3ogV5iiftuD8GgwteTOE',\n language: 'it-IT'\n };\n var searchBoxOptions = {\n minNumberOfCharacters: 0,\n searchOptions: searchOptions,\n autocompleteOptions: autocompleteOptions\n };\n\n var ttSearchBox = new tt.plugins.SearchBox(tt.services, searchBoxOptions);\n var searchBoxHTML = ttSearchBox.getSearchBoxHTML();\n $('.search-app').append(searchBoxHTML);\n\n //invio risultati form-homepage\n $('input').on('keydown', function (e) {\n var key = (e.keyCode || e.which);\n if (key == 13 || key == 3) {\n $('.form-search').submit();\n }\n });\n\n $(\".home-form form .inner-form .input-field .search-app svg\").click(function () {\n $('.form-search').submit();\n });\n\n\n\n\n\n // prendo il risultato selezionato salvo i dati di lat e lon\n ttSearchBox.on('tomtom.searchbox.resultselected', function (data) {\n var position = data['data']['result']['position'];\n console.log(position);\n var latitudine = position['lat'];\n var longitudine = position['lng'];\n console.log(latitudine, longitudine);\n $(\".lat\").val(latitudine);\n $(\".lon\").val(longitudine);\n });\n}", "function clickHandler(e) {\n\t\tvar $input = $(this).parents(\".dropdown\").siblings(\".location\");\n\t\t$input.val(this.textContent);\n\t\t$input.focus();\n\t\tvar $menu = $(this).parent();\n\t\t$menu.hide().empty();\n\t}", "function addOnChange (){\n\t // data input fields\n\t var f = document.getElementsByTagName('input');\n\t for(var i=0;i<f.length;i++){\n\t if(f[i].getAttribute('type')!='submit'){\n\t\t addChangeEvent(f[i]);\n\t }\n\t }\n\t // dropdowns\n\t var f = document.getElementsByTagName('select');\n\t for(var i=0;i<f.length;i++){\n\t\t addChangeEvent(f[i]);\n\t\t }\n\t // text areas\n\t var f = document.getElementsByTagName('textarea');\n\t for(var i=0;i<f.length;i++){\n\t\t addChangeEvent(f[i]);\n\t\t }\n\t // dojo dropdowns\n\t \tvar elem = document.getElementById('advance').elements;\n\t // var box = dijit.byId('box');\n\t for(var i = 0; i < elem.length; i++){\n\t var dijitElement = dijit.byId(elem[i].id);\n\t if (dijitElement != undefined)\n\t if (dijitElement.declaredClass == 'dijit.form.ComboBox' || (dijitElement.declaredClass == 'dijit.form.FilteringSelect'))\n\t \t dojo.connect(dijitElement, 'onChange', setChanged);\n\t }\n\t \n\t // Date images, used onclick since onchange won't fire when the\n\t\t\t// field\n\t // is modified through a script\n\t dojo.connect(dojo.byId(\"requestDateSelector\"), 'onclick', setChanged);\n\t dojo.connect(dojo.byId(\"fromDateSelector\"), 'onclick', setChanged);\n\t dojo.connect(dojo.byId(\"toDateSelector\"), 'onclick', setChanged);\n\t }", "function setBMI() {\n document.querySelectorAll(\".bmi .calc input\")[0].addEventListener(\"input\", onType);\n document.querySelectorAll(\".bmi .calc input\")[1].addEventListener(\"input\", onType);\n}", "function checkTerms(e) {\n //If someone clicked on the checkbox, it will return true. \n\tif (check.checked == true) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n} //End CheckTerms //", "function changeCity(event){\n event.preventDefault();\n let searchInput = document.querySelector(\"#search-input\");\n apiInfo(searchInput.value);\n}", "function cityInput(event){\n event.preventDefault();\n //get value of text input into search form\n citySearched = $('input[name=\"city-input\"]').val();\n citySearched = citySearched.charAt(0).toUpperCase() + citySearched.slice(1);\n\n cityNames.push(citySearched);\n\n if(!citySearched) {\n alert('you must type a city');\n return;\n }\n //append list item with submitted city\n citySearchedList = $('<li>');\n citySearchedList.attr('class', 'list-group-item');\n citySearchedList.text(citySearched);\n\n cityList.append(citySearchedList);\n \n var coordinatesRequestUrl = 'https://api.openweathermap.org/geo/1.0/direct?q='+citySearched+'&units=imperial&id=524901&appid=ab7266a3a00f62e9f68c69fe3c45b0e5';\n\n storeCities();\n geolocationCoordinates(coordinatesRequestUrl, citySearched);\n //empty search form box\n $('input[name=\"city-input\"]').val('');\n}", "function setTerm(){\n let userWordSelection = document.getElementById('termList');\n let targetTerm = userWordSelection.options[userWordSelection.selectedIndex].value;\n console.log(targetTerm);\n dispayCollocations(targetTerm);\n return targetTerm;\n}", "function travellerDetails()\n{\n// first name field\nvar element = document.getElementById(\"firstName\");\nif(element)\n{\nvar ev = new Event('input', { bubbles: true});\nev.simulated = true;\nelement.value = \"%1$@\";\nelement.style.background=\"#f19c4f\"\nelement.defaultValue = \"Something new\";\nelement.dispatchEvent(ev);\n}\n\n// middle name field\nvar element = document.getElementById(\"middleName\");\nif(element)\n{\nvar ev = new Event('input', { bubbles: true});\nev.simulated = true;\nelement.value = \"%11$@\";\nelement.style.background=\"#f19c4f\"\nelement.defaultValue = \"Something new\";\nelement.dispatchEvent(ev);\n}\n// last name field\nvar element = document.getElementById(\"lastName\");\nif(element)\n{\nvar ev = new Event('input', { bubbles: true});\nev.simulated = true;\nelement.value = \"%3$@\";\nelement.style.background=\"#f19c4f\"\nelement.defaultValue = \"Something new\";\nelement.dispatchEvent(ev);\n}\nvar letter = '%7$@';\nif(letter=='Male'){\nvar selectObj = document.querySelector('div[class=\"FormInput-wrapper FormInput-wrapper--toggle\"] label[for=\"gender\"]+ ul li button[type=\"button\"]');\nif(selectObj){\nselectObj.click();\n}\n}\nelse{\nvar selectObj = document.querySelector('div[class=\"FormInput-wrapper FormInput-wrapper--toggle is-correct\"] label[for=\"gender\"]+ul li[class=\"Toggle-listItem\"] button[class=\"Toggle-button Toggle-button--form\"]');\nif(selectObj){\nselectObj.click();\n}\n}\n// DOB\n\n// phone number field\n\n//Month\n var letter = '%4$@';\n var selectObj = document.querySelector('div[class=\"Dropdown FormInputDateDropdown-dropdown\"] select[name=\"bday bday-month\"]');\n fillDropDown(letter, selectObj);\n\n//Day\n var letter = '%5$@';\n var selectObj = document.querySelector('div[class=\"Dropdown FormInputDateDropdown-dropdown\"] select[name=\"bday bday-day\"]');\n fillDropDown(letter, selectObj);\n\n//Years\n var letter = '%6$@';\n var selectObj = document.querySelector('div[class=\"Dropdown FormInputDateDropdown-dropdown\"] select[name=\"bday bday-year\"]');\n fillDropDown(letter, selectObj);\n\nvar letter = '%8$@%9$@%10$@'; var selectObj = document.querySelector('div[class=\"FormInputPhone-input\"] input[type=\"number\"][id=\"phoneNumbers.phoneNumber0\"]');\nfillTextField(letter, selectObj);\n\n// email field\nvar letter = '%11$@'; var selectObj = document.querySelector('div[class=\"FormInput FormInput--large\"] input[id=\"email\"]');\nfillTextField(letter, selectObj);\n\n\n}", "handleDescriptionChange(ev) {\n this.setMarkerContent({description: ev.target.value});\n }", "onInputChange(event) {\n const currentValue = event.target.value;\n // bug - event.target.value will no longer exist inside setState\n // so have a variable to save it outside\n this.setState(() => ({ term: currentValue }));\n }", "function addressBookSelectBtn(section, self) {\r\n let address = self.closest('.input-group').querySelector('input');\r\n self.closest('.address-book').querySelectorAll('input').forEach(function(item) {\r\n if (item.checked) {\r\n let addressTitle = item.closest('.address-content').querySelector('.address-content-title').textContent.trim(),\r\n addressDetail = item.closest('.address-content').querySelector('.address-content-detail').textContent.trim();\r\n if (address.value === '') {\r\n address.value = addressTitle + ', ' + addressDetail;\r\n } else {\r\n address.value += ', ' + addressTitle + ', ' + addressDetail;\r\n }\r\n item.closest('.address-book').classList.remove('active');\r\n formValidation(section, address, false);\r\n address.classList.add('complete-input');\r\n formValidationOnInput(section);\r\n }\r\n })\r\n}", "termChanged({ currentTarget: t }) {\n this.setState({ term: t.value });\n }", "chooseLocation() {\n \n }", "function updateInputText(replaceInput)\n{\n var inputTypeSelect = document.getElementById('INPUT_TYPE');\n var locale = document.getElementById('LOCALE').value;\n if (inputTypeSelect.options.length == 0 || locale == 'fill-me') { // nothing to do yet\n\t return;\n }\n \tvar inputType = inputTypeSelect.options[inputTypeSelect.selectedIndex].text;\n\n\t// Keep track of AJAX concurrency across the two requests:\n\tvar retrievingVoiceExample = false;\n\tvar haveVoiceExample = false;\n\tvar retrievingTypeExample = false;\n\tvar typeExample = \"\";\n\t\n\t// Only worth requesting type example if replaceInput is true:\n\tif (replaceInput) {\n\t var xmlHttp = GetXmlHttpObject();\n\t if (xmlHttp==null) {\n\t alert (\"Your browser does not support AJAX!\");\n\t return;\n\t }\n\t var url = my_super_variable+\"/exampletext?datatype=\" + inputType + \"&locale=\" + locale;\n\t xmlHttp.onreadystatechange = function() {\n\t if (xmlHttp.readyState==4) {\n\t \tif (xmlHttp.status == 200) {\n\t\t typeExample = xmlHttp.responseText;\n\t \t} else {\n\t \t\talert(xmlHttp.responseText);\n\t \t}\n\t \tretrievingTypeExample = false;\n\t \tif (replaceInput && !retrievingTypeExample && !retrievingVoiceExample) {\n\t \t\tif (haveVoiceExample) {\n\t \t\t\texampleChanged();\n\t \t\t} else {\n\t \t\t\tdocument.getElementById('INPUT_TEXT').value = typeExample;\n\t \t\t}\n\t \t}\n\t }\n\t };\n\t retrievingTypeExample = true;\n\t xmlHttp.open(\"GET\", url, true);\n\t xmlHttp.send(null);\n\t}\n \n // Only worth requesting voice example if input type is TEXT:\n if (inputType == \"TEXT\") {\n\t var xmlHttp2 = GetXmlHttpObject();\n\t var voice = document.getElementById('VOICE').value;\n\t var url2 = my_super_variable+\"/exampletext?voice=\" + voice;\n \txmlHttp2.onreadystatechange = function() {\n\t if (xmlHttp2.readyState==4) {\n\t \tif (xmlHttp2.status == 200) {\n\t \t\tvar examples = xmlHttp2.responseText;\n\t \t\tif (examples != \"\") {\n\t\t \thaveVoiceExample = true;\n\t \t\t\t\t\tdocument.getElementById(\"exampleTexts\").style.display = 'inline';\n\t\t\t\t\t\tdocument.getElementById(\"exampleTexts\").length = 0;\n\t \t\t\t var lines = examples.split('\\n');\n\t\t\t for (l in lines) {\n\t\t \t \tvar line = lines[l];\n\t\t \t \tif (line.length > 0) {\n\t\t\t \t \taddOption(\"exampleTexts\", line);\n\t\t\t \t}\n\t\t \t}\n\t \t\t} else {\n\t\t \thaveVoiceExample = false;\n\t \t\t\t\t\tdocument.getElementById(\"exampleTexts\").style.display = 'none';\n\t\t }\n\t \t} else {\n\t \t\talert(xmlHttp.responseText);\n\t \t}\n\t \tretrievingVoiceExample = false;\n\t \tif (replaceInput && !retrievingTypeExample && !retrievingVoiceExample) {\n\t \t\tif (haveVoiceExample) {\n\t \t\t\texampleChanged();\n\t \t\t} else {\n\t \t\t\tdocument.getElementById('INPUT_TEXT').value = typeExample;\n\t \t\t}\n\t \t}\n\t }\n\t };\n\t retrievingVoiceExample = true;\n\t xmlHttp2.open(\"GET\", url2, true);\n\t xmlHttp2.send(null);\n \t\n } else { // input type not text, hide examples, don't send request\n \tdocument.getElementById(\"exampleTexts\").style.display = 'none';\n }\n}", "onSearchTermChange() {\n this.search();\n Metrics.getInstance().updateMetric(Filters.SEARCH, 1);\n }", "function handleIt(type)\t{\n\t\t\t\t\tif(Number(sfo[index]) === 1)\t{\n\t\t\t\t\t\tr.push(index.replace('+','=')); // input name is navcat+.something, so simply changing + to = makes it macroesque-ready.\n\t\t\t\t\t\t}\n\t\t\t\t\t}", "function modifyAnnotation() {\n var tipo = $(\"#hiddenTip\").val();\n var cod = $(\"#hiddenCod\").val();\n var tar = $(\"#hiddenTg\").val();\n var newTipo = $(\"#changeType\").val();\n var newOggetto = $(\"#changeObj\").val();\n var questoSpan = $(\"span[codice='\"+cod+\"']\");\n\n if(newOggetto !== '') {\n if (newTipo === 'autore' && !hasWhiteSpace(newOggetto.trim())) {\n $('#errorAuthor4').css(\"display\", \"block\");\n $('#changeObj').parent().addClass('has-error has-feedback');\n $('#changeObj').parent().append('<span class=\"glyphicon glyphicon-remove form-control-feedback\" aria-hidden=\"true\">' +\n '</span><span id=\"inputErrorStatus\" class=\"sr-only\">(error)</span>');\n } else {\n questoSpan.attr('tipo', newTipo);\n var oldEmail = questoSpan.attr('email'); // Vecchia email di provenance\n questoSpan.attr('username', username);\n questoSpan.attr('email', email);\n // Setto nuova annotazione come annotazione da inviare\n questoSpan.attr('new', 'true');\n questoSpan.attr(\"graph\", \"Heisenberg\");\n \n // Cancella la vecchia annotazione dagli array d'appoggio\n reprocessArray(cod);\n\n if(tar === 'doc') {\n var value = questoSpan.attr(\"value\"); // Vecchio valore\n // Modifica dei valori dello span\n questoSpan.attr('value', newOggetto.trim());\n questoSpan.attr('class', 'annotation ' + newTipo);\n questoSpan.attr('onclick', 'displayAnnotation(\"'+questoSpan.attr(\"username\")+'\", \"'+questoSpan.attr(\"email\")+'\", ' +\n '\"'+newTipo+'\", \"'+newOggetto+'\", \"'+questoSpan.attr(\"data\")+'\")');\n questoSpan.text(newOggetto);\n // Rimozione del vecchio punto e aggiunta del nuovo nel caso di ann su documento\n var punto = $(\"li[codice='\"+cod+\"']\").html();\n $(\"li[codice='\"+cod+\"']\").remove();\n\n var tipoStatement;\n switch(newTipo) {\n case 'autore':\n $('#lista-autore').append(\"<li codice='\"+cod+\"'>\"+punto+\"</li>\");\n tipoStatement = \"Autore\";\n break;\n case 'pubblicazione':\n $('#lista-pubblicazione').append(\"<li codice='\"+cod+\"'>\"+punto+\"</li>\");\n tipoStatement = \"AnnoPubblicazione\";\n break;\n case 'titolo':\n $('#lista-titolo').append(\"<li codice='\"+cod+\"'>\"+punto+\"</li>\");\n tipoStatement = \"Titolo\";\n break;\n case 'doi':\n $('#lista-doi').append(\"<li codice='\"+cod+\"'>\"+punto+\"</li>\");\n tipoStatement = \"DOI\";\n break;\n case 'url':\n $('#lista-url').append(\"<li codice='\"+cod+\"'>\"+punto+\"</li>\");\n tipoStatement = \"URL\";\n break;\n }\n\n arrayAnnotazioni.push({\n code : cod,\n username : username,\n email : email,\n type : questoSpan.attr(\"tipo\"),\n content : questoSpan.attr(\"value\"),\n date : questoSpan.attr(\"data\")\n });\n databaseAnnotations.push({\n code : cod,\n username : username,\n email : email,\n type : questoSpan.attr(\"tipo\"),\n content : questoSpan.attr(\"value\"),\n date : questoSpan.attr(\"data\")\n });\n } else {\n var value = questoSpan.attr(tipo); // Vecchio valore\n // Modifica dei valori dello span\n questoSpan.removeAttr(tipo);\n questoSpan.attr(newTipo, newOggetto);\n questoSpan.attr('class', 'annotation ' + newTipo);\n questoSpan.attr('onclick', 'displayAnnotation(\"'+questoSpan.attr(\"username\")+'\", \"'+questoSpan.attr(\"email\")+'\", ' +\n '\"'+newTipo+'\", \"'+newOggetto+'\", \"'+questoSpan.attr(\"data\")+'\")');\n\n var start;\n var end;\n var idFrag;\n // Cerco nell'array che contiene lo storico delle annotazioni lo start e end del frammento dell'annotazione che sto modificando\n for (var i = 0; i < databaseAnnotations.length; i++) {\n if(databaseAnnotations[i].code == cod) {\n idFrag = databaseAnnotations[i].id;\n start = databaseAnnotations[i].start;\n end = databaseAnnotations[i].end;\n }\n }\n \n arrayAnnotazioni.push({\n code : cod,\n username : username,\n email : email,\n id : idFrag,\n start : start,\n end : end,\n type : questoSpan.attr(\"tipo\"),\n content : questoSpan.attr(questoSpan.attr(\"tipo\")),\n date : questoSpan.attr(\"data\")\n });\n databaseAnnotations.push({\n code : cod,\n username : username,\n email : email,\n id : idFrag,\n start : start,\n end : end,\n type : questoSpan.attr(\"tipo\"),\n content : questoSpan.attr(questoSpan.attr(\"tipo\")),\n date : questoSpan.attr(\"data\")\n });\n }\n deleteSingleAnnotation(tipo, value, activeURI, questoSpan.attr('data'));\n $(\"#modalModificaAnnotazione\").modal(\"hide\");\n $(\"#modalGestioneAnnotazioni\").modal(\"hide\");\n }\n } else {\n // Messaggio d'errore\n $('#errorType4').css(\"display\", \"block\");\n $('#errorAuthor4').css(\"display\", \"none\");\n $('#changeObj').parent().addClass('has-error has-feedback');\n $('#changeObj').parent().append('<span class=\"glyphicon glyphicon-remove form-control-feedback\" aria-hidden=\"true\">' +\n '</span><span id=\"inputErrorStatus\" class=\"sr-only\">(error)</span>');\n }\n // Chiamata funzione che gestisce l'onhover\n onHover();\n}" ]
[ "0.54640776", "0.5349804", "0.53165483", "0.5291185", "0.52713245", "0.52152944", "0.5211825", "0.5150715", "0.51490843", "0.5141344", "0.5122521", "0.5112396", "0.51123685", "0.5086095", "0.50419736", "0.5003833", "0.49658164", "0.49428698", "0.49408758", "0.49325418", "0.4930881", "0.49147654", "0.49142656", "0.4896205", "0.48712638", "0.4859061", "0.4856422", "0.48561105", "0.48508358", "0.4814194", "0.4808328", "0.48018038", "0.48015195", "0.47867814", "0.4785452", "0.47665554", "0.4756468", "0.47543293", "0.4746061", "0.47424465", "0.4739357", "0.47370017", "0.46785086", "0.46754268", "0.46734592", "0.46714765", "0.4663498", "0.46620834", "0.4662036", "0.46593976", "0.46547195", "0.46495876", "0.4648742", "0.46451092", "0.46383786", "0.46347576", "0.46347576", "0.46331704", "0.4632973", "0.46293455", "0.46139407", "0.46131867", "0.46126232", "0.4612368", "0.4611464", "0.4608516", "0.4607665", "0.46048504", "0.46047962", "0.46022725", "0.45986226", "0.45955124", "0.45932102", "0.45908082", "0.45861873", "0.45840487", "0.45824376", "0.45775554", "0.45755205", "0.45718834", "0.45668265", "0.45668158", "0.4566094", "0.4562408", "0.45611945", "0.45588705", "0.45573765", "0.45565784", "0.45562112", "0.45500308", "0.45484543", "0.4542732", "0.45425433", "0.45414534", "0.45395732", "0.4538954", "0.4538276", "0.45376715", "0.45353162", "0.4533859", "0.45329297" ]
0.0
-1
Build GO button functionality
handleSearch(event) { this.props.searchYelp(this.state.term, this.state.location, this.state.sortBy); event.preventDefault(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function buildButtonDef(trumbowyg) {\n return {\n fn: function () {\n var $modal = trumbowyg.openModal('Code', [\n '<div class=\"' + trumbowyg.o.prefix + 'highlight-form-group\">',\n ' <select class=\"' + trumbowyg.o.prefix + 'highlight-form-control language\">',\n (function () {\n var options = '';\n\n for (var lang in Prism.languages) {\n if (Prism.languages[lang].comment) {\n options += '<option value=\"' + lang + '\">' + lang + '</option>';\n }\n }\n\n return options;\n })(),\n ' </select>',\n '</div>',\n '<div class=\"' + trumbowyg.o.prefix + 'highlight-form-group\">',\n ' <textarea class=\"' + trumbowyg.o.prefix + 'highlight-form-control code\"></textarea>',\n '</div>',\n ].join('\\n')),\n $language = $modal.find('.language'),\n $code = $modal.find('.code');\n\n // Listen clicks on modal box buttons\n $modal.on('tbwconfirm', function () {\n trumbowyg.restoreRange();\n trumbowyg.execCmd('insertHTML', highlightIt($code.val(), $language.val()));\n trumbowyg.execCmd('insertHTML', '<p><br></p>');\n\n trumbowyg.closeModal();\n });\n\n $modal.on('tbwcancel', function () {\n trumbowyg.closeModal();\n });\n }\n };\n }", "function makeButtons() {\n\t// attach script to reset button\n\tvar resetObject = GameObject.CreatePrimitive(PrimitiveType.Quad);\n\tvar resetScript = resetObject.AddComponent(resetButtonMouse);\n\tresetScript.init(this);\n\t\n\t// attach script to menu button\n\tvar menuObject = GameObject.CreatePrimitive(PrimitiveType.Quad);\n\tvar menuScript = menuObject.AddComponent(menuButtonMouse);\n\tmenuScript.init(this);\n\t\n\t// attach script to help button\n\tvar helpObject = GameObject.CreatePrimitive(PrimitiveType.Quad);\n\tvar helpScript = helpObject.AddComponent(helpButtonMouse);\n\thelpScript.init(this);\n\n\t// attach script to mute button\n\tvar muteObject = GameObject.CreatePrimitive(PrimitiveType.Quad);\n\tvar muteScript = muteObject.AddComponent(muteButtonMouse);\n\tmuteScript.init(this);\n\n\tvar tempheight: int =Screen.height/500;\n\t\tmenuObject.transform.position = Vector3(-2, 7, 0);\n\t\tresetObject.transform.position = Vector3(-2, 6, 0);\n\t\tmuteObject.transform.position = Vector3(-2, 5, 0);\n\t\thelpObject.transform.position = Vector3(-2, 4, 0);\n}", "function generateBtnTrigger() {\n map = new Map(); // Options\n map.set(\"show_list\", show_listCheck.checked);\n map.set(\"w\", wSlider.value);\n map.set(\"cheat\", cheatCheck.checked);\n map.set(\"words\", wlist.getWords().join(\",\"));\n window.location.href = getOutputUrl(map); // Redirect to output page\n}", "_generateComponents (){\n this._generateJumpButtons();\n }", "function createButtons() {\n lat = createSlider(-90,90,40).position(10,10);\n long = createSlider(-180,180,-75).position(560,10);\n speed = createSlider(-40,40,0).position(10,height-20);\n createButton(\"toggle constellations\").mousePressed(()=>bigSphere.constellations = !bigSphere.constellations).position(10,60);\n createButton(\"now\").mousePressed(()=>bigSphere.resetTime()).position(10,120);\n createButton(\"stop\").mousePressed(()=>speed.value(0)).position(10,90);\n}", "function VButton(columnName, mandatory, isReadOnly, isUpdateable, text, description, help, AD_Process_ID, isLink, isRightLink, AD_Form_ID, isBGProcess, isAskUserBGProcess) {\n\n this.actionListner;\n this.AD_Process_ID = AD_Process_ID;\n this.AD_Form_ID = AD_Form_ID;\n this.description = description;\n this.help = help;\n this.text = text;\n this.isLink = isLink;\n this.isRightLink = isRightLink;\n this.actionLink = null;\n this.isCsv = false;\n this.isPdf = false;\n this.askUserBGProcess = isAskUserBGProcess;\n this.isBackgroundProcess = isBGProcess;\n\n this.values = null;\n\n var $img = $(\"<i title='\" + text + \"'>\");\n\n var $txt = $(\"<span>\").text(text);\n var rootPath = VIS.Application.contextUrl + \"Areas/VIS/Images/base/\";\n\n var $ctrl = null;\n //Init Control\n if (!isLink) {\n $ctrl = $('<button>', { type: 'button', name: columnName });\n $img.css(\"margin-right\", \"8px\");\n $ctrl.append($img).append($txt);\n }\n else {\n $ctrl = $('<li>');\n $ctrl.append($txt).append($img);\n }\n\n //\tSpecial Buttons\n if (columnName.equals(\"PaymentRule\")) {\n this.readReference(195);\n $ctrl.css(\"color\", \"blue\"); //\n setIcon(\"vis vis-payment\"); // 29*14\n }\n else if (columnName.equals(\"DocAction\")) {\n this.readReference(135);\n $ctrl.css(\"color\", \"blue\"); //\n setIcon(\"vis vis-cog\"); // 16*16\n }\n else if (columnName.equals(\"CreateFrom\")) {\n setIcon(\"vis vis-copy\"); // 16*16\n }\n else if (columnName.equals(\"Record_ID\")) {\n setIcon(\"vis vis-find\"); // 16*16\n $ctrl.text(VIS.Msg.getMsg(\"ZoomDocument\"));\n }\n else if (columnName.equals(\"Posted\")) {\n this.readReference(234);\n $ctrl.css(\"color\", \"magenta\"); //\n setIcon(\"fa fa-line-chart\"); // 16*16\n }\n else if (isLink) {\n setIcon(\"vis vis-action\");\n }\n\n function setIcon(img) {\n $img.addClass(img);\n };\n\n IControl.call(this, $ctrl, VIS.DisplayType.Button, isReadOnly, columnName, mandatory);\n\n if (isReadOnly || !isUpdateable) {\n this.setReadOnly(true);\n //this.Enabled = false;\n }\n else {\n this.setReadOnly(false);\n }\n\n var self = this; //self pointer\n var $ulPopup = null;\n\n $ulPopup = getPopupList();\n function getPopupList() {\n var ullst = $(\"<ul class='vis-apanel-rb-ul'>\");\n //ullst.append($(\"<li data-action='D'>\").text(VIS.Msg.getMsg(\"Default\")));\n ullst.append($(\"<li data-action='C'>\").text(VIS.Msg.getMsg(\"OpenCSV\")));\n ullst.append($(\"<li data-action='P'>\").text(VIS.Msg.getMsg(\"OpenPDF\")));\n return ullst;\n };\n\n\n $ctrl.on(VIS.Events.onClick, function (evt) { //click handler\n evt.stopPropagation();\n\n var isReport = null;\n // self.invokeActionPerformed({ source: self });\n if (!self.isReadOnly) {\n var sqlQry = \"VIS_81\";\n var param = [];\n param[0] = new VIS.DB.SqlParam(\"@AD_Process_ID\", AD_Process_ID);\n isReport = executeScalar(sqlQry, param);\n\n\n sqlQry = \"VIS_149\";\n param = [];\n param[0] = new VIS.DB.SqlParam(\"@AD_Process_ID\", AD_Process_ID);\n var isCrystalReport = executeScalar(sqlQry, param);\n\n if (isCrystalReport == \"Y\" && VIS.context.getIsUseCrystalReportViewer()) {\n self.invokeActionPerformed({ source: self });\n }\n else {\n if (isReport == 'Y') {\n $img.w2overlay($ulPopup.clone(true));\n }\n else {\n self.invokeActionPerformed({ source: self });\n }\n }\n }\n });\n\n if ($ulPopup) {\n $ulPopup.on(\"click\", \"LI\", function (e) {\n var target = $(e.target);\n\n if (target.data(\"action\") == \"P\") {\n self.isPdf = true;\n self.isCsv = false;\n }\n else if (target.data(\"action\") == \"C\") {\n self.isCsv = true;\n self.isPdf = false;\n }\n self.invokeActionPerformed({ source: self });\n });\n }\n\n\n this.setText = function (text) {\n if (text == null) {\n $txt.text(\"\");\n return;\n }\n var pos = text.indexOf('&');\n if (pos != -1)\t\t\t\t\t//\tWe have a nemonic - creates ALT-_\n {\n var mnemonic = text.toUpperCase().charAt(pos + 1);\n if (mnemonic != ' ') {\n //setMnemonic(mnemonic);\n text = text.substring(0, pos) + text.substring(pos + 1);\n }\n }\n $txt.text(text);\n\n };\n\n this.disposeComponent = function () {\n $ctrl.off(VIS.Events.onClick);\n $ctrl = null;\n self = null;\n //this.actionListner = null;\n this.AD_Process_ID = null;\n this.description = null;\n this.help = null;\n this.setText = null;\n };\n }", "function ButtonControl() {\n}", "function buildGameButton(){\n\tbuttonStart.cursor = \"pointer\";\n\tbuttonStart.addEventListener(\"click\", function(evt) {\n\t\tplaySound('soundClick');\n\t\tgoPage('select');\n\t});\n\t\n\tbuttonContinue.cursor = \"pointer\";\n\tbuttonContinue.addEventListener(\"click\", function(evt) {\n\t\tplaySound('soundClick');\n\t\tgoPage('select');\n\t});\n\t\n\tbuttonFacebook.cursor = \"pointer\";\n\tbuttonFacebook.addEventListener(\"click\", function(evt) {\n\t\tshare('facebook');\n\t});\n\tbuttonTwitter.cursor = \"pointer\";\n\tbuttonTwitter.addEventListener(\"click\", function(evt) {\n\t\tshare('twitter');\n\t});\n\tbuttonWhatsapp.cursor = \"pointer\";\n\tbuttonWhatsapp.addEventListener(\"click\", function(evt) {\n\t\tshare('whatsapp');\n\t});\n\t\n\tbuttonSoundOff.cursor = \"pointer\";\n\tbuttonSoundOff.addEventListener(\"click\", function(evt) {\n\t\ttoggleGameMute(true);\n\t});\n\t\n\tbuttonSoundOn.cursor = \"pointer\";\n\tbuttonSoundOn.addEventListener(\"click\", function(evt) {\n\t\ttoggleGameMute(false);\n\t});\n\t\n\tbuttonFullscreen.cursor = \"pointer\";\n\tbuttonFullscreen.addEventListener(\"click\", function(evt) {\n\t\ttoggleFullScreen();\n\t});\n\t\n\tbuttonExit.cursor = \"pointer\";\n\tbuttonExit.addEventListener(\"click\", function(evt) {\n\t\tif(!$.editor.enable){\n\t\t\ttoggleConfirm(true);\n\t\t}\n\t});\n\t\n\tbuttonSettings.cursor = \"pointer\";\n\tbuttonSettings.addEventListener(\"click\", function(evt) {\n\t\ttoggleOption();\n\t});\n\t\n\tbuttonConfirm.cursor = \"pointer\";\n\tbuttonConfirm.addEventListener(\"click\", function(evt) {\n\t\ttoggleConfirm(false);\n\t\tstopGame(true);\n\t\tgoPage('main');\n\t\ttoggleOption();\n\t});\n\t\n\tbuttonCancel.cursor = \"pointer\";\n\tbuttonCancel.addEventListener(\"click\", function(evt) {\n\t\ttoggleConfirm(false);\n\t});\n\t\n\tbuttonTutContinue.cursor = \"pointer\";\n\tbuttonTutContinue.addEventListener(\"click\", function(evt) {\n\t\ttoggleTutorial(false);\n\t});\n}", "static get BUTTON_START() {\n return \"start\";\n }", "function Procedure_button(main, str){\n\n\t//creat button, set class\n\tvar btn = document.createElement(\"button\");\n\tbtn.classList.add(\"ui\", \"circular\",\"icon\",\"button\",\"procedure\",\n\t\t\t\t\t main.stepObject.length.toString());\n\tbtn.setAttribute ('id', \"ui circular icon button procedure \" + \n\t\t\t\t\t main.stepObject.length.toString())\n\t//set button string\n\tvar t = document.createTextNode(str);\n\tbtn.appendChild(t);\n\t\n //add button to Web\n document.getElementById(\"Procedure_List\").appendChild(btn);\n\n //record scene object\n RecordObjects(main);\n main.stepNumber += 1;\n\n //set the click action\n btn.addEventListener(\"click\", function(){\n\n \t//if is the last step, create the step button\n\t if(main.lastStep == true){\n\t \tmain.lastStep = false;\n\t \tProcedure_button(main, main.stepOperationName);\n\t }\n\n\t //console.log(btn.classList[5]);\n\t buttonClicked(main, btn.classList[5]);\n\t main.stepNumber = btn.classList[5];\n\t main.stepOperationName = btn.firstChild.nodeValue;\n\n\t //Initialise the model button\n\t main.processor.executeDesign(\"MODEL_ALIGN\", \"initial\");\n\t main.processor.executeDesign(\"MODEL_PAINTING\", \"initial\");\n main.processor.executeDesign(\"MODEL_WRAP\", \"initial\");\n main.processor.executeDesign(\"MODEL_ROTATION\", \"initial\");\n main.processor.executeDesign(\"MODEL_ADDBETWEEN\", \"initial\");\n main.processor.executeDesign(\"MODEL_CUT\", \"initial\");\n main.processor.executeDesign(\"MODEL_ADD\", \"initial\");\n\t //show the control buttons\n\t if(btn.firstChild.nodeValue != 'Initial')\n\t \t$('#parameter_control_tool_' + btn.firstChild.nodeValue).show();\t \n\n\t});\n\t\n}", "activateButton(){\n //If the button already exists, we want to remove and rebuilt it\n if(this.button)\n this.button.dispose();\n\n //Create button called but with Activate SpeedBoost as its text\n this.button = Button.CreateSimpleButton(\"but\", \"Activate\\nSpeedBoost\");\n this.button.width = 0.8;\n this.button.height = 0.8;\n this.button.color = \"white\";\n this.button.background = \"red\";\n this.button.alpha = 0.8;\n this.stackPanel.addControl(this.button);\n //Scope these attributes so they can be used below\n var button = this.button;\n var app = this.app;\n\n //Function for if they click it\n //Function is a member of the button object, not of this class\n this.button.onPointerDownObservable.add(function() {\n if(button.textBlock.text != \"Activate\\nSpeedBoost\")\n return;\n app.buttonPressed(\"speedBoost\");\n button.textBlock.text = \"SpeedBoost\\nActivated\";\n }); \n }", "function _setupGoLiveButton() {\n _$btnGoLive = $(\"#toolbar-go-live\");\n _$btnGoLive.click(function onGoLive() {\n _handleGoLiveCommand();\n });\n $(LiveDevelopment).on(\"statusChange\", function statusChange(event, status) {\n // status starts at -1 (error), so add one when looking up name and style\n // See the comments at the top of LiveDevelopment.js for details on the \n // various status codes.\n _setLabel(_$btnGoLive, null, _statusStyle[status + 1], _statusTooltip[status + 1]);\n });\n \n // Initialize tooltip for 'not connected' state\n _setLabel(_$btnGoLive, null, _statusStyle[1], _statusTooltip[1]);\n }", "function OnGUI() {\n\t\t\n\t\tGUI.Button (Rect (300,50,300,50), \"This is a button\");\n\t}", "function Alib_Ui_Button(content, options, type)\r\n{\r\n // button or anchor\r\n if (type == 'link')\r\n type = 'a';\r\n\r\n if (type == 'span')\r\n type = 'span';\r\n \r\n if (!type)\r\n type = 'button';\r\n\t/**\r\n\t * The button dom element\r\n\t *\r\n\t * @private\r\n\t * @type {DOMElement[button]}\r\n\t */\r\n\tthis.m_main = alib.dom.createElement(type);\r\n \r\n\tvar opts = options || new Object();\r\n \r\n if (opts.className)\r\n alib.dom.styleAddClass(this.m_main, opts.className);\r\n\r\n\tif (typeof content == \"string\")\r\n\t\tthis.m_main.innerHTML = content;\r\n\telse\r\n\t\tthis.m_main.appendChild(content);\r\n\r\n\tif (opts.tooltip)\r\n\t\tthis.m_main.title = opts.tooltip;\r\n \r\n // Add cursor pointer if type is link\r\n if (type == 'a')\r\n alib.dom.styleSet(this.m_main, \"cursor\", \"pointer\");\r\n\r\n\t// Set actions for button\r\n\t// -----------------------------------------\r\n\tthis.m_main.m_btnh = this;\r\n\tthis.m_main.opts = opts;\r\n\tthis.m_main.opts.m_btnh = this;\r\n\r\n\tif (opts.onmouseover)\r\n\t\tthis.m_main.onmouseover = function() { if (!this.disabled) this.opts.onmouseover(); };\r\n\tif (opts.onmouseout)\r\n\t\tthis.m_main.onmouseout = function() { if (!this.disabled) this.opts.onmouseout(); };\r\n\tif (opts.onclick)\r\n\t{\r\n\t\tthis.m_main.clickAction = opts.onclick;\r\n\t\tthis.m_main.onclick = function() { if (!this.disabled) this.clickAction(); };\r\n\t}\r\n\r\n\t// Set all other variables in options to this.m_main scope\r\n\tfor (var prop in opts)\r\n\t{\r\n\t\tif (prop != \"onmouseover\" && \r\n\t\t\t\tprop != \"onmouseout\" && \r\n\t\t\t\t\tprop != \"onclick\" && \r\n\t\t\t\t\t\tprop != \"className\" && \r\n\t\t\t\t\t\t\tprop != \"tooltip\")\r\n\t\t{\r\n\t\t\tthis.m_main[prop] = opts[prop];\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Options used for this button\r\n\t *\r\n\t * @private\r\n\t * @type {Object}\r\n\t */\r\n\tthis.options = opts;\r\n\r\n\t/**\r\n\t * Generic object for storing temp callback properties\r\n\t *\r\n\t * @public\r\n\t * @var {Object}\r\n\t */\r\n\tthis.cbData = new Object();\r\n\r\n\t/**\r\n\t * Optional toggle state\r\n\t *\r\n\t * If true this button is toggled on\r\n\t *\r\n\t * @type {bool}\r\n\t */\r\n\tthis.toggeled = false;\r\n\r\n\t// trigger click events\r\n\talib.events.listen(this.m_main, \"click\", function(evt) {\r\n\t\talib.events.triggerEvent(evt.data.btncls, \"click\");\r\n\t}, {btncls:this});\r\n\r\n}", "handleButton() {}", "function startGameButton() {\n return $(\"<button class='btn btn-success form-control padded' id='showQrBtn'>\"+tr(\"Let's go!\")+\"</button>\").click(hostNewGame);\n}", "function generate_button(href, type, text) {\n var button = '<a class=\"btn btn-' + type + '\" ';\n button += 'href=\"' + href + '\" ';\n button += 'data-remote=\"true\" data-method=\"patch\">';\n button += text + '</a>';\n return button;\n }", "createButtons() {\n this.settingsButton = this._createConnectionButton(TEXTURE_NAME_SETTINGS);\n this.deleteButton = this._createConnectionButton(TEXTURE_NAME_DELETE);\n }", "function buildGameButton(){\r\n\tbtnPlay.cursor = \"pointer\";\r\n\tbtnPlay.addEventListener(\"click\", function(evt) {\r\n\t\tplaySound('soundChalk');\r\n\t\tgoPage('game');\r\n\t});\r\n\t\r\n\tbtnServe.cursor = \"pointer\";\r\n\tbtnServe.addEventListener(\"click\", function(evt) {\r\n\t\tif(serveEnable){\r\n\t\t\tplaySound('soundChalk');\r\n\t\t\tplaySound('soundCashier');\r\n\t\t\tincreaseScore();\r\n\t\t\tcreateOrder();\r\n\t\t}\r\n\t});\r\n\t\r\n\tbtnPlayAgain.cursor = \"pointer\";\r\n\tbtnPlayAgain.addEventListener(\"click\", function(evt) {\r\n\t\tplaySound('soundChalk');\r\n\t\tgoPage('game');\r\n\t});\r\n\t\r\n\tfor(n=0;n<ingredients_arr.length;n++){\r\n\t\t$.icons[n].clicknum = n;\r\n\t\t$.icons[n].cursor = \"pointer\";\r\n\t\t$.icons[n].addEventListener(\"click\", function(evt) {\r\n\t\t\tcheckSelectIngredient(evt.target.clicknum);\r\n\t\t});\r\n\t}\r\n\t\r\n\tbtnFacebook.cursor = \"pointer\";\r\n\tbtnFacebook.addEventListener(\"mousedown\", function(evt) {\r\n\t\tshare('facebook');\r\n\t});\r\n\tbtnTwitter.cursor = \"pointer\";\r\n\tbtnTwitter.addEventListener(\"mousedown\", function(evt) {\r\n\t\tshare('twitter');\r\n\t});\r\n\tbtnGoogle.cursor = \"pointer\";\r\n\tbtnGoogle.addEventListener(\"mousedown\", function(evt) {\r\n\t\tshare('google');\r\n\t});\r\n}", "function actionButton() {\n\t\t\tif ($('#status').hasClass('play')) {\n\t\t\t\tif (common.type == 'blockly') {\n\t\t\t\t\t// capture screenshot\n\t\t\t\t\tvar xml = capture.captureXml();\n\n\t\t\t\t\t// log screenshot data to database\n\t\t\t\t\tdbService.saveProgram(xml);\n\n\t\t\t\t\t// capture blockly and run generated code\n\t\t\t\t\tvar code = Blockly.JavaScript.workspaceToCode(vm.workspace);\n\t\t\t\t\teval(code);\n\t\t\t\t} else {\n\t\t\t\t\t// capture screenshot and save to database\n\t\t\t\t\tcapture.capturePng('.program-inner');\n\n\t\t\t\t\t// convert program in to list of instructions\n\t\t\t\t\tvar program = [];\n\n\t\t\t\t\tfor (var i = 0; i < vm.program.length; i++) {\n\t\t\t\t\t\tvar ins = vm.program[i];\n\t\t\t\t\t\tprogram.push(ins.name);\n\t\t\t\t\t}\n\n\t\t\t\t\tdbService.saveProgram(program);\n\t\t\t\t}\n\n\t\t\t\t// run program\n\t\t\t\trun();\n\n\t\t\t\t// log button press\n\t\t\t\tdbService.buttonPress('play');\n\n\t\t\t} else if ($('#status').hasClass('stop')) {\n\n\t\t\t\t// stop program\n\t\t\t\tstate.current = state.STOPPED;\n\n\t\t\t\tif (common.type == 'blockly') {\n\t\t\t\t\tvm.program.length = 0;\n\t\t\t\t}\n\n\t\t\t\t// log button press\n\t\t\t\tdbService.buttonPress('stop');\n\n\t\t\t} else if ($('#status').hasClass('rewind')) {\n\t\t\t\trewind();\n\t\t\t}\n\t\t}", "makeReverbRouteButton() {\n this.reverbRouteActive = false;\n this.reverbRouteButton = createButton('DELAY -> VERB');\n this.reverbRouteButton.position(0.2 * this.parentXpos, this.parentYpos + 1.1 * this.parentButHt);\n this.reverbRouteButton.size(0.5 * this.parentButWd, 0.5 * this.parentButHt);\n this.reverbRouteButton.mousePressed(() => {\n this.reverbRouteActive = this.reverbRouteActive ? this.reverbRouteActive = false : this.reverbRouteActive = true;\n if (this.reverbRouteActive) {this.delay.connect(this.verb);}\n else {this.delay.disconnect(this.verb);}\n \n })\n }", "buy_tower_btns() {\n var tt = this;\n var ph = loadImage(\"img/ph.jpg\");\n\t//create 3 btns\n tt.normal_tower = tt.add_btn(0, -30, 10, 10, ph);\n tt.ice_tower = tt.add_btn(0, 0, 10, 10, ph);\n tt.poison_tower = tt.add_btn(0, 30, 10, 10, ph);\n //hide the tooltip\n\ttt.hide();\n }", "RenderButtonAction(Name = null, Action = null, TreeDotsAction = null){\n let Conteneur= NanoXBuild.DivFlexRowSpaceEvenly(null, \"ConteneurDevice Largeur\", null)\n let DivDevice = NanoXBuild.DivFlexRowStart(null, \"DeviceCard\", null)\n //let DivImage = NanoXBuild.DivFlexColumn(null, null, \"height: 100%; width: 20%; margin-right: 0.5rem;\")\n //DivImage.innerHTML = IconModule.Start()\n //DivDevice.appendChild(DivImage)\n DivDevice.appendChild(NanoXBuild.DivText(Name, null, \"Text\", \"\"))\n DivDevice.onclick = Action\n Conteneur.appendChild(DivDevice)\n // Div Trois points\n let DivTroisPoints = NanoXBuild.DivFlexRowStart(null, \"DeviceTroisPoints\", null)\n let DivImageTroisPoints = NanoXBuild.DivFlexColumn(null, null, \"height: 100%; width: 100%;\")\n DivImageTroisPoints.innerHTML = IconModule.ThreeDots()\n DivTroisPoints.appendChild(DivImageTroisPoints)\n DivTroisPoints.onclick = TreeDotsAction\n Conteneur.appendChild(DivTroisPoints)\n return Conteneur\n }", "function do_btn( )\n{ \n\n g_button2 = createButton( \"Save Image\" );\n g_button2.position( 150, 900 );\n g_button2.mousePressed( save_image ); // the callback // will call mousePressed( ) function below\n}", "function makeBtn() {\n // Deleting the gifs prior to adding new gifs\n // (this is necessary otherwise we will have repeat buttons)\n $(\"#btnDump\").empty();\n // Looping through the array of movies\n for (var i = 0; i < topics.length; i++) {\n var b = $(\"<button>\");\n b.addClass(\"gifButton\");\n // Adding a data-attribute\n b.attr(\"data-subject\", topics[i]);\n // Providing the initial button text\n b.text(topics[i]);\n // Adding the button to the HTML\n $(\"#btnDump\").append(b);\n }\n }", "function DecorativeCtrl_CColorButton(form,component)\n{\n var codegen=form.Code;\n //var cmpName=component.Item(\"Name\");\n \n CheckComponent(form, component);\n\n var headerStr=codegen.Format(component,\"\\tCColorButton\\t[!Name];\\n\"); \n headerStr+=MakeContainedDecl(form,component);\n headerStr+=MakeFontDeclaration(component);\n\n var sourceStr=codegen.Format(component,\"\\t[!Name].Create([!ParentName],\"); \n sourceStr+=MakeRect(component)+\",\";\n sourceStr+=MakeLocalizedCString(component.Item(\"Caption\"),component)+\",\"+\n MakeWindowStyle(component)+\"|BS_OWNERDRAW,\"+\n MakeExWindowStyle(component)+\",\"+\n component.Item(\"ID\")+\");\\n\"; \n sourceStr+=MakeControlFont(component); \n sourceStr+=MakeToolTip(component); \n sourceStr+=\"\\n\";\n\n MakeSetFocus(form,component); \n MakeContained(form,component);\n\n codegen.Insert(endMemberDecl,headerStr);\n codegen.Insert(endMemberCreation,sourceStr);\n codegen.Insert(endCtrlIDDecl,MakeControlID(component));\n}", "draw_buttons(){\n for(let item in build){\n if(build[item].button !== false && (resources.all_available(build[item].button) || utilities.state_get('buttons').includes(item))){\n // we have met the available resource requirements\n console.log(`Build button: ${build[item].title}`);\n // work out the cost for the tooltip\n let cost = '';\n for(let resource in build[item].cost){\n let amount = build[item].cost[resource]\n cost += `${resource}: ${amount} `;\n }\n let tile = `Build on: ${build[item].requires_tile}`;\n if(build[item].requires_tile === false){\n tile = '';\n }\n // create the button code\n $('#build_buttons').append(\n `<a href=\"#\" id=\"build_${item}\" class=\"list-group-item list-group-item-action disabled\">\n <div class=\"d-flex w-100 justify-content-between\">\n <h5><i class=\"${build[item].icon}\"></i> &nbsp; ${build[item].title}</h5>\n <small>Cost: ${cost}\n </small>\n </div>\n <div class=\"d-flex w-100 justify-content-between\">\n ${build[item].desc}\n <small>${tile}</small>\n </div>\n </a>`\n );\n build[item].button = false; // dont build a second button\n utilities.state_append_unique('buttons', item); // we've unlocked it, keep it unlocked if we die\n actions.attach();\n }\n };\n }", "function createButton(clsName,btntype,btnid,btnparrent,slug){\n const button = document.createElement(\"button\")\n //button.className = \"close\"\n button.className = clsName\n button.type = btntype\n button.id = btnid\n button.innerHTML = btnid\n button.addEventListener(\"click\",(e) => {\n e.preventDefault()\n let country = slug\n let status = btnid\n let url = \"https://api.covid19api.com/dayone/country/\" + country + \"/status/\" + status\n console.log(url)\n getval(url).then(values => {renderChart(values,\"canvas2\")})\n })\n btnparrent.appendChild(button)\n}", "function SetBuildChoice(btnObj : GameObject)\n{\n\t//when the buttons are clicked, they send along thier GameObject as a parameter, which is caught by \"btnObj\" above\n\t//we then use that btnObj variable, and get it's name, so we can easily check exactly which button was pressed\n\tvar btnName : String = btnObj.name;\n\t\n\t//here, we set an \"index\" based on which button was pressed\n\t//by doing this, we can easily tell, from anywhere in the script, which structure is currently selected\n\t//also, if we order things just right, we can use this \"index\" to reference the correct array items automatically!\n\tif(btnName == \"Btn_Cannon\")\n\t{\n\t\tstructureIndex = 0;\n\t}\n\telse if(btnName == \"Btn_Missile\")\n\t{\n\t\tstructureIndex = 1;\n\t}\n\telse if(btnName == \"Btn_Mine\")\n\t{\n\t\tstructureIndex = 2;\n\t}\n\t\n\t//call this as a seperate function so that, as things get more complicated,\n\t//all GUI can be updated at once, in the same way\n\tUpdateGUI();\n}", "function buildButton( control, columnIndex ){\n return $( '<div/>' ).addClass( BUTTON_CLASS ).text( control.label );\n }", "function createToolBtn(obj) {\n var btn = $('<button/>', {\n title: obj.title,\n name: obj.name,\n text: obj.text\n }).addClass(obj.classes);\n return btn;\n }", "function ShowTextButton(strFirst : String , strMiddle : String , strLast : String , strButton , obj : GameObject , funcName : String){\n//\tlabelTextButtonFirst.text = strFirst;\n//\tlabelTextButtonMiddle.text = strMiddle;\n//\tlabelTextButtonLast.text = strLast;\n\tlabelTextButton.text = strButton;\n\tptimeTextButton = Time.time + 8;\n//\tobjTextButton.SetActiveRecursively(true);\n\t//spriteBezelTextButton.enabled = false;\n\tboolTextButton = true;\n\tobjReturnButton = obj;\n\tobjFunctionName = funcName;\n}", "static get BUTTON_B() {\n return \"b\";\n }", "function createButtons() {\n\n // Load control button template\n Ractive.load('templates/buttons.html').then(function (buttonControl) {\n\n buttonsControl = new buttonControl({\n el: 'buttonControl',\n data: {\n controlButton: updateButtons\n }\n });\n\n // Added listener to update progress bar value\n buttonsControl.on('upadateBar', function (event) {\n var selectedbar = selectControls.find(\"#selectProgress\").value;\n var valueUpdate = parseInt(this.get(event.keypath));\n updateProgressBar(selectedbar, valueUpdate,limit);\n });\n\n });\n}", "function addButtonEvent() {\n\t\t\tbtnList.begin.click(API.begin);\n\t\t\tbtnList.fastBackward.click(function () {API.backward(FAST_STEP_NUM); });\n\t\t\tbtnList.backward.click(function () {API.backward(1); });\n\t\t\tbtnList.forward.click(function () {API.forward(1); });\n\t\t\tbtnList.fastForward.click(function () {API.forward(FAST_STEP_NUM); });\n\t\t\tbtnList.end.click(API.end);\n\t\t\tbtnList.flag.click(API.flag);\n\t\t\tbtnList.auto.click(API.setAuto);\n\t\t}", "function Buttons({page, thing, generate}) {\n\n return (\n // As a player, I want to see a generate button and home button on to eat/to drink/to do pages\n <div className='btnBox'>\n {/* As a player, I want to click on generate button and see a new to eat/to drink/to do suggestion */}\n <button onClick={generate}>\n <Link to={page}>Generate a new {thing}</Link>\n </button>\n {/* As a player, I want to click on the home button and go back to the home page */}\n <button>\n <Link to={'/'}>Home</Link>\n </button>\n </div>\n );\n}", "function create_basic_button_alias(prettyName, objectName, functionName, functionLabel) {\n mcCreateBlocklyBlock({\n \"type\": objectName + \"_constructor\",\n \"colour\": \"%{BKY_LOGIC_HUE}\",\n \"fields\": [\n {\n \"name\": objectName + \"_variable\",\n \"label\": \"Set \" + prettyName + \" \",\n \"type\": \"object_dropdown\",\n \"object\": objectName, //Used with object_dropdown (required if object_dropdown)\n },\n {\n \"name\": objectName + \"_number\",\n \"label\": \" to \",\n \"type\": \"dropdown\",\n \"options\": [\n [\"1\", \"1\"],\n [\"2\", \"2\"],\n [\"3\", \"3\"],\n [\"4\", \"4\"],\n [\"5\", \"5\"],\n [\"6\", \"6\"],\n [\"7\", \"7\"],\n [\"8\", \"8\"],\n [\"9\", \"9\"],\n [\"10\", \"10\"],\n ],\n }\n ],\n \"generator\": \"try:\\n\" +\n \" {{\" + objectName + \"_variable}}\\n\" +\n \" ___exists = True\\n\" +\n \"except NameError:\\n\" +\n \" ___exists = False\\n\" +\n \"if ___exists == False or not isinstance({{\" + objectName + \"_variable}}, Button):\\n\" +\n \" {{\" + objectName + \"_variable}} = Button({{\" + objectName + \"_number}})\\n\" +\n \"del ___exists\\n\"\n });\n\n mcCreateBlocklyBlock({\n \"type\": objectName + \"_\" + functionName,\n \"colour\": \"%{BKY_LOGIC_HUE}\",\n \"fields\": [\n {\n \"name\": objectName + \"_variable\",\n \"label\": prettyName + \" \",\n \"type\": \"object_dropdown\",\n \"object\": objectName, //Used with object_dropdown (required if object_dropdown)\n },\n {\n \"name\": objectName + \"_\" + functionName + \"_callback\",\n \"label\": functionLabel,\n \"type\": \"function_dropdown\",\n },\n\n ],\n \"generator\": \"try:\\n\" +\n \" {{\" + objectName + \"_variable}}\\n\" +\n \" ___exists = True\\n\" +\n \"except NameError:\\n\" +\n \" ___exists = False\\n\" +\n \"try:\\n\" +\n \" {{\" + objectName + \"_\" + functionName + \"_callback}}\\n\" +\n \" ___cb_exists = True\\n\" +\n \"except NameError:\\n\" +\n \" ___cb_exists = False\\n\" +\n \"if ___exists and isinstance({{\" + objectName + \"_variable}}, Button) and ___cb_exists:\\n\" +\n \" {{\" + objectName + \"_variable}}.on_press({{\" + objectName + \"_\" + functionName + \"_callback}})\\n\" +\n \"del ___exists\\n\"\n });\n\n mcCreateBlocklyBlock({\n \"type\": objectName + \"_read\",\n \"colour\": \"%{BKY_LOGIC_HUE}\",\n \"output\": \"Number\",\n \"fields\": [\n {\n \"name\": objectName + \"_variable\",\n \"label\": prettyName + \" %1 digital read\",\n \"type\": \"object_dropdown\",\n \"object\": objectName, //Used with object_dropdown (required if object_dropdown)\n }\n ],\n \"generator\": \"({{\" + objectName + \"_variable}}.read() if ('{{\" + objectName + \"_variable}}' in globals() and isinstance({{\" + objectName + \"_variable}}, Button)) else 0)\"\n });\n}", "function commandButtons()\n{\n\t// find the index of the current recordset in MM.rsTypes\n\t//rsIndex = recordsetDialog.searchByType(RECORDSET_TYPE);\n\t\n\tbtnArray = new Array(\n\t\tMM.BTN_OK, \"clickedOK()\", \n MM.BTN_Cancel, \"clickedCancel()\", \n MM.BTN_Test, \"PopUpTestDialog()\");\n\t// add a button for each different rs type\n\tfor (i = 0;i < MM.rsTypes.length;i++) {\n\t\tif(MM.rsTypes[i].single == \"true\") {\n\t\t\tcontinue;\n\t\t}\n \tif (dw.getDocumentDOM().serverModel.getServerName() == MM.rsTypes[i].serverModel) {\n \t\tif (RECORDSET_TYPE.toLowerCase() != MM.rsTypes[i].type.toLowerCase()) {\n\t\t\t\tvar btnLabel = dw.loadString(\"recordsetType/\" + MM.rsTypes[i].type);\n\t\t\t\tif (!btnLabel)\n\t\t\t\t\tbtnLabel = MM.rsTypes[i].type;\n\t\t\t\tbtnArray.push(btnLabel+\"...\");\n\t\t\t\tbtnArray.push(\"clickedChange(\" + i + \")\");\n\t\t\t}\n\t\t}\n\t}\n\tbtnArray.push(MM.BTN_Help);\n\tbtnArray.push(\"displayHelp()\"); \n\treturn btnArray;\n}", "function button.crystal1() {\r\n\t// body...\r\n}", "function tambah() {\n var operasi_tambah = new button(\"+\");\n}", "static get BUTTON_X() {\n return \"x\";\n }", "function addExtraButtons () {\n\tmw.toolbar.addButtons(\n\t{\n\t\t'imageId': 'button-redirect',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_redirect.png', \n\t\t'speedTip': 'Redirect',\n\t\t'tagOpen': '#REDIRECT[[',\n\t\t'tagClose': ']]',\n\t\t'sampleText': 'Target page name'\n\t},\n\t{\n\t\t'imageId': 'button-strike',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_strike.png', \n\t\t'speedTip': 'Strike',\n\t\t'tagOpen': '<s>',\n\t\t'tagClose': '</s>',\n\t\t'sampleText': 'Strike-through text'\n\t},\n\t{\n\t\t'imageId': 'button-enter',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_enter.png', \n\t\t'speedTip': 'Line break',\n\t\t'tagOpen': '<br/>',\n\t\t'tagClose': '',\n\t\t'sampleText': ''\n\t}, \n\t\t'imageId': 'button-hide-comment',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_hide_comment.png', \n\t\t'speedTip': 'Insert hidden Comment',\n\t\t'tagOpen': '<!-- ',\n\t\t'tagClose': ' -->',\n\t\t'sampleText': 'Comment'\n\t}, \n\t{\n\t\t'imageId': 'button-blockquote',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_blockquote.png',\n\t\t'speedTip': 'Insert block of quoted text',\n\t\t'tagOpen': '<blockquote>\\n',\n\t\t'tagClose': '\\n</blockquote>',\n\t\t'sampleText': 'Block quote'\n\t},\n\t{\n\t\t'imageId': 'button-insert-table',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_insert_table.png',\n\t\t'speedTip': 'Insert a table',\n\t\t'tagOpen': '{| class=\"wikitable\"\\n|',\n\t\t'tagClose': '\\n|}',\n\t\t'sampleText': '-\\n! header 1\\n! header 2\\n! header 3\\n|-\\n| row 1, cell 1\\n| row 1, cell 2\\n| row 1, cell 3\\n|-\\n| row 2, cell 1\\n| row 2, cell 2\\n| row 2, cell 3'\n\t},\n\t{\n\t\t'imageId': 'button-insert-reflink',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_reflink.png',\n\t\t'speedTip': 'Insert a reference',\n\t\t'tagOpen': '<ref>',\n\t\t'tagClose': '</ref>',\n\t\t'sampleText': 'Insert footnote text here'\n\t}\n\t);\n}", "function markButton(event){\n// $(\"#qwerty button\").on(\"click\", (event) => {\nevent.target.disabled = true;\nevent.target.classList.add (\"chosen\")\n// if (event.target.tagName === \"BUTTON\")\napp.handleInteraction(event.target.innerHTML.toLowerCase());\n}", "function generate() {\n // Generate 'Hot' Button\n $(\"#mustafar-btn\").empty();\n var nextHotBtn = $(\"<button>\");\n nextHotBtn.addClass('waves-effect waves-light btn-large mustafar-btn')\n nextHotBtn.attr(\"data-Hvalue\", person);\n nextHotBtn.text(\"MUSTAFAR\");\n $(\"#mustafar-btn\").html(nextHotBtn); \n\n // Generate 'Cold' Button\n $(\"#hoth-btn\").empty();\n var nextColdBtn = $(\"<button>\");\n nextColdBtn.addClass('waves-effect waves-light btn-large hoth-btn ')\n nextColdBtn.attr(\"data-Cvalue\", person);\n nextColdBtn.text(\"HOTH\");\n $(\"#hoth-btn\").html(nextColdBtn); \n\n // Function to deliver images and character info\n getImage(person); \n charInfo(person); \n}", "function boton1() {\n var x = document.createElement(\"BUTTON\");\n var t = document.createTextNode(\"Nothing\");\n x.appendChild(t);\n EJERCICIO2.appendChild(x);\n}", "static get tag() {\n return \"lrn-button\";\n }", "prop_new_collision_body(editor) {\n editor.el.newCollisionBody = new Components.button.Basic({\n label: 'New Collision Body',\n parent: editor,\n onclick: () => {\n Components.notification.Close();\n\n Components.notification.Create({\n label: 'Select the kind of body',\n pause: true,\n components: [{\n component: 'select',\n label: 'Kind:',\n data: this.collision_kind_data(),\n onchange: (current) => {\n $.temp.kind = current.kind;\n }\n },\n {\n component: 'text',\n placeholder: 'Set the name of your collision body',\n label: 'Name ID:',\n onchange: (value, element) => {\n value = this.to_id(value);\n element.set(value);\n $.temp.name = value;\n }\n },\n {\n component: 'button',\n label: 'Create',\n editor: this,\n class: 'btn-white',\n onclick: function () {\n //this.setup.editor.new_collision_body_option(this.setup.editor.editor)\n $.temp.kind = $.temp.kind || 'circle';\n // if ($.temp.kind === 'circle') {\n // this.setup.editor.new_collision_body_circle(this.setup.editor.editor)\n // } else if ($.temp.kind === 'rect') {\n // this.setup.editor.new_collision_body_rect(this.setup.editor.editor)\n // }\n this.setup.editor.new_collision_body_option(this.setup.editor.editor)\n //\n this._popup.destroy(true)\n }\n },\n {\n component: 'button',\n label: 'Return',\n class: 'btn-white',\n onclick: function () {\n this._popup.destroy(true)\n }\n }\n ]\n })\n }\n })\n }", "function addMainControlButton(){\n (tdpersonnalised.controleUniqueButton)?addMainButonsUnique():addMainButonsMultiple();\n }", "get codeButton() {\n return {\n command: \"wrapRange\",\n commandVal: \"CODE\",\n toggles: true,\n label: \"Code\",\n type: \"rich-text-editor-button\",\n };\n }", "function Window_PDButtonCommand() {\n this.initialize.apply(this, arguments);\n}", "static get tag(){return\"rich-text-editor-button\"}", "get appBtn () { return $(\"~App\")}", "function generateBtns() {\n for (i = 0; i < selectionsKeys.length; i++) {\n var btn = document.createElement('button')\n btn.type = 'button'\n btn.id = selectionsKeys[i]\n btn.innerText = selectionsKeys[i]\n btn.className = 'btn'\n btnWrapper.appendChild(btn)\n }\n}", "function new_toogle_button(classButton, textButton){\n\nreturn \"<span class=\\\"padding\\\" style=\\\"cursor:pointer;\\\" onclick=\\\"\"+classButton+\"()\\\" >&nbsp;&nbsp;&nbsp;&nbsp;\"+textButton+\"&nbsp;<img src=\\\"/pics/sort_btn_gray_on.gif\\\" class=\\\"\"+classButton+\"\\\"/></span>\";\n}", "_htmlForSiGMLPlayButtons(surl, stext) {\nvar bstext, bstop, bsurl, gap, html, sep;\nif (typeof lggr.debug === \"function\") {\nlggr.debug(`HTMLForAvatarGUI: PlayButtons: URL=${surl}, Text=${stext}`);\n}\nbstop = `<input type=\\\"button\\\" value=\\\"Stop\\\" class=\\\"bttnStop av${this.ix}\\\" />`;\nbsurl = !surl ? \"\" : \"<input type=\\\"button\\\" value=\\\"Play SiGML URL\\\" \" + `class=\\\"bttnPlaySiGMLURL av${this.ix}\\\" />`;\nbstext = !stext ? \"\" : \"<input type=\\\"button\\\" value=\\\"Play SiGML Text\\\" \" + `class=\\\"bttnPlaySiGMLText av${this.ix}\\\" />`;\nsep = \"\";\ngap = \"\";\nif (bsurl.length !== 0 && bstext.length !== 0) {\nsep = \"\\n\";\ngap = \"&nbsp;\";\n}\nreturn html = !surl && !stext ? \"\" : `<span class=\"spanSiGMLCtrlA av${this.ix}\" >\n<!--input type=\"button\" value=\"Play CAS\" class=\"bttnPlayCAS av${this.ix}\" /-->\n${bsurl}${sep}${bstext}\n${gap}\n${bstop}\n</span> <!--class=\"spanSiGMLCtrlA av${this.ix}\"-->`;\n}", "function makeButton(backgroundImage, title, type) {\n var button = L.DomUtil.create(\"a\", \"leaflet-control-view-\" + type);\n button.title = title;\n button.href = \"#\";\n button.setAttribute(\"role\", \"button\");\n button.setAttribute(\"aria-label\", title);\n button.style.backgroundImage = \"url(\" + backgroundImage + \")\";\n button.style.backgroundSize = \"contain\";\n\n return button;\n }", "function createButtons() {\n\t\tvar buttonHTML = '<input id=\"CustomNextButton\" class=\"FakeButton Button\" title=\"→\" ' \n\t\t+ 'type=\"button\" name=\"CustomNextButton\" value=\"→\" aria-label=\"Next\">'\n\t\t+ '<input id=\"ShowAnswerButton\" style = \"display:none\" class=\"FakeButton Button\" title=\"Show Answer\" ' \n\t\t+ 'type=\"button\" name=\"ShowAnswerButton\" value=\"Show Answer\" aria-label=\"Show Answer\">'\n\t\t+ '<style>.Total {display: none !important;}</style>';\n\t\tjQuery('#showbuttons').append(buttonHTML);\n\t}", "initButtons() {\n this.setupButton(\"efecBtn\", (e) => {\n\n })\n\n }", "function InsertButtonsToToolBar()\n{\n//Strike-Out Button\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/en/c/c9/Button_strike.png\",\n \"speedTip\": \"Strike\",\n \"tagOpen\": \"<s>\",\n \"tagClose\": \"</s>\",\n \"sampleText\": \"Strike-through text\"}\n//Line break button\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/en/1/13/Button_enter.png\",\n \"speedTip\": \"Line break\",\n \"tagOpen\": \"<br />\",\n \"tagClose\": \"\",\n \"sampleText\": \"\"}\n//Superscript\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/en/8/80/Button_upper_letter.png\",\n \"speedTip\": \"Superscript\",\n \"tagOpen\": \"<sup>\",\n \"tagClose\": \"</sup>\",\n \"sampleText\": \"Superscript text\"}\n//Subscript\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/en/7/70/Button_lower_letter.png\",\n \"speedTip\": \"Subscript\",\n \"tagOpen\": \"<sub>\",\n \"tagClose\": \"</sub>\",\n \"sampleText\": \"Subscript text\"}\n//Small Text\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/en/5/58/Button_small.png\",\n \"speedTip\": \"Small\",\n \"tagOpen\": \"<small>\",\n \"tagClose\": \"</small>\",\n \"sampleText\": \"Small Text\"}\n//Comment\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/en/3/34/Button_hide_comment.png\",\n \"speedTip\": \"Insert hidden Comment\",\n \"tagOpen\": \"<!-- \",\n \"tagClose\": \" -->\",\n \"sampleText\": \"Comment\"}\n//Gallery\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/en/1/12/Button_gallery.png\",\n \"speedTip\": \"Insert a picture gallery\",\n \"tagOpen\": \"\\n<gallery>\\n\",\n \"tagClose\": \"\\n</gallery>\",\n \"sampleText\": \"Image:Example.jpg|Caption1\\nImage:Example.jpg|Caption2\"}\n//Block Quote\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/en/f/fd/Button_blockquote.png\",\n \"speedTip\": \"Insert block of quoted text\",\n \"tagOpen\": \"<blockquote>\\n\",\n \"tagClose\": \"\\n</blockquote>\",\n \"sampleText\": \"Block quote\"}\n// Table\nmwCustomEditButtons[mwCustomEditButtons.length] = {\n \"imageFile\": \"http://upload.wikimedia.org/wikipedia/commons/0/04/Button_array.png\",\n \"speedTip\": \"Insert a table\",\n \"tagOpen\": '{| class=\"wikitable\"\\n|-\\n',\n \"tagClose\": \"\\n|}\",\n \"sampleText\": \"! header 1\\n! header 2\\n! header 3\\n|-\\n| row 1, cell 1\\n| row 1, cell 2\\n| row 1, cell 3\\n|-\\n| row 2, cell 1\\n| row 2, cell 2\\n| row 2, cell 3\"}\n}", "handleJDotterClick() {}", "function makeButt ( bopts ) {\n \"use strict\"; \n var stytxt = \"style='width:\" + bopts.width + \";font-family:\" + bopts.fontFamily + \";font-style:\" + bopts.fontStyle + \";background-color:\" + bopts.bgColor + \";height:\" + bopts.height + \";font-size:\" + bopts.fontSize + \";'\";\n return \"<input type='button' value='\"+bopts.text+\"' \"+stytxt+\" id='\"+bopts.idtext+\"'>\";\n}", "makeButtonHandler() {\n\t\tconst filter = (interaction) => true;\n\n\t\tvar collector = this.globalScrollUpdateMessage.createMessageComponentCollector({filter, time: 120000})\n\n\t\tcollector.on(\"collect\", interaction => {\n\t\t\tconsole.log(interaction);\n\n\t\t\tif(interaction.customId == \"next\") {\n\t\t\t\tinteraction.update(this.getOffsetGlobalScrollIndex(1))\n\t\t\t} else if (interaction.customId == \"back\") {\n\t\t\t\tinteraction.update(this.getOffsetGlobalScrollIndex(-1));\n\t\t\t}\n\t\t})\n\t\n\t}", "static generate() {\n try {\n HelpGenerator.buttons = []; // Empty existing buttons for LiveReload\n Object.entries(HelpGenerator.docs).map( page => {\n // Generate embed\n const embed = new MessageEmbed()\n .setAuthor(\"Predictions • Help\", HelpGenerator.avatar_url)\n .setTitle(`${page[1]['emoji']} ${page[0]}`)\n .setDescription(page[1][\"description\"]);\n \n page[1][\"fields\"].map( field => {\n embed.addField(field[\"title\"], field[\"content\"]);\n });\n\n // Generate button\n const button = {\n button: new MessageButton()\n .setCustomId(`help_${page[1][\"id\"]}`)\n .setEmoji(page[1]['emoji'])\n .setLabel(page[0])\n .setStyle(page[1]['style']),\n \n /**\n * \n * @param {ButtonInteraction} interaction \n */\n async execute(interaction) {\n // Find out identity of button\n const page_id = interaction.customId.slice(5);\n\n // Disable current button\n const row = HelpGenerator.getRow();\n row.components.filter( button => button.customId == interaction.customId )[0].setDisabled(true);\n\n interaction.update({ embeds: [HelpGenerator.embeds[page_id]], components: [row] });\n }\n }\n\n HelpGenerator.embeds[page[1][\"id\"]] = embed;\n HelpGenerator.buttons.push(button)\n })\n } catch (e) {\n console.error(`[HelpGenerator] ${e}`);\n }\n }", "function initCommandButton(){\n var btn=$('.cmd-btn');\n var input=$('.cmd-input');\n var msg_box=$('.msg-box-tem');\n var funcs={\n \"edit\":()=>{\n var sw=switches.editable[0];\n var btn=$('#btn-editable');\n show(btn);\n sw.easyTurnOn();\n return true;\n },\n \"exit\":()=>{\n var sw=switches.editable[0];\n sw.easyTurnOff();\n return true;\n },\n \"mode\":(param)=>{\n if(param=='close'){\n fman.closeMode();\n return true;\n }\n else if(param=='dark'){\n fman.setMode('mode-dark');\n return true;\n }\n return false;\n },\n \"#\":(param)=>{\n location.href=\"#\" + param;\n }\n }\n new Commander(input,btn,funcs,msg_box);\n}", "function handleTool(event){\n // Don't change the button until the user hasn't finished his draw\n if(g['shape'].open || g['active_tool']){\n user_help('close_draw');\n return;\n }\n var target = cross_target(event);\n // take the element type from attributes of the buttons\n var el = target.getAttribute('value');\n var el = target.getAttribute('value').toLowerCase();\n if(el=='<'){\n g['pages'].down();\n return;\n }\n if(el=='>'){\n g['pages'].up();\n return;\n }\n if(el=='clear'){\n g['pages'].clear();\n sender_add('clear');\n return;\n }\n // Clicking on the 'path' button switches between single path and\n // multipath\n if(el == 'path'){\n if(g['tool'] == 'path')\n g['tool'] = 'multipath';\n else\n g['tool'] = 'path';\n }\n else\n g['tool'] = el;\n\n // Unselect the old pressed button if necessary\n if (g['pressedButton'])\n g['pressedButton'].className = 'draw_button';\n // Highlight the new pressed button. The 'multipath' case has a\n // special style\n g['pressedButton'] = getById(target.id);\n if(g['tool']=='multipath')\n g['pressedButton'].className = 'draw_button_special';\n else\n g['pressedButton'].className = 'draw_button_pushed';\n\n show_additional_panel(g['tool']);\n // Set the new shape, if one\n g['shape'] = g['shape_generator'].generate_shape(g['tool']);\n // Show a short tip about the current tool\n user_help(g['tool']);\n // Sometimes the canvas offsets could be outdated due to little\n // recenterings of the whiteboard. This is an additional\n // (redundant) measure to make sure that canvas offsets are fine\n // before starting to draw\n update_canvas_offsets();\n}", "function buildButton(code) {\n\n var btn = document.createElement(\"button\");\n btn.className = \"tb-btn\";\n btn.type = \"button\";\n btn.style.fontFamily = \"FontAwesome\";\n btn.style.fontStyle = \"normal\";\n btn.style.fontWeight = \"normal\";\n btn.style.fontVariant = \"normal\";\n btn.style.lineHeight = 1;\n btn.innerHTML = '&#xf1c5';\n\n var existing = document.querySelector(\"button.tb-btn.img-btn\");\n existing.parentElement.insertBefore(btn, existing.nextSibling);\n\n return btn;\n }", "function button() {\n\n\t\tvar eventListeners = {\n\t\t\t\"pressed\": []\n\t\t};\n\t\tvar on = function(eventType, callback) {\n\t\t\teventListeners[eventType].push(callback);\n\t\t};\n\t\tvar trigger = function(eventType) {\n\t\t\teventListeners[eventType].forEach(function(callback) {\n\t\t\t\tcallback();\n\t\t\t});\n\t\t};\n\n\t\tvar enabled = true;\n\t\tvar enable = function() {\n\t\t\tenabled = true;\n\t\t\tdomElement.classList.add(\"enabled\");\n\t\t};\n\t\tvar disable = function() {\n\t\t\tenabled = false;\n\t\t\tdomElement.classList.remove(\"enabled\");\n\t\t};\n\n\t\tvar onDomClick = function() {\n\t\t\tif (enabled) {\n\t\t\t\ttrigger(\"pressed\");\n\t\t\t}\n\t\t};\n\n\t\tvar domElement = (function() {\n\t\t\tvar button = document.createElement(\"button\");\n\t\t\tvar text = document.createTextNode(\"Button\");\n\t\t\tbutton.appendChild(text);\n\t\t\tbutton.classList.add(\"enabled\");\n\t\t\tbutton.addEventListener(\"click\", onDomClick);\n\t\t\treturn button;\n\t\t})();\n\n\t\treturn {\n\t\t\ton: on,\n\t\t\tenable: enable,\n\t\t\tdisable: disable,\n\t\t\tdomElement: domElement\n\t\t};\n\t}", "function createButton (action, name) {\n var button = document.createElement('button');\n button.innerHTML = name;\n button.setAttribute('id', action);\n document.getElementById('visualizer').appendChild(button);\n}", "function sayThings() {\n console.log(\"this button is clicked!\")\n}", "function addButtons() {\n\t\tcreateButton(\"Outdent\");\n\t\tcreateButton(\"Indent\");\n\t}", "function rebuild_track_btn(){\n $(\".main-grid-container\").prepend('<div class=\"createTrackBtns\">Rebuild Tracking Buttons|v'+window.version+'</div>');\n $(\".createTrackBtns\").click(function(){\n $('.main-grid-cell-content span.main-grid-plus-button').click();\n $('.trackBtn, .actionBtn').remove();\n buildTracker();\n }); \n }", "function buildBtn(array) {\n var template = ``;\n array.forEach(function(val, index, array) {\n template += `<a href=\"#rocket\"><div class=\"myButton\" data-name=\"${val}\">${val.toUpperCase()}</div></a>\n `;\n });\n $('#grid').append(template);\n // gets button array\n var buttonsArray = Array.from(document.getElementsByClassName('myButton'));\n // console.logs button array : html collection\n addListener(buttonsArray);\n}", "function buttonClick(e) {\n\n var editor = this,\n buttonDiv = e.target,\n buttonName = $.data(buttonDiv, BUTTON_NAME),\n button = buttons[buttonName],\n popupName = button.popupName,\n popup = popups[popupName];\n\n // Check if disabled\n if (editor.disabled || $(buttonDiv).attr(DISABLED) === DISABLED)\n return;\n\n // Fire the buttonClick event\n var data = {\n editor: editor,\n button: buttonDiv,\n buttonName: buttonName,\n popup: popup,\n popupName: popupName,\n command: button.command,\n useCSS: editor.options.useCSS\n };\n\n if (button.buttonClick && button.buttonClick(e, data) === false)\n return false;\n\n // Toggle source\n if (buttonName === \"source\") {\n \n // Show the iframe\n if (sourceMode(editor)) {\n delete editor.range;\n editor.$area.hide();\n editor.$frame.show();\n buttonDiv.title = button.title;\n }\n\n // Show the textarea\n else {\n editor.$frame.hide();\n editor.$area.show();\n\t\t\t\teditor.$main.find(\".cleditorSizing\").hide();\n buttonDiv.title = \"リッチテキストに切り替え\";//\"Show Rich Text\";\n }\n\n }\n\n // Check for rich text mode\n else if (!sourceMode(editor)) {\n\n // Handle popups\n if (popupName) {\n var $popup = $(popup),\n\t\t\t\t\tframeDocument=editor.$frame.contents(),\n\t\t\t\t\tframeBody=editor.$frame.contents().find(\"body\");\n\n // URL\n if (popupName === \"url\") {\n\n // Check for selection before showing the link url popup\n if (buttonName === \"link\" && selectedText(editor) === \"\") {\n showMessage(editor, \"A selection is required when inserting a link.\", buttonDiv);\n return false;\n }\n\n // Wire up the submit button click event handler\n $popup.children(\":button\")\n .off(CLICK)\n .on(CLICK, function () {\n\n // Insert the image or link if a url was entered\n var $text = $popup.find(\":text\"),\n url = $.trim($text.val());\n if (url !== \"\")\n execCommand(editor, data.command, url, null, data.button);\n\n // Reset the text, hide the popup and set focus\n $text.val(\"http://\");\n hidePopups();\n focus(editor);\n\n });\n\n }\n\n // Paste as Text\n else if (popupName === \"pastetext\") {\n\n // Wire up the submit button click event handler\n $popup.children(\":button\")\n .off(CLICK)\n .on(CLICK, function () {\n\n // Insert the unformatted text replacing new lines with break tags\n var $textarea = $popup.find(\"textarea\"),\n text = $textarea.val().replace(/\\n/g, \"<br />&#10;\");\n if (text !== \"\")\n execCommand(editor, data.command, text, null, data.button);\n\n // Reset the text, hide the popup and set focus\n $textarea.val(\"\");\n hidePopups();\n focus(editor);\n\n });\n\n }\n\n\t\t\t\t//insert textbox\n\t\t\t\telse if(buttonName === \"textbox\"){\n\n\t\t\t\t\t// Wire up the submit button click event handler\n $popup.children(\"div\")\n .off(CLICK)\n .on(CLICK, function (e) {\n\t\t\t\t\t\t// Build the html\n\t\t\t\t\t\tvar scrTop=$(frameBody).scrollTop(),\n\t\t\t\t\t\t\tvalue = $(e.target).css(\"background-color\"),\n\t\t\t\t\t\t\thtml = \"<textarea style='position:\"+editor.options.position+\";top:\"+scrTop\n\t\t\t\t\t\t\t\t\t+\"px;left:0px;width:100px;height:20px;background-color:\"\n\t\t\t\t\t\t\t\t\t+value+\";'></textarea>&#10;\";\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Insert the html\n\t\t\t\t\t\tif (html)\n\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\texecCommand(editor,data.command,html,null,data.button);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\thidePopups();\n focus(editor);\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t//insert table\n\t\t\t\telse if(buttonName === \"table\")\n\t\t\t\t{\t\n\t\t\t\t\t$popup.children(\":button\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK,function(e) {\n\n\t\t\t\t\t\t// Get the column and row count\n\t\t\t\t\t\tvar $text = $popup.find(\":text\"),\n\t\t\t\t\t\t\tcols = parseInt($text[0].value),\n\t\t\t\t\t\t\trows = parseInt($text[1].value);\n\n\t\t\t\t\t\t// Build the html\n\t\t\t\t\t\tvar html;\n\t\t\t\t\t\tif (cols > 0 && rows > 0) {\n\t\t\t\t\t\t\thtml=\"&#10;<table style='border-collapse:collapse;border:1px solid black;\"\n\t\t\t\t\t\t\t\t\t+\"background-color:white;position:\"+editor.options.position+\";top:0px;left:0px'>&#10;\";\n\t\t\t\t\t\t\tfor (y = 0; y < rows; y++) {\n\t\t\t\t\t\t\t\thtml += \"&#09;<tr>\";\n\t\t\t\t\t\t\t\tfor (x = 0; x < cols; x++)\n\t\t\t\t\t\t\t\t\thtml += \"<td style='border:1px solid black;min-width:30px;height:15px'></td>\";\n\t\t\t\t\t\t\t\thtml += \"</tr>&#10;\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\thtml += \"</table>&#10;<br />&#10;\";\n\t\t\t\t\t\t} \n\n\t\t\t\t\t\t// Insert the html\n\t\t\t\t\t\tif (html)\n\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\texecCommand(editor,data.command,html,null,data.button);\n\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Reset the text, hide the popup and set focus\n\t\t\t\t\t\t$text.val(\"4\");\n\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//insert rows and columns in table\n\t\t\t\telse if (buttonName === \"insertrowcol\")\n\t\t\t\t{\n\t\t\t\t\t$popup.children(\":button\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK,function(e) {\n\t\t\t\t\t\t\t// Get insert position\n\t\t\t\t\t\t\tvar $radi=$popup.find(\"input[name='insertFR']:checked\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Get the column and row count\n\t\t\t\t\t\t\tvar $text = $popup.find(\":text\"),\n\t\t\t\t\t\t\t\tcols = parseInt($text[0].value),\n\t\t\t\t\t\t\t\trows = parseInt($text[1].value);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//Click event\n\t\t\t\t\t\t\tif($(focusedObj).closest(\"table\").length==1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar html;\n\t\t\t\t\t\t\t\t//insert columns part\n\t\t\t\t\t\t\t\tif(cols>0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\thtml=$(\"<td style='\"+$(focusedObj).attr(\"style\")+\";min-width:2em'></td>\")\n\t\t\t\t\t\t\t\t\t\t.css({\"border-top\":objStyle.top,\"border-bottom\":objStyle.bottom,\n\t\t\t\t\t\t\t\t\t\t\t\t\"border-left\":objStyle.left,\"border-right\":objStyle.right});\n\t\t\t\t\t\t\t\t\t//Get current column index\n\t\t\t\t\t\t\t\t\tvar c=parseInt($(focusedObj).closest(\"tr\").children().index($(focusedObj)));\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t//loop each tr\n\t\t\t\t\t\t\t\t\tvar targetTable=$(focusedObj).closest(\"table\");\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t$(targetTable).find(\"tr\").each(function(idx,elem)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif($radi.val()===\"front\")\n\t\t\t\t\t\t\t\t\t\t{//front\n\t\t\t\t\t\t\t\t\t\t\t//insert columns\n\t\t\t\t\t\t\t\t\t\t\tfor(var i=0;i<cols;i++)\n\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\t\t\t\t\t\t$(elem).find(\"td:nth-child(\"+(1+c)+\")\").before(html[0].outerHTML);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t{//rear\n\t\t\t\t\t\t\t\t\t\t\t//insert columns\n\t\t\t\t\t\t\t\t\t\t\tfor(var i=0;i<cols;i++)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t$(elem).find(\"td:nth-child(\"+(1+c)+\")\").after(html[0].outeHTML);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\t\t});\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//insert rows part\n\t\t\t\t\t\t\t\tif(rows>0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//Get current row\n\t\t\t\t\t\t\t\t\tvar thisTr=$(focusedObj).closest(\"tr\");\n\t\t\t\t\t\t\t\t\tvar r=parseInt($(thisTr).closest(\"table\").find(\"tr\").index());\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t//Get column number\n\t\t\t\t\t\t\t\t\tvar cs=$(thisTr).find(\"td\").length;\n\t\t\t\t\t\t\t\t\thtml=\"&#09;<tr style='\"+$(thisTr).attr(\"style\")+\"'>\";\n\t\t\t\t\t\t\t\t\t$(thisTr).find(\"td\").each(function(idx,elem)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\thtml+=$(\"<td style='\"+$(elem).attr(\"style\")+\";min-height:1em'></td>\")\n\t\t\t\t\t\t\t\t\t\t\t.css({\"border-top\":objStyle.top,\"border-bottom\":objStyle.bottom,\n\t\t\t\t\t\t\t\t\t\t\t\t\"border-left\":objStyle.left,\"border-right\":objStyle.right})[0].outerHTML;\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\thtml+=\"</tr>&#10;\";\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif($radi.val()===\"front\")\n\t\t\t\t\t\t\t\t\t{//front\n\t\t\t\t\t\t\t\t\t\t//insert columns\n\t\t\t\t\t\t\t\t\t\tfor(var i=0;i<rows;i++)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$(thisTr).before(html);\n\t\t\t\t\t\t\t\t\t\t}\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{//rear\n\t\t\t\t\t\t\t\t\t\t//insert columns\n\t\t\t\t\t\t\t\t\t\tfor(var i=0;i<rows;i++)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t$(thisTr).after(html);\n\t\t\t\t\t\t\t\t\t\t}\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\teditor.updateTextArea();//update iframe\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//off event -- cancel when click except table (include td)\n\t\t\t\t\t\t\teditor.$frame.contents().off(CLICK);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Reset the text\n\t\t\t\t\t\t\t$text.val(\"0\");\n\t\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//resize cell\n\t\t\t\telse if (buttonName === \"resizecell\")\n\t\t\t\t{\n\t\t\t\t\t$popup.children(\":button\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK,function(e) {\n\t\t\t\t\t\t\t// Get the column and row count\n\t\t\t\t\t\t\tvar $text = $popup.find(\":text\"),\n\t\t\t\t\t\t\t\twid = parseInt($text[0].value),\n\t\t\t\t\t\t\t\thei = parseInt($text[1].value);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif($(focusedObj).is(\"td\"))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//change width size\n\t\t\t\t\t\t\t\tif(wid>0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"min-width\",wid+\"px\");\n\t\t\t\t\t\t\t\t\teditor.updateTextArea();//update iframe\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//change height size\n\t\t\t\t\t\t\t\tif(hei>0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"height\",hei+\"px\");\n\t\t\t\t\t\t\t\t\teditor.updateTextArea();//update iframe\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}\n\t\t\t\t\t\t\t//off event -- cancel when click except table (include td)\n\t\t\t\t\t\t\teditor.$frame.contents().off(\"click\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Reset the text\n\t\t\t\t\t\t\t$text.val(\"0\");\t\n\t\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t//border style\n\t\t\t\telse if (buttonName === \"borderstyle\")\n\t\t\t\t{\n\t\t\t\t\tvar borderColor,bdColor,bdImage,\n\t\t\t\t\t\tcurrentStyle=$(focusedObj).attr(\"style\"),\n\t\t\t\t\t\tcbs = $popup.find(\".appobj\");\n\t\t\t\t\t\t\n\t\t\t\t\t$popup.find(\".colorpicker\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK,function(e){\n\n\t\t\t\t\t\tvar rgbColor=$(e.target).css(\"background-color\")!=\"transparent\" ?\n\t\t\t\t\t\t\t\t\t\t$(e.target).css(\"background-color\") : \"0,0,0,0\";\n\t\t\t\t\t\tborderColor=$popup.find(\".bordersample\").css(\"border-color\");\n\t\t\t\t\t\tvar rgb=rgbColor.replace(\"rgb(\",\"\").replace(\"rgba(\",\"\").replace(\")\",\"\").split(\",\");\n\t\t\t\t\t\t\n\t\t\t\t\t\t$popup.find(\".rgbaColor.r\").val(parseInt(rgb[0]));\n\t\t\t\t\t\t$popup.find(\".rgbaColor.g\").val(parseInt(rgb[1]));\n\t\t\t\t\t\t$popup.find(\".rgbaColor.b\").val(parseInt(rgb[2]));\n\t\t\t\t\t\t$popup.find(\".rgbaColor.a\").val(rgb.length!=3 ? 0 : 1 );\n\t\t\t\t\t\tbdColor=\"rgba(\"+rgb[0]+\",\"+rgb[1]+\",\"+rgb[2]+\",\"+ (rgb.length!=3 ? 0 : 1)+\")\";\n\t\n\t\t\t\t\t\t$popup.find(\".samplecolor\").css(\"background-color\",bdColor);\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Get the which positions are change\n\t\t\t\t\t\tvar cb = $(popup).find(\"input[type=checkbox]\");\n\t\t\t\t\t\t\n\t\t\t\t\t\t//switch background color visibility by checkbox\n\t\t\t\t\t\tif($(cb[0]).prop(\"checked\")==true)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$(focusedObj).css(\"border-color\",bdColor);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$(focusedObj).css(\"border-color\",\"\");\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\t//drag and drop\n\t\t\t\t\tdndImage(\".sampleimage\",focusedObj,popup,buttonName);//sampleimage\n\t\t\t\t\t\n\t\t\t\t\t//on change RGBA number\n\t\t\t\t\t$popup.find(\".rgbaColor\")\n\t\t\t\t\t\t.on(\"change input paste\", function (e) {\n\t\t\t\t\t\t\tbdColor=\"rgba(\"+$popup.find(\".rgbaColor.r\").val()+\",\"+$popup.find(\".rgbaColor.g\").val()\n\t\t\t\t\t\t\t\t\t+\",\"+$popup.find(\".rgbaColor.b\").val()+\",\"+$popup.find(\".rgbaColor.a\").val()+\")\";\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t$popup.find(\".samplecolor\").css(\"background-color\",bdColor);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif($(cbs[0]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-color\",bdColor);\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t//on change Select tag\n\t\t\t\t\t$popup.find(\".border\")\n\t\t\t\t\t\t.on(\"change\",function(e){\n\t\t\t\t\t\t\t// Get the which positions are ON\n\t\t\t\t\t\t\tvar cb = $(popup).find(\"input[type=checkbox]\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//color\n\t\t\t\t\t\t\tfor(var i=0;i<4;i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif($(cbs[0]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-\"+$(cb[i]).val()+\"-style\",$(popup).find(\".border.Style\").val());\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-\"+$(cb[i]).val()+\"-width\",$(popup).find(\".border.Width\").val());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-\"+$(cb[i]).val()+\"-style\",\"\");\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-\"+$(cb[i]).val()+\"-width\",\"\");\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\n\t\t\t\t\t//on change Check Box \n\t\t\t\t\t$popup\n\t\t\t\t\t\t.on(\"change\",\"input[type=checkbox]\", function (e) {\n\t\t\t\t\t\t\t// Get the which positions are change\n\t\t\t\t\t\t\tvar cb=$popup.find(\"input[type=checkbox]\");\n\n\t\t\t\t\t\t\t//remove all border (or initilize)\n\t\t\t\t\t\t\tif($(cb[4]).prop(\"checked\")==true && e.target==cb[4])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$(cb).not(cb[4]).prop(\"checked\",false);\n\t\t\t\t\t\t\t\tif($(focusedObj).is(\"td\"))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border\",\"1px solid black\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border\",\"\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if(e.target!=cb[4] && $(e.target).prop(\"checked\")==true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$(cb[4]).prop(\"checked\",false);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//switch background color or image visibility by checkbox\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor(var i=0;i<4;i++){\n\t\t\t\t\t\t\t\t//color\n\t\t\t\t\t\t\t\tif($(cbs[0]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image\",\"\");\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-\"+$(cb[i]).val()+\"-color\",bdColor);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-\"+$(cb[i]).val()+\"-color\",\"\");\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//image\n\t\t\t\t\t\t\t\tif($(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-source\",\"url('\"+imageObj+\"')\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-source\",\"\");\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\n\t\t\t\t\t//on change check Box of image type \n\t\t\t\t\t$popup\n\t\t\t\t\t\t.on(\"change input\",\"input[type=radio],.imageOptions,.appobj\", function (e) {\n\t\t\t\t\t\t\tif($(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//check selection with URL or Gradient\n\t\t\t\t\t\t\t\tif($popup.find(\"input[type=radio]:checked\").val()==\"url\" \n\t\t\t\t\t\t\t\t\t&& $popup.find(\".sampleimage\").css(\"background-image\").indexOf(\"url(\")!=-1\n\t\t\t\t\t\t\t\t\t&& $(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{//URL\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image\",\"\");\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-source\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".sampleimage\").css(\"background-image\"));\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-slice\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='slice']\").val());\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-width\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='width']\").val());\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-outset\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='outset']\").val());\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-repeat\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='repeat']\").val());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if($(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{//Gradient\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-source\",\"\");\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image\",\n\t\t\t\t\t\t\t\t\t\t($popup.find(\".imageOptions[name='repeat']\").val()==\"repeat\" ?\n\t\t\t\t\t\t\t\t\t\t\t\"repeating-linear-gradient(\" : \"linear-gradient(\") +\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='angle']\").val() + \"deg,\" +\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='colors']\").val() +\")\");\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-slice\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='slice']\").val());\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-width\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='width']\").val());\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-outset\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='outset']\").val());\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"border-image-repeat\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='repeat']\").val());\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\t\n\t\t\t\t\t// Wire up the apply button click event handler\n\t\t\t\t\t$popup.children(\":button\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK, function (e) {\n\t\t\t\t\t\t\tif($(e.target).prop(\"class\")==\"apply\")\n\t\t\t\t\t\t\t{//apply\t\t\t\t\t\t\n\t\t\t\t\t\t\t\teditor.updateTextArea();//update iframe\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t//stack current style\n\t\t\t\t\t\t\t\tcurrentStyle=$(focusedObj).attr(\"style\")\n\t\t\t\t\t\t\t\t//stack the border style of target object\n\t\t\t\t\t\t\t\tobjStyle.top=$(focusedObj).css(\"border-top\");\n\t\t\t\t\t\t\t\tobjStyle.bottom=$(focusedObj).css(\"border-bottom\");\n\t\t\t\t\t\t\t\tobjStyle.left=$(focusedObj).css(\"border-left\");\n\t\t\t\t\t\t\t\tobjStyle.right=$(focusedObj).css(\"border-right\");\n\n\t\t\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if($(e.target).prop(\"class\")==\"cancel\")\n\t\t\t\t\t\t\t{//cancel\n\t\t\t\t\t\t\t\t//roll back\n\t\t\t\t\t\t\t\t$(focusedObj).attr(\"style\",currentStyle);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{//close\n\t\t\t\t\t\t\t\t//off event\n\t\t\t\t\t\t\t\t$(frameDocument).off(CLICK);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t//Changes background image and color\n\t\t\t\telse if (buttonName === \"background\")\n\t\t\t\t{\n\t\t\t\t\tvar imageObj,bgColor,\n\t\t\t\t\t\tcurrentBG=$(focusedObj).attr(\"style\"),\n\t\t\t\t\t\tcbs = $popup.find(\".appobj\");\t\n\t\t\t\t\t\n\t\t\t\t\t//Get clicked color code \n\t\t\t\t\t$popup.find(\".colorpicker\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK, function (e) {\n\n\t\t\t\t\t\t\t//Get the background-color from color picker\n\t\t\t\t\t\t\tvar rgbColor=$(e.target).css(\"background-color\")!=\"transparent\" ?\n\t\t\t\t\t\t\t\t\t\t\t$(e.target).css(\"background-color\") : \"0,0,0,0\";\n\t\t\t\t\t\t\tbgColor=$popup.find(\".samplecolor\").css(\"background-color\");\n\t\t\t\t\t\t\tvar rgb=rgbColor.replace(\"rgb(\",\"\").replace(\"rgba(\",\"\").replace(\")\",\"\").split(\",\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t$popup.find(\".rgbaColor.r\").val(parseInt(rgb[0]));\n\t\t\t\t\t\t\t$popup.find(\".rgbaColor.g\").val(parseInt(rgb[1]));\n\t\t\t\t\t\t\t$popup.find(\".rgbaColor.b\").val(parseInt(rgb[2]));\n\t\t\t\t\t\t\t$popup.find(\".rgbaColor.a\").val(rgb.length!=3 ? 0 : 1 );\n\t\t\t\t\t\t\tbgColor=\"rgba(\"+rgb[0]+\",\"+rgb[1]+\",\"+rgb[2]+\",\"+ (rgb.length!=3 ? 0 : 1)+\")\";\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t$popup.find(\".samplecolor\").css(\"background-color\",bgColor);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Get the which positions are change\n\t\t\t\t\t\t\tvar cb = $popup.find(\"input[type=checkbox]\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//switch background color visibility by checkbox\n\t\t\t\t\t\t\tif($(cb[0]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-color\",bgColor);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-color\",\"\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t//drag and drop\n\t\t\t\t\tdndImage(\".sampleimage\",focusedObj,$popup,buttonName);\n\t\t\t\t\t\n\t\t\t\t\t//on change RGBA number\n\t\t\t\t\t$popup.find(\".rgbaColor\")\n\t\t\t\t\t\t.on(\"change\", function (e) {\n\t\t\t\t\t\t\t\tbgColor=\"rgba(\"+$popup.find(\".rgbaColor.r\").val()+\",\"+$popup.find(\".rgbaColor.g\").val()\n\t\t\t\t\t\t\t\t\t\t+\",\"+$popup.find(\".rgbaColor.b\").val()+\",\"+$popup.find(\".rgbaColor.a\").val()+\")\";\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t$popup.find(\".samplecolor\").css(\"background-color\",bgColor);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\t//on change Check Box \n\t\t\t\t\t$popup\n\t\t\t\t\t\t.on(\"change\",\"input[type=checkbox]\", function (e) {\n\t\t\t\t\t\t\t\t// Get the which positions are change\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t//switch background color or image visibility by checkbox\n\t\t\t\t\t\t\t\tif($(cbs[0]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-color\",bgColor);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-color\",\"\");\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\tif($(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-image\",\"url('\"+imageObj+\"')\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-image\",\"\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\n\t\t\t\t\t//on change check Box of image type \n\t\t\t\t\t$popup\n\t\t\t\t\t\t.on(\"change input\",\"input[type=radio],.imageOptions,.appobj\", function (e) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar imageOptions=$popup.find(\".imageOptions[name='repeat']\");\t\n\t\t\t\t\t\t\t\t//check selection with URL or Gradient\n\t\t\t\t\t\t\t\tif($popup.find(\"input[type=radio]:checked\").val()==\"url\" \n\t\t\t\t\t\t\t\t\t&& $popup.find(\".sampleimage\").css(\"background-image\").indexOf(\"url(\")!=-1\n\t\t\t\t\t\t\t\t\t&& $(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{//url\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background\",\"\");\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-image\",\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".sampleimage\").css(\"background-image\"));\n\t\t\t\t\t\t\t\t\tif($(imageOptions).val()==\"cover\" || $(imageOptions).val()==\"contain\")\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-size\",\n\t\t\t\t\t\t\t\t\t\t\t$(imageOptions).val());\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-repeat\",\n\t\t\t\t\t\t\t\t\t\t\t$(imageOptions).val());\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\telse if($(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t{//gradient\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background-image\",\"\");\n\t\t\t\t\t\t\t\t\t$(focusedObj).css(\"background\",\n\t\t\t\t\t\t\t\t\t\t($popup.find(\".imageOptions[name='repeat']\").val()==\"repeat\" ?\n\t\t\t\t\t\t\t\t\t\t\t\"repeating-linear-gradient(\" : \"linear-gradient(\") +\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='angle']\").val() + \"deg,\" +\n\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='colors']\").val() +\")\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\n\t\t\t\t\t//Submit\n\t\t\t\t\t$popup.find(\"input[type='button']\") \n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK, function (e) {\n\t\t\t\t\t\t\tbgColor=\"rgba(\"+$popup.find(\".rgbaColor.r\").val()+\",\"+$popup.find(\".rgbaColor.g\").val()+\",\"\n\t\t\t\t\t\t\t\t\t+$popup.find(\".rgbaColor.b\").val()+\",\"+$popup.find(\".rgbaColor.a\").val()+\")\";\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//forced fire when button was 'Apply to body'\n\t\t\t\t\t\t\tif($(e.target).prop(\"class\")==\".apply\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//Apply the image to cell\n\t\t\t\t\t\t\t\tdrawBackground(focusedObj);\n\t\t\t\t\t\t\t\tcurrentBG=$(focusedObj).attr(\"style\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if($(e.target).prop(\"class\")==\".cancel\")\n\t\t\t\t\t\t\t{//cancelation\n\t\t\t\t\t\t\t\t$(focusedObj).attr(\"style\",currentBG);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//close\n\t\t\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//common draw procedure\n\t\t\t\t\t\t\tfunction drawBackground(target)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif($(target).is(\"td\") || $(target).is(\"hr\") || $(target).is(\"body\")\n\t\t\t\t\t\t\t\t|| $(target).is(\"img\") || $(target).is(\"textarea\") || $(target).is(\"input\"))\n\t\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\t\tif($(cbs[0]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t$(target).css(\"background\",\"\");\n\t\t\t\t\t\t\t\t\t\t$(target).css(\"background-color\",bgColor);\n\t\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tvar imageOptions=$popup.find(\".imageOptions[name='repeat']\");\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif($popup.find(\"input[type=radio]:checked\").val()==\"url\" \n\t\t\t\t\t\t\t\t\t\t&& $popup.find(\".sampleimage\").css(\"background-image\").indexOf(\"url(\")!=-1\n\t\t\t\t\t\t\t\t\t\t&& $(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t\t{//url\n\t\t\t\t\t\t\t\t\t\t$(target).css(\"background\",\"\");\n\t\t\t\t\t\t\t\t\t\t$(target).css(\"background-image\",\n\t\t\t\t\t\t\t\t\t\t\t$popup.find(\".sampleimage\").css(\"background-image\"));\n\t\t\t\t\t\t\t\t\t\tif($(imageOptions).val()==\"cover\" || $(imageOptions).val()==\"contain\")\n\t\t\t\t\t\t\t\t\t\t\t$(target).css(\"background-size\",$(imageOptions).val());\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t$(target).css(\"background-repeat\",$(imageOptions).val());\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if($(cbs[1]).prop(\"checked\")==true)\n\t\t\t\t\t\t\t\t\t{//gradient\n\t\t\t\t\t\t\t\t\t\t$(target).css(\"background-image\",\"\");\n\t\t\t\t\t\t\t\t\t\t$(target).css(\"background\",\n\t\t\t\t\t\t\t\t\t\t\t($popup.find(\".imageOptions[name='repeat']\").val()==\"repeat\" ?\n\t\t\t\t\t\t\t\t\t\t\t\t\"repeating-linear-gradient(\" : \"linear-gradient(\") +\n\t\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='angle']\").val() + \"deg,\" +\n\t\t\t\t\t\t\t\t\t\t\t$popup.find(\".imageOptions[name='colors']\").val() +\")\");\n\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\teditor.updateTextArea();//update iframe\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//off event -- cancel when click except table (include td)\n\t\t\t\t\t\t\t\t$(frameDocument).off(\"click\");\n\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}\n\t\t\t\t\n\t\t\t\t//rotation\n\t\t\t\telse if (buttonName === \"rotation\")\n\t\t\t\t{\n\t\t\t\t\tvar target=\"\",defX,defY,defD,defS,$tempObj=$(focusedObj);\n\t\t\t\t\tif($(focusedObj).is(\"body\"))\n\t\t\t\t\t{\n\t\t\t\t\t\talert(\"Please select object except body.\");\n\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t\t\tif($(focusedObj).is(\"td\") || $(focusedObj).is(\"th\"))\n\t\t\t\t\t\t\t$tempObj=$(focusedObj).closest(\"table\");\n\t\t\t\t\t\tif($tempObj.css(\"position\")==\"static\") $tempObj.css(\"position\",editor.options.position);\n\t\t\t\t\t\tvar tempPos= $tempObj.css(\"transform-origin\")!=undefined ? \n\t\t\t\t\t\t\t$tempObj.css(\"transform-origin\").split(\" \") : [0,0] ,\n\t\t\t\t\t\t\ttempD=$tempObj.css(\"transform\");\n\t\t\t\t\t\tdefX=parseInt(tempPos[0]);\n\t\t\t\t\t\tdefY=parseInt(tempPos[1]);\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar tempH=$tempObj.outerHeight(),\n\t\t\t\t\t\t\ttempW=$tempObj.outerWidth();\n\t\t\t\t\t\t$popup.find(\".XPosition:nth-child(\"+(parseInt(defX/tempW*2)+1)+\")\").prop(\"selected\",true);\n\t\t\t\t\t\t$popup.find(\".YPosition:nth-child(\"+(parseInt(defY/tempH*2)+1)+\")\").prop(\"selected\",true);\n\t\t\t\t\t\tif(tempD==\"none\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdefD=0;\n\t\t\t\t\t\t\tdefS=1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttempD=tempD.replace(\"matrix(\",\"\");\n\t\t\t\t\t\t\tvar aryD=tempD.split(\",\");\n\t\t\t\t\t\t\tdefD=Math.atan2(parseFloat(aryD[1]),parseFloat(aryD[0]))*180/Math.PI;\n\t\t\t\t\t\t\tdefS=Math.sqrt(Math.pow(parseFloat(aryD[0]),2)+Math.pow(parseFloat(aryD[1]),2));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$popup.find(\".deg\").val(defD);\n\t\t\t\t\t\n\t\t\t\t\t$popup\n\t\t\t\t\t\t.on(\"change input\",\".deg,.XPosition,.YPosition\",function(e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(!$(focusedObj).is(\"html\") )\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\tvar x=$popup.find(\".XPosition\").val(),\n\t\t\t\t\t\t\t\t\ty=$popup.find(\".YPosition\").val(),\n\t\t\t\t\t\t\t\t\tdeg=$popup.find(\".deg\").val();\n\t\t\t\t\t\t\t\t$tempObj.css({\"transform-origin\":x+\" \"+y,\n\t\t\t\t\t\t\t\t\t\"transform\":\"rotate(\"+deg+\"deg) scale(\"+defS+\")\"});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\talert(\"Please select object.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t$popup.find(\"input[type='button']\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK,function(e) {\n\t\t\t\t\t\t\tif($(e.target).attr(\"class\")!=\"apply\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$tempObj.css({\"transform-origin\":defX+\" \"+defY,\n\t\t\t\t\t\t\t\t\t\"transform\":\"rotate(\"+defD+\"deg) scale(\"+defS+\")\"});\n\t\t\t\t\t\t\t\teditor.updateTextArea();//update iframe\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//perspect\n\t\t\t\telse if (buttonName === \"perspect\")\n\t\t\t\t{\n\t\t\t\t\t$popup.find(\":button\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK,function(e) {\n\t\t\t\t\t\t\tvar perspect=$(e.target).attr(\"class\");\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tperspective(focusedObj,perspect);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t//perspective control\n\t\t\t\t\tfunction perspective(target,perspect)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar children=$(frameBody).children(),\n\t\t\t\t\t\t\tmaxid;\n\t\t\t\t\t\tzidx=0;\n\t\t\t\t\t\t$(children).each(function(idx,item)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif($(item).css(\"z-index\")!=\"auto\")\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(zidx <= parseInt($(item).css(\"z-index\")))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tzidx=parseInt($(item).css(\"z-index\"));\n\t\t\t\t\t\t\t\t\tmaxid=idx;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$(item).css(\"z-index\",$(children).index(item));\n\t\t\t\t\t\t\t\tif(zidx < parseInt($(children).index(item)))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tzidx=parseInt($(children).index(item));\n\t\t\t\t\t\t\t\t\tmaxid=idx;\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\tif(perspect ==\"toFront\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar z=parseInt($(target).css(\"z-index\"));\n\t\t\t\t\t\t\tvar dz= (zidx - z) < 0 ? 0 : zidx -z ;\n\t\t\t\t\t\t\tvar pair=maxid;\t\n\t\t\t\t\t\t\t//check if same value as z was existed\n\t\t\t\t\t\t\tif(dz!=0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$(children).each(function(idx,item)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif(idx != $(children).index(target))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar c = parseInt($(item).css(\"z-index\"));\n\t\t\t\t\t\t\t\t\t\tif(dz>c-z && c-z > 0)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tdz=c-z;\n\t\t\t\t\t\t\t\t\t\t\tpair=idx;\n\t\t\t\t\t\t\t\t\t\t}\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\t//convert\n\t\t\t\t\t\t\t\t$(target).css(\"z-index\",z+dz);\n\t\t\t\t\t\t\t\t$($(children).get(pair)).css(\"z-index\",z);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(perspect == \"toBack\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar z=parseInt($(target).css(\"z-index\"));\n\t\t\t\t\t\t\tvar dz= z,\n\t\t\t\t\t\t\t\tpair=parseInt($(children).index(target));\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//check if same value as z was existed\n\t\t\t\t\t\t\tif(dz>0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$(children).each(function(idx,item)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif(idx != $(children).index(target))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar c = parseInt($(item).css(\"z-index\"));\n\t\t\t\t\t\t\t\t\t\tif(dz>=z-c && z-c >= 0)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tdz=z-c;\n\t\t\t\t\t\t\t\t\t\t\tpair=idx;\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(z,c,idx);\n\t\t\t\t\t\t\t\t\t\t}\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\t//convert\n\t\t\t\t\t\t\t\t$(target).css(\"z-index\",z - dz);\n\t\t\t\t\t\t\t\t$($(children).get(pair)).css(\"z-index\",z);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(perspect == \"toMostFront\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tzidx++;\n\t\t\t\t\t\t\t$(target).css(\"z-index\",zidx);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(perspect == \"toMostBack\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$(target).css(\"z-index\",0);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t$(children).each(function(idx,item)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(idx != $(children).index(target))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvar zz=parseInt($(item).css(\"z-index\"));\n\t\t\t\t\t\t\t\t\tzz++;\n\t\t\t\t\t\t\t\t\t$(item).css(\"z-index\",zz);\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\teditor.updateTextArea();//update iframe\n\t\t\t\t\t\teditor.$frame.contents().off(\"click\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//body style\n\t\t\t\telse if (buttonName === \"bodystyle\")\n\t\t\t\t{\n\t\t\t\t\t//insert style of body\n\t\t\t\t\t$popup.find(\"textarea\").val($(frameBody).attr(\"style\"));\n\t\t\t\t\t//Submit\n\t\t\t\t\t$popup.find(\"input[type='button']\") //children(\":button\")\n\t\t\t\t\t\t.off(CLICK)\n\t\t\t\t\t\t.on(CLICK, function (e) {\n\t\t\t\t\t\t\teditor.hidePopups();\n\t\t\t\t\t\t\teditor.focus();\n\t\t\t\t\t\t\treturn false;\t\t\t\t\n\t\t\t\t\t\t});\n\t\t\t\t}\n\n // Show the popup if not already showing for this button\n if (buttonDiv !== $.data(popup, BUTTON)) {\n showPopup(editor, popup, buttonDiv);\n return false; // stop propagination to document click\n }\n\n // propaginate to document click\n return;\n\n }\n\t\t\t\n\t\t\t\n // Print\n else if (buttonName === \"print\")\n editor.$frame[0].contentWindow.print();\n\n // All other buttons\n else if (!execCommand(editor, data.command, data.value, data.useCSS, buttonDiv))\n return false;\n\n }\n\n // Focus the editor\n focus(editor);\n\n }", "function CreateMainButton(Parent) {\n // search the page for already created button\n var btn = $(\"#fm2_\" + MenuName + \"_mobile_button\");\n if (btn.length > 0) {\n btn.attr('href', '#').removeAttr('style');\n MenuButton = btn[0];\n } else {\n // create a new button\n MenuButton = document.createElement(\"a\");\n MenuButton.innerHTML += \"<span class='down-arrow'>&#x25BC;</span><span class='caption'>Menu</span>\";\n MenuButton.setAttribute(\"href\", \"#\");\n MenuButton.setAttribute(\"id\", \"fm2_\" + MenuName + \"_mobile_button\");\n $(MenuButton).addClass(\"fm2_mobile_button\").appendTo(Parent);\n }\n $(MenuButton).unbind('click').click(function (ev) {\n ev.preventDefault();\n ev.stopPropagation();\n // Toggle visible.\n Self.Show(Visible = !Visible);\n var opeEvent = 'ope-mobile-menu-' + (Visible ? \"show\" : \"hide\");\n jQuery(document).trigger(opeEvent);\n });\n }", "function EXButton(opt)\r\n{\r\n Sprite.Set(opt.bt,Sprite.Expand);\r\n $(opt.bt).addClass(\"clickable\");\r\n opt.bt.Expand=function()\r\n {\r\n Sprite.Set(opt.bt,Sprite.Collapse);\r\n opt.bt.IsExpanded = true;\r\n $(opt.expansion).slideDown(200);\r\n if (opt.OnExpand) opt.OnExpand(opt.bt);\r\n if (opt.OnToggle) opt.OnToggle(opt.bt);\r\n };\r\n opt.bt.Collapse=function()\r\n {\r\n Sprite.Set(opt.bt,Sprite.Expand);\r\n opt.bt.IsExpanded = false;\r\n $(opt.expansion).slideUp(200);\r\n if (opt.OnCollapse) opt.OnExpand(opt.bt);\r\n if (opt.OnToggle) opt.OnToggle(opt.bt);\r\n };\r\n opt.bt.Toggle=function()\r\n {\r\n if (opt.bt.IsExpanded)\r\n opt.bt.Collapse();\r\n else\r\n opt.bt.Expand();\r\n };\r\n $(opt.bt).click(opt.bt.Toggle);\r\n}", "get Joystick3Button14() {}", "function pmMakeButton(title,functionName,params) {\n let paramStr = '';\n if(params !== null && params.length > 0){\n if( typeof params === 'string' ) {\n params = [ params ];\n }\n for (let i = 0;i<params.length;i++){\n paramStr += '\\''+params[i]+'\\'';\n paramStr += ',';\n }\n paramStr = paramStr.slice(0,-1);\n }\n return '<input onclick=\"'+functionName+'('+paramStr+');\" type=\"button\" value=\"'+title+'\"/>';\n}", "function specialButtonCreator() {\n if (buttonWrapper.contains(specialButton)) {\n return\n } else {\n specialButton.setAttribute('class', 'special glow');\n specialButton.textContent = \"Special\"\n specialButton.addEventListener('click', battle);\n buttonWrapper.appendChild(specialButton);\n }\n}", "get Joystick3Button19() {}", "function makerequest(){\n console.log(\"Buton Clicked\");\n\n}", "function ClickOnStartContinue()\n{\n if(Btn_Start_Continue.Exists)\n {\n Btn_Start_Continue.ClickButton()\n Log.Message(\"Clicked on Start Button on Quick CMC\")\n return true\n }\n else\n {\n Log.Message(\"Button Start doesn't exists\")\n return false\n }\n}", "function getButtonTemplate(btnText){var buttonTemplate='';if(!btnText)btnText=buttonText;// get from global buttonText option\nif(_theme==='cosmo-theme'){buttonTemplate+='<sfanspan class=\"icon-element-wrapper\">'+iconCosmo+'</sfanspan>';buttonTemplate+='<sfanspan class=\"sarafan-button-text\">'+btnText+'</sfanspan>';return buttonTemplate;}if(_theme==='topnews-theme'){buttonTemplate+='<sfanspan class=\"icon-element-wrapper\">'+iconTopnews+'</sfanspan>';buttonTemplate+='<sfanspan class=\"sarafan-button-text topnews-button-text\">'+btnText+'</sfanspan>';return buttonTemplate;}switch(_btnType){case'btn-only-icon':if(_buttonSize==='small'){svgEye=svgEyeSmall;}buttonTemplate+='<sfanspan class=\"icon-element-wrapper\">'+svgEye+'</sfanspan>';break;case'btn-only-text':buttonTemplate+='<sfanspan class=\"sarafan-button-text\">'+btnText+'</sfanspan>';break;case'sfn-btn__type1'||'sfn-btn__type2':buttonTemplate+='<sfanspan class=\"sfn-btn__label\">'+btnText+'</sfanspan>';break;default:if(_buttonSize==='small'){svgEye=svgEyeSmall;}buttonTemplate+='<sfanspan class=\"icon-element-wrapper\">'+svgEye+'</sfanspan>';buttonTemplate+='<sfanspan class=\"sarafan-button-text\">'+btnText+'</sfanspan>';}if(optionsFromApiData.buttonTemplate){buttonTemplate=optionsFromApiData.buttonTemplate;var btn=document.createElement('div');btn.innerHTML=buttonTemplate;var btnTextNode=btn.querySelector('.sarafan-button-text');if(btnTextNode){btnTextNode.innerHTML=btnText;buttonTemplate=btn.innerHTML;}}return buttonTemplate;}", "function buildGiveUpBtn(){\n giveUpBtn.innerText = \"Give up!!!\"\n giveUpDiv.style.display = \"none\"\n \n giveUpBtn.addEventListener(\"click\", giveUpHandler)\n \n giveUpDiv.appendChild(giveUpBtn)\n btnDiv.appendChild(giveUpDiv)\n }", "function ClickStart()\n{\n if(Btn_Start.Exists)\n {\n Btn_Start.ClickButton()\n Log.Message(\"Clicked on Start Button on Quick CMC\")\n return true\n }\n else\n {\n Log.Message(\"Button Start doesn't exists\")\n return false\n }\n}", "addCustomButton(btn)\n {\n var exec = window[btn.func];\n if (typeof exec === \"function\") {\n this.oEditor.addCommand('cmd_' + btn.func, {exec: function(oEditor) {window[btn.func](oEditor);}});\n this.oEditor.ui.addButton(btn.func, {label: btn.name, command: 'cmd_' + btn.func, icon: btn.icon});\n } else if (typeof displayJSError === \"function\") {\n displayJSError('Handler for Custom Button [' + btn.func + '] is not defined!', 'error');\n }\n }", "function _initWithButtonGeneration () {\n\n var merchantConfig = config.merchantConfig,\n jsBtnIds = merchantConfig && merchantConfig.container,\n customBtnIds = merchantConfig && merchantConfig.button,\n jsBtnTypes = merchantConfig && merchantConfig.type || [],\n color = merchantConfig && merchantConfig.color,\n size = merchantConfig && merchantConfig.size,\n condFn = merchantConfig && merchantConfig.condition,\n clickFn = merchantConfig && merchantConfig.click,\n btnsConfigList = merchantConfig && merchantConfig.buttons,\n btnContainers = [];\n\n if (btnsConfigList && btnsConfigList.length) {\n for (var i = 0; i < btnsConfigList.length; i++) {\n var btnConfig = btnsConfigList[i];\n var elId = btnConfig.container || btnConfig.button;\n var elDom = typeof elId === 'string' ? document.getElementById(elId) : elId;\n\n if (btnConfig.container) {\n _addButtonElement(elDom, {\n label: btnConfig.type || 'checkout',\n color: btnConfig.color,\n size: btnConfig.size\n }, btnConfig.click, btnConfig.condition);\n } else if (btnConfig.button) {\n btnList.push(_getBtnObject(elDom, btnConfig.click, btnConfig.condition));\n }\n }\n } else {\n // get all container list\n _getBtnContainers(jsBtnIds || customBtnIds, btnContainers);\n\n for (var j = 0; j < btnContainers.length; j++) {\n if (customBtnIds) {\n btnList.push(_getBtnObject(btnContainers[j], clickFn, condFn));\n } else {\n _addButtonElement(btnContainers[j], {\n label: jsBtnTypes[j] || 'checkout',\n color: color,\n size: size\n }, clickFn, condFn);\n }\n }\n }\n\n _track({\n status: 'IC_SETUP',\n 'button-type': customBtnIds ? 'STATIC' : 'JS',\n 'button-number': btnList.length\n });\n\n _init();\n\n // to ensure users not able to click static buttons before script is loaded\n var hideBtns = document.querySelectorAll('.' + constants.STATIC_BUTTON_HIDDEN_STYLE);\n var hideBtnsLength = hideBtns.length;\n for (var k = 0; k < hideBtnsLength; k++) {\n hideBtns[k].className = hideBtns[k].className.replace(constants.STATIC_BUTTON_HIDDEN_STYLE, '');\n }\n }", "function test_generic_object_button_execute_playbook() {}", "function handleUi() {\n var buttonText = 'Copy event URL';\n // create button copy url node\n var button = (function () {\n var buttonTemplate = `<div id=\":999.copy_url_top\" class=\"ep-ea-btn-wrapper\">&nbsp;<div class=\"goog-inline-block goog-imageless-button\" role=\"button\" tabindex=\"0\" style=\"-webkit-user-select: none;\"><div class=\"goog-inline-block goog-imageless-button-outer-box\"><div class=\"goog-inline-block goog-imageless-button-inner-box\"><div class=\"goog-imageless-button-pos\"><div class=\"goog-imageless-button-top-shadow\">&nbsp;</div><div class=\"goog-imageless-button-content\">${buttonText}</div></div></div></div></div></div>`;\n var button = document.createElement('div');\n button.innerHTML = buttonTemplate;\n return button.childNodes[0];\n })();\n\n // container where all the action buttons are in like save, discard etc\n var buttonContainer = document.querySelector('.ep-ea');\n var lastButton = buttonContainer.querySelector('.ep-ea-btn-wrapper:last-of-type');\n\n // insert button after the last button\n buttonContainer.insertBefore(button, lastButton.nextSibling);\n var buttonTextContainer = button.querySelector('.goog-imageless-button-content');\n\n button.addEventListener('click', function () {\n var eventUrl = retrieveEventUrl();\n var confirmButtonText = buttonText + ' ✔';\n copyToClipboard(eventUrl);\n buttonTextContainer.textContent = confirmButtonText;\n\n window.setTimeout(function () {\n buttonTextContainer.textContent = buttonText;\n }, 5000);\n });\n\n }", "function makeBtns() {\n\tfor (let btn of btnList) {\n\t\tconst newBtn = document.createElement(\"button\");\n\t\tnewBtn.addEventListener(\"click\", () => selectClimoSite(btn));\n\t\tnewBtn.innerText = btn.site;\n\t\tif (btn.site === \"KTUS\") {\n\t\t\tnewBtn.classList.add(\"active\");\n\t\t}\n\t\tbtns.append(newBtn);\n\t}\n}", "contClick() {\n // temporarily goes right to the workspace registration\n app.goto('/init/newworkspace');\n }", "_buildButton(tar, content) {\n // Build text display\n tar.innerHTML = `<textarea rows=\"1\" cols=\"80\" style='margin-right:5px'>${content}</textarea>`;\n // Build button\n Util.createLinkButton(tar, 'none', 'Copy', 2);\n document.querySelector('.mp_crRow .mp_button_clone').classList.add('mp_reading');\n // Return button\n return document.querySelector('.mp_reading');\n }", "function setupBuyButton(){\n\t//if(location.href.indexOf(\"webdesign-flash.ro\") == -1) return;\n\tFWDBuyButton.setPrototype();\n\tbuyButton = new FWDBuyButton(\"graphics/buy.png\",\"graphics/hello.png\", 70,70,30,60);\n\tbuyButton.setX(0);\n\tbody_el.appendChild(buyButton.screen);\n\tself.positionBuyButton();\n}", "fCreateBtn( className, idName, counter, appendedTo, label ) {\n\t\t\t\tlet divName = document.createElement( \"BUTTON\" );\n\t\t\t\tdivName.id = idName + \"Id_\" + counter; //set id\n\t\t\t\tdivName.className = className; //title + \"Class\";\n\t\t\t\t//divName.href = \"#modalCarousel\";\n\t\t\t\t//let divNameId = $ (\"#\" + title + \"Id_\" + counter); //get id\n\t\t\t\t$( divName ).appendTo( appendedTo );\n\t\t\t\tlet buttonLabel = document.createTextNode( label );\n\t\t\t\t$( buttonLabel ).appendTo( divName );\n\t\t\t}", "function guiLoop() {\n updateCustomButtons();\n}", "get Joystick2Button14() {}", "function addHeroButtons(){\n for (c = 0; c < Object.keys(heroes).length; c++){\n buttons.push(new Button(125,-155 + c*10,10,10,\"\",\"heroselect\",\"changeHero\",Object.keys(heroes)[c],\"circle\",heroes[Object.keys(heroes)[c]].pal.r,heroes[Object.keys(heroes)[c]].pal.g,heroes[Object.keys(heroes)[c]].pal.b))\n }\n}", "get Joystick1Button19() {}", "get Joystick5Button14() {}", "function setupAPIButtons(){\n\taddMessage(\"Event listeners console...\");\n\tFWDPageSimpleButton.setPrototype();\n\tplayButton = new FWDPageSimpleButton(\"play\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tplayButton.getStyle().marginRight = \"14px\";\n\tplayButton.getStyle().marginTop = \"6px\";\n\tplayButton.addListener(FWDPageSimpleButton.CLICK, playClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tpauseButton = new FWDPageSimpleButton(\"pause\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tpauseButton.getStyle().marginRight = \"14px\";\n\tpauseButton.getStyle().marginTop = \"6px\";\n\tpauseButton.addListener(FWDPageSimpleButton.CLICK, pauseClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tstopButton = new FWDPageSimpleButton(\"stop\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tstopButton.getStyle().marginRight = \"14px\";\n\tstopButton.getStyle().marginTop = \"5px\";\n\tstopButton.addListener(FWDPageSimpleButton.CLICK, stopClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tscrubbButton = new FWDPageSimpleButton(\"scrub to 50%\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tscrubbButton.getStyle().marginRight = \"14px\";\n\tscrubbButton.getStyle().marginTop = \"6px\";\n\tscrubbButton.addListener(FWDPageSimpleButton.CLICK, scrubbClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tvolumeButton = new FWDPageSimpleButton(\"set volume to 50%\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tvolumeButton.getStyle().marginRight = \"14px\";\n\tvolumeButton.getStyle().marginTop = \"6px\";\n\tvolumeButton.addListener(FWDPageSimpleButton.CLICK, volumeClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tfullscreenButton = new FWDPageSimpleButton(\"go fullscreen\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tfullscreenButton.getStyle().marginRight = \"14px\";\n\tfullscreenButton.getStyle().marginTop = \"6px\";\n\tfullscreenButton.addListener(FWDPageSimpleButton.CLICK, fullscreenClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tsetPosterButton = new FWDPageSimpleButton(\"set poster src\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tsetPosterButton.getStyle().marginRight = \"14px\";\n\tsetPosterButton.getStyle().marginTop = \"6px\";\n\tsetPosterButton.addListener(FWDPageSimpleButton.CLICK, setPosterClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tsetYoutubeButton = new FWDPageSimpleButton(\"set youtube src\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tsetYoutubeButton.getStyle().marginRight = \"14px\";\n\tsetYoutubeButton.getStyle().marginTop = \"6px\";\n\tsetYoutubeButton.addListener(FWDPageSimpleButton.CLICK, setYoutubeClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tvimeoYoutubeButton = new FWDPageSimpleButton(\"set vimeo src\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tvimeoYoutubeButton.getStyle().marginRight = \"14px\";\n\tvimeoYoutubeButton.getStyle().marginTop = \"6px\";\n\tvimeoYoutubeButton.addListener(FWDPageSimpleButton.CLICK, setVimeoClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tmp4Button = new FWDPageSimpleButton(\"set mp4 source\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tmp4Button.getStyle().marginRight = \"14px\";\n\tmp4Button.getStyle().marginTop = \"6px\";\n\tmp4Button.addListener(FWDPageSimpleButton.CLICK, setMp4ClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tmp4Button = new FWDPageSimpleButton(\"set mp4 source\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tmp4Button.getStyle().marginRight = \"14px\";\n\tmp4Button.getStyle().marginTop = \"6px\";\n\tmp4Button.addListener(FWDPageSimpleButton.CLICK, setMp4ClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tgetCurrentTimeButton = new FWDPageSimpleButton(\"get time\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tgetCurrentTimeButton.getStyle().marginRight = \"14px\";\n\tgetCurrentTimeButton.getStyle().marginTop = \"6px\";\n\tgetCurrentTimeButton.addListener(FWDPageSimpleButton.CLICK, getCurrentTimeClickHandler);\n\t\n\tFWDPageSimpleButton.setPrototype();\n\tgetTotalTimeButton = new FWDPageSimpleButton(\"get duration\", \"#FFFFFF\", \"#000000\", \"#000000\", \"#FFFFFF\");\n\tgetTotalTimeButton.getStyle().marginRight = \"14px\";\n\tgetTotalTimeButton.getStyle().marginTop = \"6px\";\n\tgetTotalTimeButton.addListener(FWDPageSimpleButton.CLICK, getTotalTimeClickHandler);\n\t\n\tapiButtonsHolder_el.appendChild(playButton.screen);\n\tapiButtonsHolder_el.appendChild(pauseButton.screen);\n\tapiButtonsHolder_el.appendChild(stopButton.screen);\n\tapiButtonsHolder_el.appendChild(scrubbButton.screen);\n\tapiButtonsHolder_el.appendChild(volumeButton.screen);\n\tapiButtonsHolder_el.appendChild(fullscreenButton.screen);\n\tapiButtonsHolder_el.appendChild(setPosterButton.screen);\n\tapiButtonsHolder_el.appendChild(setYoutubeButton.screen);\n\tapiButtonsHolder_el.appendChild(vimeoYoutubeButton.screen);\n\tapiButtonsHolder_el.appendChild(mp4Button.screen);\n\tapiButtonsHolder_el.appendChild(getCurrentTimeButton.screen);\n\tapiButtonsHolder_el.appendChild(getTotalTimeButton.screen);\n}", "get Joystick1Button14() {}", "addButtonComponent(component) {\nthis\n.addInfoToComponent(component, formEditorConstants.COMPONENT_TYPE_BUTTON)\n.addProperty(component, 'name', this._componentList.findComponentText(component.type, 'name', 'Button'))\n.addProperty(component, 'zIndex', 0)\n.addProperty(component, 'value', component.name)\n.addProperty(component, 'title', component.name)\n.addProperty(component, 'color', 'green');\nreturn component;\n}" ]
[ "0.67070943", "0.66719586", "0.6615435", "0.6566278", "0.655044", "0.654363", "0.6522419", "0.6509046", "0.64899176", "0.6462648", "0.64305085", "0.6381419", "0.6377197", "0.6373988", "0.6318765", "0.63171023", "0.63163835", "0.6300956", "0.6296716", "0.6290063", "0.6284369", "0.6268481", "0.6260284", "0.6214353", "0.6205993", "0.6182844", "0.61783856", "0.61736226", "0.613625", "0.61343074", "0.61280966", "0.61183685", "0.6116817", "0.6116645", "0.61031497", "0.60898906", "0.60862184", "0.60806537", "0.6078792", "0.6063819", "0.60570323", "0.6051407", "0.6047429", "0.6037583", "0.60266244", "0.60233635", "0.6019143", "0.6015582", "0.60150224", "0.6005621", "0.600195", "0.59896433", "0.5988486", "0.5978393", "0.5968833", "0.5960824", "0.59551007", "0.5952099", "0.59518474", "0.5951743", "0.5951014", "0.5943631", "0.5942189", "0.59418225", "0.5938617", "0.59359306", "0.5933261", "0.5933185", "0.5928276", "0.5927907", "0.59187746", "0.5917872", "0.59043264", "0.59020215", "0.5896261", "0.5894653", "0.5889868", "0.58898044", "0.58882916", "0.58852816", "0.5884175", "0.5883817", "0.58818775", "0.5878673", "0.5874399", "0.5872291", "0.5872021", "0.58706206", "0.58675414", "0.5865199", "0.5863142", "0.58585656", "0.5854641", "0.5847101", "0.58465517", "0.5845301", "0.584422", "0.5840309", "0.5838028", "0.5836394", "0.5836156" ]
0.0
-1
Render the SearchBar Component
render() { return ( <div className="SearchBar"> <div className="SearchBar-sort-options"> <ul> {this.renderSortByOptions()} </ul> </div> <div className="SearchBar-fields"> <input placeholder="Search Businesses" onChange={this.handleTermChange}/> <input placeholder="Where?" onChange={this.handleLocationChange}/> </div> <div className="SearchBar-submit"> <a onClick={this.handleSearch}>Go</a> </div> </div> ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "render(){\n\t\t// every class must have a render method \n\t\treturn(\n\t\t\t<div className=\"search-bar\">\n\t\t \t\t<input \n\t\t \t\t\tvalue = {this.state.term} // this turns into controlled component\n\t\t \t\t\tonChange={(event) => this.onInputChange(event.target.value)} />\n\t\t \t</div>\n\t\t );\n\t}", "render() {\n\t\treturn(\n\t\t\t<section className='search-bar'>\n\t\t\t\t<label>Search</label>\n\t\t\t\t<input\n\t\t\t\t\tvalue = {this.state.term}\n\t\t\t\t\t// rather than calling directly to the SearchBar props,\n\t\t\t\t\t// call a separate method (below)\n\t\t\t\t\tonChange={ event => this.onInputChange(event.target.value) }\n\t\t\t\t/>\n\t\t\t\t<br/>\n\t\t\t</section>\n\t\t);\n\t}", "render() {\n\t\treturn (\n\t\t\t<div className=\"search-bar\">\n\t\t\t\t<input \n\t\t\t\t\tvalue={this.state.term}\n\t\t\t\t\tonChange={event =>\n\t\t\t\t\t\t\tthis.onInputChange(event.target.value)}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t);\n\t}", "render() {\r\n\r\n\t\t\r\n\t\treturn (\r\n\t\t\t<div class={style.searchBar}>\r\n\t\t\t\t<input type=\"text\" onKeyPress={this.props.onKeyPressed} placeholder=\"Search For A City\" />\r\n\t\t\t</div>\r\n\t\t);\r\n\t}", "render() {\n\t\treturn (\n\t\t\t<div className=\"search-bar\"> \n\t\t\t\n\t\t\t<input \n\t\t\tvalue={this.state.term}\n\t\t\tonChange={event=>{this.onInputChange(event.target.value)}}\n\t\t\t/>\n\t\t\t\n\t\t\t</div>\n\t\t\t);\n\t}", "render(){\n\t\tconst searchTerm = this.props.searchTerm\n\t\treturn(\n\t\t\t<form className=\"search-bar\">\n\t\t\t\t<input value={searchTerm} onChange={this.handleChange} type=\"text\" placeholder=\"Search...\" />\n\t\t\t\t<div>\n\t\t\t\t\t<input id=\"in-stock\" type=\"checkbox\" /> Only show products in stock\n\t\t\t\t</div>\n\t\t\t</form>\n\t\t)\n\t}", "function _renderSearch() {\n _$navbar.setMod(_B_BAR, _M_SEARCH, false);\n setTimeout(function() {\n _$navbar.setMod(_B_BAR, _M_SEARCH, _searchIsActive);\n }, CFG.TIME.ANIMATION);\n }", "render() {\n return (React.createElement(\"div\", { className: \"jp-extensionmanager-search-bar\" },\n React.createElement(InputGroup, { className: \"jp-extensionmanager-search-wrapper\", type: \"text\", placeholder: this.props.placeholder, onChange: this.handleChange, value: this.state.value, rightIcon: \"search\", disabled: this.props.disabled })));\n }", "render(){\n\n\t\t//return <input onChange={this.onInputChange} />;\n\n\t\treturn(\n\t\t\t //below input is a controled input and its value is controled by state term\n\t\t\t<div className=\"search-bar\">\n\t\t\t\n\t\t\t\t<input value={this.state.term}\n\n\t\t\t\tonChange={event=> this.onInputChange(event.target.value)} />\n\t\t\t\t\n\t\t\t</div>\n\n\t\t\t) \n\t}", "render() { \n\t\t// onChange is available on all elements; {} evaluates the JS inside the HTML\n\t\treturn (\n\t\t\t<div className=\"search-bar\">\n\t\t\t\t<input onChange={event => this.onInputChange(event.target.value)} value={this.state.term} />\n\t\t\t</div>\n\t\t\t)\n\t}", "function renderSearchBar(apollo = getMockApollo()) {\n\treturn render(SearchBar, {\n\t\tprovide: { apollo }\n\t});\n}", "render() {\n\t\t//always manipulate state, using this.setState\n\t\t//this.state.term : referencing is ok\n\t\treturn (\n\t\t\t<div className=\"search-bar\">\n\t\t\t\t<input \n\t\t\t\t\tvalue={this.state.term} //update the user input whenever the state changes\n\t\t\t\t\tonChange={event => this.onInputChange(event.target.value)} />\n\t\t\t</div>\n\t\t); //pass that event handler function which is defined as method within SearchBar class. All HTML input elements emit change event whenever a user interacts with them\t\t\n\t}", "render(){\n\t\t// return <input onChange = {(event) => this.setState({ term: event.target.value })} />;\n\t\t\n\t\t// If we set the value variable to a controller input, \n\t\treturn (\n\t\t\t<div className = \"search-bar\">\n\t\t\t\t<input \t\n\t\t\t\t\tvalue = {this.state.term}\n\t\t\t\t\tonChange = {(event) => this.onInputChange( event.target.value )} />\n\t\t\t</div>\n\t\t);\n\t}", "render() {\n\t\t// onChange is a special property in JS\n\t\t\t\t\t\t\t\t// event handler passed as value to onChange property\n\t\t\t\t\t\t\t\t// reset the value of state.term (with this.setState) and pass the value of property onChange\n\t\treturn (\n\t\t\t<div className=\"search-bar\">\n\t\t\t\t<input\n\t\t\t\t\tplaceholder=\"Enter search here\"\n\t\t\t\t\tvalue={this.state.term}\n\t\t\t\t\tonChange={event => this.onInputChange(event.target.value)} />\n\t\t\t</div>\n\t\t);\t\n\t}", "render() {\n return (\n <div className=\"SearchBar\">\n <div className=\"SearchBar-sort-options\">\n <ul>\n {this.renderSortByOptions()}\n </ul>\n </div>\n <div className=\"SearchBar-fields\">\n <input placeholder=\"Search Businesses\" />\n <input placeholder=\"Where?\" />\n </div>\n <div className=\"SearchBar-submit\">\n <a>Let's Go</a>\n </div>\n </div>\n );\n }", "render() { \n return (\n <div className='container'>\n <h1 className='text-center mt-3'>REACT 101</h1>\n <SearchBar/>\n </div>\n ) \n }", "render() {\n return (\n <div className=\"search-bar\">\n <input \n value={this.state.term}\n onChange = {event => this.onInputChange(event.target.value)} />\n \n </div>\n );\n //could add this to the div to see the contents of the search bar\n // Value of the input: {this.state.term}\n }", "render() {\n\t\treturn (\n\t\t\t<div className=\"partsSearchFilter\">\n\n\t\t\t\t<div>Component type:</div>\n\t\t\t\t<TypeAheadMultiSelect />\n\t\t\t\t<div>Component name:</div>\n\t\t\t\t<TypeAheadMultiSelect />\n\n\n\n\n\n\n\n\n\n\n\t\t\t</div>\n\t\t);\n\t}", "render() {\n return (\n\n <div>\n This is React search Component !\n </div>\n );\n }", "render() {\n // onChange is a specific React-defined event handler\n return (\n <div className=\"search-bar\">\n <input\n value={this.state.term} // the state is telling the input what its value is\n onChange={e => this.onInputChange(e.target.value)}\n />\n </div>\n );\n }", "render() {\n\t\treturn (\n\t\t\t<div className=\"search\">\n\t\t\t\t<Autocomplete\n\t\t\t\t\tgetItemValue={(item) => item.symbol}\n\t\t\t\t\titems={this.state.renderData}\n\t\t\t\t\trenderItem={(item, isHighlighted) =>\n\t\t\t\t\t\t<div style={{ background: isHighlighted ? 'lightgray' : 'white' }} key={item.symbol}>\n\t\t\t\t\t\t\t{item.symbol} - {item.name}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t}\n\t\t\t\t\tvalue={this.state.searchTerm}\n\t\t\t\t\tonChange={this.handleChange}\n\t\t\t\t\tonSelect={this.handleSelect}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t)\n\t}", "render() {\n\t\tconst searchResults = this.state.searchresults;\n\t\tlet results = <div className=\"recipe-not-found\"><h3>Sorry, there were no results found.</h3></div>;\n\t\tif (searchResults.length > 0) {\n\t\t\tresults = <SearchResults searchresults={searchResults}/>\n\t\t}\n\t\treturn(\n\t\t\t<div className=\"searchbox\">\n\t\t\t\t<div style={{marginBottom: '70px'}}>\n\t\t\t\t\t<SearchBox \n\t\t\t\t\t\tonSearchClick={this.handleSearchClick}/>\n\t\t\t\t</div>\n\t\t\t\t<br />\n\t\t\t\t<div className=\"center-contents-div\">\n\t\t\t\t\t{results}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t);\n\t}", "render() {\n let filteredData = this.state.data.filter(this.searchDetails);\n let displayResults = \"\"\n if (this.state.query !== \"\") {\n displayResults = (\n <div class=\"searchContainer\">\n <ul>{\n filteredData.map((details, i) => (\n <div key={i} className=\"searchResults\">\n\n <button>\n <Link to={`/movie_details/${details.id}`}>\n <li>{details.original_title}</li>\n </Link>\n </button>\n\n </div>\n ))}</ul></div>)\n } else {\n displayResults = \"\";\n }\n\n return (\n <div className=\"searchBar\">\n <Search query={this.state.query} handleSearch={this.handleSearch} className=\"searchBox\" />\n {displayResults}\n </div>\n );\n }", "render() {\n return (\n <div className=\"search-bar\">\n <input\n value={this.state.term}\n onChange={event => this.onSearch(event.target.value)} />\n </div>\n );\n }", "render() {\n return (React.createElement(\"div\", { className: \"jp-extensionmanager-search-bar\" },\n React.createElement(\"div\", { className: \"jp-extensionmanager-search-wrapper\" },\n React.createElement(\"input\", { type: \"text\", className: \"jp-extensionmanager-input\", placeholder: this.props.placeholder, onChange: this.handleChange.bind(this), value: this.state.value }))));\n }", "render() {\n return (\n <div className=\"searchbarDiv\">\n <nav>\n <input\n value={this.state.term}\n onChange={event => this.onInputChange(event.target.value)}\n className=\"searchBar\"\n placeholder=\"Search\"\n />\n </nav>\n </div>\n );\n }", "render() {\n\t\tconst searchUserData = this.processData(this.props.barSearchData, this.props.userData);\n\n\t\tconst results = _.map(searchUserData, (data, index) => {\n\t\t\tdata.addBar = this.props.addBar;\n\t\t\tdata.removeBar = this.props.removeBar;\n\t\t\treturn <SearchResult {...data} index={index} authenticated={this.props.authenticated} history={this.context.router.history} key={data.id} />\n\t\t});\n\n\t\treturn (\n\t\t\t<div>\n <ul className=\"list-group\">\n {results}\n </ul>\n </div>\n\t\t);\n\t}", "render() {\r\n return (\r\n <div className=\"search-bar\">\r\n <input\r\n value={this.state.term}\r\n onChange = {event => this.onInputChange(event.target.value)} />\r\n </div>\r\n );\r\n }", "render() {\n return (\n\n <div className=\"search-bar\">\n <input\n value={this.state.term}\n onChange={event => this.onInputChange(event.target.value)}/>\n </div>\n )\n\n }", "function SearchBar(props){\n return(\n <SearchContainer>\n <SearchBox onChange={props.onChange} placeholder=\"Search for artist\"></SearchBox>\n {/* <SearchButton>\n <SearchIcon/>\n </SearchButton> */}\n </SearchContainer>\n )\n}", "render() {\n return (\n <div className=\"search-bar\">\n <input\n value={this.state.term}\n onChange={event => this.onInputChange(event.target.value)} />\n </div>\n );\n }", "render() {\n\t\treturn (\n\t\t\t<div className=\"wc-products-list-card__search-wrapper\" ref={ this.setWrapperRef }>\n\t\t\t\t<input type=\"search\"\n\t\t\t\t\tclassName=\"wc-products-list-card__search\"\n\t\t\t\t\tvalue={ this.state.searchText }\n\t\t\t\t\tplaceholder={ __( 'Search for products to display' ) }\n\t\t\t\t\tonChange={ this.updateSearchResults }\n\t\t\t\t/>\n\t\t\t\t<ProductSpecificSearchResults\n\t\t\t\t\tsearchString={ this.state.searchText }\n\t\t\t\t\taddProductCallback={ this.props.addProductCallback }\n\t\t\t\t\tselectedProducts={ this.props.selectedProducts }\n\t\t\t\t/>\n\t\t\t</div>\n\t\t);\n\t}", "render() {\n return (\n <div className=\"search-bar\">\n <input\n value={this.state.term}\n onChange={event => this.onInputChange(event.target.value)}\n />\n </div>\n );\n }", "render() {\n return (\n <div className=\"search-bar\">\n <input\n value={this.state.term}\n onChange={event => this.onInputChange(event.target.value)}\n />\n </div>\n );\n }", "render(){\n return(\n <div className='search-bar'>\n <input type=\"text\"\n value={this.state.term}\n onChange={(event)=> this.onInputChange(event.target.value)} placeholder=\"Search\"/>\n\n </div>\n )\n }", "function SearchBar(props) {\n return (\n <div className=\"SearchBar\">\n <form>\n <i className=\"SearchIcon fa fa-search\"></i>\n <input type=\"text\" name=\"query\" placeholder=\"Search...\"/>\n </form>\n </div>\n );\n}", "render() {\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t<SearchBar \n\t\t\t\t\tfilterText={this.state.filterText}\n\t\t\t\t\tinStockOnly={this.state.inStockOnly} />\n\t\t\t\t<ProductTable \n\t\t\t\t\tproducts={this.props.products} \n\t\t\t\t\tfilterText={this.state.filterText}\n\t\t\t\t\tinStockOnly={this.state.inStockOnly} />\n\t\t\t</div>\n\t\t);\n\t}", "render() {\n\t\tconst divClass = 'wc-products-list-card__search-wrapper';\n\n\t\treturn (\n\t\t\t<div className={ divClass + ( this.state.dropdownOpen ? ' ' + divClass + '--with-results' : '' ) } ref={ this.setWrapperRef }>\n\t\t\t\t<div className=\"wc-products-list-card__input-wrapper\">\n\t\t\t\t\t<Dashicon icon=\"search\" />\n\t\t\t\t\t<input type=\"search\"\n\t\t\t\t\t\tclassName=\"wc-products-list-card__search\"\n\t\t\t\t\t\tvalue={ this.state.searchText }\n\t\t\t\t\t\tplaceholder={ __( 'Search for products to display' ) }\n\t\t\t\t\t\tonChange={ this.updateSearchResults }\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t\t<ProductSpecificSearchResultsDropdown\n\t\t\t\t\tsearchString={ this.state.searchText }\n\t\t\t\t\taddOrRemoveProductCallback={ this.props.addOrRemoveProductCallback }\n\t\t\t\t\tselectedProducts={ this.props.selectedProducts }\n\t\t\t\t\tisDropdownOpenCallback={ this.isDropdownOpen }\n\t\t\t\t/>\n\t\t\t</div>\n\t\t);\n\t}", "function SearchBar()\n{\n return(\n <div className= \"SearchBar\">\n <input className = \"Search\" type = \"text\" placeholder = \"Type to search...\" />\n </div>\n )\n}", "render() {\n return (\n <div className=\"search-bar\">\n <input \n value={this.state.term}\n onChange={ event => this.onInputChange(event.target.value) } />\n </div>\n );\n }", "render() {\n\t\t// must return some JSX to avoid errors\n\t\t// onChange lets you get access to the standard Change event\n\t\t// return <input onChange={this.onInputChange} />;\n\t\t// ES6 arrow function syntax alternative to event handler below\n\t\t// parentheseses around (event) aren't necessary if you have a single argument\n\n\t\t// how to manipulate state: use this.setState\n\t\t// if not modifying value of term, just referencing it; this makes it okay to use this.state.term\n\t\t// whenever we change the value/update a component, the event handler runs, we set the state with the new value of the input. it re-renders and pushes the new data into the DOM every time it's updated\n\t\t// when you tell the input that the value is determined by this.state.term, you turn input into a controlled element. its value only changes when state changes\n\t\t// when it re-renders due to this.setState(), the value is set to the new value of this.state.term\n\t\t// when the onChange handler runs, the value of the input hasn't actually changed yet (until it re-renders)\n\t\t// when a user types something, they didn't change the input value; they only triggered the event. the value of the input changes only because this.State changed the state\n\t\treturn (\n\t\t\t<div className=\"search-bar\">\n\t\t\t\t<input\n\t\t\t\tvalue={this.state.term} \n\t\t\t\tonChange={event => this.onInputChange(event.target.value)} />\n\t\t\t</div>\n\t\t);\n\t}", "onActionClickSearchBar() {\n this.search(this.state.search)\n }", "function render() {\n var children = [SearchBar({\n update: updateSearchState\n }), ItemsList({\n items: _state.items,\n onUpdate: updateState\n })];\n if (!_node) {\n return _node = createElement('div', { class: 'main' }, children);\n } else {\n return _node.html(children);\n }\n }", "render() {\n const filteredRobots = this.state.robots.filter(robots => {\n return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase());\n })\n return (\n <div className='tc'>\n <h1 className=\"f2\">Current Porfolio Skills</h1>\n <SearchBox searchChange={this.onSearchChange} />\n {/* <Scroll> */}\n <CardList robots={filteredRobots} />\n {/* </Scroll> */}\n </div >\n );\n }", "render() {\n // Every time you change the state, use 'this.setState()'\n return (\n <div className=\"search-bar\">\n <input \n value = {this.state.term}\n onChange={(event) => this.onInputChange(event.target.value)} />\n </div>\n );\n }", "render() {\n //manipulating state example\n return (\n <div className=\"search-bar\">\n <input\n value={this.state.term}\n onChange={event => this.onInputChange(event.target.value)} />\n </div>\n );\n }", "render() {\n //onChange is the input handler\n return (\n <div className=\"search-bar\">\n <input\n value={this.state.term}\n onChange={event => this.onInputChange(event.target.value)} />\n </div>\n );\n }", "render() {\n return (\n <div id=\"navMenu\" className=\"o-navbar\">\n <NavList />\n\n <Search />\n </div>\n )\n }", "render() {\n // console.log([\"cat\", \"dog\"]);\n // console.log({ name: \"ben\", job: \"tutor\" });\n return (\n <Container>\n <Jumbotron />\n <Row>\n <Col>\n <SearchForm\n handleInputChange={this.handleInputChange}\n search={this.state.search}\n />\n <SearchResults results={this.state.filtered} sortBy={this.sortBy} />\n </Col>\n </Row>\n </Container>\n );\n }", "renderSearchBar () {\n const changeHandler = this.setPattern\n\n return (\n <input\n id='search-bar'\n className='search'\n placeholder='Search'\n onChange={changeHandler}\n />\n )\n }", "render() { \n return (\n <div>\n <h3 className=\"display-4\" title=\"topic of search term\">TOPIC: <span className=\"badge badge-secondary\">{this.state.searchTerm}</span></h3>\n <SearchResult key={this.props.search} value={this.props.search} onChange={this.handleChange} ></SearchResult>\n </div>\n );\n }", "render() {\n return (\n // className to give it a class - then css the hell out of it\n // note it is done with jsx instead of html, attributes are slightly different (className instead of class)\n <div className=\"search-bar\">\n <input\n // input value is that of the state.term. This is where it is held in the document\n // okay to referenece state but never modify this way. Only modify using this.setState(). Value of input will update everytime state is modified.\n // here we are telling it that the value of the input is equal to the state\n value={this.state.term}\n //all html input elements emmit a change event whenever a user reacts with them. \n //To use these browser events, simply use 'on' and the name of the event 'Change' then set it equal to the method you want to use. Also include the event handler as simply event=>. Keep it all in curly braces.\n //method syntax should follow basic structure of 'on' or 'handle' follow by the element watching for events, and then the name of the event itself. This way it tells its purpose.\n // event argument (what gets passed into the event handler) will provide the information about the event that occured. Can use this to get value of input.\n //Change is the name of the event we are wishing to tap into. This is a plain vanillaJS with HTML thing. Please look into different events\n onChange={event => this.onInputChange(event.target.value)}\n />\n </div>\n );\n }", "function Search(props){\n return (\n <div className=\"search-cont side-content\">\n <h1>Search</h1>\n <form>\n <label htmlFor=\"search-name\">Title</label>\n <input id=\"search-name\" onChange={(ev) => props.changeFilter(ev, 'title')}></input>\n <label htmlFor=\"search-studio\">Studio</label>\n <input id=\"search-studio\" onChange={(ev) => props.changeFilter(ev, 'studio')}></input>\n <label htmlFor=\"search-content\">Content</label>\n <input id=\"search-content\" onChange={(ev) => props.changeFilter(ev, 'synopsis')}></input>\n </form>\n </div>\n )\n }", "render(){\n return (\n <div className=\"container\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> \n <div id=\"search\" className=\"search\">\n <input \n type=\"text\" \n name=\"search\" \n id=\"search-input\" \n className=\"search-input\" \n placeholder=\"Search movie by title...\"\n ref={input => this.search = input} \n onChange={this.changeInput} /> \n\n <br /><br /> \n </div>\n <LoadingIndicator />\n <br /> \n <ResultsContainer results={this.state.results} query={this.state.query}/> \n </div>\n );\n }", "render() {\n return (\n <div className=\"search-bar\">\n <input\n value={this.state.term}\n onChange ={event => this.onInputChange(event.target.value)} />\n </div>\n );\n }", "render() {\n\t\tconst { handleSubmit } = this.props;\n\t\treturn (\n\t\t\t<React.Fragment>\n\t\t\t\t<Header />\n\t\t\t\t<div className=\"container\">\n\t\t\t\t\t<form className=\"form-group pt-5\" onSubmit={handleSubmit(this.onSubmit)}>\n\t\t\t\t\t\t<Field name=\"searchTerm\" component={this.renderSearchBar} />\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tclassName=\"btn btn-primary\"\n\t\t\t\t\t\t\tid=\"submit-button\"\n\t\t\t\t\t\t\tstyle={{ marginLeft: '45%', marginTop: '10px' }}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\tSearch\n\t\t\t\t\t\t</button>\n\t\t\t\t\t</form>\n\n\t\t\t\t\t<div className=\"video-list\">{this.renderVideos()}</div>\n\t\t\t\t</div>\n\t\t\t</React.Fragment>\n\t\t);\n\t}", "render() {\n return (\n <div>\n <form onSubmit={this.onFormSubmit} className=\"searchBar\">\n <input\n className=\"search-bar\"\n placeholder=\"search by ingredients\"\n value={this.state.term}\n onChange={this.onInputChange}\n />\n <button className=\"search-button\" type=\"submit\">\n <i className=\"fa fa-search\" />\n </button>\n </form>\n </div>\n );\n }", "render() {\n const { final, title, open } = this.state;\n const {\n dataList,\n displayKey,\n searchKey,\n searchItem,\n alignSearchItem\n } = this.props;\n return (\n <div className=\"container\" ref={this.container}>\n <div onClick={this.togglePanel} className=\"header\" role=\"presentation\">\n {title}\n <i className=\"fa fa-caret-down\" />\n </div>\n {open ? (\n <div className=\"content\">\n <SearchInput\n dataList={dataList}\n displayKey={displayKey}\n searchKey={searchKey}\n searchItem={searchItem}\n alignSearchItem={alignSearchItem}\n selectOptions={this.selectOptions}\n getIndexes={this.getIndexes}\n onBlur={this.togglePanel}\n />\n <div className=\"scroll\">\n {final.map(item => {\n return (\n <div\n onClick={this.selectValue}\n role=\"presentation\"\n key={item}\n className=\"options\"\n style={{\n textAlign: \"left\",\n borderTop: \"1px solid lightgray\",\n padding: \"10px\"\n }}\n >\n {item}\n </div>\n );\n })}\n </div>\n </div>\n ) : null}\n </div>\n );\n }", "render() {\n\t\treturn (\n\t\t\t<form>\n\t\t\t\t<input \n\t\t\t\t \ttype=\"text\" \n\t\t\t\t \tplaceholder=\"Search...\" \n\t\t\t\t \tvalue={this.props.filterText} />\n\t\t\t\t<p>\n\t\t\t\t\t<input \n\t\t\t\t\t\ttype=\"checkbox\" \n\t\t\t\t\t\tchecked={this.props.inStockOnly} />\n\t\t\t\t\t{' '}\n\t\t\t\t\tOnly show products in stock\n\t\t\t\t</p>\n\t\t\t</form>\n\t\t);\n\t}", "function SearchBar(props) { \n return (\n <div>\n <div className=\"search-container\">\n <input type=\"text\" placeholder={props.placeholder}\n name=\"search\"\n onChange={(e) => props.onChange(e)}\n >\n </input>\n <button type=\"submit\" onClick={() => props.onClick()}><img alt=\"\" className=\"searchImg\" src={searchImg}></img></button>\n </div>\n\n </div>\n ) \n}", "render() {\n const {showOptions, data, selected, searchKey, loading} = this.state;\n \n return <div className=\"auto-complete\" onClick={this.onContentClick}>\n <div className=\"label-c\">\n <input ref={this.inputRef} onBlur={this.onBlur} onChange={this.debounceSearch} onFocus={this.onFocus}/>\n {!showOptions &&\n <div className=\"label\" onClick={() => this.onFocus(null, true)}>{selected} {!selected && <span>Search</span>}</div> \n } \n </div>\n {showOptions && (\n <div className=\"dropdown\">\n {loading && <div className=\"loader\"></div>}\n {searchKey && data.length === 0 && !loading && <div className=\"no-res\">No Results</div>}\n <div className=\"lists\">\n {data.map(d => \n <div className=\"list-itm\" key={d.name} onClick={() => this.onSelect(d)}>\n <HighletText text={d.name} highlet={searchKey}/>\n </div>\n )}\n </div>\n </div>\n )}\n \n </div>\n }", "renderHeaderSearch(iconName = \"menu\") {\n const left = (\n <Button transparent onPress={this._leftClick}>\n <Icon style={styles.menuIcon} name={iconName} />\n </Button>\n )\n const center = (\n <Item style={styles.searchContainer}>\n {/*<Icon name=\"search\" style={styles.searchIcon} />*/}\n <Input value={this.props.searchString}\n autoCapitalize=\"none\"\n autoCorrect={false} onChangeText={this._search}\n placeholderTextColor=\"#222\" style={styles.searchInput}\n placeholder=\"Novame Search\" />\n </Item>\n )\n const right = (\n <Button transparent>\n <Icon style={styles.searchIcon} name=\"search\" />\n </Button>\n )\n return this.renderHeader(left, center, right)\n }", "render(){\n return (\n <div className=\"App\">\n\n <div id='searchDiv'>\n \n <SearchBar changingText={this.changeSearchText} />\n \n </div>\n\n <CoolContainer\n searchText={this.state.searchText}\n adjetive={word}\n />\n \n </div>\n );\n }", "render() {\n return (\n <div className=\"head-bar\">\n <h1 className=\"head-title\">POLUTFORSKER</h1>\n <form className=\"search-form\" onSubmit={this.handleSubmit}>\n <Field\n name=\"search\"\n component=\"input\"\n type=\"text\"\n placeholder=\"Search...\"\n />\n </form>\n </div>\n );\n }", "searchBarCondition() {\n return <Grid className=\"Search\" item xs={12} sm={6}>\n <h1>Search Movies</h1>\n <div className=\"SearchBar\">\n <form onSubmit={this.handleSubmit}>\n <label>\n <input type=\"text\" value={this.state.searchVal} ref={el => this.searchBar = el} onChange={this.handleSearchInputChange} />\n </label>\n <input type=\"submit\" value=\"Search\" />\n {this.state.searchVal != \"\" && this.clearSearchButton()}\n </form>\n </div>\n <div className=\"ScoreRange\">\n <RangeSlider handleSliderChange={this.handleSliderChange}></RangeSlider>\n </div>\n <div className=\"Genres\">\n <GenreSelect handleGenreChange={this.handleGenreChange}></GenreSelect>\n </div>\n </Grid>\n }", "render(){\n\t\t//videoSearch can only now be called every 300 milliseconds\n\t\tconst videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300);\n\t\t//old: <SearchBar onSearchTermChange = {term => this.videoSearch(term)} />\n\t\treturn (\n\t\t<div>\n\t\t\t<SearchBar onSearchTermChange = {videoSearch} />\n\t\t\t<VideoDetail video={this.state.selectedVideo}/>\n\t\t\t<VideoList \n\t\t\t\tonVideoSelect={selectedVideo => this.setState({selectedVideo}) }\n\t\t\t\tvideos={this.state.videos}/>\n\t\t</div>);\n\t}", "render() {\r\n\t\t// on the input element we're setting the state value and on the very next line we're displaying it.\r\n\t\t//if you want to reference js variable, wrap them in {}\r\n\t\t//here we set the state with this.state.searchKeyWord with whatever we tyoe inside the input box\r\n\t\t//and whenever we update our state with this.setState it causes our comp. to automatically re-render.\r\n\t\t//and push all the updated info. from render method to DOM.\r\n\t\treturn (\r\n\t\t\t<div className=\"search-bar\">\r\n\t\t\t\t\t{/* \r\n\t\t\t\t\t\ttry to comment onChage line, now you can't type anything inside the input box\r\n\t\t\t\t\t\tthe reason is we're setting the value of input to this.state.searchKeyWord which in our\r\n\t\t\t\t\t\tcase is '' if you're not setting the state value. Instead of empty string we can also use\r\n\t\t\t\t\t\tsome other info that is visible to user before updating the state.\r\n\t\t\t\t\t\tThis is called controlled comp. in React, without setting the state we can't chage it's value.\r\n\t\t\t\t\t\tA controlled comp. has it's value set by state, so it's value only ever changes when\r\n\t\t\t\t\t\tstate changes. Refer video-18 for more info \r\n\t\t\t\t\t*/}\r\n\t\t\t\t<input \r\n\t\t\t\t\tvalue={this.state.searchKeyWord}\r\n\t\t\t\t\tonChange={event => this.onInputChage(event.target.value)} />\r\n\t\t\t\t{/* this is how comment looks like in JSX */}\r\n\t\t\t\t{/* just un-comment the below code, that's how we're displaying the value we set on previous line */}\r\n\t\t\t\t{/* Value of input: {this.state.searchKeyWord} */}\r\n\t\t\t</div>\r\n\t\t);\r\n\t}", "render() {\n return (\n <div>\n <center>\n <div className=\"Item-List\">\n <div style={{\"width\": \"100%\", \"textAlign\": \"center\"}}>\n <span>Results for&nbsp;\n {this.props.search.length === 0 ? \"''\" : \"'\" + this.props.search + \"'\"}.\n </span>\n </div>\n <br/>\n\n {((this.props.search === '' || this.props.start_search === false) && !this.state.loading) ?\n // Gif when results are empty\n (<div>\n <p>Search someone.</p>\n </div>) :\n\n // Condition that checks if the results are finished loading\n (this.props.start_search !== '' && this.state.loading) ?\n // Loading gif when waiting for the fetch results\n (<img src=\"/loading.gif\" alt=\"\"/>) :\n // Function call that will return an appropriate render object\n (this.renderResults())}\n </div>\n </center>\n </div>\n );\n }", "render() {\n return (\n\t\t<div className=\"search-books\">\n <div className=\"search-books-bar\">\n\t\t\t\t<Link to='/' className=\"close-search\">\n\t\t\t\t\t\tClose\n\t\t\t\t</Link>\n\t\t\t\t<div className=\"search-books-input-wrapper\">\n \t<input \n\t\t\t\t\t\ttype=\"text\" \n\t\t\t\t\t\tplaceholder=\"Search by title or author\"\n\t\t\t\t\t\tonChange={(event) => {\n\t\t\t\t\t\t\tthis.props.search(event.target.value)\n\t\t\t\t\t\t\tthis.setState({searchQuery: event.target.value})\n\t\t\t\t\n\t\t\t\t\t\t}}\n\t\t\t\t\t/>\n </div>\n\n </div>\n\n\t<div className=\"search-books-results\">\n\t\t\n{this.checkResults()}\n{console.log(this.state)}\n\t</div>\n </div>\n\t\n )\n }", "render($$) {\n const header = $$('div')\n .addClass(styles.header)\n .append([\n $$('div')\n .addClass(styles.logoWrapper)\n .append([\n $$('a').addClass(styles.logo),\n $$('h3')\n .addClass(styles.heading)\n .append(this.getLabel('Oovvuu Video Search')),\n ]),\n this.getAuthComponents($$),\n ]);\n\n const container = $$('div')\n .addClass(styles.wrapper)\n .append(header);\n\n if (this.state.authenticated !== true) {\n return container;\n }\n\n return container.append(\n $$(SearchWrapper, {\n genres: this.state.genres ?? [],\n providers: this.state.providers ?? [],\n }),\n );\n }", "render() {\n return (\n <header className=\"menu\">\n <div className=\"menu-container\">\n <div className=\"menu-holder\">\n <h1>ELC</h1>\n <nav>\n <a href=\"#\" className=\"nav-item\">HOLIDAY</a>\n <a href=\"#\" className=\"nav-item\">WHAT'S NEW</a>\n <a href=\"#\" className=\"nav-item\">PRODUCTS</a>\n <a href=\"#\" className=\"nav-item\">BESTSELLERS</a>\n <a href=\"#\" className=\"nav-item\">GOODBYES</a>\n <a href=\"#\" className=\"nav-item\">STORES</a>\n <a href=\"#\" className=\"nav-item\">INSPIRATION</a>\n\n <a href=\"#\" onClick={(e) => this.showSearchContainer(e)}>\n <i className=\"material-icons search\">search</i>\n </a>\n\n </nav>\n </div>\n </div>\n <div className={(this.state.showingSearch ? \"showing \" : \"\") + \"search-container\"}>\n <input type=\"text\" onChange={(e) => this.onSearch(e)} value={this.state.searchTerm}/>\n <a href=\"#\" onClick={(e) => this.showSearchContainer(e)}>\n <i className=\"material-icons close\">close</i>\n </a>\n { /* TODO All this should be in a SearchResults component */}\n {this.state.searchResults.items.length > 0 && (\n <div>\n <p className=\"results-info\">{`Showing ${this.state.searchResults.items.length} of ${this.state.searchResults.total} products` }</p>\n <div className=\"search-results\">\n {this.state.searchResults.items.map((item) => (\n <div key={item._id} className=\"result-item\" >\n <h3 className=\"item-title\">{item.name}</h3>\n <div className=\"item-body\">\n <img src={item.picture} alt={`Picture of ${item.name}`} />\n <p className=\"item-description\">{ item.about }</p>\n </div>\n </div>))}\n </div>\n </div>\n )}\n </div>\n </header>\n );\n }", "render() {\n\n // Canviem els this.states per this.props en el cas de fer servir l'store\n return <main className=\"container\">\n <SearchForm onSubmit={this.onSubmit} search={this.props.search}/>\n <RepositoryList\n data={this.props.results} search={this.props.search}\n loading={this.props.loading} queried={this.props.queried}/>\n </main>;\n }", "render() {\n return (\n <>\n <SearchBar handleSearch={this.handleSearch} />\n <SearchResTable\n employees={this.state.filteredEmployees}\n handleSort={this.handleSort}\n />\n </>\n );\n }", "function SearchLight(props) { return <SearchInput initText={ props.initText } appTheme={ props.appTheme } onSubmit={ props.onSubmit } onDismiss={ props.onDismiss }/> }", "render() {\n\t\tconst { text } = this.state;\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t<form className=\"form-inline AutoCompleteText my-2 my-lg-0\">\n\t\t\t\t\t<input\n\t\t\t\t\t\tvalue={text}\n\t\t\t\t\t\tonChange={this.onTextChanged}\n\t\t\t\t\t\tclassName=\"form-control mr-sm-2 text-monospace\"\n\t\t\t\t\t\ttype=\"search\"\n\t\t\t\t\t\tplaceholder=\"SEARCH\"\n\t\t\t\t\t\taria-label=\"Search\"\n\t\t\t\t\t/>\n\t\t\t\t\t{this.renderSuggestions()}\n\t\t\t\t</form>\n\t\t\t</div>\n\t\t);\n\t}", "render() {\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t<Jumbotron>\n\t\t\t\t\t<h1>Google Book Search</h1>\n\t\t\t\t\t<h3 />\n\t\t\t\t</Jumbotron>\n\t\t\t\t<Link type=\"button\" className=\"btn btn-primary\" to=\"/saved\">\n\t\t\t\t\tSaved\n\t\t\t\t</Link>\n\t\t\t\t<Link type=\"button\" className=\"btn btn-primary\" to=\"/\">\n\t\t\t\t\tSearch\n\t\t\t\t</Link>\n\t\t\t\t<Container>\n\t\t\t\t\t<Row>\n\t\t\t\t\t\t<SearchBar\n\t\t\t\t\t\t\tvalue={this.state.searchInput}\n\t\t\t\t\t\t\tonChange={this.handleInputChange}\n\t\t\t\t\t\t\tname=\"title\"\n\t\t\t\t\t\t\tplaceholder=\"Search Book Title\"\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t<SearchBtn onClick={this.handleFormSubmit} className=\"btn btn-primary\" buttonTitle=\"Search\" />\n\t\t\t\t\t</Row>\n\t\t\t\t\t<h2>Book Results</h2>\n\n\t\t\t\t\t{this.state.showBooks.map((book, index) => (\n\t\t\t\t\t\t<div key={index}>\n\t\t\t\t\t\t\t<BookListItem\n\t\t\t\t\t\t\t\timage={\n\t\t\t\t\t\t\t\t\tbook.volumeInfo.imageLinks.thumbnail ? book.volumeInfo.imageLinks.thumbnail : null\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttitle={book.volumeInfo.title}\n\t\t\t\t\t\t\t\tauthor={book.volumeInfo.authors[0]}\n\t\t\t\t\t\t\t\tdescription={book.volumeInfo.description}\n\t\t\t\t\t\t\t\tdate={book.volumeInfo.date}\n\t\t\t\t\t\t\t/>\n\n\t\t\t\t\t\t\t<Link to={`/book/${book.id}/${book.volumeInfo.title}`}>View</Link>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t))}\n\t\t\t\t</Container>\n\t\t\t</div>\n\t\t);\n\t}", "function Search(props) {\n return (\n <div className=\"Search\">\n <label id=\"searchBar\">\n <input id=\"searchInput\" placeholder=\"Enter your search here...\" onChange={(event) => props.searchContent(event)}></input>\n <select id=\"media\" onChange={(event) => props.searchMedia(event)}>\n <option>--Media--</option>\n <option>music</option>\n <option>movie</option>\n <option>podcast</option>\n <option>musicVideo</option>\n <option>audiobook</option>\n <option>shortFilm</option>\n <option>tvShow</option>\n <option>software</option>\n <option>ebook</option>\n </select>\n <button id=\"searchButton\" type=\"submit\" onClick={props.search}>Search</button>\n </label>\n </div>\n );\n}", "_renderFilter() {\n return (React.createElement(\"div\", { className: filterWrapperClass },\n React.createElement(\"div\", { className: filterClass },\n React.createElement(\"input\", { className: filterInputClass, type: \"text\", onChange: this._onFilterChange, value: this.state.filter, placeholder: \"Filter\", title: \"Filter branch menu\" }),\n this.state.filter ? (React.createElement(\"button\", { className: filterClearClass },\n React.createElement(ClearIcon, { titleAccess: \"Clear the current filter\", fontSize: \"small\", onClick: this._resetFilter }))) : null)));\n }", "render() {\n const { robots, searchfield } = this.state;\n const filteredRobots = robots.filter(robot =>{\n return robot.name.toLowerCase().includes(searchfield.toLowerCase());\n });\n if(!robots.length) {\n return <h1>Loading</h1>\n }\n else {\n return(\n <div className='tc'>\n <h1 className='f1'>Mr. Robot and Friends</h1>\n <SearchBox searchChange={this.onSearchChange}/>\n <Scroll>\n <ErrorBoundary>\n <CardList robots={filteredRobots}/>\n </ErrorBoundary>\n </Scroll>\n </div>\n );\n }\n }", "render() {\n let { foundBooks } = this.state;\n let { handleShelfUpdate } = this.props;\n return (\n <div className=\"search-books\">\n <div className=\"search-books-bar\">\n <Link className=\"close-search\" to=\"/\">\n Close\n </Link>\n <div className=\"search-books-input-wrapper\">\n <input\n type=\"text\"\n placeholder=\"Search by title or author\"\n onChange={(event) => this.searchBooks(event.target.value)}\n />\n </div>\n </div>\n <div className=\"search-books-results\">\n {foundBooks.length > 0 ? (\n <ShelfRow\n books={foundBooks}\n shelfName={\"Search Results\"}\n handleShelfUpdate={handleShelfUpdate}\n />\n ) : null}\n </div>\n </div>\n );\n }", "render() {\n return (\n <div>\n <SelectSearch options={this.props.options} value={this.props.value} />\n </div>\n );\n }", "function Searchbar({searchfield,searchChange}){\r\n\treturn(\r\n\t\t\t<div>\r\n\t\t\t\t<input className=\"pa3 ba b--green bg-lightest-green\" \r\n\t\t\t\ttype=\"search\" \r\n\t\t\t\tplaceholder=\"Search!!\"\r\n\t\t\t\tonChange={searchChange} />\r\n\t\t\t\t// triggers searchChange method of main app component event\r\n\t\t\t</div>\t\r\n\t);\r\n}", "render(){\n return(\n <div className = \"item-search-box\">\n <img className = \"query-image\" src = {this.props.image}/>\n <div className = \"inline-text\">\n <h2>\n {this.props.title}\n </h2>\n <p className =\"author-text\">\n By {this.props.author}\n </p>\n </div>\n <button className = \"in-library\">\n IN LIBRARY\n </button>\n \n </div>\n )\n }", "render(){\n const {robotsNewFromSearch, searchField} = this.state\n const filteredRobots = robotsNewFromSearch.filter(robot=>{\n return robot.name.toLowerCase().includes(searchField.toLowerCase())\n })\n // console.log(filteredRobots)\n if(!filteredRobots.length){\n return <h1>Loading</h1>\n }else{\n return (\n <Fragment>\n <section className='tc'>\n \n <h1 className='f1'>Robo Friends</h1> \n {/* data flow--inpute----> */}\n <SearchBox inputSearch={this.dataFromInpute}/>\n \n {/* <----output----data flow */}\n <Scroll>\n <CardList robotsPassed={filteredRobots} />\n </Scroll>\n </section>\n </Fragment> \n )\n }\n\n }", "render() {\n return (\n <div>\n <Input placeholder='Search Here' value={this.state.searchTerm} onChange={this.handleSearch.bind(this)} onBlur={this.handleSearch.bind(this)} />\n <h3>Results:</h3>\n <p> {this.searchFunction(this.state.searchTerm).map(thing => (\n <li>{thing}</li>\n ))}</p>\n </div>\n );\n }", "search() {\n let location = ReactDOM.findDOMNode(this.refs.Search).value;\n if (location !== '') {\n let path = `/search?location=${location}`;\n makeHTTPRequest(this.props.updateSearchResults, path);\n }\n }", "render() {\n console.log(this.props)\n return <div>\n <input type=\"text\" placeholder=\"Search\" onChange={this.props.Changer} value={this.props.input} />\n <button type=\"button\" onClick={this.props.titleSearch} style={{ marginBottom: \"30px\" }}>Search</button>\n </div>\n }", "render() {\n return (\n <div>\n <SearchBox \n handleInputChange={this.handleInputChange} \n />\n <TableResults \n results={this.state.results} \n onSortChange={this.onSortChange} \n search={this.state.search}\n />\n </div>\n );\n }", "render() {\n\n\t\tconst {locations, query} = this.props;\n\t\tconst locationList = locations.filter(\n\t\t\titem => item.title.toLowerCase().indexOf(query.toLowerCase()) !== -1);\n\t\t\n return (<div className=\"options-box\">\n <header><h1>Find Your Neighborhood Places</h1></header> \t\n \n <input type=\"text\" className=\"search-location\" tabIndex=\"0\" role=\"search\" placeholder=\"Search Places\" value={query}\n onChange={event => this.props.searchByQuery(event)}/>\n <div>\n \t<ul className=\"location-item-list\">\n \t{locationList.map((item, index) => (\n\t\t\t\t\t\t\t<LocationListItem key={index} location={item} markerClick={item => {\n\t\t\t\t\t\t\t\tthis.props.markerClick(item);\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\n \t</ul> \n </div>\n </div>); \n\t}", "renderSearchPage() {\n\t\tfor (let iter = 0; iter < this.sidebarOptions.length; iter++)\n\t\t\tif (\n\t\t\t\tthis.optionRefs[iter].current.classList.contains(\n\t\t\t\t\t\"sidebar-button-active\"\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthis.optionRefs[iter].current.classList.remove(\n\t\t\t\t\t\"sidebar-button-active\"\n\t\t\t\t);\n\t\tthis.setState({ ...this.state, sidebarOptionSelected: 9 });\n\t}", "render() {\n // handling user inputs with property onChange\nreturn (\n <div className =\"search-bar\">\n <input\n value={this.state.term}\n onChange={event => this.onInputChange(event.target.value)}/>\n\n </div>\n );\n }", "function Search(props) {\n return (\n <div className=\"form-group\">\n <label >Search Name:</label>\n <input\n type = \"search\"\n onChange={event => props.getFilterEmployees(event)}\n />\n </div>\n );\n}", "displaySearch() {\n\n //first retrieve all docs again, to reverse any filters\n db.allDocs({\n include_docs: true\n }, (err, doc) => {\n if (err) {\n return this.error(err);\n }\n if (doc.rows.length > 0) {\n this.setState({\n pageLoading: false\n });\n this.redrawResources(doc.rows);\n }\n });\n this.setState({\n appbarTitle: 'ShoutHealth'\n });\n this.setState({\n appbarSubtitle: 'Find Accessible Healthcare.'\n });\n this.setState({\n appbarState: false\n });\n this.setState({\n appbarIcon: <NavigationMenu />\n });\n this.setState({\n searchBar: <SearchInputs container={this.refs.content}\n getSearchstring={()=>this.state.searchString}\n filterResources={(searchString)=>this.filterResources(searchString)}\n searchString={this.state.searchString}\n getselectedIndex={()=>this.state.selectedIndex}\n onSelect={(index) => this.footerSelect(index)}/>\n });\n this.setState({\n screen: <Search container={this.refs.content}\n footer={this.refs.footer}\n displayResult={(result) => this.displayResult(result)}\n displaySearch={() => this.displaySearch()}\n filterResources={(string) => this.filterResources(string)}\n displayAddResource={() => this.displayAddResource()}\n getFilteredResources={() => this.state.filteredResources}\n getPageLoading={() => this.state.pageLoading}\n onGoogleApiLoad={(map, maps) => this.onGoogleApiLoad(map, maps)}\n userLat={this.state.userLat} userLng={this.state.userLng}\n getSearchstring={()=>this.state.searchString} />\n });\n\n }", "attached() {\n this.renderUniversalSearch();\n }", "render(){\n //on change is a react defined property\n // we could have the onInputChange as a function outside and call this.onInputChange\n //with es6 can call function directly and as it is one line don't need curly braces\n //we can even omit the leading braces around the event argument as there is only one\n return(\n <div className=\"search-bar\">\n <input\n value = {this.state.term}\n onChange={event => this.onInputChange(event.target.value)} />\n {/*Value of the input : {this.state.term}*/}\n </div>\n\n ) ;\n }", "searchContent(){\n if(this.state.results.length === 0){\n return(<h1>NO RESULTS</h1>);\n }\n else{\n return(\n <Items results={this.state.results} />\n )\n }\n }", "render(){\n const styleInfo = {\n paddingRight:'10px'\n }\n const elementStyle ={\n border:'solid',\n borderRadius:'10px',\n position:'relative',\n left:'10vh',\n height:'3vh',\n width:'20vh',\n marginTop:'5vh',\n marginBottom:'10vh'\n }\n //filters through posts\n const items = Information.filter((data)=>{\n if(this.state.search == null)\n return data\n else if(data.name.toLowerCase().includes(this.state.search.toLowerCase()) || data.breed.toLowerCase().includes(this.state.search.toLowerCase())){\n return data\n }\n })\n //maps returned posts\n .map(data=>{\n return(\n <div>\n <Card\n style={{ width: 320 }}\n cover={<NavImage src={data.imageURL} to={`/post/${data.ID}`} />}\n hoverable={true}\n actions={[\n ]}>\n \n <Meta title={data.name} description={data.breed} />\n </Card>\n </div>\n )\n })\n\n return (\n <div>\n <input type=\"text\" placeholder=\"Enter item to be searched\" style={elementStyle} onChange={(e)=>this.searchSpace(e)} />\n {items}\n </div>\n )\n }", "render() {\n return (\n <section className=\"home\">\n <div className=\"home-container\">\n <div className=\"home-form\">\n <Titulo>Buscador de Peliculas</Titulo>\n <Formulariobusqueda onResults={this.handleResults}></Formulariobusqueda>\n </div>\n\n <div className=\"home-description\">\n { /*si el usuario ingreso el texto de una pelicula a buscar entonces se renderizan los*/}\n {\n this.state.usedSearch\n ? this.renderResults()\n : <h6>Podes buscar peliculas,series y Videojuegos</h6>\n }\n </div>\n\n <div className=\"home-credits\">\n <p><i>\n Aplicacion construida con ReactJS\n </i></p>\n <small>Desarrollador: Almiron Cristian</small>\n \n </div>\n\n </div>\n </section>\n );\n }", "_renderInput(css) {\n return (\n <div className={`inputContainer ${css}`}>\n <input value={this.state.query} type=\"text\" className=\"\" placeholder=\"Search...\" id=\"searchText\" onChange={(e) => this.setState({ query: e.target.value })}\n onKeyPress={(e) => {\n if (e.key === 'Enter')\n this.search();\n }}\n />\n <button onClick={() => this.search()}>\n <img src={searchIconC} alt=\"\" />\n </button>\n </div>\n )\n }", "render() {\n const { gotcaste, searchfield } = this.state;\n //filtering and showing only those characters whose name matches the input value\n const filteredChars = gotcaste.filter(char => {\n return char.name.toLowerCase().includes(searchfield.toLowerCase());\n });\n return (\n <div className=\"tc\">\n <h1 className=\"f1\">GOT FLASH CARDS</h1>\n {/*Passing props*/}\n <Searchbox\n searchChange={this.onSearchChange}\n placeholder={\"search characters...\"}\n />\n <CardList arr={filteredChars} />\n </div>\n );\n }" ]
[ "0.7845681", "0.7794488", "0.764205", "0.75933236", "0.74759215", "0.74707884", "0.7363707", "0.73508847", "0.7344061", "0.7335953", "0.7325167", "0.73117745", "0.7269368", "0.7254632", "0.724693", "0.7229457", "0.71430224", "0.71334285", "0.71125776", "0.7060655", "0.7041672", "0.70107096", "0.69891334", "0.6980095", "0.6968234", "0.69654566", "0.6960775", "0.6942248", "0.6930574", "0.6919529", "0.6898917", "0.68896323", "0.68871117", "0.68871117", "0.68775934", "0.6842643", "0.6841123", "0.68329424", "0.6820899", "0.6773748", "0.672597", "0.67171544", "0.6707542", "0.67060244", "0.66999364", "0.6685939", "0.66854393", "0.66416174", "0.6635723", "0.6604861", "0.6589314", "0.6582679", "0.6580875", "0.6564607", "0.6557338", "0.6555753", "0.6533696", "0.6498354", "0.647018", "0.6465653", "0.6464848", "0.646408", "0.64550894", "0.6454426", "0.6447614", "0.6441791", "0.6424147", "0.6417156", "0.64147156", "0.6405821", "0.6392827", "0.63866484", "0.6381757", "0.6366657", "0.6365437", "0.6362608", "0.63594395", "0.6357919", "0.6351498", "0.63428086", "0.6336034", "0.63183385", "0.6276124", "0.62747914", "0.6267037", "0.6265983", "0.6264747", "0.62540126", "0.6248754", "0.6241457", "0.6222749", "0.62186", "0.621825", "0.6198237", "0.6180573", "0.6158562", "0.6142839", "0.6134124", "0.6133128", "0.61252785" ]
0.7320015
11
to get the coordinate from the address
function jsonTransform() { console.log("in json function"); $.getJSON("ajax/WagPregeo.json",function(data) { $.each(data,function(key, val) { addressArray.push({id: val.id, name: val.name,addresseng: val.addresseng, addresscn: val.addresscn}); }); initializeGeo(); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static async getCoordsFromAddress(address = '') {\n const platform = this.setPlatform();\n let data = {};\n const geocoder = platform.getGeocodingService();\n const geocodingParams = {\n searchText: address\n };\n await geocoder.geocode(geocodingParams, (result) => {\n const locations = result.Response.View[0].Result;\n if (locations[0]) {\n data = {\n lat: locations[0].Location.DisplayPosition.Latitude,\n lng: locations[0].Location.DisplayPosition.Longitude\n };\n }\n });\n return data;\n }", "async function getCoordsFromAddress(address) {\n const response = await fetch(`https://geocode-maps.yandex.ru/1.x/?format=json&apikey=${YANDEX_API_KEY}&geocode=${address}`);\n if (!response.ok) {\n throw new Error('failed to fetch coordinates, try again')\n }\n const data = await response.json();\n if (data.error) {\n throw new Error(data.message)\n }\n const coordsArr = data.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos.split(' ');\n return {lng: coordsArr[0], lat: coordsArr[1]}\n}", "function getCoordinates(address) {\n var apiToken = \"pk.eyJ1IjoiY3B0c3Bvb2t5IiwiYSI6ImNrZDlpcDRheDA0b2IzM2pxZDZzNnI2Y2cifQ.0GQCDJlDIwPOy_9uR0Vgsw\";\n var mapboxURL = \"https://api.mapbox.com/geocoding/v5/mapbox.places/\" + address + \".json?access_token=\" + apiToken;\n\n $.ajax({\n url: mapboxURL,\n method: 'GET'\n }).then(function(response) {\n renderMarker(response.features[0].center);\n });\n }", "function GetAddress(address) {\n return ParseAddress(address)[1];\n}", "function getPosition(address){\n console.log('Convertendo:',address)\n return new Promise( (resolve, reject)=>{\n googleMapsClient.geocode({\n address: address\n }, (err, response) => {\n if (!err) {\n let location = {\n formatted_address: response.json.results[0].formatted_address,\n latitude: response.json.results[0].geometry.location.lat,\n longitude: response.json.results[0].geometry.location.lng\n }\n resolve(location)\n } else {\n reject(err)\n }\n });\n })\n}", "function getLatLngFromAddress(address){\n\tvar geocoder = new google.maps.Geocoder();\n\tgeocoder.geocode({'address': address}, function(results, status){\n\t\tconsole.log(status);\n\t\tconsole.log(results[0].geometry.location);\n\t\treturn results[0].geometry.location;\n\t});\n\n}", "function GetLatLngForLocation(address) {\n\tRequiredLatitude = \"\";\n\tRequiredLongitude = \"\";\n\n\tif ($.trim(address).length == 0)\n\t\treturn;\n\n\ttry {\n\t\tvar geocoder = new google.maps.Geocoder();\n\t\taddress = address + \",Australia\";\n\n\t\tgeocoder.geocode({ 'address': address }, function (results, status) {\n\t\t\tif (status == google.maps.GeocoderStatus.OK) {\n\t\t\t\t// alert(\"Address : \" + results[0].formatted_address + \"\\n\" + \"Coordinates : \" + results[0].geometry.location);\n\t\t\t\tRequiredLatitude = results[0].geometry.location.lat();\n\t\t\t\tRequiredLongitude = results[0].geometry.location.lng();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (typeof console === \"undefined\") {\n\t\t\t\t\tconsole.log(\"GetLatLngForLocation Error : \" + status);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t} catch (e) {\n\t\tif (typeof console === \"undefined\") {\n\t\t\tconsole.log(\"Google error getting location coordinates.\" + '\\n' + e);\n\t\t}\n\t}\n}", "GetPosition(address) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tvar geocoder = new window.google.maps.Geocoder();\n\t\t\tgeocoder.geocode( {'address' : address}, (results, status) => {\n\t\t\t\tif (status == window.google.maps.GeocoderStatus.OK) {\n\t\t\t\t\tresolve(results[0].geometry.location)\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treject()\n\t\t\t\t}\n\t\t\t})\n })\n\t}", "async getAddressCoord(){\n \n let url = new URL('https://api.tomtom.com/search/2/geocode/.json')\n url.search = new URLSearchParams({\n query: this.searchAddress,\n key: 'HgVrAuAcCtAcxTpt0Vt2SyvAcoFKqF4Z',\n versionNumber: '2',\n limit: '1'\n })\n \n const response = await fetch(url);\n\n const data = await response.json();\n this.lat = data.results[0].position.lat;\n this.lon = data.results[0].position.lon;\n\n console.log(this.lat);\n }", "function get_coordinate(address, region) {\n\n\tif(region==null || region == '' || region == 'undefined') {\n\t\tregion = 'us';\n\t}\n\n\tif(address != '') {\n\t\t$('#ajax_msg').html('<p>Loading location</p>');\n\n\t\tgeocoder.geocode( {'address':address,'region':region}, function(results, status) {\n\t\t\n\t\t\tif(status == google.maps.GeocoderStatus.OK) {\n\t\t\t\t$('#ajax_msg').html('<p></p>');\n\t\t\t\n\t\t\t\t$('#latitude').val( results[0].geometry.location.lat() );\n\t\t\t\t$('#longitude').val( results[0].geometry.location.lng() );\n\n\n\t\t\t\tmap.setZoom(10);\n\n\t\t\t\tmap.setCenter(results[0].geometry.location);\n\n\t\t\t\tvar marker = new google.maps.Marker({\n\t\t\t\t\tmap: map,\n\t\t\t\t\tposition: results[0].geometry.location\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\t$('#ajax_msg').html('<p>Google map geocoder failed: '+status+'</p>');\n\t\t\t}\n\t\t});\n\t}\n}", "function getAddress(placemark) {\n return placemark.address;\n }", "getCoordinatesByAddress() {\n if ( this.props.locationData.address.length > 0 ) {\n LocationActions.getCoordinatesByAddress(this.props.dispatch, this.props.locationData.address);\n }\n }", "function getLatLonCoordinates(address) {\n const baseURL = \"https://us1.locationiq.com/v1/search.php\";\n const params = {\n key: locationIQKey,\n street: address.street,\n city: address.city,\n county: address.county,\n state: address.state,\n country: address.country,\n postalCode: address.postalCode,\n format: \"json\",\n normalizecity: \"1\",\n addressdetails: \"1\",\n matchquality: \"1\",\n limit: \"50\"\n };\n const queryParams = formatQueryParams(params);\n const url = baseURL + \"?\" + queryParams;\n console.log(`Fetching data from the LocationIQ API: ${url}`);\n\n return fetchCoordinatesJson(url);\n }", "address(value) {\n return Object(address_lib_esm[\"a\" /* getAddress */])(value);\n }", "getAddress() {\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(\n (position) => {\n var requestOptions = {\n method: \"GET\",\n redirect: \"follow\",\n };\n\n fetch(\n `https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.coords.latitude},${position.coords.longitude}&key=AIzaSyDtU4wnc7N3-U9QMpRCG5CCaqCJc2nYuz8&language=en_AU`,\n requestOptions\n )\n .then((response) => response.text())\n .then((result) => {\n // console.log(\"address\",result);\n let res = JSON.parse(result);\n // console.log(\"address\", res.results[0].formatted_address);\n this.entered_address = res.results[0].formatted_address;\n })\n .catch((error) => console.log(\"error\", error));\n }\n // () => {\n // handleLocationError(true, infoWindow, map.getCenter());\n // }\n );\n } else {\n // Browser doesn't support Geolocation\n // handleLocationError(false, infoWindow, map.getCenter());\n }\n }", "function GetPosition(position) {\n lattitude = position.coords.latitude;\n longitude = position.coords.longitude;\n\n console.log(\"coordinates: \" + lattitude + \" \" + longitude);\n\n var latLng = new google.maps.LatLng(lattitude, longitude);\n var geocoder = new google.maps.Geocoder();\n var address;\n geocoder.geocode({ 'latLng': latLng }, function (results, status) {\n console.log(results[0].formatted_address);\n address = results[0].formatted_address;\n $(\"#location\").val(address);\n });\n}", "function coordsToAdress(coords) {\n const url =`https://www.mapquestapi.com/geocoding/v1/reverse?key=${GAPI_KEY}&location=${coords.coords.latitude},${coords.coords.longitude}`;\n console.log(coords);\n $.getJSON(url, function (response) {\n const addressObject = response.results[0].locations[0];\n const address = `${addressObject.street}, ${addressObject.adminArea5}, ${addressObject.adminArea3}`\n $(\"#from\").val(address);\n console.log(coords);\n });\n }", "function geocodeAddress(address, fn) {\n\tgeocoderPackage.geocoder.geocode(address, function(err, res) {\n\t\tfn(res[0]);\n\t});\n}", "function getLocation (address, language) {\n return Location.getLocation({\n address: address,\n language: language\n });\n }", "function getLatLng(){\n var address = document.getElementById('addressInput').value;\n geocode(address)\n .then(function(response){\n\t\t// var l = response.data.results[0].geometry.location;\n setLocation(response.data.results[0].geometry.location,true);\n })\n .catch(function(error){\n console.log(error)\n });\n}", "function addressToGeo (street, city, state, zip, radius) {\n fetch(`https://www.mapquestapi.com/geocoding/v1/address?key=${mapquestKey}&street=${street}&city=${city}&state=${state}&postalCode=${zip}`)\n .then(response => {\n return response.json();\n })\n .then(body => {\n let userLat = body.results[0].locations[0].latLng.lat\n let userLng = body.results[0].locations[0].latLng.lng\n console.log(\"User lat and lon: \", userLat, userLng)\n console.log(\"Minutes: \", radius)\n getResults(userLat, userLng, radius)\n })\n .catch(error => {\n console.error(\"ERROR\", error);\n return error;\n })\n}", "function getLatLonFromAddress(geocoder, resultsMap) {\n var address = document.getElementById('address').value;\n geocoder.geocode({\n 'address': address\n }, function(results, status) {\n if (status === google.maps.GeocoderStatus.OK) {\n $(\"#error-message\").html(\"\");\n resultsMap.setCenter(results[0].geometry.location);\n var latitude = results[0].geometry.location.lat();\n var longitude = results[0].geometry.location.lng();\n console.log(latitude);\n console.log(longitude);\n getNearbyLocations(latitude, longitude, resultsMap);\n } else {\n $(\"#error-message\").html(\"<p>Address is not availabble.</p>\");\n }\n\n });\n return false;\n}", "function GetPersonal(address) {\n return ParseAddress(address)[0];\n}", "function GetGeoAddress ( address\t///< This is either a string, or a GLatLng object. If the latter, this will be a reverse lookup.\n\t\t\t\t\t\t\t)\n\t{\n\t\tvar\tgeocoder = new google.maps.Geocoder;\n\t\t\n\t\tif ( geocoder )\n\t\t\t{\n\t\t\tvar\tstatus = geocoder.geocode ( { 'address' : address }, GeoCallback );\n\t\t\t\n\t\t\tif ( google.maps.OK != status )\n\t\t\t\t{\n\t\t\t\tif ( google.maps.INVALID_REQUEST != status )\n\t\t\t\t\t{\n\t\t\t\t\talert ( c_g_address_lookup_fail );\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\tif ( google.maps.ZERO_RESULTS != status )\n\t\t\t\t\t\t{\n\t\t\t\t\t\talert ( c_g_address_lookup_fail );\n\t\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\talert ( c_g_server_error );\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}\n\t\telse\t// None of that stuff is defined if we couldn't create the geocoder.\n\t\t\t{\n\t\t\talert ( c_g_server_error );\n\t\t\t};\n\t}", "function getLatitudeLongitude(address) {\n\t// If adress is not supplied, use default\n\tvar address = address || 'New York';\n\t// Initialize the Geocoder\n\tgeocoder = new google.maps.Geocoder();\n\tif (geocoder) {\n\t\tgeocoder.geocode({ 'address': address},\n\t\t\tfunction (results, status) {\n\t\t\tif (status == google.maps.GeocoderStatus.OK) {\n\t\t\t\tvar lat = results[0].geometry.location.lat();\n\t\t\t\tvar long = results[0].geometry.location.lng();\n\t\t\t\tvar location = new google.maps.LatLng(lat, long);\n\t\t\t\tif (marker) { // if marker already exists\n\t\t\t\t\tmarker.setPosition(location); //sets location to marker\n\t\t\t\t} else {\n\t\t\t\t\tmarker = new google.maps.Marker({ //creates a new marker object - somehow this one isn't working\n\t\t\t\t\t\t\tposition: location,\n\t\t\t\t\t\t\tmap: map,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tgetAddress(new google.maps.LatLng(lat, long));\n\t\t\t\tmap.panTo(location);\n\t\t\t\tconsole.log(lat);\n\t\t\t\tconsole.log(long);\n\t\t\t}\n\t\t});\n\t}\n}", "function handleAddress(value) {\n if (value === '0x') {\n return null;\n }\n return address_1.getAddress(value);\n}", "function getCoordinates(addressEntered) {\n $('.errorText').empty();\n var requestOptions = {\n method: 'GET',\n redirect: 'follow'\n };\n\n fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${addressEntered}&key=AIzaSyCGnZ67EDIku1msVd4nZwRzzB-rDPnGAZc`, requestOptions)\n .then(response => response.json())\n .then(responseJson => getPlaces(responseJson))\n .catch(error => $('.errorText').append(`<h4>Please enter your city and state.</h4>`));\n\n}", "function bindAddress(){\n\n \t// retrieve the address value\n \tvar address=$(\"#address\").val();\n\n \t// perform ajax call to nominatim\n \t$.ajax({\n \t\ttype: \"GET\",\n \t\turl: \"https://nominatim.openstreetmap.org/search\",\n \t\tdata: { q: address, format: \"json\", polygon : \"1\" , addressdetails :\"1\" }\n \t\t})\n \t\t.done(function( data ) { // if address found\n\n \t\t// takes the first geolocated data\n \t\t// and record current_marker variable\n \t\tcurrent_marker = data[0];\n \t\t// draws a marker from geolocated point\n \t\tsetMarker();\n\n \t});\n\n }", "function getaddressLocation(nameBrewery, city, first) {\n var queryURL = \"\";\n var zoomLevel = 0;\n if(nameBrewery === \"\"){\n zoomLevel = 11;\n } else{\n zoomLevel = 15;\n }\n \n if(first){\n var lat = 0;\n var long = 0;\n console.log(navigator);\n\n function success(pos) {\n lat = pos.coords.latitude;\n long = pos.coords.longitude;\n onLanding(lat, long, zoomLevel);\n console.log(\"success\")\n }\n\n function error(err) {\n lat = 41.8781;\n long = -87.6298;\n onLanding(lat, long, zoomLevel);\n console.log(err);\n console.warn(`ERROR(${err.code}): ${err.message}`);\n }\n navigator.geolocation.getCurrentPosition(success, error)\n\n } else{\n var address = nameBrewery.replace(/[\\/\\\\#,+()$~%'\":*?<>{}]/g, '');\n queryURL = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + address + \" \" + city + '.json?&access_token=' + key;\n console.log(queryURL);\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n console.log(response);\n if (response.features.length === 0) {\n $(\"#myModal\").modal();\n return;\n }\n $('.currentCity').html(city);\n var map = new mapboxgl.Map({\n container: 'map', // container id\n style: 'mapbox://styles/mapbox/streets-v11',\n center: [response.features[0].geometry.coordinates[0], response.features[0].geometry.coordinates[1]], // starting position\n zoom: zoomLevel // starting zoom\n })\n // Add zoom and rotation controls to the map.\n map.addControl(new mapboxgl.NavigationControl());\n\n var marker = new mapboxgl.Marker()\n .setLngLat([response.features[0].geometry.coordinates[0], response.features[0].geometry.coordinates[1]])\n .addTo(map);\n \n var checked = $('input:checked');\n if(checked.length === 0){\n getBreweries(city);\n }\n \n });\n }\n }", "function showAddress(address) {\n\t\tgeocoder = new GClientGeocoder();\n\t\tif (geocoder) {\n geocoder.getLatLng(\n address+\",India\",\n function(point) {\n if (!point) {\n alert(address + \" not found\");\n } else {\n\t\t //var lat=point.lat().toFixed(5);\n\t \t //var lang=point.lng().toFixed(5);\n\t \t document.getElementById('lath').value=point.lat().toFixed(5);\n\t \t document.getElementById('langh').value=point.lng().toFixed(5);\n }});\n\n }\n return true;\n }", "async function googleGeoCode(address) {\n // parse address into payload\n let payload = {\n 'address': address\n }\n\n // push out for geocoding\n let response = await _googleGeocodingApi.get('', { params: payload })\n .then(res => {\n // parse response for lat lon\n if (res.data.results.length > 0) {\n // use first result\n let resLocation = res.data.results[0].geometry.location;\n return `${resLocation.lat},${resLocation.lng}`;\n } else {\n throw new Error('Address invalid')\n }\n })\n .catch(error => { throw new Error(error) });\n return response;\n}", "function getCity(coordinates) {\n\tvar xhr = new XMLHttpRequest();\n\tvar lat = coordinates[0];\n\tvar lng = coordinates[1];\n\n\t// Paste your LocationIQ token below.\n\txhr.open('GET', \"https://us1.locationiq.com/v1/reverse.php?key=pk.49fd5203799fe38a65295fec96174630&lat=\"+lat+\"&lon=\"+lng+\"&format=json\", true);\n\txhr.send();\n\txhr.onreadystatechange = processRequest;\n\txhr.addEventListener(\"readystatechange\", processRequest, false);\n\n\tfunction processRequest(e) {\n\t\tif (xhr.readyState == 4 && xhr.status == 200) {\n\t\t\tvar response = JSON.parse(xhr.responseText);\n\t\t\tvar city = response.address.city;\n\t\t\tsetAddr(response.address);\n\t\t\treturn;\n\t\t}\n\t}\n}", "getAdressFromPix(lat,long,url){\n\n\t\tlet format = \"?json=1\"\n\t\taxios.get(url+lat+\",\"+long+format).then((response) => {\n\t\t\tlet city = response.data.city;\n\t\t\tlet street = \"\";\n\t\t\tlet number = \"\";\n\t\t\tconsole.log(typeof response.data.staddress)\n\t\t if(typeof response.data.staddress !== \"string\"){\n\t\t \tfor (let localisation in response.data.loc){\n\t\t \t\tif(typeof response.data.staddress === \"string\"){\n\t\t \t\t\tstreet = response.data.staddress;\n\t\t \t\t\tnumber = response.data.stnumber;\n\t\t \t\t\tbreak;\n\t\t \t\t}\n\t\t \t}\n\t\t }else{\n\t\t \tstreet = response.data.staddress;\n\t\t \tnumber = response.data.stnumber;\n\t\t }\n\t\t let position=[lat,long]\n\t\t \n\t\t console.log(response)\n\t\t console.log('##__EMIT -> fireUpdateAddress - Success __##')\n\t\t Event.$emit('fireUpdateAddress', street+\" \"+number+\", \"+city, position);\n\n\t\t }).catch(function (error) {\n\t\t \tconsole.log(error)\n\t\t \tconsole.log('##__EMIT -> fireUpdateAddress - Error __##')\n\t\t Event.$emit('fireUpdateAddress', 'Aucune addresse trouvée...', position);\n\t\t })\n\t}", "function geocode( p_address, callback ){\n // Location Object that will hold the p_address location\n var loc = {};// {\"lat\":null, \"lng\":null};\n // Create a new google geocoder\n var geocoder = new google.maps.Geocoder();\n geocoder.geocode( {\"address\":p_address}, function(results, status){\n if( status == google.maps.GeocoderStatus.OK ){\n loc.lat = results[0].geometry.location.lat();\n loc.lng = results[0].geometry.location.lng();\n }else{\n loc.lat = null;\n loc.lng = null;\n }\n callback(loc);\n });\n}", "function geocode(address){\n return new Promise(function(fulfill,reject){\n request('https://maps.googleapis.com/maps/api/geocode/json?' +\n 'address=' + encodeURIComponent(address) +\n '&key=' + googleGeoCodeKey\n ,function(err,res){\n if(!err) fulfill(JSON.parse(res.body).results[0].geometry)\n if(err) reject(err)\n })\n })\n}", "getFormattedAddress() {\n\n }", "function getGeoLocation(address) {\r\n\tvar geocoder = new google.maps.Geocoder();\r\n\t//var address = document.getElementById(\"taAddress\").value;\r\n\t\r\n\tgeocoder.geocode({ 'address': address }, function (results, status) {\r\n\t\t\r\n\t\tif (status === google.maps.GeocoderStatus.OK) \r\n\t\t{\r\n\t\t\t$.jStorage.set(\"jsLat\", results[0].geometry.location.lat());\r\n\t\t\t$.jStorage.set(\"jsLong\", results[0].geometry.location.lng());\r\n\t\t\t\r\n\t\t} else \r\n\t\t{\r\n\t\t\t$.jStorage.set(\"jsLat\", \"0.0\"); \r\n\t\t\t$.jStorage.set(\"jsLong\", \"0.0\");\r\n\t\t\talert(\"Not a proper address to fetch latitude and longitude from google maps.\");\r\n\t\t}\r\n\t});\r\n}", "function getGeoByAddress() {\n\tvar geocoder = new google.maps.Geocoder();\n\tvar address = document.getElementById('address').value;\n\tgeocoder.geocode( { 'address': address}, function(results, status) {\n\t if (status == 'OK') {\n\t \tresult = results[0];\n\t map.setCenter(results[0].geometry.location);\n\t \n\t //add annotation on the map\n\t var marker = new google.maps.Marker({\n\t map: map,\t \n\t position: results[0].geometry.location,\n\t label: {\n\t \ttext: results[0].formatted_address,\n\t \tcolor: \"red\"\n\t }\n\t });\n\t \t \n\t } else {\n\t \n\t }\n\t});\n}", "function map_location(address){\n getGeo(address, function(error, location){\n map_initialize(location.lat, location.lng);\n })\n}", "function geocodeAddress(address) {\n\n L.esri.Geocoding.geocode().text(address).run(function (err, results) {\n\n searchLatLng = L.latLng(results.results[\"0\"].latlng.lat, results.results[\"0\"].latlng.lng);\n findNewLocation(searchLatLng);\n });\n }", "function getLatitudeLongitude(callback, address) {\n // If adress is not supplied, use default value 'Ferrol, Galicia, Spain'\n address = address || 'Ferrol, Galicia, Spain';\n // Initialize the Geocoder\n geocoder = new google.maps.Geocoder();\n if (geocoder) {\n geocoder.geocode({\n 'address': address\n }, function (results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n callback(results[0]);\n }\n });\n }\n // else{\n // console.log($cookieStore.get('userLatitude'));\n // lat = $cookieStore.get('userLatitude');\n // lon = $cookieStore.get('userLongitude');\n //}\n }", "function getGeocodeByAddress(addr, callback) {\n // If googleMapsclient node.js library for google map is declared, use it.\n if (googleMapsClient) {\n googleMapsClient.geocode({ \"address\": addr }, function(err, response) {\n if (!err) {\n console.log(\"getGeocodeByAddress : \", response.json.results);\n callback(response.json.results);\n } else if (err === 'timeout') {\n // Handle timeout.\n console.log(err);\n } else if (err.json) {\n // Inspect err.status for more info.\n console.log(err);\n } else {\n // Handle network error.\n console.log(\"err : other\", err);\n }\n });\n } else {\n var url = \"https://maps.googleapis.com/maps/api/geocode\";\n var key = \"google map api key for place\";\n \n doOpenApiCall({\n url: url,\n retType: \"json\",\n key: key,\n params: { \"address\": addr }\n }, function(ret) {\n console.log(\"getGeocodeByAddress : \", ret.results);\n callback(ret.results);\n });\n }\n }", "function geocodePosition(marker) {\n var geocoder = new google.maps.Geocoder();\n var location = new google.maps.LatLng(marker.getPosition().lat(),marker.getPosition().lng() );\n geocoder.geocode({ 'location': location }, function (results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n if (results[1]) {\n document.getElementById('street_number').value=results[1].address_components[0].long_name;\n document.getElementById('sublocality').value=results[1].address_components[1].long_name;\n console.log(results[1].address_components[2].long_name);\n console.log(results[1].address_components[3].long_name);\n }\n }\n });\n}", "function getLatitudeLongitude(address) {\n // Degrees, Minutes and Seconds: DDD° MM' SS.S\"\n var latLongDegreesMinutesSeconds = /^([0-9]{1,3})(?:°[ ]?| )([0-9]{1,2})(?:'[ ]?| )([0-9]{1,2}(?:\\.[0-9]+)?)(?:\"[ ]?| )?(N|E|S|W) ?([0-9]{1,3})(?:°[ ]?| )([0-9]{1,2})(?:'[ ]?| )([0-9]{1,2}(?:\\.[0-9]+)?)(?:\"[ ]?| )?(N|E|S|W)$/g; // Degrees and Decimal Minutes: DDD° MM.MMM'\n\n var latLongDegreesMinutes = /^([0-9]{1,3})(?:°[ ]?| )([0-9]{1,2}(?:\\.[0-9]+)?)(?:'[ ]?| )?(N|E|S|W) ?([0-9]{1,3})(?:°[ ]?| )([0-9]{1,2}(?:\\.[0-9]+)?)(?:'[ ]?| )?(N|E|S|W)$/g; // Decimal Degrees: DDD.DDDDD°\n\n var latLongDegrees = /^([-|+]?[0-9]{1,3}(?:\\.[0-9]+)?)(?:°[ ]?| )?(N|E|S|W)?,? ?([-|+]?[0-9]{1,3}(?:\\.[0-9]+)?)(?:°[ ]?| )?(N|E|S|W)?$/g;\n var latLongFormats = [latLongDegreesMinutesSeconds, latLongDegreesMinutes, latLongDegrees];\n var latLongMatches = latLongFormats.map(function (latLongFormat) {\n return address.match(latLongFormat);\n });\n /*\n * Select the first latitude and longitude format that is matched.\n * Ordering:\n * 1. Degrees, minutes, and seconds,\n * 2. Degrees, and decimal minutes,\n * 3. Decimal degrees.\n */\n\n var latLongMatch = latLongMatches.reduce(function (accumulator, value, index) {\n if (!accumulator && value) {\n var latLongResult = latLongFormats[index].exec(address);\n var lat = latLongResult.slice(1, latLongResult.length / 2 + 1);\n var lng = latLongResult.slice(latLongResult.length / 2 + 1, latLongResult.length);\n return {\n lat: lat,\n lng: lng\n };\n }\n\n return accumulator;\n }, null);\n return new Promise(function (resolve, reject) {\n // If we've got a match on latitude and longitude, use that and avoid geocoding\n if (latLongMatch) {\n var latDecimalDegrees = getDecimalDegrees.apply(void 0, _toConsumableArray(latLongMatch.lat));\n var longDecimalDegrees = getDecimalDegrees.apply(void 0, _toConsumableArray(latLongMatch.lng));\n resolve({\n lat: latDecimalDegrees,\n lng: longDecimalDegrees\n });\n } else {\n // Otherwise, geocode the assumed address\n var geocoder = new google.maps.Geocoder();\n geocoder.geocode({\n address: address\n }, function (results, status) {\n if (status !== google.maps.GeocoderStatus.OK || !results[0]) {\n reject(status);\n } else {\n resolve(results[0].geometry.location);\n }\n });\n }\n });\n}", "function geoCodeAddress(address){\n geocoder.geocode( { 'address': address}, function(results, status) {\n console.log('direccion: ' + address);\n //si el estado de la llamado es OK\n if (status == google.maps.GeocoderStatus.OK) {\n \n //Verigica que el marcador no exista.\n latLng = results[0].geometry.location;\n if(isLocationFree(latLng)){\n setMarkerAndCenter(latLng, address);\n }else{\n map.setCenter(latLng);\n }\n\n } else {\n //si no es OK devuelvo error\n alert(\"No podemos encontrar la direccion, error: \" + status);\n }\n });\n }", "function getUserAndBankLocation(address) {\n let addressArray = address.split(\" \");\n let url = \"https://maps.googleapis.com/maps/api/geocode/json?address=\" + addressArray[0] + \"+\" + \",+Seattle,+WA&key=AIzaSyA3-dO5SwXlolulr_KzS2rxXU2IUas_YjE\";\n let position = 58;\n let curPosition = position+(addressArray[0].length)+1;\n for(let i = 1; i < addressArray.length-1; i++) {\n url = [url.slice(0, curPosition), addressArray[i]+\"+\", url.slice(curPosition)].join(\"\");\n curPosition = curPosition+(addressArray[i].length)+1;\n position = curPosition;\n }\n url = [url.slice(0, position), addressArray[addressArray.length-1], url.slice(position)].join(\"\");\n state.userInfo.url = url;\n return fetch(url)\n .then(function(response) {\n return response.json();\n })\n .then(function(myJson) {\n updateUserGeo(myJson.results[0].geometry.location);\n getNearbyFoodbank();\n });\n \n}", "function getAddress() { \n \t\n \t coords = [];\n \t geocoder = new google.maps.Geocoder();\n \t \n \t var address = document.getElementById('address').value;\n \t geocoder.geocode( { 'address': address}, function(results, status) {\n \t if (status == 'OK') {\n \t \t\n \t \n \t \t coords.latitude = results[0].geometry.location.lat();\n \t \t coords.longitude = results[0].geometry.location.lng();\n \t \t coords.deliveryAddress = address;\n \t \n \t \t\n \t \t// put the lat and lng unto the index hidden fields\n \t \t var java_lat = coords.latitude;\n \t \t $(\"#googleLat\").attr(\"value\",java_lat);\n \t \t \n \t \t var java_lng = coords.longitude;\n \t \t $(\"#googleLng\").attr(\"value\",java_lng);\n \t \t \n \t \t \n \t \t var java_address = coords.deliveryAddress;\n \t\t \t $(\"#deliveryAddress\").attr(\"value\",java_address);\n \t \t\n \t \t\n \t } else {\n \t alert('Geocode was not successful for the following reason: ' + status);\n \t }\n \t });\n \t }", "async function getLocationInfo(address) {\n return new Promise((resolve, reject) => {\n const publicConfig = {\n key: \"AIzaSyAxF2aW5TWMiclJI5MdizMLBUFzXECbWM0\",\n stagger_time: 1000,\n secure: true\n };\n const gmAPI = new GoogleMapsAPI(publicConfig);\n const params = {\n address,\n language: \"en\",\n region: \"US\"\n };\n gmAPI.geocode(params, function(err, result) {\n var locationInfo = {};\n if (err) {\n reject(err);\n }\n if (result.status === \"ZERO_RESULTS\" || !result.results[0]) {\n return resolve(undefined);\n }\n const rawLocationInfo = result.results[0];\n locationInfo.formattedAddress = rawLocationInfo.formatted_address;\n locationInfo.lat = rawLocationInfo.geometry.location.lat;\n locationInfo.lng = rawLocationInfo.geometry.location.lng;\n const svParams = {\n location: locationInfo.lat + \",\" + locationInfo.lng,\n size: \"800x400\",\n heading: 108.4,\n pitch: 7,\n fov: 40\n };\n locationInfo.streetView = gmAPI.streetView(svParams);\n resolve(locationInfo);\n });\n });\n}", "function geocode(address, callback) {\n var query = qs.stringify({ address: address, sensor: false, components: 'country:US' })\n , reqtmpl = \"http://maps.googleapis.com/maps/api/geocode/json?%s\"\n , req = util.format(reqtmpl, query)\n , geo\n ;\n \n request(req, function(err, res, body) {\n if (err) {\n console.log('ERROR: ' + err);\n return callback(err);\n }\n\n console.log(body);\n\n geo = parseGoogleGeocodes(JSON.parse(body));\n\n if (!geo) {\n return callback(\"can't determine address\");\n } else {\n return callback(null, geo);\n }\n });\n}", "function getAddress() {\n event.preventDefault();\n let addressEntered = $('input[name=\"locationBox\"]').val().toLowerCase();\n\n getCoordinates(addressEntered);\n}", "function getAddress1(coords) {\n myPlacemark1.properties.set(\"iconCaption\", \"searching...\");\n ymaps.geocode(coords).then(function (res) {\n var firstGeoObject = res.geoObjects.get(0);\n\n myPlacemark1.properties.set({\n // Forming a string with the object's data.\n iconCaption: [\n // The name of the municipality or the higher territorial-administrative formation.\n firstGeoObject.getLocalities().length\n ? firstGeoObject.getLocalities()\n : firstGeoObject.getAdministrativeAreas(),\n // Getting the path to the toponym; if the method returns null, then requesting the name of the building.\n firstGeoObject.getThoroughfare() ||\n firstGeoObject.getPremise(),\n ]\n .filter(Boolean)\n .join(\", \"),\n // Specifying a string with the address of the object as the balloon content.\n balloonContent: firstGeoObject.getAddressLine(),\n });\n address1.val(firstGeoObject.getAddressLine());\n });\n }", "geocodeCoordinates(coordinates) {\n\n\t\tymaps.geocode(coordinates, {result: 1}).then((result) => {\n\n\t\t\t// Get first result\n\t\t\tlet nearest = result.geoObjects.get(0);\n\n\t\t\t// Get city from nearest result\n\t\t\tlet city = nearest.getLocalities()[0];\n\n\t\t\t// Get address from nearest result\n\t\t\tlet address = nearest.properties.get(\"name\");\n\n\t\t\t// Prepare data for broadcast\n\t\t\tlet data = {\n\t\t\t\tcity: city,\n\t\t\t\taddress: address,\n\t\t\t\tcoordinates: coordinates\n\t\t\t};\n\n\t\t\t// Transfer address to input\n\t\t\tthis.$timeout(() => this.$rootScope.$broadcast(\"geocoded:address\", data));\n\t\t});\n\n\t}", "function getLng(placemark) {\n return placemark.Point.coordinates[0];\n }", "function locate() {\n map.graphics.clear();\n var address = {\n \"SingleLine\": $('#address').val()\n };\n locator.outSpatialReference = map.spatialReference;\n var options = {\n address: address,\n outFields: [\"Loc_name\"]\n }\n locator.addressToLocations(options);\n }", "function parseAddress(user){\n let address = '';\n return address = `${user.location.street.number} ${user.location.street.name}, ${user.location.city}, ${user.location.state} ${user.location.postcode}`\n}", "getCityName() {\n Geocode.setApiKey(\"AIzaSyBQTJkuKvUP2y4uRp6kyzSxFm3IJpQMmuc\");\n Geocode.setLocationType(\"ROOFTOP\");\n Geocode.fromLatLng(\"48.8583701\", \"2.2922926\").then(\n (response) => {\n const address = response.results[0].formatted_address;\n let city, state, country;\n for (let i = 0; i < response.results[0].address_components.length; i++) {\n for (let j = 0; j < response.results[0].address_components[i].types.length; j++) {\n switch (response.results[0].address_components[i].types[j]) {\n case \"locality\":\n city = response.results[0].address_components[i].long_name;\n break;\n case \"administrative_area_level_1\":\n state = response.results[0].address_components[i].long_name;\n break;\n case \"country\":\n country = response.results[0].address_components[i].long_name;\n break;\n }\n }\n }\n console.log(city, state, country);\n console.log(address);\n },\n (error) => {\n console.error(error);\n }\n );\n }", "function getLatLon(adres,lijst){\n\t$.getJSON(\"https://maps.googleapis.com/maps/api/geocode/json?address=\"+ adres+\"&key=AIzaSyA2hhwsyvOFvwf6YJABI74dDS8ccSyGvf8\", function(data) {\n\t\t$(data).each(function( index_pjct , value_pjct ) {\n\t\t\tif(value_pjct.status!=\"ZERO_RESULTS\"){\n\t\t\t\tcodeAddress(value_pjct.results[0].geometry.location,lijst);\n\t\t\t}\n\t\t});\n\t});\n}", "function getCoordinates(zipCode) {\n \n // read the value of gck from the database\n database.ref().on(\"value\", function(snapshot) {\n let geoCodeKey = snapshot.val().gck;\n // console.log(\"gck is \" + geoCodeKey);\n return geoCodeKey;\n });\n let queryURL = \"https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:\" + zipCode + \"&key=\" + geoCodeKey;\n\n $.ajax({\n url: queryURL,\n method: \"GET\",\n dataType: \"json\",\n success: function(response){\n latitude = response.results[0].geometry.location.lat;\n longitude= response.results[0].geometry.location.lng;\n map.setCenter({lat: latitude, lng: longitude});\n }\n \n });\n \n }", "function reverseGeocode(points) {\n var geocoder = new google.maps.Geocoder(),\n coordinates = new google.maps.LatLng(points[0], points[1]),\n setting = { 'latLng': coordinates };\n geocoder.geocode(setting, function (results, status) {\n if (status === 'OK') {\n var address = (results[0].formatted_address);\n console.log(address);\n } else {\n alert(status);\n }\n });\n}", "function fillInAddressSource() {\n var coords = sourceQuery.getPlace().geometry.location;\n lat = coords.lat();\n lon = coords.lng();\n}", "function getPlacemarks(address, callback, context) {\n this.geocoder.getLocations(address.join(', '), \n function(response){ _onGeocodingCompleted(response, callback, context)});\n }", "function getAddress(latitude, longitude) {\n\t\t\treturn $http({\n\t\t\t\turl: 'https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=' + latitude + '&lon=' + longitude,\n\t\t\t\tmethod: \"GET\"\n\t\t\t}).then(\n\t\t\t\tfunction success(response) {\n\t\t\t\t\treturn response.data;\n\t\t\t\t},\n\t\t\t\tfunction error(error) {\n\t\t\t\t\treturn error.data;\n\t\t\t\t});\n\t\t}", "function codeAddress(address) {\n var geocoder = new google.maps.Geocoder();\n var result = '';\n\n geocoder.geocode({\n 'address': address\n }, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n result = results[0].geometry.location;\n addToMapBox(map, result);\n } else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n\n return result;\n}", "getCoordsByAddress() {\n //API call to google to get coords when user input is an address\n var address = this.state.location.replace(' ', '+');\n var key = 'AIzaSyCrkf6vpb_McrZE8p4jg4oUH-oqyGwFdUo';\n var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + key;\n console.log('are you in here?', url);\n fetch(url, {\n method: 'GET',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n }\n }).then((res) => {\n return res.json(); \n }).then((resJson) => {\n this.setState({latitude: resJson.results[0].geometry.location.lat});\n this.setState({longitude: resJson.results[0].geometry.location.lng});\n })\n .then((res) => {\n this._onForward()\n })\n .catch((err) => {\n console.log('There is an error. It\\'s sad day D=', err.status, err);\n });\n }", "function codeAddress(address) {\nconsole.log(document.getElementById('ZippyZip').value);\n //var address = document.getElementById('ZippyZip').value;\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == 'OK') {\n map.setCenter(results[0].geometry.location);\n var marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location,\n zIndex:999999\n });\n\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n}", "function getAddress(addr) \r\n\t{\r\n let address = '';\r\n address = addr ? addr : document.getElementById('address').value;\r\n address = address.trim();\r\n\t\t\r\n\t\tif ( ! _delta.web3.isAddress(address))\r\n\t\t{\r\n\t\t\t//check if url ending in address\r\n\t\t\tif(address.indexOf('/0x') !== -1)\r\n\t\t\t{\r\n\t\t\t\tlet parts = address.split('/');\r\n\t\t\t\tlet lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash\r\n\t\t\t\tif(lastSegment)\r\n\t\t\t\t\taddress = lastSegment;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(! _delta.web3.isAddress(address)) \r\n\t\t\t{\r\n\t\t\t\tif (address.length == 66 && address.slice(0, 2) === '0x') \r\n\t\t\t\t{\r\n\t\t\t\t\t// transaction hash, go to transaction details\r\n\t\t\t\t\twindow.location = window.location.origin + window.location.pathname + 'tx.html#' + address;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t} \r\n\r\n\t\t\t\t// possible private key, show warning (private key, or tx without 0x)\r\n\t\t\t\tif (address.length == 64 && address.slice(0, 2) !== '0x') \r\n\t\t\t\t{\r\n\t\t\t\t\tif (!addr) // ignore if in url arguments\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tshowError(\"You likely entered your private key, NEVER do that again\");\r\n\t\t\t\t\t\t// be nice and try generate the address\r\n\t\t\t\t\t\taddress = _util.generateAddress(address);\r\n\t\t\t\t\t}\r\n\t\t\t\t} \r\n\t\t\t\telse if (address.length == 40 && address.slice(0, 2) !== '0x') \r\n\t\t\t\t{\r\n\t\t\t\t\taddress = `0x${addr}`;\r\n\t\t\t\t\t\r\n\t\t\t\t} \r\n\t\t\t\telse \r\n\t\t\t\t{\r\n\t\t\t\t\tif (!addr) // ignore if in url arguments\r\n\t\t\t\t\t{\r\n\t\t\t\t\t showError(\"Invalid address, try again\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn undefined;\r\n\t\t\t\t}\r\n\t\t\t\tif(! _delta.web3.isAddress(address))\r\n\t\t\t\t{\r\n\t\t\t\t\tif (!addr) // ignore if in url arguments\r\n\t\t\t\t\t{\r\n\t\t\t\t\t showError(\"Invalid address, try again\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn undefined;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tdocument.getElementById('address').value = address;\r\n\t\tdocument.getElementById('addr').innerHTML = 'Address: <a target=\"_blank\" href=\"' + _delta.addressLink(address) + '\">' + address + '</a>';\r\n\t\tsetAddrImage(address);\r\n\t\treturn address;\r\n }", "function getCoordinates(locality, cb){\n\n let path=\"\";\n let pathPrefix = \"/maps/api/geocode/json?address=\";\n let pathSuffix = \"&key=\";\n path = path + pathPrefix;\n path = path + locality;\n path = path + pathSuffix + geoCodeAPIKey;\n var coordinatesPromiseResponse = getPromiseResponse(geoCodeAPIURL, path);\n coordinatesPromiseResponse.then((output) => {\n console.log(output)\n if(output){\n console.log(\"coordinatesResponse => \" + output);\n let response = JSON.parse(output);\n let latitude = response['results'][0]['geometry']['location']['lat'];\n let longitude = response['results'][0]['geometry']['location']['lng'];\n getDealersNearCoordindates(latitude,longitude, cb)\n }\n});\n}", "componentDidMount() {\n Geocode.fromLatLng(\n this.state.mapPosition.lat,\n this.state.mapPosition.lng\n ).then(\n (response) => {\n const address = response.results[0].formatted_address,\n addressArray = response.results[0].address_components;\n },\n (error) => {\n console.error(error);\n }\n );\n }", "function codeAddress(address) {\r\n\t geocoder.geocode( { 'address': address}, function(results, status) {\r\n\t if (status == google.maps.GeocoderStatus.OK) {\r\n\t map.setCenter(results[0].geometry.location);\r\n\t var marker = new google.maps.Marker({\r\n\t map: map, \r\n\t position: results[0].geometry.location\r\n\t });\r\n\t } else {\r\n\t alert(\"Geocode was not successful for the following reason: \" + status);\r\n\t }\r\n\t });\r\n\t }", "function searchLatToLng(query){\n const geoDataUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${query}&key=${process.env.GEOCODING_API_KEY}`\n return superagent.get(geoDataUrl)\n\n .then(geoData => {\n // console.log('hey',geoData)\n\n\n const location = new Location(geoData.body.results[0]);\n console.log('what', geoData.body.results)\n return location;\n })\n .catch(err => console.error(err))\n // const geoData = require('./data/geo.json');\n}", "function positionToAddress() {\n var sheet = SpreadsheetApp.getActiveSheet();\n var cells = sheet.getActiveRange();\n\n var popup = SpreadsheetApp.getUi();\n \n // Must have selected at least 3 columns (Address, Lat, Lng).\n // Must have selected at least 1 row.\n\n var columnCount = cells.getNumColumns();\n\n if (columnCount < 3) {\n popup.alert(\"Select at least 3 columns: Latitude, Longitude in the first 2 columns; the reverse-geocoded Address will go into the last column.\");\n return;\n }\n\n var latColumn = 1;\n var lngColumn = 2;\n\n var addressRow;\n var addressColumn = columnCount;\n\n var geocoder = Maps.newGeocoder().setRegion(getGeocodingRegion());\n var location;\n \n for (addressRow = 1; addressRow <= cells.getNumRows(); ++addressRow) {\n var lat = cells.getCell(addressRow, latColumn).getValue();\n var lng = cells.getCell(addressRow, lngColumn).getValue();\n \n // Geocode the lat, lng pair to an address.\n location = geocoder.reverseGeocode(lat, lng);\n \n // Only change cells if geocoder seems to have gotten a \n // valid response.\n Logger.log(location.status);\n if (location.status == 'OK') {\n var address = location[\"results\"][0][\"formatted_address\"];\n\n cells.getCell(addressRow, addressColumn).setValue(address);\n }\n }\n}", "function geoCodeAddress(addr,txt,callback){\n\t// example: http://maps.googleapis.com/maps/api/geocode/json?address=350+5th+Avenue+New+York%2C+NY&sensor=false\n\tvar url = \"http://maps.googleapis.com/maps/api/geocode/json?address=\";\n\turl += encodeURIComponent(addr);\n\turl += \"&sensor=false\";\n\t$.ajax({\n type: 'GET',\n url: url,\n // Add markers to the map for each bathroom location\n success: function(response){ \n \tvar lat = response.results[0].geometry.location.lat;\n \tvar lng = response.results[0].geometry.location.lng;\n \t\n\t \t\t// send back the lat/long info\n\t \t\tcallback({la:lat,lo:lng,location_name:txt});\n }\n });\n}", "function codeAddress(geocoding){\n if(snapspot_address.length > 0){\n geocoding.geocode({'address': snapspot_address},function(results, status){\n if(status == google.maps.GeocoderStatus.OK){\n map.setCenter(results[0].geometry.location);\n marker.setPosition(results[0].geometry.location);\n\n } else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n }\n }", "function codeAddress() {\n var address = document.getElementById(\"user_location_input\").value;\n geocoder.geocode({'address': address}, setUserLatLongFromAddress);\n}", "async function getCoordinates(req){\n\n try {\n\n var city = req.body.city || saved_loc;\n\n var url = `https://maps.googleapis.com/maps/api/geocode/json?address=${city}&key=${Geocode_API_KEY}&unit=metric`\n\n const response = await fetch(url);\n var data = await response.json();\n return [data.results[0].geometry.location.lat, data.results[0].geometry.location.lng];\n\n } catch(err){\n console.log(err);\n }\n}", "async function getLocationFromAddress(address) {\n\n\n var apiKey = \"AIzaSyB9Soo0S1gk2QTcexPqwoIhQKZOfNAxRvE\";\n\n //Erases diacritics\n var addressAux1 = await eliminarDiacriticos(address)\n\n //Adds epublica dominicana to the addresso itis more specific for google services to find it\n var addressAux = addressAux1 + \", Republica Dominicana\";\n\n //Adds theparameters to the url\n var url = \"https://maps.googleapis.com/maps/api/geocode/json?key=\" + apiKey + \"&address=\" + addressAux;\n\n console.log(url);\n\n //Calls the service\n Http.open(\"POST\", url);\n try {\n Http.send();\n\n } catch (error) {\n console.log(\"Error in the sending to arcgis\");\n console.log(error);\n return -1;\n }\n\n //returns a promise with the resulting coordinates or -1\n return new Promise((resolve, reject) => {\n\n\n Http.onreadystatechange = function (err, data) {\n\n //If its ready and the demand wassuccesfull\n if (this.readyState == 4 && this.status == 200) {\n var result = JSON.parse(this.responseText);\n\n //If the response fro the service has the status ZERO_RESULTS means there wereno results\n //for the specified address soit reutrns a -1\n if (result.status == \"ZERO_RESULTS\") {\n reject(-1);\n return;\n }\n\n //Otherwise goes to the pertinent field of the recived object to get the coordinates\n var coordinates = result.results[0].geometry.location;\n\n console.log(\"Coordenadas\" + coordinates.lat + coordinates.lng);\n\n //Checks if the cordinatesare inside an imaginary square that contains dominican republic\n //If so, returns an object with the coordinates\n if ((17.3926782 < coordinates.lat) && (coordinates.lat < 20.79844) && (-74.3962979 < coordinates.lng) && (coordinates.lng < -68.2227217)) {\n console.log(\"la dirección ha sido encontrada en dominicana\");\n resolve([coordinates.lng, coordinates.lat])\n return;\n\n //Otherwise returns a -1\n } else {\n console.log(\"No esta en rd\");\n\n reject(-1)\n }\n\n //If the result is ready but its status is 400(an arror ocurred) itreturns a -1\n } else if (err || (this.status == 400 && this.readyState == 4)) {\n console.log(\"llega 5\");\n\n reject(-1)\n }\n };\n })\n}", "function geocode(lat, lon, callback) {\n if (!lat || !lon) {\n return callback(new Error(\"Both Latitude and Longitude MUST be submitted.\"));\n }\n //\n var longitute = parseFloat(lon);\n var latitute = parseFloat(lat);\n\n geocoder.reverseGeocode(latitute, longitute, function(err, data) {\n if (!err) {\n var geocodedAddress = (data.results && data.results[0] ? data.results[0].formatted_address : \"\");\n return callback(null, geocodedAddress);\n }\n\telse{\n\t\treturn callback(err);\n\t}\n });\n}", "function getLoc(cityName) {\n\tlet positie = \"\";\n\tgetData(`https://geocode.search.hereapi.com/v1/geocode?apiKey=${apiHereKey}&q=${cityName},%20NL`)\n\t.then(result => {\n\t\treturn result.json();\n\t})\n\n\t.then(coorData => {\n\t\tpositie = coorData.items[0].position;\n\t});\n\treturn positie;\n}", "async function getCoords(data) {\n const res = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?${new URLSearchParams(data).toString()}`);\n let obj = await res.json();\n\n return {\n lat: obj.results[0].geometry.location.lat,\n long: obj.results[0].geometry.location.lng\n }\n}", "function showPropinsi(address) {\n\t\tgeocoder.getLatLng(\n\t address,\n\t function(point) {\n\t\t\tif (!point) {\n\t \talert(address + \" tidak ditemukan\");\n\t \t}else{\n\t \tmap.setCenter(point, 8);\n\t \t}\n\t });\n\t}", "function point(){\n console.log(position);\n console.log(\"lat:\"+ position.coordinate.lat + \"/lon:\" + position.coordinate.lon + \"/ip:\" + position.ip ) ;\n}", "function getLat(placemark) {\n return placemark.Point.coordinates[1];\n }", "function onSuccess(result) {\n let location = result.Response.View[0].Result[0];\n return resolve(location.Location.Address)\n }", "function googleGeocodeAddress(address) {\n if (geocoder && address) {\n geocoder.geocode( {'address': address, region: 'AU'}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n // geocode was successful\n var latlng = new L.LatLng(results[0].geometry.location.k, results[0].geometry.location.D); //results[0].geometry.location;\n updateLocation(latlng);\n } else {\n bootbox.alert(\"Location coordinates were not found, please try a different address - \" + status);\n }\n });\n }\n}", "function geocodeAddress(resultsMap, address) {\r\n var geocoder = new google.maps.Geocoder();\r\n geocoder.geocode({'address': address}, function(results, status) {\r\n if (status === 'OK') {\r\n resultsMap.setCenter(results[0].geometry.location);\r\n chosenLoc = {lat: results[0].geometry.location.lat(),long: results[0].geometry.location.lng()};\r\n } else {\r\n alert('Geocode was not successful for the following reason: ' + status);\r\n }\r\n });\r\n }", "function getAddress2(coords) {\n myPlacemark2.properties.set(\"iconCaption\", \"searching...\");\n ymaps.geocode(coords).then(function (res) {\n var firstGeoObject = res.geoObjects.get(0);\n myPlacemark2.properties.set({\n // Forming a string with the object's data.\n iconCaption: [\n // The name of the municipality or the higher territorial-administrative formation.\n firstGeoObject.getLocalities().length\n ? firstGeoObject.getLocalities()\n : firstGeoObject.getAdministrativeAreas(),\n // Getting the path to the toponym; if the method returns null, then requesting the name of the building.\n firstGeoObject.getThoroughfare() ||\n firstGeoObject.getPremise(),\n ]\n .filter(Boolean)\n .join(\", \"),\n // Specifying a string with the address of the object as the balloon content.\n balloonContent: firstGeoObject.getAddressLine(),\n });\n address2.val(firstGeoObject.getAddressLine());\n });\n }", "function getCoords(data) {\n latitude = data.results[0].geometry.location.lat;\n longitude = data.results[0].geometry.location.lng;\n console.log(\"Lat: \" + latitude + \"Long: \" + longitude);\n url = \"?zipInput=\" + zipInput + \"&addressInput=\" + addressInput + \"&cityInput=\" + cityInput + \"&stateInput=\" + stateInput + \"&longitude=\" + longitude + \"&latitude=\" + latitude;\n url = url.replace(/ /g, '') // Remove White Space\n console.log(url);\n getURL(url);\n}", "getAddress()\n {\n return this.adress;\n }", "toLatLon(addressString) {\n // Wait in a step-dependent interval, then create and subsequently execute our promise\n\t\treturn this.sleep().then(() => {\n\t\t let promise = new Promise((resolve, reject) => {\n console.log(`****** ADDRESS OF INTEREST ${addressString}`);\n this.client.geocodeForward(addressString, (err, result) => {\n if (err) reject(err);\n\n resolve(result.features[0].geometry.coordinates);\n });\n });\n return promise;\n });\n }", "function address(address)\r\n{\r\n var requestAddr = new XMLHttpRequest();\r\n requestAddr.onreadystatechange = function() {\r\n if (this.readyState == 4) {\r\n dataAddr = JSON.parse(this.responseText);\r\n dataAddr = dataAddr._embedded.addresses[0];\r\n popuAddrDetails(dataAddr);\r\n }\r\n };\r\n\r\n requestAddr.open(\"GET\", address, true);\r\n requestAddr.send();\r\n}", "function mapper_get_location() {\n var x = document.getElementById(\"note[longitude]\");\n var y = document.getElementById(\"note[latitude]\");\n if(x && y ) {\n x = parseFloat(x.value);\n y = parseFloat(y.value);\n }\n if(x && y && ( x >= -180 && x <= 180 ) && (y >= -90 && y <= 90) ) {\n return new google.maps.LatLng(y,x);\n }\n return new google.maps.LatLng(lat,lon);\n}", "async function fetchCoordinatesFromLocation(req, res) {\n try {\n let postalCode = encodeURIComponent(req.body.postalCode);\n let location = encodeURIComponent(req.body.location);\n let response = await fetch(`http://api.geonames.org/postalCodeSearchJSON?postalcode=${postalCode}&placename=${location}&maxRows=1&username=XXXX`);\n let data = await response.json();\n res.status(200).send(data);\n } catch (error) {\n console.log(error);\n res.status(400).send(error);\n }\n}", "function codeAddress() {\n var address = gId('address').value;\n geocoder.geocode({\n 'address': address\n }, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n}", "function accessingCoordinates(cleaned_location){\n const mapquestKey = 'ZGADDfaBd92GKnmxjk6sAupluGqbaZgG'\n fetch('https://www.mapquestapi.com/geocoding/v1/address?key=' + mapquestKey + '&location=' + cleaned_location)\n .then(response =>{\n if(response.ok){\n return response.json()\n }\n })\n .then(mapquestResponse =>{\n if(mapquestResponse.results[0].locations[0].adminArea1 === 'US'){\n return cleanCoordinates(mapquestResponse);\n }else{\n alert(\"This location cannot be found. Please double check that the address, city, or zip code you have entered is valid in the United States\");\n }\n })\n .catch(error => alert(\"Uh-Oh Something Went Wrong! Try Again Later!\"));\n}", "getAddressComponentReference() {\n return this.addressComponent;\n }", "function geocoding(address) {\n // create AJAX request\n var xhttp = new XMLHttpRequest();\n \n // when server gives OK and ready\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) { \n // create json object \n addressLookup = JSON.parse(this.response);\n\n // takes coordinates and inserts into database\n insertCoordinates(addressLookup.results[0].geometry.location.lng, addressLookup.results[0].geometry.location.lat, address.Restaurant_ID);\n }\n };\n\n // this block of code takes address and returns cleaned string that will be used captures a restaurants coordinates\n var location = JSON.stringify(address);\n var string_start = location.indexOf(\":\")+2;\n var string_end = location.lastIndexOf(\"\\\"\");\n location = location.slice(string_start,string_end);\n\n // open connection with server\n xhttp.open(\"GET\",\"https://maps.googleapis.com/maps/api/geocode/json?address=\"+location+\"&key=AIzaSyDHSI4KzoulBbnrXCiIiID4asbLxqVAyZE\", true); \n\n // send request\n xhttp.send();\n }", "formatAddress(address, str) {\n const formattedAddress = address.split(',');\n const streetAddress = formattedAddress.splice(0, 1);\n const cityAddress = formattedAddress.join('');\n\n if (str === 'street') {\n return streetAddress;\n }\n return cityAddress;\n }", "function codeAddress(address) {\n geocoder = new google.maps.Geocoder();\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n marker.setPosition(results[0].geometry.location);\n\t$('#client_latitude').val(results[0].geometry.location.lat());\n\t$('#client_longitude').val(results[0].geometry.location.lng());\n\tgoogle.maps.event.trigger(map, \"resize\");\n }\n\t//else {\n // alert(\"Geocode was not successful for the following reason: \" + status);\n // }\n });\n }", "function showAddress()\n{\n\tvar geocoder = new google.maps.Geocoder();\n\taddress = document.getElementById(\"street1\").value + \" \" + document.getElementById(\"city\").value + \" \" + document.getElementById(\"state\").value + \" \" + document.getElementById(\"zipcode\").value;\n\t//geocoder.getLocations(address, handleGeoCodes);\n\tgeocoder.geocode( { 'address': address}, handleGeoCodes);\n}", "function getAddress() {\n // remove any routes\n clearRoutes();\n\n // get value of search box\n var search = $('#address_search').val();\n\n // build uri for ban data\n var uri = 'https://api-adresse.data.gouv.fr/search/?q=' + search;\n\n // if position set, use to inform address returns\n if (pos.length > 0) {\n uri = uri + '&lat=' + pos[0] + '&lon=' + pos[1];\n }\n\n $.getJSON(uri, function (data) {\n if (addressMarker) {map.removeLayer(addressMarker);};\n\n var coords = data.features[0].geometry.coordinates;\n addressPos = [coords[1], coords[0]];\n\n addressMarker = L.marker(addressPos, {\n icon: L.mapbox.marker.icon({\n 'marker-size': 'large',\n 'marker-symbol': 'rocket',\n 'marker-color': '#66ccff',\n }),\n }).addTo(map);\n var group = new L.featureGroup([posMarker, addressMarker]);\n map.fitBounds(group.getBounds().pad(0.5));\n $('#route-menu').prop('disabled', false);\n });\n}", "function geocodeLatLng() {\n var latlng = {lat: userLat, lng: userLng};\n geocoder.geocode({'location': latlng}, function (results, status) {\n if (status === 'OK') {\n if (results[0]) {\n formattedAddress = results[0].formatted_address;\n formattedAddressPrint = formattedAddress.split(', India')\n $(\".your_address\").removeClass('hidden');\n $(\".your_address2\").html(formattedAddressPrint);\n\n }\n }\n });\n }" ]
[ "0.7615943", "0.74447", "0.73975205", "0.7380073", "0.7339588", "0.7115024", "0.7087174", "0.7076664", "0.6960761", "0.6901964", "0.6863626", "0.67996913", "0.66416305", "0.6625145", "0.6583819", "0.65761966", "0.6563513", "0.6541144", "0.6497", "0.649529", "0.64813447", "0.6448742", "0.64347863", "0.6425348", "0.63991207", "0.63810724", "0.63706577", "0.6364889", "0.6352871", "0.6346017", "0.63348657", "0.63179845", "0.6312782", "0.63112855", "0.6310864", "0.63107806", "0.6294534", "0.629408", "0.62934613", "0.6284109", "0.62819344", "0.627434", "0.6273396", "0.6260246", "0.62560797", "0.62516975", "0.6248748", "0.6242749", "0.62397593", "0.6238661", "0.62330973", "0.62295306", "0.62139374", "0.61988753", "0.6197393", "0.6194226", "0.6190491", "0.61816233", "0.6178498", "0.6173564", "0.61733794", "0.6172321", "0.6160089", "0.615937", "0.6155218", "0.6143611", "0.61371434", "0.6135863", "0.61284477", "0.6120959", "0.6119851", "0.6118796", "0.61066616", "0.61066127", "0.6101356", "0.6079691", "0.60787183", "0.6073643", "0.6069868", "0.60681653", "0.6068107", "0.6061696", "0.60571796", "0.60539746", "0.6052211", "0.60518897", "0.6051356", "0.60349864", "0.60309094", "0.6023281", "0.6022931", "0.60059446", "0.60016537", "0.600145", "0.60008466", "0.5996676", "0.5994878", "0.5984987", "0.59823847", "0.59796065", "0.5978416" ]
0.0
-1
need a loop on all the line of the JSON
function initializeGeo() { console.log("in initializeGeo function"); console.log(addressArray.length); syncLoop(addressArray.length, function(loop){ // console.log("loop : " + loop.iteration()); var tmpId = loop.iteration(); function callnext() { loop.next(); } // SUBWAY GOOGLE // codeAddressGoogle(addressArray[loop.iteration()].station, tmpId, callnext); // STORE BAIDU codeAddressBaidu(addressArray[loop.iteration()].addresscn, tmpId, callnext); }, function (){ // console.log("finish !") }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function auxiliar(json){\n if(json.length==0 || json == null){\n alert(\"No hay productos en ese rango de precios\");\n return;\n }\n for(let producto of json){\n items(producto);\n }\n }", "function jsonlStreamForEach( ins, fn ) {\n return lineParser( ins, async ( line ) => {\n if( line.length > 0 ) {\n await fn( JSON.parse( line ) );\n }\n });\n}", "async function getNameFetch (){\n try{\n let request = await fetch(\"json.txt\");\n let result = await request.json();\n for(one in result){\n console.group(result[one].name + \" \" + result[one].lastname);\n console.log(\"Name: \" + result[one].name);\n console.log(\"Lastname: \" + result[one].lastname);\n console.log(\"Age: \" + result[one].age);\n console.log(\"Note: \" + result[one].note);\n console.groupEnd();\n };\n } catch(err){\n console.log(\"LA API FALLO\");\n };\n}", "parseFile(file) {\n\n var content = this.lire(file);\n\n var lines = content.split(/\\r?\\n/);\n\n //string that contains keys\n var header = lines[0];\n\n //array containing data separate with \";\"\n var dataLines = lines.slice(1);\n\n // data = dataLines.map(this.parser);\n\n var data = this.jsonifydata(header,dataLines);\n\n console.log(data);\n\n }", "function forLoop(data){\n\tfor(var i = 0; i<data.length;++i){\nconsole.log(data[i].username);\n\t}\n}", "function SplitJSON(JSON) {\r\n\r\n for (i = 0; i < recJSON.length; i++) {\r\n sidequotes.push(JSON[i].sidequote);\r\n }\r\n\r\n}", "function createLines(json) {\n var meta = json.meta;\n var data = json.data;\n\n var newLines = [];\n\n for (var i=0; i < meta.lines.length; i++) {\n // Get the tag\n var lineTag = meta.lines[i].tag;\n\n newLines.push([]);\n // Generate the list of data (month, measurement)\n for (var j=0; j < data.length; j++) {\n // Assumes data has a \"Length\" tag in each element\n newLines[i].push([data[j][\"Length\"], data[j][lineTag]]);\n }\n }\n return newLines;\n }", "function handleData(json) {\n for (i in json.users) {\n var point = {\n 'x':json.users[i].time,\n 'y':json.users[i].mood\n }\n data.push(point)\n }\n console.log(data)\n}", "function processLine (context, line) {\n const object = parseJSON(line)\n if (object == null) return\n\n context.buffer.objects.push(object)\n\n if (!shouldProcessBuffer(context)) return\n\n processBuffer(context)\n}", "function populateMonsterList(json) {\n for (monster of json) {\n renderSingleMonster(monster);\n }\n}", "function JsonOnSring(dataJson){\n\nlet objJson ='{ \"Sensores\" : [ {';\nlet pivote=0, i= -1;\nlet value;\nlet props= 1;\nlet flag = false;\nwhile(pivote >= 0){\n \n pivote = dataJson.indexOf(\",\",i+1);\n if(pivote == -1){\n flag = true;\n value = dataJson.substring(i+1, dataJson.length);\n }\n \n if(!flag)\n value = dataJson.substring(i+1, pivote);\n\n \n\n objJson += `\n \"${props}\": \"${value}\",\n `;\n \n i = pivote;\n props++;\n \n if(flag)\n break;\n}\n\nobjJson += '\"TEST\": \"ON\" } ]}';\nreturn objJson;\n}", "function jsonTransform() {\n\tconsole.log(\"in json function\");\n\t$.getJSON(\"ajax/WagPregeo.json\",function(data) {\n\t\t$.each(data,function(key, val) {\t\n\t\t\taddressArray.push({id: val.id, name: val.name,addresseng: val.addresseng, addresscn: val.addresscn});\n\t\t});\n\t\tinitializeGeo();\t\n\t});\n}", "function jsonData() {\n getJSONP(jsonLink, function(data) {\n fillList(data);\n });\n}", "async function hentJsonTal() {\n\n let jsonObjekt = await fetch(\"http://kea.jonascisum.dk/kea/eksamen-02/lerja/wordpress/wp-json/wp/v2/infografik\");\n\n //Tag jsonObjekt og lav det til Json\n\n indholdTal = await jsonObjekt.json();\n\n console.log(indholdTal);\n\n //start funktion insertTal\n\n insertTal();\n }", "function readJSON() {\r\n\r\n $.getJSON(\"resources/damageTypes.json\", function (json) {\r\n var i = 1;\r\n for (const key of Object.keys(json)) {\r\n damageCards(json[key], i++);\r\n }\r\n });\r\n\r\n}", "function processJSON(json) {\n\tif (json.error) {\n\t\terrorCalendar(json.number, json.message);\n\t\treturn;\n\t}\n\tsetUpCalendar();\n\t// params: course, title, type, section, instructor, start, end, days, term, id\n\n\tfor (var i=0;i<json.length;i++) {\n\t\tvar days = json[i].days;\n\t\tfor (var j=0;j<days.length;j++) {\n\t\t\tvar cur = parseInt(days.charAt(j), 10);\n\t\t\taddToCalendar(cur,json[i]);\n\t\t}\n\t}\n}", "function json_exploder(json_input,loop){\n\n\tvar json_output = \"<dl>\";\n\tvar i;\n\tvar x;\n\n\t// we may have only a string - this should fix it\n\tif (typeof(json_input)==\"string\"){\n\t\treturn json_input;\n\t}\n\t\n\tfor (x in json_input){\n\tlogMessage(typeof(json_input[x]));\n\n\t\tif (typeof(json_input[x]) == \"object\" && json_input[x] !== null){\n\n\t\t\tfor (i=0;i<loop;i++){ json_output +=\"&nbsp; \"; } // indent\n\n\t\t\tif (x != \"0\"){\n\t\t\t\tjson_output += \"<span style='text-decoration:underline; margin-top:5px; display:inline-block;'>\" + x + \"</span>\";\n\t\t\t}\n\t\t\tjson_output += json_exploder(json_input[x],loop+1);\n\t\t\tjson_output += \"\";\n\n\t\t} else if (typeof(json_input[x])== \"string\") {\n\t\t\tfor (i=1;i<loop;i++){\n\t\t\t\tjson_output +=\"&nbsp; \";\n\t\t\t}\n\t\t\tjson_output += \"\" + x.camelCaseToRegular() + \": \" + json_input[x] + \"<br />\";\n\t\t}\n\t}\n\treturn json_output + \"</dl>\";\n}", "function jsonNotation() {\n \n var addressData = fs.readFileSync('addressdata.txt');\n var addressDataParsed = JSON.parse(addressData);\n \n for (i=0; i<22; i++) {\n \n var thisLocation = new Object;\n \n thisLocation.groupName = leftCol[i][1];\n thisLocation.address = address[i];\n thisLocation.lat = addressDataParsed[i].lat;\n thisLocation.long = addressDataParsed[i].long;\n thisLocation.notes = leftCol[i][4];\n thisLocation.wheelchair = leftCol[i][5];\n thisLocation.meetings = details[i];\n \n jsonMeetings.push(thisLocation);\n }\n// console.log(jsonMeetings)\n}", "function parseJsonFeatured() {\n var results = metadata;\n\n // can't bind elements to carousel due to possible bug\n for (var i=0;i<4;i++)\n {\n var shelf = getActiveDocument().getElementsByTagName(\"shelf\").item(i)\n var section = shelf.getElementsByTagName(\"section\").item(0)\n \n //create an empty data item for the section\n section.dataItem = new DataItem()\n \n //create data items from objects\n let newItems = results.map((result) => {\n let objectItem = new DataItem(result.type, result.ID);\n objectItem.url = result.url;\n objectItem.title = result.title;\n objectItem.onselect = result.onselect;\n objectItem.watchtime = result.watchtime;\n return objectItem;\n });\n \n //add the data items to the section's data item; 'images' relates to the binding name in the protoype where items:{images} is all of the newItems being added to the sections' data item;\n section.dataItem.setPropertyPath(\"images\", newItems)\n }\n}", "function fetchLines(){\n fetch(baseURL + \"/api/lines/\" + gamecode)\n .then(response => response.json())\n .then(json => lines = json)\n}", "function ParseJSON() {\n // console.log(scheduleList[1]);\n for (var i = 0, length = scheduleList.length; i < length; i++) {\n //This loop will read through all of the elements of an array\n var scheduleFile = fs.readFileSync('./schedule/' + scheduleList[i] + '', 'utf-8');\n var json = checkJSON(scheduleFile);\n if (json != undefined) {\n playlist = json;\n }\n }\n}", "function loadJSONCallback(response) {\n // parse JSON string into object\n let actual_JSON = JSON.parse(response);\n // create HTML element for each product\n for (let i = 0; i < actual_JSON.length; i++) { \n let slide = actual_JSON[i][i];\n // create and append the new carousel element\n createSlide(slide, i);\n }\n }", "function gotData(data)\n{\n console.log(data);\n for (var i = 0; i < data.data.length; i++)\n {\n id = data.data[i].id;\n locationData.push(data.data[i]);\n }\n\n if(itr < pages)\n {\n url = data.paging.next;\n loadJSON(url, gotData);\n }\n else{\n console.log('LOCATIONS RETREIVED');\n console.log(locationData);\n }\n itr++\n\n }", "function initialize(){\n\t\t//loop through the json object\n\tif(model.selectedMachine != null){\n\t\t for(var i=0; i < model.data.machines[model.selectedMachine].components.length; i++){\n\t\t\t//output a line item for each json object found\n\t\t\tvar id = model.data.machines[model.selectedMachine].components[i].id\n\t\t\tvar name = model.data.machines[model.selectedMachine].components[i].component\n\t\t\tvar hours = model.data.machines[model.selectedMachine].components[i].hours\n\t\t\tvar projection = model.data.machines[model.selectedMachine].components[i].projection\n\t\t\tgenerateLineItem(id,name,hours,projection);\n\t\t}\n\t}\n}", "function processData(allText) {\n restJson = JSON.parse(allText);\n console.log(restJson);\n buildTable(restJson);\n }", "function try2(){\n user= new XMLHttpRequest();\n user.open('GET','users.json',true)\n user.onload=function(){\n if (this.status=200) {\n var u=JSON.parse(this.responseText)\n console.log(u)\n outptut='<h1></h1>'\n u.forEach(function(q){\n outptut+=`\n <li>${q.id}</li>\n <li>${q.name}</li>\n <li>${q.email}</li>\n\n\n\n\n\n `;\n if (q.id==1) {\n\n console.log('hii',q.name)\n }\n }\n\n )\n\n document.getElementById('one').innerHTML=outptut;\n }\n\n }\n user.send()\n}", "function processJSON ( file ) {\n 'use strict';\n var _json = JSON.parse(file.contents.toString());\n var _jsonOut = [];\n for (var i in _json) {\n _jsonOut[i] = {};\n _jsonOut[i].id = md5(i.toString());\n\n for (var j in _json[i]) {\n\n if (j in COL_NAME_MAP) {\n var v = COL_NAME_MAP[j];\n\n if (typeof v === 'object') {\n\n var content = _json[i][j];\n\n if (v.slugify) {\n content = slugify(content);\n }\n\n if ('parent' in v) {\n if (!(v.parent in _jsonOut[i])) {\n _jsonOut[i][v.parent] = v.many ? [] : {};\n }\n\n if (v.many) {\n var _split = content.split(v.delimiter);\n\n for (var s in _split) {\n if (_jsonOut[i][v.parent].length == 0) {\n let a = v.value;\n let b = {};\n b[a] = '';\n _jsonOut[i][v.parent][s] = b;\n }\n _jsonOut[i][v.parent][s][v.value] = _split[s].trim();\n }\n }\n }\n\n _jsonOut = populateChildren(_jsonOut, content, v, i);\n\n } else {\n _jsonOut[i][v] = _json[i][j];\n }\n }\n }\n }\n var out = JSON.stringify(_jsonOut);\n file.contents = new Buffer(out);\n}", "function toJSON() {\n\n for (let i = 0; i < tokenList.length; i++) {\n current = tokenList[i];\n if (current !== undefined && current !== null && current[\"type\"] !== \"WS\") {\n // console.log(i + 1)\n updateJSON(current);\n // console.log(\"---------------------------------------\")\n }\n }\n }", "function parseFile(file_data){\n let s = ''\n let read = false\n // find the index correspondding to the start of the json data\n for (i in file_data){\n if (file_data[i] == '{') {\n read = true\n }\n\n if (read) {\n s+=file_data[i]\n }\n }\n return s\n }", "function drawAllLines(){\n\tfor(var i = -1; i < packetsJSON.length - 1; i++){\n\t\tif(globalIndex < packetsJSON.length - 1){\n\t\t\tglobalIndex++;\n\t\t\tdrawLine(globalIndex);\n\t\t\tupdateInformationBar(globalIndex);\n\t\t}\n\t}\n}", "function myCustomFunction(data){\n for(singleData of data){\n // console.log(singleData.title)\n }\n}", "function getJSON(file){\n reader.onload = function (file) {\n var obj = JSON.parse(file.target.result);\n for(var i = 0; i < obj.Result.length; i++)\n appendToScreen(obj.Result[i].title, obj.Result[i].url, obj.Result[i].description);\n };\n reader.readAsText(file);\n}", "function createJsonOne(currentLine,prevYear)\n{\n\n console.log(currentLine[5]);\n if(currentLine[5]===\"ROBBERY\")\n {\n var flag1=0;\n // console.log(JSON_One[0].value.length);\n for(var j=0;j<JSON_One[0].value.length;j++)\n {\n // console.log(JSON_One[0].value.length);\n if(currentLine[17]===JSON_One[0][\"value\"][j][\"Year\"])\n {\n // console.log(JSON_One[0][\"value\"][j][\"Year\"]);\n console.log(\"ROBBERY updated in \"+currentLine[17]);\n JSON_One[0][\"value\"][j][\"Count\"] ++;\n flag1++;\n break;\n }\n }\n if(flag1===0)\n {\n JSON_One[0][\"value\"].push(\n {\n \"Year\" : currentLine[17],\n \"Count\": 1\n }\n );\n }\n // console.log(flag1);\n // break;\n }\n\n if(currentLine[5]==='BURGLARY')\n {\n var flag2=0;\n for(var j=0;j<JSON_One[1][\"value\"].length;j++)\n {\n if(currentLine[17]===JSON_One[1][\"value\"][j][\"Year\"])\n {\n console.log(\"BURGLARY found in \"+ JSON_One[1][\"value\"][j][\"Year\"]);\n JSON_One[1][\"value\"][j][\"Count\"] ++;\n flag2++;\n break;\n }\n\n }\n if(flag2===0)\n {\n JSON_One[1][\"value\"].push(\n {\n \"Year\" : currentLine[17],\n \"Count\": 1\n }\n );\n }\n // break;\n }\n else\n {\n return;\n }\n }", "function iterate() {\n cursor.read(1000, (err, rows) => {\n if (err) return cb(err);\n\n if (!rows.length) {\n done();\n return cb();\n }\n\n for (let row of rows) {\n if (turf.lineDistance(row.geom) < 0.001) continue;\n\n row.name = row.name.filter(name => {\n if (!name.display) return false;\n return true;\n });\n\n if (!row.name.length) continue;\n\n let feat = {\n type: 'Feature',\n properties: {\n 'carmen:text': row.name,\n 'carmen:rangetype': 'tiger',\n 'carmen:parityl': [[]],\n 'carmen:parityr': [[]],\n 'carmen:lfromhn': [[]],\n 'carmen:rfromhn': [[]],\n 'carmen:ltohn': [[]],\n 'carmen:rtohn': [[]]\n },\n geometry: {\n type: 'GeometryCollection',\n geometries: [\n row.geom\n ]\n }\n };\n\n if (self.opts.country) feat.properties['carmen:geocoder_stack'] = self.opts.country;\n\n feat = self.post.feat(feat);\n if (feat) self.output.write(JSON.stringify(feat) + '\\n');\n }\n\n return iterate();\n });\n }", "function ParseJson(result) {\n if ( statusId == 'default' ) {\n for (var i = 0; i < result.response.venues.length; i++) {\n var venue = result.response.venues[i];\n dataStFull.push({\n name: venue.name,\n latlng: [venue.location.lat, venue.location.lng],\n distance: venue.location.distance,\n addressFull: venue.location.formattedAddress,\n address: venue.location.address,\n city: venue.location.city,\n id: venue.id,\n catName: venue.categories[0].name,\n catImage: venue.categories[0].icon.prefix + '32' + venue.categories[0].icon.suffix,\n shape: 'pinTarget'\n // shape : 'pin'\n });\n }\n } else if ( statusId == 'recomendation') {\n var tempItems = result.response.groups[0].items;\n for (var i = 0; i < tempItems.length; i++) {\n var venue = tempItems[i].venue;\n dataStFull.push({\n name: venue.name,\n latlng: [venue.location.lat, venue.location.lng],\n distance: venue.location.distance,\n addressFull: venue.location.formattedAddress,\n address: venue.location.address,\n city: venue.location.city,\n id: venue.id,\n catName: venue.categories[0].name,\n catImage: venue.categories[0].icon.prefix + '32' + venue.categories[0].icon.suffix,\n shape: 'pin'\n // shape : 'pin'\n });\n }\n } else {\n console.log('ERROR with URL');\n }\n}", "function retrieve(jsonArr){\njsonArr = JSON.parse(jsonArr);\n for (j = 0; j < jsonArr.length; j++){\n new listItem(jsonArr[j].name,jsonArr[j].id,jsonArr[j].done).getHtml();\n }\n}", "function myParseJSON(data) {\n data = data.substr(data.indexOf('{'));\n while (data.substr(data.length-1)=='\\n')\n data = data.substr(0, data.length - 1);\n data = data.split(\"\\n\").join(\"<br/>\");\n data = data.split(\"\\r\").join(\"\");\n \n return jQuery.parseJSON(data);\n}", "function iterate(obj, jsonArr) {\n for(var key in obj) {\n var elem = obj[key];\n\n if(typeof elem === \"object\") {\n iterate(elem, jsonArr); // call recursively\n }\n else{\n if(!patt.test(key.toString())){\n if(elem == undefined)\n jsonArr.push({\"key\":key.toString(),\"text\":null});\n else\n {\n if($.trim(elem) != \"\")\n jsonArr.push({\"key\":key.toString(),\"text\":elem});\n }\n }\n }\n }\n}", "function processJSON(JSONstr){\n var data = JSON.parse(JSONstr);\n doStuffWithJSON(data.fishyDevices);\n}", "function getUsers(json) { return json.map(function (obj){ return obj.user; } ); }", "function handleReply() {\n\n //If the response is correct\n if (JSONrequest.readyState == 4) {\n //Save the response on a variable\n data1 = JSON.parse(this.responseText);\n //Call the function removeData from canvas.js\n removeData(myLine);\n\n //Call the function assData from canvas.js\n for (var i = 0; i < data1.length - 1; i++) {\n\n addData(myLine, data1[0][i], data1[i + 1]);\n\n }\n }\n}", "async function loadJSON(path) { \n const content = await getDataFromServer(path).catch(e => e);\n // demo: catch return null or error\n console.log('Loaded json ', content);\n\n if(content){\n content.items.forEach(x => console.log('x.Price ', x.Price));\n \n const li = '<li click=\"onLicClick()\">{{x.Names.ro}} <br/> {{formatPrice(x.Price)}}</li>'\n }\n}", "function volcarDatos(datos){//la funcion se repite hasta que no haigan mas registros\n var total = datos.length;//obtiene la logitud del json\n data=\" \";\n\n for(var i=0; i<total; i++){\n data += \" \"+ datos[i].tema+\" \";\n }\n\n return data;//retorna los archivos json\n}", "function getJson(){\n\n fetch('fetch.json')\n .then(function(res){\n return (res.json());\n }) \n\n .then(function(data){\n console.log(data);\n\n let output = ' ';\n data.forEach (function(post){\n\n output += `<li>${post.title}</li>\n <li>${post.body}</li>\n `;\n document.getElementById('output').innerHTML = output;\n });\n \n })\n \n \n\n\n\n .catch(function(err){\n\n console.log(err);\n })\n \n //Fetch returns promises\n\n}", "function getLineData(){\r\n\t \t\t var jsonUnit = \"\";\r\n\t \t\t var label=\"\";\r\n\t \t\t\t\t var fillColor = \"\";\r\n\t \t\t\t\t var strokeColor = \"\";\r\n\t \t\t\t\t var pointColor = \"\";\r\n\t \t\t\t\t var pointStrokeColor = \"#fff\";\r\n\t \t\t\t\t var pointHighlightFill = \"#fff\";\r\n\t \t\t\t\t var pointHighlightStroke = \"\";\r\n\t \t\t\t\t\tdata : \r\n\t \t\t for(var i=0; i<$scope.unit_yData.length;i++){\r\n\t \t\t\t label=$scope.unit_names[i];\r\n\t \t\t\t switch(i%5) {\r\n\t\t \t\t\t case 0:\r\n\t\t \t\t\t fillColor = \"rgba(220,220,220,0.2)\";\r\n\t\t \t\t\t strokeColor = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t pointColor = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t pointStrokeColor = \"#fff\";\r\n\t\t \t\t\t pointHighlightFill = \"#fff\";\r\n\t\t \t\t\t pointHighlightStroke = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t break;\r\n\t\t \t\t\t case 1:\r\n\t\t \t\t\t \tfillColor = \"rgba(169,152,142,0.2)\";\r\n\t\t \t\t\t strokeColor = \"rgba(215,203,209,1)\";\r\n\t\t \t\t\t pointColor = \"rgba(230,210,222,1)\";\r\n\t\t \t\t\t pointStrokeColor = \"#fff\";\r\n\t\t \t\t\t pointHighlightFill = \"#fff\";\r\n\t\t \t\t\t pointHighlightStroke = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t break;\r\n\t\t \t\t\t case 2:\r\n\t\t \t\t\t \tfillColor = \"rgba(050,125,100,0.2)\";\r\n\t\t \t\t\t strokeColor = \"rgba(125,220,025,1)\";\r\n\t\t \t\t\t pointColor = \"rgba(036,201,119,1)\";\r\n\t\t \t\t\t pointStrokeColor = \"#fff\";\r\n\t\t \t\t\t pointHighlightFill = \"#fff\";\r\n\t\t \t\t\t pointHighlightStroke = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t break;\r\n\t\t \t\t\t case 3:\r\n\t\t \t\t\t \tfillColor = \"rgba(025,082,112,0.2)\";\r\n\t\t \t\t\t strokeColor = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t pointColor = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t pointStrokeColor = \"#fff\";\r\n\t\t \t\t\t pointHighlightFill = \"#fff\";\r\n\t\t \t\t\t pointHighlightStroke = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t break;\r\n\t\t \t\t\t default:\r\n\t\t \t\t\t \tfillColor = \"rgba(255,255,0,0.2)\";\r\n\t\t \t\t\t strokeColor = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t pointColor = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t pointStrokeColor = \"#fff\";\r\n\t\t \t\t\t pointHighlightFill = \"#fff\";\r\n\t\t \t\t\t pointHighlightStroke = \"rgba(220,220,220,1)\";\r\n\t\t \t\t\t}\r\n\t \t\t\t if($scope.unit_yData.length==1){\r\n\t \t\t\t\t jsonUnit = \"[\"+jsonUnit + JSON.stringify({\"data\":$scope.unit_yData[i],\"label\":label,\"fillColor\":fillColor,\"strokeColor\":strokeColor,\"pointColor\":pointColor,\"pointStrokeColor\":pointStrokeColor,\"pointHighlightFill\":pointHighlightFill,\"pointHighlightStroke\":pointHighlightStroke}) + \"]\";\r\n\t \t\t\t\t break;\r\n\t \t\t\t }\r\n\t \t\t\t if(i==0){\r\n\t \t\t\t\t jsonUnit = \"[\"+jsonUnit + JSON.stringify({\"data\":$scope.unit_yData[i],\"label\":label,\"fillColor\":fillColor,\"strokeColor\":strokeColor,\"pointColor\":pointColor,\"pointStrokeColor\":pointStrokeColor,\"pointHighlightFill\":pointHighlightFill,\"pointHighlightStroke\":pointHighlightStroke});\r\n\t \t\t\t }\r\n\t \t\t\t if(i>0 && i<$scope.unit_yData.length-1){\r\n\t \t\t\t\t jsonUnit = jsonUnit+\",\" + JSON.stringify({\"data\":$scope.unit_yData[i],\"label\":label,\"fillColor\":fillColor,\"strokeColor\":strokeColor,\"pointColor\":pointColor,\"pointStrokeColor\":pointStrokeColor,\"pointHighlightFill\":pointHighlightFill,\"pointHighlightStroke\":pointHighlightStroke});\r\n\t \t\t\t }\r\n\t \t\t\t if(i==$scope.unit_yData.length-1){\r\n\t \t\t\t\t jsonUnit = jsonUnit +\",\" + JSON.stringify({\"data\":$scope.unit_yData[i],\"label\":label,\"fillColor\":fillColor,\"strokeColor\":strokeColor,\"pointColor\":pointColor,\"pointStrokeColor\":pointStrokeColor,\"pointHighlightFill\":pointHighlightFill,\"pointHighlightStroke\":pointHighlightStroke})+\"]\";\r\n\t \t\t\t }\r\n\t \t\t }\r\n\t \t\t return JSON.parse(jsonUnit);\r\n\t \t }", "function parseJSON(data) {\n document.write(data)\n for (var date in data) {\n if (data.hasOwnProperty(date)) {\n //console.log(date + \" -> \" + data[date]);\n var day = data[date];\n //console.log(\"Date: \" + date)\n writeDateData(date);\n for (var meal in day) {\n if (day.hasOwnProperty(meal)) {\n //console.log(meal + \" -> \" + day[meal])\n var mealOfTheDay = day[meal];\n for (var loc in mealOfTheDay) {\n if (mealOfTheDay.hasOwnProperty(loc)) {\n //console.log(loc + \" -> \" + mealOfTheDay[loc])\n var menuItems = mealOfTheDay[loc];\n if (menuItems.length > 1) {\n for (var menuItem in menuItems) {\n writeUserData(date, meal, loc, menuItems[menuItem])\n }\n } else {\n writeUserData(date, meal, \"Burton\", menuItems[0])\n writeUserData(date, meal, \"East Hall\", menuItems[0])\n writeUserData(date, meal, \"Sayles Hill Café\", menuItems[0])\n writeUserData(date, meal, \"Weitz Café\", menuItems[0])\n /*console.log(\"There should be no specials at this time\")\n console.log(\"Date\" + date)\n console.log(\"Meal\" + meal)\n console.log(\"Location\" + loc)\n console.log(menuItems[0])*/\n\n }\n }\n }\n }\n }\n }\n }\n}", "function reportToString(data){\n var myJSON = data.scans;\n const keys = Object.keys(myJSON);\n var values = Object.values(myJSON);\n\n printfyHead();\n\n for( k in keys){\n console.log(keys[k]);\n var result = JSON.stringify(values[k]);\n result = result.replace(/\\\"/g, \"\"); // removes \"}\" and ' \"\" '\n result = result.replace(/\\{|\\}/g, \"\");\n console.log(result); // object type\n printfyBody(result, keys[k]);\n }\n\n}", "function getJson(){\n fetch('posts.json')\n .then(res => res.json())\n .then(data => {\n\n console.log(data);\n let output = '';\n data.forEach(function(post){\n\n output += `<li>${post.title}</li>`\n });\n document.getElementById('output').innerHTML = output;\n \n\n })\n .catch(err => console.log(err));\n\n}", "function loadJSONs( url, which ){\n var AJAX_req = new XMLHttpRequest();\n AJAX_req.overrideMimeType(\"application/json\");\n AJAX_req.open('GET',url,false);\n AJAX_req.onreadystatechange = function(){\n if(AJAX_req.readyState==4 && AJAX_req.status==\"200\"){\n if( which == 0){\n pre = JSON.parse( AJAX_req.responseText ); \n }\n else{\n post = JSON.parse( AJAX_req.responseText );\n }\n }\n };\n\n AJAX_req.send();\n}", "function extract_json(divid, indent){\n $('#jsoninput').val(glean_json(divid,indent));\n }", "line_handler(line) {\n this.events.push(JSON.parse(line));\n }", "function fetchCodeAirline(id) {\r\n var i = 0;\r\n var display = [];\r\n fetch(urlAirlines).then(res => res.json()).then(data => {\r\n data.airline.forEach(trip => {\r\n if (id === trip.key) {\r\n console.log(\"code=\" + trip.code);\r\n var code = trip.code;\r\n logoComp = trip.logo;\r\n nameCompAirline = trip.name;\r\n fetchDataOfTrip(code, trip.country);\r\n } else {\r\n console.log(trip.key);\r\n }\r\n });\r\n\r\n });\r\n\r\n\r\n}", "initializeFromJSON(dataObject) {\n\n console.log('dataObject', dataObject);\n\n if(!dataObject) { return; }\n\n for(const stringifiedData of dataObject) {\n const fields = stringifiedData.split('-');\n\n const proteinId = fields[0];\n const start = parseInt(fields[1]);\n const end = parseInt(fields[2]);\n const color = fields[3];\n\n this.addProteinColorAnnotation({\n proteinId:proteinId,\n start:start,\n end:end,\n color:color\n });\n }\n }", "function getJson() {\n fetch(\"posts.json\")\n .then(function (res) {\n return res.json();\n })\n .then(function (data) {\n console.log(data);\n let output = \"\";\n data.forEach(function (post) {\n output += `<li>${post.title} <br> &nbsp; &nbsp; ${post.body} </li>`;\n });\n document.getElementById(\"output\").innerHTML = output;\n })\n .catch(function (err) {\n console.log(err);\n });\n}", "async function getData() {\r\n const response = await fetch('/api');\r\n const data = await response.json();\r\n\r\n for (item of data) {\r\n const root = document.createElement('p');\r\n const mood = document.createElement('div');\r\n const date = document.createElement('div');\r\n const geo = document.createElement('div');\r\n\r\n\r\n mood.textContent = `mood: ${item.mood}`;\r\n geo.textContent = `${item.lat}°, ${item.lon}°`;\r\n const dateString = new Date(item.timestamp).toLocaleDateString();\r\n date.textContent = dateString;\r\n\r\n root.append(mood, geo, date);\r\n document.body.append(root);\r\n\r\n }\r\n\r\n console.log(data);\r\n}", "function _content (json) {\n let obj = json.alternatives\n let a1 = obj[Object.keys(obj)[0]]\n let a2 = obj[Object.keys(obj)[1]]\n let a3 = obj[Object.keys(obj)[2]]\n let a4 = obj[Object.keys(obj)[3]]\n _setContent(json, a1, a2, a3, a4)\n}", "function getTweets(json) { return json; }", "getJsonFromServer() {\n fetch(`${servername}/getjson`)\n .then(res => res.json())\n .then(data=>{\n if(data != null) {\n for(let element of data) {\n if(element.jsonstring.df != null) {\n if(element.jsonstring.df.lob != null) {\n // Parse the json points to receive json data.\n let stringConverter = element.jsonstring.df.lob\n let floatStringArray = stringConverter.split(',')\n let latitude = parseFloat(floatStringArray[0])\n let longitude = parseFloat(floatStringArray[1])\n \n // Create a new feature on OpenLayers\n if(!this.doesFeatureExist(latitude, longitude)) {\n let longLat = fromLonLat([longitude, latitude])\n let newFeature = new Feature({\n geometry: new Point(longLat),\n information: element.jsonstring\n })\n this.vectorAlerts.addFeature(newFeature)\n }\n }\n else console.log('lob was null. JSON must be broken:', element)\n }\n else console.log(\"data.df was empty. Consider fixing json string?\", element)\n }\n console.log('Features were updated', this.vectorAlertLayer.getSource().getFeatures())\n }\n else console.log(\"data had returned null\")\n })\n }", "function scrapeJson() {\n var scriptTags = document.body.querySelectorAll(FUNDME_JSON_SELECTOR);\n var pointers = [];\n\n if (scriptTags.length) {\n scriptTags.forEach(function (json) {\n pointers = parseScriptJson(json);\n });\n }\n\n return pointers;\n }", "function getJson() {\n fetch('post.json')\n .then(function (response) {\n return response.json();\n })\n .then(function (data) {\n console.log(data);\n let op = '';\n data.forEach(function (post) {\n op+= `<li>${post.title}</li>`\n });\n document.getElementById('output').innerHTML = op;\n })\n .catch(function (err) {\n console.log(err);\n });\n}", "function loadJSON(fileUrl) {\n // Declare our xhr object\n const xhr = new XMLHttpRequest();\n // Set up the callback for our successful request\n xhr.onload = function() {\n // Parse the JSON\n arry = JSON.parse(xhr.responseText);\n console.log(arry);\n renderAll(arry);\n };\n // Open the request\n xhr.open('GET', fileUrl, true);\n // Send the request\n xhr.send();\n}", "function get_json_data() {\n let getBatchesURL = \"http://localhost:5000/batches/\";\n fetch(getBatchesURL)\n .then((res) => res.json())\n .then((json) => append_json(json));\n}", "function testJson() {\n var baseUrl = 'https://rxnav.nlm.nih.gov/REST/';\n var testUrl = 'https://rxnav.nlm.nih.gov/REST/rxcui?name=xanax'\n var request = Meteor.npmRequire('request');\n request(testUrl, function (error, response, body) {\n if (!error && response.statusCode == 200) {\n var info = JSON.parse(body)\n console.log(body);\n }\n });\n }", "function parseJSON () {\n var process = new Process (packagesfile);\n packages = process.parse ();\n packages = packages.packages;\n }", "async getAbi(_AbiFileName){\n let result = [];\n try {\n const response = await fetch(_AbiFileName);\n if (response.ok) {\n const jsonResponse = await response.json();\n console.log('JSON parsed successfully...');\n for(var i in jsonResponse){\n result.push(jsonResponse[i]);\n }\n return result;\n }\n\n } catch(error) {\n console.log(error);\n }\n }", "function displayNicely(apiData){\n let newData = JSON.parse(apiData);\n let count = 0;\n for(let i in newData){\n count++;\n console.log(newData[i]);\n if(count == 8){\n break;\n }\n }\n \n let htmlString = \"<div><strong>Name:</strong>\"+newData.name+\"</div>\";\n htmlString += \"<div><strong>Height:</strong>\"+newData.height+\"</div>\";\n htmlString += \"<div><strong>Weight:</strong>\"+newData.mass+\"</div>\";\n htmlString += \"<div><strong>Sex:</strong>\"+newData.gender+\"</div>\";\n htmlString += \"<div><strong>Skin:</strong>\"+newData.skin_color+\"</div>\";\n document.getElementById(\"data\").innerHTML = htmlString;\n\n}", "function parseJSON(data){\n if(data.startsWith(\"while(1);\")){\n return JSON.parse(data.substring(\"while(1);\".length))\n }\n return JSON.parse(data)\n}", "function handleCommits(json) {\n for (i in json.users) {\n if (json.users[i].Commit_ID != null) {\n var point = {\n 'x':json.users[i].time,\n 'y':json.users[i].mood,\n }\n commit_data.push(point)\n commit_types.push(json.users[i].Commit_ID)\n }\n }\n console.log(commit_data)\n}", "function jsonLoaded(obj) {\n // 6 - if there are no results, print a message and return\n // Here, we don't get an array back, but instead a single object literal with 2 properties\n\n if (obj.status != \"success\") {\n document.querySelector(\"#content\").innerHTML = \"<p><i>There was a problem!</i></p>\";\n return; // Bail out\n }\n\n // 7 - if there is an array of results, loop through them\n let results = obj.message;\n let resultMessage = \"<p><i>Here is the result!</i></p>\";\n let bigString = \"\";\n\n for (let i = 0; i < results.length; i++) {\n let result = results[i];\n let smallURL = result;\n let url = result;\n let line = `<a target='_blank' href='${url}'><div class='result' style='background-image: url(${smallURL})'>`;\n line += `</div></a>`;\n\n bigString += line;\n }\n\n // 8 - display final results to user\n document.querySelector(\"#content\").innerHTML = bigString;\n}", "function loadData() {\n var jsonRovereto = httpGet(\"https://os.smartcommunitylab.it/core.mobility/bikesharing/rovereto\");\n dataRovereto = JSON.parse(jsonRovereto);\n var jsonPergine = httpGet(\"https://os.smartcommunitylab.it/core.mobility/bikesharing/pergine_valsugana\");\n dataPergine = JSON.parse(jsonPergine);\n var jsonTrento = httpGet(\"https://os.smartcommunitylab.it/core.mobility/bikesharing/trento\");\n dataTrento = JSON.parse(jsonTrento);\n //console.log(dataTrento);\n}", "function add_markers(json_data, lat_lon_json) {\n for (let i=0; i < json_data[\"n_per_comuna\"].length; i++) {\n // world's slowest algorithm\n // search the lat lon in the array of latlons one by one\n let j = 0;\n while (j < lat_lon_json.length && lat_lon_json[j][\"name\"] !== json_data[\"n_per_comuna\"][i][\"comuna\"]) {\n j++;\n }\n if (j === lat_lon_json.length) {\n console.log(\"Error en la comuna\", json_data[\"n_per_comuna\"][i][\"comuna\"]);\n console.log(\"No sé encontró la comuna. Este problema es probablemente debido a una inconsistencia en el\" +\n \" JSON de latitudes longitudes con los nombres de las comunas en la base de datos\");\n continue;\n }\n if (lat_lon_json[j][\"name\"] === json_data[\"n_per_comuna\"][i][\"comuna\"]) {\n add_marker(lat_lon_json[j][\"lat\"], lat_lon_json[j][\"lng\"],\n lat_lon_json[j][\"name\"], json_data[\"n_per_comuna\"][i][\"comuna_id\"],\n json_data[\"n_per_comuna\"][i][\"n_avistamientos\"]);\n }\n }\n}", "function read_json(fname) {\n\t\t\tconsole.log(\"in read_json\");\n\t\t\t$.getJSON(fname, function(data) {\n\t\t\t\tconsole.log(\"returned from read_json to execute function\");\n\t\t\t\tsurface.renderSurface(data);\n\t\t\t});\t\t\t\n\t\t}", "function loadProducts () {\n data = JSON.parse(this.response);\n var contentEl = document.getElementById(\"output\");\n for (var i = 0; i < data.products.length; i++) {\n currentProduct = data.products[i]\n }\nconsole.log(\"test\")\n}", "function readReferenceHistory(json){\r\n var lista = \"\";\r\n for(var i=0; i<json.ReferenceHistory.length;i++){\r\n lista += \"<tr><td>\"+json.ReferenceHistory[i].rname+\"</td><td>\"+json.ReferenceHistory[i].rposition+\"</td><td>\"+json.ReferenceHistory[i].rphone+\"</td><td>\"+json.ReferenceHistory[i].rkind+\"</td></tr>\";\r\n }\r\n return lista;\r\n }", "async loopFunction(iterate) {\n \t\tlet results = [];\n \t\twhile (true) {\n let result = await iterate.next();\n if (result.value && result.value.value.toString()) {\n \t\t\t\tresults.push(JSON.parse(result.value.value.toString('utf8')));\n }\n if (result.done) {\n \t\t\t\tawait iterate.close();\n return results;\n }\n }\n \t}", "function n$1(r){return r&&g.fromJSON(r).features.map((r=>r))}", "function readJSON ( filename, callback ) {\n\tfs.readFile ( filename , function ( err , filedata ) {\n\t\tif (err) {\n\t\t\tconsole.log( \"We have a problem broski :\" + err )\n\t\t}\n\t\tconsole.log(countryname)\n\t\tvar jsondata = JSON.parse( filedata )\n\n\t\tjsondata.forEach( function ( country ) {\n\t\t\tif ( country.name == countryname ) {\n// possibly client wants to output all the info from a country?\n\t\tconsole.log( \"Country: \" + country.name )\n\t\tconsole.log( \"Top Level Domain: \" + country.topLevelDomain ) // tld field is an array and may contain more tld's\n\t}\n})\n\t})\n}", "function renderArticle(json) {\n //console.log(json.articles.length);\n for (let i = 0; i < json.articles.length; i++) {\n let li = document.createElement(\"li\");\n li.innerHTML = ` <p> Title=${json.articles[i].title} </p>\n <p> description=${json.articles[i].description} </p>\n <p> username=${json.articles[i].author.username} </p>\n <p> body=${json.articles[i].body} </p>\n <p> createdAt:${salam(json.articles[i].createdAt)}</p>`;\n ul.appendChild(li);\n }\n}", "printConcertInfo(data, maxEvents = this.maxEvents) {\n // let data = JSON.parse(body);\n // console.log(data);\n\n for (let i = 0; i < data.length && i < maxEvents; i++ ) {\n let element = data[i];\n let venue = element.venue;\n let location = [venue.city, venue.region, venue.country\n ].filter(e => e.length > 0).join(\", \");\n let date = this.moment(element.datetime).format(\"MM/DD/YYYY\");\n\n console.log(\"- \" + (i + 1) + \" -\");\n console.log(`\\tVenue: ${venue.name}`);\n console.log(`\\tLocation: ${location}`);\n console.log(`\\tDate: ${date}`);\n }\n }", "function getReadings(){\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n //console.log(\"[\"+this.responseText.slice(0, -1)+\"]\");\n var myObj = JSON.parse(\"[\"+this.responseText.slice(0, -1)+\"]\");\n //console.log(myObj);\n var len = myObj.length;\n if(len > 40) {\n for(var i = len-40; i<len; i++){\n plotTemperature(myObj[i].time, myObj[i].temperature);\n plotHumidity(myObj[i].time, myObj[i].humidity);\n }\n }\n else {\n for(var i = 0; i<len; i++){\n plotTemperature(myObj[i].time, myObj[i].temperature);\n plotHumidity(myObj[i].time, myObj[i].humidity);\n }\n } \n }\n }; \n xhr.open(\"GET\", \"/readings\", true);\n xhr.send();\n}", "function ReviewJson(client, json) {\n kLog.print(client.name + ': ' + json.toString())\n jimHandler.review(client, json)\n}", "function FindLine(text_input){\n $.ajax({\n url: \"/../transportation/request\",\n cache: false,\n data: {line: text_input},\n success: function(data){\n var results = new Array();\n for (i=0; i<data.length; i++) {\n results[i] = data[i];\n //console.log(results[i].route);\n AddResult(results[i]);\n }\n }\n });\n }", "function readJSON(file, response) {\n if (file.mimetype !== 'application/json') {\n response.render('error', { error: 'Wrong file format' })\n return;\n }\n\n let dataObj = JSON.parse(file.buffer.toString());\n\n // Check if dataObj contains operations\n if (!dataObj.operations || !dataObj.operations.length) {\n response.render('error', { error: 'Wrong data structure' })\n return;\n }\n\n let result = 0;\n\n for (operation of dataObj.operations) {\n // Check if operation contains all required field\n if (!operation.name || !operation.arg1 || !operation.arg2) {\n response.render('error', { error: 'Wrong data structure' })\n return;\n }\n\n // Check if agr1 is valid\n if (operation.arg1 !== 'result' && isNaN(operation.arg1)) {\n response.render('error', { error: 'Wrong data structure' })\n return;\n }\n\n // Check if agr2 is valid\n if (operation.arg2 !== 'result' && isNaN(operation.arg2)) {\n response.render('error', { error: 'Wrong data structure' })\n return;\n }\n\n let arg1 = operation.arg1 === 'result' ? result : operation.arg1;\n let arg2 = operation.arg2 === 'result' ? result : operation.arg2;\n\n switch (operation.name) {\n case 'add':\n result = arg1 + arg2;\n break;\n case 'subtract':\n result = arg1 - arg2;\n break;\n case 'multiply':\n result = arg1 * arg2;\n break;\n case 'divide':\n result = arg1 / arg2;\n break;\n default:\n response.render('error', { error: 'Wrong data structure' })\n return;\n }\n }\n\n response.render('result', { result: result })\n return;\n}", "function debugJson(data){\r\n\t\tvar i;\r\n\t\tconsole.log(data);\r\n\t\tif(typeof data == 'string'){\r\n\t\t\tdata = $.parseJSON(data);\r\n\t\t\tconsole.log(data);\r\n\t\t}\r\n\t\tfor(i in data){\r\n\t\t\tif(typeof data[i] == 'string'){\r\n\t\t\t\ttry{\r\n\t\t\t\t\tdata[i] = $.parseJSON(data[i]);\r\n\t\t\t\t\tconsole.log(data);\r\n\t\t\t\t}\r\n\t\t\t\tcatch(e){\r\n\t\t\t\t\tconsole.log('not a valid json String');\r\n\t\t\t\t\tconsole.log(data[i]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t$('#debug_content')\r\n\t\t\t.html('<pre>' + dump(data) + '</pre>')\r\n\t\t\t.show();\r\n\t}", "async getAllLines() {\n return await this.map((l) => l);\n }", "function sacarUsuarios(json){\n \n for(let usuario of json){ \n var id = usuario.id;\n var email = usuario.email;\n var pass = usuario.password;\n\n var objetoUsers = new constructorUsers(id,email,pass);\n datosUser.push(objetoUsers);\n\n contadorId=usuario.id; //sacar el ultimo valor de ID que esta en el JSON\n }\n return datosUser; \n}", "function toJSON() {\n\n for (let i = 0; i < tokenList.length; i++) {\n current = tokenList[i];\n if (current !== undefined && current !== null && current[\"type\"] !== \"WS\") {\n // console.log(i + 1)\n updateAttribute(current);\n // console.log(\"---------------------------------------\")\n\n }\n }\n }", "function searchAllData(url) {\n console.log(url)\n window\n .fetch(url)\n .then(res => res.json())\n .then(data => {\n console.log(data)\n\n data.response.rows.forEach(function(n) {\n addObject(n);\n });\n\n combineJSON(myArray)\n })\n .catch(error => {\n console.log(error)\n })\n\n}", "function indexPull() {\n $.get(\"http://10.1.254.102/Smoelenboek-3.0/PHP_JSON.php\", function(data, status){\n \n //Iterate through the JSON array for all entries\n for (x in data) {\n createAddresCardFromArray(data,x);\n }\n });\n }", "function extractFutureWeatherData(jsonData) {\n for (var i = 0; i < 33; i += 8) {\n var futureWeatherObj = {};\n futureWeather.name = jsonData.city.name;\n futureWeatherObj.date = convertToDateString(jsonData.list[i].dt);\n futureWeatherObj.weatherIcon = jsonData.list[i].weather[0].icon;\n futureWeatherObj.temperature = jsonData.list[i].main.temp;\n // console.log(jsonData.list[i].main.temp);\n futureWeatherObj.humidity = jsonData.list[i].main.humidity;\n futureWeather.daysOutlook.push(futureWeatherObj);\n }\n // console.log(futureWeather);\n}", "function listTodos(jsonObject) {\n //first of all check if we have tasks to do\n if(jsonObject.tasks.length > 0){\n //take the tasks array from the json object\n let itemsToDisplay = jsonObject.tasks;\n //build first line of the string to display\n let textToDisplay = 'You have ' + itemsToDisplay.length + ' things to do';\n itemsToDisplay.forEach(function(item,index){\n //add on a new line the index of the task and the name of it\n textToDisplay = textToDisplay + '\\n' + (index + 1) + ' ' + item;\n });\n console.log(textToDisplay);\n }else{\n //notify the user that he doesn't have any items on his todo list\n console.log('No tasks to display');\n }\n}", "function readEmploymentHistory(json){\r\n var lista = \"\";\r\n for(var i=0; i<json.EmploymentHistory.length;i++){\r\n lista += \"<tr><td>\"+json.EmploymentHistory[i].cname+\"</td><td>\"+json.EmploymentHistory[i].cjobtitle+\"</td><td>\"+json.EmploymentHistory[i].cdate1+\"</td><td>\"+json.EmploymentHistory[i].cdate2+\"</td><td>\"+json.EmploymentHistory[i].cdescription+\"</td></tr>\"; \r\n }\r\n return lista;\r\n }", "function getAddressLines(jsonAddress, fullAddress) {\n\n var address = [];\n address.push(jsonAddress[\"business_name\"]);\n\n var addressName = [jsonAddress[\"first_name\"], jsonAddress[\"last_name\"]];\n addressName = addressName.filter(function(n){return n}); // remove empty items\n address.push(addressName.join(\" \"));\n\n address.push(jsonAddress[\"address1\"]);\n if (fullAddress) {\n address.push(jsonAddress[\"address2\"]);\n address.push(jsonAddress[\"address3\"]);\n }\n\n var addressCity = [jsonAddress[\"postal_code\"], jsonAddress[\"city\"]].join(\" \");\n if (jsonAddress[\"country_code\"] && jsonAddress[\"country_code\"] !== \"CH\")\n addressCity = [jsonAddress[\"country_code\"], addressCity].join(\" - \");\n address.push(addressCity);\n\n address = address.filter(function(n){return n}); // remove empty items\n\n return address;\n}", "function splitJsons(jsons) {\n if(jsons[0] !== '{') throw new Error('Invalid response!');\n let s = [];\n let r = [];\n for(let i = 0, j = 0; i < jsons.length; i++) {\n if(jsons[i] === '{') s.push(1);\n else if(jsons[i] === '}') {\n let b = s.pop();\n if(b === undefined) throw new Error('Invalid response, expected \"{\" !');\n if(s.length === 0) {\n r.push(JSON.parse(jsons.substr(j, i + 1)));\n j = i + 1;\n }\n }\n }\n return r;\n}", "function getJson(){\n fetch('posts.json')\n .then(res => res.json())\n .then(data =>{\n console.log(data);\n let output = '';\n data.forEach(function(post){\n output += `<li>${post.title}</li>`;\n });\n document.getElementById('output').innerHTML = output;\n })\n .catch(err => console.log(err));\n}", "function Getdata() {\n $.ajax({\n type: \"GET\",\n url: \"https://raw.githubusercontent.com/jacky637006/jacky637006/master/HW/lol_js.json\",\n dataType: \"json\",\n success: function (response) {\n lolData = response;\n for (let i = 0; i < lolData.length; i++) {\n Importdata(i, lolData[i].icon, lolData[i].id, lolData[i].id, lolData[i].stats.hp,lolData[i].stats.attackdamage,lolData[i].stats.mp,lolData[i].stats.mpperlevel\n ,lolData[i].stats.movespeed,lolData[i].stats.attackrange);\n\n }\n }\n });\n}", "function getProducts() {\n let stringJSON = document.getElementById('json').value\n let myObj = JSON.parse(stringJSON)\n let products = myObj.products\n getProdsToTable(products)\n}", "function ObtenListaJsonFuenteCadena(datos) {\n var listaClima = [];\n for (i = 0; i < datos.length; i++) {\n listaClima.push(JSON.parse(datos[i]) );\n }\n return listaClima;\n}", "function getId(json, id) {\n var idQuitar = \"\";\n var newJson = \"\";\n var contador = 0;\n var encontro = 0;\n var cantComa = 0;\n var array = new Array();\n for (var item in json) {\n if (json[item] !== \"}\") {\n if (json[item] !== \"{\") {\n if (json[item] !== \",\") {\n if (cantComa !== 1) {\n if (json[item] >= 0) {\n idQuitar += json[item];\n newJson = newJson + json[item];\n if (idQuitar === id) {\n idQuitar = \"\";\n encontro = 1;\n } else {\n encontro = 0;\n }\n } else {\n newJson = newJson + json[item];\n }\n } else {\n newJson = newJson + json[item];\n }\n } else {\n cantComa = 1;\n newJson = newJson + json[item];\n }\n } else {\n newJson = newJson + json[item];\n cantComa = 0;\n }\n } else {\n newJson = newJson + json[item];\n cantComa = 0;\n if (encontro > 0) {\n array[contador] = limpiarObjert(newJson);\n contador++;\n newJson = \"\";\n encontro = 0;\n } else {\n newJson = \"\";\n idQuitar = \"\";\n }\n }\n }\n jsonNew = json.replace(array + \",\", \"\");\n return jsonNew;\n}", "function display(jsonObj)\n\t\t{\n\t\t\tfor(var i=0;i<37;++i)\n\t\t\t\tcreator(jsonObj,i)\n\t\t// \n\t\t}", "function loadFromJSON(json, CMIElement) {\n if (!_self.isNotInitialized()) {\n console.error(\"loadFromJSON can only be called before the call to LMSInitialize.\");\n return;\n }\n\n CMIElement = CMIElement || \"cmi\";\n\n for (var key in json) {\n if (json.hasOwnProperty(key) && json[key]) {\n var currentCMIElement = CMIElement + \".\" + key;\n var value = json[key];\n\n if (value[\"childArray\"]) {\n for (var i = 0; i < value[\"childArray\"].length; i++) {\n _self.loadFromJSON(value[\"childArray\"][i], currentCMIElement + \".\" + i);\n }\n } else if (value.constructor === Object) {\n _self.loadFromJSON(value, currentCMIElement);\n } else {\n setCMIValue(currentCMIElement, value);\n }\n }\n }\n }" ]
[ "0.6221983", "0.6186221", "0.6083474", "0.59135765", "0.58868086", "0.5873911", "0.58502096", "0.5830202", "0.5817008", "0.5798865", "0.5755613", "0.56673425", "0.5643661", "0.55699533", "0.55613595", "0.55257434", "0.552127", "0.5505064", "0.5503737", "0.54819936", "0.5477345", "0.54515415", "0.54352105", "0.54194957", "0.5417722", "0.54146135", "0.5411669", "0.5396959", "0.5380618", "0.5358749", "0.53546584", "0.53484964", "0.5328533", "0.5317261", "0.53151554", "0.5313031", "0.5305491", "0.52970237", "0.52772415", "0.52707076", "0.526885", "0.52680457", "0.5259663", "0.52560693", "0.52465767", "0.52408683", "0.52404326", "0.5222335", "0.522198", "0.52044153", "0.52018255", "0.51998633", "0.5199413", "0.51985765", "0.51939356", "0.51927036", "0.51871705", "0.5186373", "0.5183777", "0.5177365", "0.5169815", "0.5161142", "0.5155643", "0.51521224", "0.51514685", "0.5151117", "0.51505643", "0.51379037", "0.5137893", "0.5130475", "0.51259875", "0.5125665", "0.5124865", "0.5119075", "0.5109844", "0.5107237", "0.5105651", "0.5102025", "0.50975657", "0.50965834", "0.5095333", "0.5086417", "0.50858474", "0.50809497", "0.50773305", "0.50755316", "0.5072138", "0.507171", "0.5068803", "0.5063481", "0.50595504", "0.505917", "0.5057285", "0.50566477", "0.5052686", "0.50521857", "0.50498205", "0.50493807", "0.5048623", "0.50477815", "0.5044538" ]
0.0
-1
OLD VERSION TO GEOCOD AN ADDRESS
function codeAddressGoogle(address, tmpId, callback) { // alert("in codeAddress function"); // console.log(address); var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { // alert(results[0].geometry.location); // console.log("lat: " +results[0].geometry.location.lat()); var tmplat = results[0].geometry.location.lat(); var tmplng = results[0].geometry.location.lng(); console.log("/" + tmpId + "/" + address+ "/" + tmplat + "/" + tmplng); addressArray[tmpId] = {lat: tmplat, lng: tmplng}; // alert("After push"); callback(); } else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { // console.log("OVER_QUERY_LIMIT"); setTimeout(function() { codeAddressGoogle(address, tmpId, callback); }, 1500); } else { console.log('Geocode fail for the address: ' + address); console.log('Geocode was not successful for the following reason: ' + status); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function reverseGeocode(points) {\n var geocoder = new google.maps.Geocoder(),\n coordinates = new google.maps.LatLng(points[0], points[1]),\n setting = { 'latLng': coordinates };\n geocoder.geocode(setting, function (results, status) {\n if (status === 'OK') {\n var address = (results[0].formatted_address);\n console.log(address);\n } else {\n alert(status);\n }\n });\n}", "address(value) {\n return Object(address_lib_esm[\"a\" /* getAddress */])(value);\n }", "function onchangeAddress() {\n\tgetGeoByAddress();\t\n}", "function codeAddress(fromDb) {\n fromDb.forEach(data => {\n let address = data.address;\n address.trim()\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == 'OK') {\n map.setCenter(results[0].geometry.location);\n map.getCenter().lat()\n let points = {}\n points.id = data.id\n points.lat = map.getCenter().lat();\n points.lng = map.getCenter().lng();\n //send the new data to function\n updateAddressWithLatLng(points)\n \n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n })\n }", "getFormattedAddress() {\n\n }", "function geocodeLatLng() {\n var latlng = {lat: userLat, lng: userLng};\n geocoder.geocode({'location': latlng}, function (results, status) {\n if (status === 'OK') {\n if (results[0]) {\n formattedAddress = results[0].formatted_address;\n formattedAddressPrint = formattedAddress.split(', India')\n $(\".your_address\").removeClass('hidden');\n $(\".your_address2\").html(formattedAddressPrint);\n\n }\n }\n });\n }", "function makeGooglish(station) {\r\n var address = station.AddressInfo;\r\n var modified = {\r\n name: address.Title,\r\n vicinity: address.Town + \", \" + address.AddressLine1,\r\n geometry: {\r\n location: new google.maps.LatLng(address.Latitude, address.Longitude)\r\n }\r\n };\r\n return modified;\r\n}", "function revGeocode(lat, lng) {\n fs.readFile('keys/mapsApi', 'utf8', function(error, apikey) {\n request.post('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key=' + apikey, \n function(error, response, body) {\n var formatted = \"\";\n if(!error && response.statusCode == 200) {\n var bodyObj = JSON.parse(body);\n if(bodyObj.results && bodyObj.results[0])\n formatted = bodyObj.results[0].formatted_address;\n }\n return formatted;\n });\n }); \n}", "function normalisePlacesApiAddress(details, fromGP) {\r\n\t\t\tvar ac = fromGP.address_components;\r\n\r\n\t\t\t// Copy Googles version of an address to something more useable for us\r\n\t\t\tvar street = findPart(ac, \"street_address\");\r\n\t\t\tif (street === \"\")\r\n\t\t\t// not present so fallback to \"route\"\r\n\t\t\t\tstreet = findPart(ac, \"route\");\r\n\r\n\t\t\tvar town = findPart(ac, \"locality\"),\r\n\t\t\t\t\tarea = findPart(ac, \"administrative_area_level_1\"),\r\n\t\t\t\t\tpostCode = findPart(ac, \"postal_code\")\r\n\t\t\t;\r\n\r\n\t\t\tdetails.street = street;\r\n\t\t\tdetails.town = town;\r\n\t\t\tdetails.area = area;\r\n\t\t\tdetails.postCode = postCode;\r\n\r\n\t\t\t// and some other bits\r\n\t\t\tdetails.name = fromGP.name || \"\";\r\n\t\t\tif (fromGP.photos && fromGP.photos.length > 0)\r\n\t\t\t\tdetails.photo = fromGP.photos[0];\r\n\t\t\tdetails.url = fromGP.url || \"\";\r\n\t\t\tdetails.website = fromGP.website || \"\";\r\n\t\t\tdetails.telNo = fromGP.formatted_phone_number || fromGP.telNo || \"\";\r\n\r\n\t\t} // normalisePlacesApiAddress", "function fixAddresses(oldAddress){\n var newAddress = oldAddress.substring(0,oldAddress.indexOf(',')) + ' New York, NY';\n return newAddress;\n}", "function codeAddress() {\n\t\t\t var address = location.get('address') + ' ' + location.get('postcode') + ' ' + location.get('city'),\n\t\t\t \t myLatlng;\n\n\t\t\t geocoder = new google.maps.Geocoder();\n\t\t\t geocoder.geocode( { 'address': address}, function(results, status) {\t\t\t\t \t\n\t\t\t if (status == google.maps.GeocoderStatus.OK) {\n\t\t\t \t// myLatlng = results[0].geometry.location;\n\t\t\t \t// myLatlng = new google.maps.LatLng(50.935420, 6.965394);\n\t\t\t \tcoords = results[0].geometry.location;\n\t\t\t \t// me.setCoords(results[0].geometry.location);\n\n\t\t\t \tgmap.setHidden(false);\n\t\t\t \t// gmap.getMap().setZoom(16);\n\t\t\t \t// gmap.getMap().setCenter(results[0].geometry.location);\t \t\n\n\t\t\t // \tvar marker = new google.maps.Marker({\n\t\t\t // \tmap: gmap.getMap(),\n\t\t\t // \tposition: results[0].geometry.location\n\t\t\t // \t});\n\n\t\t\t \tvar marker = \n\t\t\t\t\t\tappHelper.setMapMarker({\n\t\t \tlatitude : results[0].geometry.location.lat(),\n\t\t \tlongitude : results[0].geometry.location.lng()\n\t\t \t}, gmap);\n\n\t\t\t \tme.setMapMarker(marker);\n\n\t\t\t } else {\n\t\t\t \tconsole.log('ContactInfo: Geocode was not successful for the following reason ' + status);\n\t\t\t \tgmap.setHidden(true);\n\t\t\t \topenMapsBt.setHidden(true);\n\t\t\t \tExt.Msg.alert('', i10n.translate('tovisit.map.nogeodata'));\n\t\t\t }\n\t\t\t });\n\t\t\t}", "function loc2geocode(query, flag) {\n console.log(query);\n $http.get('https://maps.googleapis.com/maps/api/geocode/json?key='+\n GOOG_TOKEN+\"&address=\"+query.loc).success(function(data) { // hack around\n var geocode = data.results[0].geometry.location; // lat, lng\n //console.log(\"loc2geocode: \");\n //console.log(geocode);\n instLocSearch(query, geocode, flag);\n });\n }", "editAddress() {\n this.addressRevertData = {\n address : this.vendor.address,\n state : this.vendor.state,\n zip_code: this.vendor.zip_code,\n city : this.vendor.city\n }\n }", "function setAddress(geocoding) {\n geocoding.geocode({'latLng': latLng}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n if (results[0]) {\n if(results[0].formatted_address.length>64){\n $(\"#snapspot_address\").val(results[0].formatted_address.substring(0,64)+'...')\n }\n else {\n $(\"#snapspot_address\").val(results[0].formatted_address.substring(0,64)+'...')\n }\n }\n }\n });\n }", "function parseAddress(user){\n let address = '';\n return address = `${user.location.street.number} ${user.location.street.name}, ${user.location.city}, ${user.location.state} ${user.location.postcode}`\n}", "function codeAddress(longlat,lijst) {\n\tvar contentString= undefined;\n\tfor(var i =0; i< lijst.length;i++){\n\t\tcontentString = lijst[i].toString();\n\t}\n\tcontentString = lijst[1].toString();\n\n\tvar infowindow = new google.maps.InfoWindow({\n\t content: contentString\n\t });\n\t\n map.setCenter(longlat);\n var marker = new google.maps.Marker({\n map: map,\n position: longlat\n });\n \n\t\n }", "function positionToAddress() {\n var sheet = SpreadsheetApp.getActiveSheet();\n var cells = sheet.getActiveRange();\n\n var popup = SpreadsheetApp.getUi();\n \n // Must have selected at least 3 columns (Address, Lat, Lng).\n // Must have selected at least 1 row.\n\n var columnCount = cells.getNumColumns();\n\n if (columnCount < 3) {\n popup.alert(\"Select at least 3 columns: Latitude, Longitude in the first 2 columns; the reverse-geocoded Address will go into the last column.\");\n return;\n }\n\n var latColumn = 1;\n var lngColumn = 2;\n\n var addressRow;\n var addressColumn = columnCount;\n\n var geocoder = Maps.newGeocoder().setRegion(getGeocodingRegion());\n var location;\n \n for (addressRow = 1; addressRow <= cells.getNumRows(); ++addressRow) {\n var lat = cells.getCell(addressRow, latColumn).getValue();\n var lng = cells.getCell(addressRow, lngColumn).getValue();\n \n // Geocode the lat, lng pair to an address.\n location = geocoder.reverseGeocode(lat, lng);\n \n // Only change cells if geocoder seems to have gotten a \n // valid response.\n Logger.log(location.status);\n if (location.status == 'OK') {\n var address = location[\"results\"][0][\"formatted_address\"];\n\n cells.getCell(addressRow, addressColumn).setValue(address);\n }\n }\n}", "function ArithGeo(arr) {}", "function coordsToAdress(coords) {\n const url =`https://www.mapquestapi.com/geocoding/v1/reverse?key=${GAPI_KEY}&location=${coords.coords.latitude},${coords.coords.longitude}`;\n console.log(coords);\n $.getJSON(url, function (response) {\n const addressObject = response.results[0].locations[0];\n const address = `${addressObject.street}, ${addressObject.adminArea5}, ${addressObject.adminArea3}`\n $(\"#from\").val(address);\n console.log(coords);\n });\n }", "geocodeNewAddress(address) {\n\n\t\tymaps.geocode(address, {results: 1}).then((result) => {\n\n\t\t\t// Get first result\n\t\t\tlet coordinates = result.geoObjects.get(0).geometry.getCoordinates();\n\n\t\t\t// Transfer map view to geocoded coordinates\n\t\t\tthis.myMap.panTo(coordinates, {flying: true});\n\n\t\t\t// Set placemark from geocoded coordinates\n\t\t\tthis.setPlacemark(coordinates);\n\n\t\t\tthis.$timeout(() => this.$rootScope.$broadcast(\"geocoded:coordinates\", coordinates));\n\t\t});\n\n\t}", "function showAddress(address) {\n\t\tgeocoder = new GClientGeocoder();\n\t\tif (geocoder) {\n geocoder.getLatLng(\n address+\",India\",\n function(point) {\n if (!point) {\n alert(address + \" not found\");\n } else {\n\t\t //var lat=point.lat().toFixed(5);\n\t \t //var lang=point.lng().toFixed(5);\n\t \t document.getElementById('lath').value=point.lat().toFixed(5);\n\t \t document.getElementById('langh').value=point.lng().toFixed(5);\n }});\n\n }\n return true;\n }", "function geocodeTo()\r\n\t\t{\r\n\t\tGEvent.addListener(map, \"click\", getAddress);\r\n\t\ttextLocation = \"end\";\r\n\t\tgeocoder = new GClientGeocoder();\r\n\t\t}", "function formatAddress(place) {\n var returnString;\n if (place.vicinity.split(\",\").length > 2) {\n returnString = place.vicinity.split(\",\")[0] + \", Trondheim\";\n } else {\n returnString = place.vicinity;\n }\n return returnString;\n}", "function geocodeAddress(address) {\n\n L.esri.Geocoding.geocode().text(address).run(function (err, results) {\n\n searchLatLng = L.latLng(results.results[\"0\"].latlng.lat, results.results[\"0\"].latlng.lng);\n findNewLocation(searchLatLng);\n });\n }", "function codeAddress(address) {\n geocoder = new google.maps.Geocoder();\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n marker.setPosition(results[0].geometry.location);\n\t$('#client_latitude').val(results[0].geometry.location.lat());\n\t$('#client_longitude').val(results[0].geometry.location.lng());\n\tgoogle.maps.event.trigger(map, \"resize\");\n }\n\t//else {\n // alert(\"Geocode was not successful for the following reason: \" + status);\n // }\n });\n }", "function codeAddress() {\n var address = gId('address').value;\n geocoder.geocode({\n 'address': address\n }, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n}", "function codeAddress(address) {\n geocoder.geocode({ 'address': address[\"address\"] }, function (results, status) {\n if (status == 'OK') {\n map.setCenter(results[0].geometry.location);\n var cds = {}\n cds.id = address[\"id\"]\n cds.name = address[\"name\"]\n cds.address = address[\"address\"]\n cds.lat = map.getCenter().lat()\n cds.long = map.getCenter().lng()\n updateNull(cds)\n marker(cds, \"False\")\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n}", "function codeAddress(geocoding){\n if(snapspot_address.length > 0){\n geocoding.geocode({'address': snapspot_address},function(results, status){\n if(status == google.maps.GeocoderStatus.OK){\n map.setCenter(results[0].geometry.location);\n marker.setPosition(results[0].geometry.location);\n\n } else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n }\n }", "getAddress() {\n let encodable = [\n me.record ? me.record.id : this.pubkey,\n bin(this.box.publicKey),\n PK.usedBanks\n ]\n return base58.encode(r(encodable))\n }", "function geoCodeAddress(address){\n geocoder.geocode( { 'address': address}, function(results, status) {\n console.log('direccion: ' + address);\n //si el estado de la llamado es OK\n if (status == google.maps.GeocoderStatus.OK) {\n \n //Verigica que el marcador no exista.\n latLng = results[0].geometry.location;\n if(isLocationFree(latLng)){\n setMarkerAndCenter(latLng, address);\n }else{\n map.setCenter(latLng);\n }\n\n } else {\n //si no es OK devuelvo error\n alert(\"No podemos encontrar la direccion, error: \" + status);\n }\n });\n }", "concatDorAddress(parcel, includeUnit) {\n includeUnit = !!includeUnit;\n var STREET_FIELDS = [ 'STDIR', 'STNAM', 'STDES', 'STDESSUF' ];\n var props = parcel.properties;\n\n // handle house num\n var addressLow = this.cleanDorAttribute(props.HOUSE);\n var addressHigh = this.cleanDorAttribute(props.STEX);\n // maybe should be props.SUF below (it said props.SUFFIX)\n var addressSuffix = this.cleanDorAttribute(props.SUF);\n var address = addressLow;\n address = address + (addressHigh ? '-' + addressHigh : '');\n address = address + (addressSuffix || '');\n\n // handle unit\n var unit = this.cleanDorAttribute(props.UNIT);\n if (unit) {\n unit = '# ' + unit;\n }\n\n // clean up attributes\n var comps = STREET_FIELDS.map(function(streetField) {\n return props[streetField];\n });\n comps = comps.map(this.cleanDorAttribute);\n // TODO handle individual address comps (like mapping stex=2 => 1/2)\n // addressLow = comps.HOUSE,\n // addressHigh = comps.STEX,\n // streetPredir = comps.STDIR,\n // streetName = comps.STNAM,\n // streetSuffix = comps.STDES,\n // streetPostdir = comps.STDESSUF,\n\n // add address to front\n comps = [ address ].concat(comps);\n\n // add unit to end\n if (includeUnit) {\n comps = comps.concat([ unit ]);\n }\n\n // remove nulls and concat\n address = comps.filter(Boolean).join(' ');\n\n // console.log('concatDorAddress address result:', address);\n if (address === '') {\n address = 'Parcel has no address';\n }\n return address;\n }", "function codeLocation(geocoder) {\n var address = $id(\"report_location\").value;\n geocoder.geocode({'address': address}, function (results, status) {\n if (status === \"OK\") {\n\n\n var message = 'Coordonnées GPS qui seront enregistrées : ' + results[0].geometry.location;\n generateMsg('jsGenerated','jsGeneratedMsg',message,'#5fdda1');\n\n var data = results[0].geometry.location.toString();\n var addressToUpper = address.charAt(0).toUpperCase() + address.slice(1);\n\n\n address.match( /^[a-zA-Z\\s\\-]*$/) ?\n $id('report_location').value = addressToUpper + ', ' + results[0].address_components[2].long_name\n :\n $id('report_location').value = results[0].address_components[2].long_name + ', ' + results[0].address_components[4].long_name\n ;\n\n $id('report_satNav').value = data.replace(/\\(|\\)/g,'') ;\n disable('reportBtn','reportForm');\n\n } else {\n generateMsg('jsGenerated','jsGeneratedMsg','Aucune données pour ce lieu !','#ff5240');\n }\n });\n}", "function finalAddrParse ( addrObj ) {\n\n if (addrObj.city == \"nocity\") addrObj.city = \"\";\n \n addrObj.streetName = (addrObj.streetNumber.trim()+\" \"+addrObj.streetName.trim());\n \n if (addrObj.streetName == \" RR\") addrObj.streetName = \"\";\n \n const \n addrStr = addrObj.streetName.split(\" \"),\n lastAddrStr = addrStr[addrStr.length-1];\n \n const regExTes1 = /[A-Z|0-9][A-Z]/;\n const regExTes2 = /[A-Z|0-9][A-Z][a-z]/;\n \n if (regExTes1.test(lastAddrStr) && lastAddrStr.length != 2) { \n \n const splitIndex = indexOfRegex(regExTes1, addrObj.streetName, addrObj.streetName.indexOf(lastAddrStr));\n const newStreetName = addrObj.streetName.substr(0,splitIndex);\n const newCityName = addrObj.streetName.substr(splitIndex+1)\n addrObj.streetName = newStreetName;\n addrObj.city = newCityName+\" \"+addrObj.city.trim()\n \n } else if (regExTes2.test(addrObj.city)) {\n \n const splitIndex = indexOfRegex(regExTes2, addrObj.city, 0);\n const streetAdd = addrObj.city.substr(0,splitIndex+1);\n const newCityName = addrObj.city.substr(splitIndex+1)\n addrObj.streetName = addrObj.streetName+\" \"+streetAdd;\n addrObj.city = newCityName;\n \n } else if (regExTes1.test(addrObj.city) && !regExTes2.test(addrObj.city)) {\n \n addrObj.streetName = addrObj.streetName+\" \"+addrObj.city;\n addrObj.city = \"Washington\"\n addrObj.state = \"DC\"\n \n } else if (addrObj.city.length == 2 && addrObj.city != 'of') {\n \n addrObj.streetName = addrObj.streetName+\" \"+addrObj.city\n addrObj.city = \"\";\n \n }\n \n \n const cityArr = addrObj.city.split(\" \");\n const len = cityArr.length;\n \n if (\n stateMap[cityArr[1]] != undefined\n || ( len > 2 && stateMap[(cityArr[len-2]+\" \"+cityArr[len-1])] != undefined )\n ) {\n addrObj.city = cityArr[0];\n }\n \n return addrObj;\n \n}", "function reverseGeocodeAddress(lat, lng, callback) {\n\tvar geocoder = new google.maps.Geocoder();\n\tvar latlng = new google.maps.LatLng(lat, lng);\n\tgeocoder.geocode({\n\t\t\"latLng\": latlng\n\t}, function (results, status) {\n\t\tvar address = '';\n\t\tif (status == google.maps.GeocoderStatus.OK) {\n\t\t\taddress = results[0].formatted_address;\n\t\t}\n\t\tcallback(address);\n\t});\n}", "function Geohash() {\n }", "function doGeocode() {\n var addr = document.getElementById(\"address\");\n // Get geocoder instance\n var geocoder = new google.maps.Geocoder();\n\n // Geocode the address\n geocoder.geocode({\n 'address': addr.value\n }, function(results, status) {\n if (status === google.maps.GeocoderStatus.OK && results.length > 0) {\n\n // set it to the correct, formatted address if it's valid\n //addr.value = results[0].formatted_address;;\n\n // show an error if it's not\n } else {alert(\"Invalid address\");return;}\n });\n}", "function updateAddressField(){\n geocoder.geocode({\n 'latLng': pos\n }, function (results, status) {\n if (status === google.maps.GeocoderStatus.OK) {\n if (results[1]) {\n $('#start-address').val(results[1].formatted_address);\n }\n }\n });\n}", "function createToCode(geodata) {\n const to3 = [];\n\n\n geodata.features.forEach(\n (feature) => {\n to3.push([feature.properties.ADMIN, feature.properties.ISO_A3]);\n }\n );\n\n // Create a single js map between country names and country codes\n // This is needed because Google data uses country names and JSON data uses country codes\n // Some need to be edited for match to succeed\n const toCode = new Map(to3);\n // updates for Google country names\n toCode.set('United States', 'USA')\n toCode.set('Myanmar (Burma)', 'MMR')\n toCode.set('Tanzania', 'TZA')\n toCode.set('Hong Kong', 'HKG')\n toCode.set('Bosnia & Herzegovina', 'BIH')\n toCode.set('Czechia', 'CZE')\n toCode.set('Serbia', 'SRB')\n toCode.set('Côte d’Ivoire', 'CIV')\n toCode.set('Congo - Brazzaville', 'COG')\n toCode.set('Congo - Kinshasa', 'COD')\n toCode.set('Micronesia', 'FSM')\n toCode.set('Guinea-Bissau', 'GNB')\n toCode.set('Timor-Leste', 'TLS')\n toCode.set('North Macedonia', 'MKD')\n toCode.set('eSwatini', 'SWZ')\n return toCode\n}", "function codeAddressBySelectedOption() {\n \n //Obtengo el select del formulario.\n var select = document.getElementById(\"selectSucs\");\n //obtengo la direccion de la sucursal del formulario\n var address = select.options[select.selectedIndex].id;\n\n console.log('direccion: ' + address);\n \n //hago la llamada al geodecoder\n geoCodeAddress(address);\n }", "function formatAddress(acc) {\n return T_Address.canonicalize(acc); // TODO: typing\n }", "function companyAddress(number, st, postal, building, officeNumber) {\n var that = address(number, st, postal);\n //Augment that object\n that.building = building;\n that.officeNumber = officeNumber;\n that.toString = function() {\n let {number, st, postal, building, officeNumber} = that;\n return `${number} ${st}, ${building}-${officeNumber}, P.C. ${postal}`;\n }\n return that;\n}", "function Geocoder() {\n}", "function fillInAddress() {\n // Get the place details from the autocomplete object.\n place = autocomplete.getPlace();\n console.log(place);\n // updating address data \n number = place.address_components[0].long_name;\n street = place.address_components[1].long_name;\n city = place.address_components[3].long_name;\n state_short = place.address_components[5].short_name;\n zipCode = place.address_components[7].long_name;\n // undating geocode data\n latitude = place.geometry.location.lat();\n longitude = place.geometry.location.lng();\n\n // replacing “ ” to \"+\" \n number = number.replace(\" \", \"+\");\n street = street.replace(\" \", \"+\");\n city = city.replace(\" \", \"+\");\n street = street.replace(\" \", \"+\");\n zipCode = zipCode.replace(\" \", \"+\");\n }", "function geocodeAddress(address, fn) {\n\tgeocoderPackage.geocoder.geocode(address, function(err, res) {\n\t\tfn(res[0]);\n\t});\n}", "_getQueryGeocodeAddresses(data) {\n const records = [];\n data.forEach((address, index) => {\n if (isString(address)) {\n records.push({\n attributes: {\n OBJECTID: index,\n SingleLine: address,\n },\n });\n } else {\n // allow user to specify their own OBJECTIDs\n if (!address.OBJECTID) {\n address.OBJECTID = index;\n }\n records.push({\n attributes: address,\n });\n }\n });\n return { addresses: { records } };\n }", "function codeAddress(address) {\r\n\t geocoder.geocode( { 'address': address}, function(results, status) {\r\n\t if (status == google.maps.GeocoderStatus.OK) {\r\n\t map.setCenter(results[0].geometry.location);\r\n\t var marker = new google.maps.Marker({\r\n\t map: map, \r\n\t position: results[0].geometry.location\r\n\t });\r\n\t } else {\r\n\t alert(\"Geocode was not successful for the following reason: \" + status);\r\n\t }\r\n\t });\r\n\t }", "function fillInAddressSource() {\n var coords = sourceQuery.getPlace().geometry.location;\n lat = coords.lat();\n lon = coords.lng();\n}", "function codeAddress(address) {\n var geocoder = new google.maps.Geocoder();\n var result = '';\n\n geocoder.geocode({\n 'address': address\n }, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n result = results[0].geometry.location;\n addToMapBox(map, result);\n } else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n\n return result;\n}", "async function getLocationFromAddress(address) {\n\n\n var apiKey = \"AIzaSyB9Soo0S1gk2QTcexPqwoIhQKZOfNAxRvE\";\n\n //Erases diacritics\n var addressAux1 = await eliminarDiacriticos(address)\n\n //Adds epublica dominicana to the addresso itis more specific for google services to find it\n var addressAux = addressAux1 + \", Republica Dominicana\";\n\n //Adds theparameters to the url\n var url = \"https://maps.googleapis.com/maps/api/geocode/json?key=\" + apiKey + \"&address=\" + addressAux;\n\n console.log(url);\n\n //Calls the service\n Http.open(\"POST\", url);\n try {\n Http.send();\n\n } catch (error) {\n console.log(\"Error in the sending to arcgis\");\n console.log(error);\n return -1;\n }\n\n //returns a promise with the resulting coordinates or -1\n return new Promise((resolve, reject) => {\n\n\n Http.onreadystatechange = function (err, data) {\n\n //If its ready and the demand wassuccesfull\n if (this.readyState == 4 && this.status == 200) {\n var result = JSON.parse(this.responseText);\n\n //If the response fro the service has the status ZERO_RESULTS means there wereno results\n //for the specified address soit reutrns a -1\n if (result.status == \"ZERO_RESULTS\") {\n reject(-1);\n return;\n }\n\n //Otherwise goes to the pertinent field of the recived object to get the coordinates\n var coordinates = result.results[0].geometry.location;\n\n console.log(\"Coordenadas\" + coordinates.lat + coordinates.lng);\n\n //Checks if the cordinatesare inside an imaginary square that contains dominican republic\n //If so, returns an object with the coordinates\n if ((17.3926782 < coordinates.lat) && (coordinates.lat < 20.79844) && (-74.3962979 < coordinates.lng) && (coordinates.lng < -68.2227217)) {\n console.log(\"la dirección ha sido encontrada en dominicana\");\n resolve([coordinates.lng, coordinates.lat])\n return;\n\n //Otherwise returns a -1\n } else {\n console.log(\"No esta en rd\");\n\n reject(-1)\n }\n\n //If the result is ready but its status is 400(an arror ocurred) itreturns a -1\n } else if (err || (this.status == 400 && this.readyState == 4)) {\n console.log(\"llega 5\");\n\n reject(-1)\n }\n };\n })\n}", "function addressFill(no_mymap = false) {\n var fullAddress = '';\n\n opcion = $('#spaceAddress').val();\n\n previous = '';\n if ($('#spaceAddress').val() != '' && ($(\"#spaceCountry option:selected\").val() != '' || $(\"#spaceState option:selected\").text() != '' || $(\"#spaceCities option:selected\").text() != '' || $(\"#selectedZipcode\").text() != '')) {\n previous = ', ';\n }\n if (opcion == '') {\n opcion = '';\n }\n //console.log('Address: ' + opcion+ ' Previous: ' + previous);\n fullAddress += opcion + previous;\n $(\"#selectedAddress\").text(opcion + previous);\n\n opcion = $('#spaceZipcode').val();\n\n previous = '';\n if ($('#spaceZipcode').val() != '' && ($(\"#spaceCountry option:selected\").val() != '' || $(\"#spaceState option:selected\").text() != '' || $(\"#spaceCities option:selected\").text() != '')) {\n previous = ', ';\n }\n if (opcion == '') {\n opcion = '';\n }\n //console.log('Zipcode: ' + opcion+ ' Previous: ' + previous);\n fullAddress += opcion + previous;\n $(\"#selectedZipcode\").text(opcion + previous);\n\n opcion = $(\"#spaceCities option:selected\").text();\n\n previous = '';\n if (opcion != 'Seleccione una Ciudad' && opcion != '' && ($(\"#spaceCountry option:selected\").val() != '' || $(\"#spaceState option:selected\").text() != '')) {\n previous = ', ';\n }\n if (opcion == 'Seleccione una Ciudad') {\n opcion = '';\n }\n //console.log('City: ' + opcion+ ' Previous: ' + previous);\n fullAddress += opcion + previous;\n $(\"#selectedCity\").text(opcion + previous);\n\n opcion = $(\"#spaceState option:selected\").text();\n\n previous = '';\n if (opcion != 'Seleccione un Estado' && opcion != '' && ($(\"#spaceCountry option:selected\").val() != '')) {\n previous = ', ';\n }\n if (opcion == 'Seleccione un Estado') {\n opcion = '';\n }\n //console.log('Estado: ' + opcion + ' Previous: ' + previous);\n fullAddress += opcion + previous;\n $(\"#selectedState\").text(opcion + previous);\n\n\n opcion = $('#spaceCountry option:selected').text();\n //alert(opcion);\n if (opcion == 'Selecciona un Pais') {\n opcion = '';\n //alert(opcion);\n }\n //console.log('Pais: ' + opcion);\n fullAddress += opcion;\n $(\"#selectedCountry\").text(opcion);\n\n console.log(fullAddress);\n if (no_mymap) {\n\n } else {\n myMap(fullAddress);\n }\n\n }", "function pubkeyToAddress(pubkey) {\n // transform the value according to what ethers expects as a value\n const concatResult = `0x04${pubkey\n .map(coord => coord.toHexString())\n .join('')\n .replace(/0x/gi, '')}`;\n return ethers_1.utils.computeAddress(concatResult);\n}", "function Convert_LatLng_To_Address(lat, lng, callback) {\n var url = \"http://maps.googleapis.com/maps/api/geocode/json?latlng=\" + lat + \",\" + lng + \"&sensor=false\";\n jQuery.getJSON(url, function (json) {\n Create_Address(json, callback,lng,lat);\n }); \n }", "function fnConvertAddress() {\n //Get the values from the text box\n var sAddress = $(\"#txtCreatePropertyAddress\").val();\n //Create a new Geocoder object\n geocoder = new google.maps.Geocoder();\n //Initiate function to convert the variable sAddress to two coordinates\n geocoder.geocode({ 'address': sAddress }, function(results, status) {\n //If the Geocoder status is ok then run the following\n if (status == google.maps.GeocoderStatus.OK) {\n //Store the latitude and longitude in two new variables\n var iLat = results[0].geometry.location.lat();\n var iLng = results[0].geometry.location.lng();\n //Put the values in the text input boxes\n $(\"#txtCreatePropertyLat\").val(iLat);\n $(\"#txtCreatePropertyLng\").val(iLng);\n }\n });\n}", "function codeAddress() {\n \n //obtengo la direccion del formulario\n var address = document.getElementById(\"direccion\").value;\n //hago la llamada al geodecoder\n geocoder.geocode( { 'address': address}, function(results, status) {\n \n //si el estado de la llamado es OK\n if (status == google.maps.GeocoderStatus.OK) {\n //centro el mapa en las coordenadas obtenidas\n map.setCenter(results[0].geometry.location);\n //coloco el marcador en dichas coordenadas\n marker.setPosition(results[0].geometry.location);\n //actualizo el formulario \n updatePosition(results[0].geometry.location);\n \n //Añado un listener para cuando el markador se termine de arrastrar\n //actualize el formulario con las nuevas coordenadas\n google.maps.event.addListener(marker, 'dragend', function(){\n updatePosition(marker.getPosition());\n });\n } else {\n //si no es OK devuelvo error\n alert(\"No podemos encontrar la direcci&oacute;n, error: \" + status);\n }\n });\n }", "function codeAddress(address) {\n geocoder.geocode({\n 'address': address\n }, function (results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n map.setZoom(15);\n marker.setPosition(results[0].geometry.location);\n document.getElementById(latInput).value = results[0].geometry.location.lat();\n document.getElementById(lngInput).value = results[0].geometry.location.lng();\n /**\n * using response from services to get nearby venues\n */\n getNearbyVenues();\n\n } else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n}", "function geocodeAddress() {\n\t\t//alert('Inside geocodeAddress');\n\t\t//thisID = document.getElementById(\"id\").value;\n\t\tvar theCity = document.getElementById(\"city\").value;\n\t\tvar theState = document.getElementById(\"state\").value;\n\t\tvar theLocale = theCity + \",\" + theState;\n var geocoder = new google.maps.Geocoder();\n geocoder.geocode( { 'address': theLocale}, function(results, status) {\n\t\t\tif (status == google.maps.GeocoderStatus.OK) {\n\t\t\t\tvar location = results[0].geometry.location;\n\t\t\t\t//alert('LAT: ' + location.lat() + ' LANG: ' + location.lng());\n\t\t\t\tstoreLatLong(location.lat(), location.lng());\n\t\t\t} // close if\n\t\t\telse {\n\t\t\t\talert(\"Something got wrong because status = \" + status);\n\t\t\t} // close else\n });\t// close geocoder\n\t}", "function formatAddress(address) {\n\treturn address;\n}", "function codeAddress() {\n var address = document.getElementById(\"user_location_input\").value;\n geocoder.geocode({'address': address}, setUserLatLongFromAddress);\n}", "function reverseGeocodeGoogle(lat, lng) {\n var pos = new google.maps.LatLng(lat, lng);\n if (pos) {\n geocoder.geocode({\n latLng: pos\n }, function(responses) {\n if (responses && responses.length > 0) {\n //console.log(\"geocoded position\", responses[0]);\n var address = responses[0].formatted_address;\n $('#locality').val(address);\n } else {\n $('#locality').val('Error: cannot determine address for this location.');\n }\n });\n }\n}", "function getAddress2(coords) {\n myPlacemark2.properties.set(\"iconCaption\", \"searching...\");\n ymaps.geocode(coords).then(function (res) {\n var firstGeoObject = res.geoObjects.get(0);\n myPlacemark2.properties.set({\n // Forming a string with the object's data.\n iconCaption: [\n // The name of the municipality or the higher territorial-administrative formation.\n firstGeoObject.getLocalities().length\n ? firstGeoObject.getLocalities()\n : firstGeoObject.getAdministrativeAreas(),\n // Getting the path to the toponym; if the method returns null, then requesting the name of the building.\n firstGeoObject.getThoroughfare() ||\n firstGeoObject.getPremise(),\n ]\n .filter(Boolean)\n .join(\", \"),\n // Specifying a string with the address of the object as the balloon content.\n balloonContent: firstGeoObject.getAddressLine(),\n });\n address2.val(firstGeoObject.getAddressLine());\n });\n }", "function codeAddress(address) {\nconsole.log(document.getElementById('ZippyZip').value);\n //var address = document.getElementById('ZippyZip').value;\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == 'OK') {\n map.setCenter(results[0].geometry.location);\n var marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location,\n zIndex:999999\n });\n\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n}", "function showAddress()\n{\n\tvar geocoder = new google.maps.Geocoder();\n\taddress = document.getElementById(\"street1\").value + \" \" + document.getElementById(\"city\").value + \" \" + document.getElementById(\"state\").value + \" \" + document.getElementById(\"zipcode\").value;\n\t//geocoder.getLocations(address, handleGeoCodes);\n\tgeocoder.geocode( { 'address': address}, handleGeoCodes);\n}", "getAddress() {\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(\n (position) => {\n var requestOptions = {\n method: \"GET\",\n redirect: \"follow\",\n };\n\n fetch(\n `https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.coords.latitude},${position.coords.longitude}&key=AIzaSyDtU4wnc7N3-U9QMpRCG5CCaqCJc2nYuz8&language=en_AU`,\n requestOptions\n )\n .then((response) => response.text())\n .then((result) => {\n // console.log(\"address\",result);\n let res = JSON.parse(result);\n // console.log(\"address\", res.results[0].formatted_address);\n this.entered_address = res.results[0].formatted_address;\n })\n .catch((error) => console.log(\"error\", error));\n }\n // () => {\n // handleLocationError(true, infoWindow, map.getCenter());\n // }\n );\n } else {\n // Browser doesn't support Geolocation\n // handleLocationError(false, infoWindow, map.getCenter());\n }\n }", "function prepareAddress(data) {\n const addressComponents = {\n city: null,\n region: null,\n country: null,\n location: {\n locationPoint: prepareLocation(data)\n },\n };\n data.address_components.forEach((addressComponent) => {\n switch (addressComponent.types[0]) {\n case 'locality':\n addressComponents.city = addressComponent.long_name;\n break;\n case 'administrative_area_level_2':\n addressComponents.region = addressComponent.long_name;\n break;\n case 'administrative_area_level_1':\n /**\n * Skip if already added region in block bellow\n */\n addressComponents.region = (addressComponents.region !== null) ?\n addressComponents.region :\n addressComponent.long_name;\n break;\n case 'country':\n addressComponents.country = addressComponent.long_name;\n break;\n default:\n break;\n }\n });\n return addressComponents;\n}", "function getAddressDetails(place) {\n \t\n \t for (var component in componentForm) {\n document.getElementById(component).value = ''; \t \n }\n\n // Get each component of the address from the place details\n // and fill the corresponding field on the form.\n \t\n for (var i = 0; i < place.address_components.length; i++) {\n var addressType = place.address_components[i].types[0];\n if (componentForm[addressType]) {\n var val = place.address_components[i][componentForm[addressType]];\n document.getElementById(addressType).value = val;\n \n }\n }\n }", "function reverseGeocode(coords) {\n const templateStr = `https://nominatim.openstreetmap.org/reverse?lat=${coords.lat}&lon=${coords.lon}&format=geojson`;\n //console.log(templateStr);\n return axios.get(templateStr)\n .then(res => res.data)\n .catch(err => { throw err; })\n}", "function actualizarPosicion(posicion){\r\n\r\n /* Prueba: Mostrar lat y long\r\n $respuesta.text(`latitud: ${posicion.coords.latitude} longitud: ${posicion.coords.longitude}`);\r\n */ \r\n var api_dir='https://reverse.geocoder.api.here.com/6.2/reversegeocode.json'; \r\n\r\n $.ajax({\r\n url: api_dir,\r\n type: 'GET',\r\n dataType: 'jsonp',\r\n jsonp: 'jsoncallback',\r\n data:{\r\n prox: `${posicion.coords.latitude},${posicion.coords.longitude},10`,\r\n mode: 'retrieveAddresses',\r\n maxresults: '1',\r\n app_id: app_id,\r\n app_code: app_code\r\n },\r\n success: function(response) {\r\n //console.log(response.Response.View[0].Result[0].Location.Address.City);\r\n $('#busqueda').val(response.Response.View[0].Result[0].Location.Address.Label);\r\n $respuesta.text(\"Tu lugar fue encontrado correctamente\");\r\n },\r\n error:function(e){\r\n $respuesta.text(\"no se obtuvo posición\");\r\n }\r\n }); \r\n}", "function codeLatLng(pos) {\r\n\t\t//var infowindow = new google.maps.InfoWindow();\r\n\t\tvar ll=\"\"+pos; //pasamos latitud y longitud a string?\r\n\t\tvar newPos = ll.substr(1, ll.length-2); //sacamos los parentesis\r\n\t\tvar input = newPos; //pasamos longitud y latitud a la variable input -000,000\r\n\t\tvar latlngStr = input.split(',', 2);//divido en las comas y guardo en 2 cadena\r\n\t\tvar lat = parseFloat(latlngStr[0]);//obtengo la primera cadena\r\n\t\tvar lng = parseFloat(latlngStr[1]);//obtengo la segunda cadena\r\n\t\tvar latlng = new google.maps.LatLng(lat, lng);\r\n\t\tgeocoder.geocode({'latLng': latlng}, function(results, status) {\r\n\t\t\tif (status == google.maps.GeocoderStatus.OK) {\r\n\t\t\t\tif (results[1]) {\r\n\t\t\t\t\t$('#start').val(results[0].address_components[1].long_name+\" \"+results[0].address_components[0].short_name);\r\n\t\t\t\t\t$( \"#btnEstado\" ).attr(\"disabled\", false);\r\n\t\t\t\t}else {alert('No results found');}\r\n\t\t\t}else {alert('Geocoder failed due to: ' + status);}\r\n\t\t});\r\n\t}//////FIN FUNCION REVERSE GEOLOCATION!", "function geoCodeAddress(address)\n {\n if (address) {\n var geoCoder = new google.maps.Geocoder();\n\n geoCoder.geocode({'address': address}, function (results, status) {\n if ( status === google.maps.GeocoderStatus.OK ) {\n\n var location = results[0].geometry.location;\n var formatted_address = results[0].formatted_address;\n\n map.panTo(location);\n request.location = location;\n addSearchMarker(location);\n\n $('#wbfInputAddress').val(formatted_address);\n } else {\n Raven.captureMessage('Unable to geocode address.', {level: 'error', message: status});\n }\n });\n }\n }", "getAddress() {\n return this.wallet.legacyAddress;\n }", "setAddress(e){\n\t\tvar place = this.autocomplete.getPlace();\n\t\tlet addressModel = {};\n\t\tplace.address_components.forEach(item => {\n\t\t\tif(item.types.includes('country')){ addressModel.addressCountry = item.long_name }\n\t\t\tif(item.types.includes('locality')){ addressModel.addressLocality = item.long_name }\n\t\t\tif(item.types.includes(\"administrative_area_level_1\")){ addressModel.addressRegion = item.short_name }\n\t\t\tif(item.types.includes(\"postal_code\")){ addressModel.postalCode = item.short_name }\n\t\t})\n\t\t//LAT LONG\n\t\tlet lat = place.geometry.location.lat();\n\t\tlet lng = place.geometry.location.lng();\n\t\taddressModel.disambiguatingDescription = `${lat},${lng}`;\n\t\t//Send to value, so it can handle it\n\t\tthis.value = addressModel;\n\t}", "function reverseGeocodePosition() {\n var pos = map.getCenter();\n var geocoder = new google.maps.Geocoder();\n geocoder.geocode({\n 'latLng': pos\n }, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n if (results[1]) {\n $('.of').html('Around ' + results[1].formatted_address);\n return;\n }\n } else {\n console.warn(\"WARNING: \" + status)\n }\n $('.of').html('Around somewhere');\n });\n}", "function bindAddress(){\n\n \t// retrieve the address value\n \tvar address=$(\"#address\").val();\n\n \t// perform ajax call to nominatim\n \t$.ajax({\n \t\ttype: \"GET\",\n \t\turl: \"https://nominatim.openstreetmap.org/search\",\n \t\tdata: { q: address, format: \"json\", polygon : \"1\" , addressdetails :\"1\" }\n \t\t})\n \t\t.done(function( data ) { // if address found\n\n \t\t// takes the first geolocated data\n \t\t// and record current_marker variable\n \t\tcurrent_marker = data[0];\n \t\t// draws a marker from geolocated point\n \t\tsetMarker();\n\n \t});\n\n }", "function getAddress(points) {\n return new Promise(function (resolve, reject) {\n var geocoder = new google.maps.Geocoder(),\n coordinates = new google.maps.LatLng(points[0], points[1]),\n setting = { 'latLng': coordinates };\n geocoder.geocode(setting, function (results, status) {\n if (status === 'OK') {\n resolve(results[0].formatted_address);\n } else {\n reject(status);\n }\n });\n });\n}", "function geocodeAddress(reverseGeocode) {\n var address = $('input#address').val();\n\n if(geocoder && address) {\n geocoder.geocode({ 'address': address, region: 'AU' }, function(results, status) {\n if(status === google.maps.GeocoderStatus.OK) {\n // geocode was successful\n updateMarkerAddress(results[0].formatted_address);\n updateMarkerPosition(results[0].geometry.location);\n // reload map pin, etc\n initialize();\n loadRecordsLayer();\n } else {\n // TODO Handle empty results response.\n console.error(status);\n }\n });\n } else {\n initialize();\n }\n }", "toGeo(locationZip) {\n return locationData[locationZip];\n }", "function getAddress1(coords) {\n myPlacemark1.properties.set(\"iconCaption\", \"searching...\");\n ymaps.geocode(coords).then(function (res) {\n var firstGeoObject = res.geoObjects.get(0);\n\n myPlacemark1.properties.set({\n // Forming a string with the object's data.\n iconCaption: [\n // The name of the municipality or the higher territorial-administrative formation.\n firstGeoObject.getLocalities().length\n ? firstGeoObject.getLocalities()\n : firstGeoObject.getAdministrativeAreas(),\n // Getting the path to the toponym; if the method returns null, then requesting the name of the building.\n firstGeoObject.getThoroughfare() ||\n firstGeoObject.getPremise(),\n ]\n .filter(Boolean)\n .join(\", \"),\n // Specifying a string with the address of the object as the balloon content.\n balloonContent: firstGeoObject.getAddressLine(),\n });\n address1.val(firstGeoObject.getAddressLine());\n });\n }", "function oneLineAddress( address ) {\r\n\tif( ! address )\r\n\t\treturn '';\r\n\t//if( typeof address == 'string' )\r\n\t//\treturn H(address).replace( /, USA$/, '' );\r\n\treturn H( S(\r\n\t\taddress.line1 ? address.line1 + ', ' : '',\r\n\t\taddress.line2 ? address.line2 + ', ' : '',\r\n\t\taddress.city, ', ', address.state,\r\n\t\taddress.zip ? ' ' + address.zip : ''\r\n\t) );\r\n}", "function getAddress(latitude, longitude) {\n\t\t\treturn $http({\n\t\t\t\turl: 'https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=' + latitude + '&lon=' + longitude,\n\t\t\t\tmethod: \"GET\"\n\t\t\t}).then(\n\t\t\t\tfunction success(response) {\n\t\t\t\t\treturn response.data;\n\t\t\t\t},\n\t\t\t\tfunction error(error) {\n\t\t\t\t\treturn error.data;\n\t\t\t\t});\n\t\t}", "function googleGeocodeAddress(address) {\n if (geocoder && address) {\n geocoder.geocode( {'address': address, region: 'AU'}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n // geocode was successful\n var latlng = new L.LatLng(results[0].geometry.location.k, results[0].geometry.location.D); //results[0].geometry.location;\n updateLocation(latlng);\n } else {\n bootbox.alert(\"Location coordinates were not found, please try a different address - \" + status);\n }\n });\n }\n}", "function _zoneGotoAddr(addr, ct) \n{\n\n /* get the latitude/longitude for the zip */\n //var url = \"http://ws.geonames.org/postalCodeSearch?postalcode=\"+zip+\"&country=\"+ct+\"&style=long&maxRows=5\";\n var url = \"./Track?page=\" + PAGE_ZONEGEOCODE + \"&addr=\" + addr + \"&country=\" + ct + \"&_uniq=\" + Math.random();\n //alert(\"URL \" + url);\n try {\n var req = jsmGetXMLHttpRequest();\n if (req) {\n req.open(\"GET\", url, true);\n //req.setRequestHeader(\"CACHE-CONTROL\", \"NO-CACHE\");\n //req.setRequestHeader(\"PRAGMA\", \"NO-CACHE\");\n //req.setRequestHeader(\"If-Modified-Since\", \"Sat, 1 Jan 2000 00:00:00 GMT\");\n req.onreadystatechange = function() {\n if (req.readyState == 4) {\n var lat = 0.0;\n var lon = 0.0;\n for (;;) {\n\n /* get xml */\n var xmlStr = req.responseText;\n if (!xmlStr || (xmlStr == \"\")) {\n break;\n }\n \n /* get XML doc */\n var xmlDoc = createXMLDocument(xmlStr);\n if (xmlDoc == null) {\n break;\n }\n\n /* try parsing as \"geocode\" encaspulated XML */\n var geocode = xmlDoc.getElementsByTagName(TAG_geocode);\n if ((geocode != null) && (geocode.length > 0)) {\n //alert(\"geocode: \" + xmlStr);\n var geocodeElem = geocode[0];\n if (geocodeElem != null) {\n var latn = geocodeElem.getElementsByTagName(TAG_lat);\n var lonn = geocodeElem.getElementsByTagName(TAG_lng);\n if (!lonn || (lonn.length == 0)) { lonn = geocodeElem.getElementsByTagName(TAG_lon); }\n if ((latn.length > 0) && (lonn.length > 0)) {\n lat = numParseFloat(latn[0].childNodes[0].nodeValue,0.0);\n lon = numParseFloat(lonn[0].childNodes[0].nodeValue,0.0);\n break;\n }\n }\n break;\n }\n\n /* try parsing as forwarded XML from Geonames */\n var geonames = xmlDoc.getElementsByTagName(TAG_geonames);\n if ((geonames != null) && (geonames.length > 0)) {\n //alert(\"geonames: \" + xmlStr);\n // returned XML was forwarded as-is from Geonames\n var geonamesElem = geonames[0];\n var codeList = null;\n if (geonamesElem != null) {\n codeList = geonamesElem.getElementsByTagName(TAG_code);\n if (!codeList || (codeList.length == 0)) {\n codeList = geonamesElem.getElementsByTagName(TAG_geoname);\n }\n }\n if (codeList != null) {\n for (var i = 0; i < codeList.length; i++) {\n var code = codeList[i];\n var latn = code.getElementsByTagName(TAG_lat);\n var lonn = code.getElementsByTagName(TAG_lng);\n if ((latn.length > 0) && (lonn.length > 0)) {\n lat = numParseFloat(latn[0].childNodes[0].nodeValue,0.0);\n lon = numParseFloat(lonn[0].childNodes[0].nodeValue,0.0);\n break;\n }\n }\n }\n break;\n }\n\n /* break */\n //alert(\"unknown: \" + xmlStr);\n break;\n\n }\n\n /* set lat/lon */\n if ((lat == 0.0) && (lon == 0.0)) {\n // skip\n } else {\n var radiusM = MAX_ZONE_RADIUS_M / 10;\n jsvZoneIndex = 0;\n //_jsmSetPointZoneValue(0, lat, lon, radiusM);\n //for (var z = 1; z < jsvZoneCount; z++) {\n // _jsmSetPointZoneValue(z, 0.0, 0.0, radiusM);\n //}\n\n // first non-zero point\n var firstPT = null;\n for (var x = 0; x < jsvZoneList.length; x++) {\n var pt = jsvZoneList[x]; // JSMapPoint\n if ((pt.lat != 0.0) || (pt.lon != 0.0)) {\n firstPT = pt;\n break;\n }\n }\n\n if (firstPT == null) {\n // no valid points - create default geofence\n if (jsvZoneType == ZONE_POINT_RADIUS) {\n // single point at location\n var radiusM = zoneMapGetRadius(true);\n _jsmSetPointZoneValue(0, lat, lon, radiusM);\n } else\n if (jsvZoneType == ZONE_SWEPT_POINT_RADIUS) {\n // single point at location\n var radiusM = zoneMapGetRadius(true);\n _jsmSetPointZoneValue(0, lat, lon, radiusM);\n } else {\n var radiusM = 450;\n var crLat = geoRadians(lat); // radians\n var crLon = geoRadians(lon); // radians\n for (x = 0; x < jsvZoneList.length; x++) {\n var deg = x * (360.0 / jsvZoneList.length);\n var radM = radiusM / EARTH_RADIUS_METERS;\n if ((deg == 0.0) || ((deg > 170.0) && (deg < 190.0))) { radM *= 0.8; }\n var xrad = geoRadians(deg); // radians\n var rrLat = Math.asin(Math.sin(crLat) * Math.cos(radM) + Math.cos(crLat) * Math.sin(radM) * Math.cos(xrad));\n var rrLon = crLon + Math.atan2(Math.sin(xrad) * Math.sin(radM) * Math.cos(crLat), Math.cos(radM)-Math.sin(crLat) * Math.sin(rrLat));\n _jsmSetPointZoneValue(x, geoDegrees(rrLat), geoDegrees(rrLon), radiusM);\n }\n }\n } else {\n // move all points relative to first point\n var radiusM = zoneMapGetRadius(true);\n var deltaLat = lat - firstPT.lat;\n var deltaLon = lon - firstPT.lon;\n for (var x = 0; x < jsvZoneList.length; x++) {\n var pt = jsvZoneList[x];\n if ((pt.lat != 0.0) || (pt.lon != 0.0)) {\n _jsmSetPointZoneValue(x, (pt.lat + deltaLat), (pt.lon + deltaLon), radiusM);\n }\n }\n }\n\n // reset\n _zoneReset();\n\n }\n\n } else\n if (req.readyState == 1) {\n // alert('Loading GeoNames from URL: [' + req.readyState + ']\\n' + url);\n } else {\n // alert('Problem loading URL? [' + req.readyState + ']\\n' + url);\n }\n }\n req.send(null);\n } else {\n alert(\"Error [_zoneCenterOnZip]:\\n\" + url);\n }\n } catch (e) {\n alert(\"Error [_zoneCenterOnZip]:\\n\" + e);\n }\n\n}", "function getAddress(placemark) {\n return placemark.address;\n }", "address(value) {\n return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__ethersproject_address__[\"a\" /* getAddress */])(value);\n }", "function reverseGeocode(e) {\n e.preventDefault();\n const lat = txtLat.value.trim();\n const lng = txtLng.value.trim();\n console.log('reverseGeocode() lat ', lat); \n console.log('reverseGeocode() lng ', lng); \n if(lat === '' || lng === '') {\n console.log('lat or lng missing', lat, lng);\n return;\n }\n const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${lng},${lat}.json?access_token=${keys.privateKey}`;\n fetch(url)\n .then(response => response.json())\n .then(data => {\n console.log('data', data);\n });\n}", "function reverseGeocode(location, callback) {\n var latlng = util.format(\"%s,%s\", location.lat, location.lng)\n , query = qs.stringify({ latlng: latlng, sensor: false })\n , reqtmpl = \"http://maps.googleapis.com/maps/api/geocode/json?%s\"\n , req = util.format(reqtmpl, query)\n , geo\n ;\n \n request(req, function(err, res, body) {\n if (err) {\n console.log('ERROR: ' + err);\n return callback(err);\n }\n\n console.log(body);\n\n geo = parseGoogleGeocodes(JSON.parse(body));\n\n if (!geo) {\n return callback(\"can't determine address\");\n } else {\n return callback(null, geo);\n }\n });\n}", "static getGeocodeData( result ) {\n\t\tlet db_fields = {\n\t\t\t'country': 'country',\n\t\t\t'administrative_area_level_1': 'state',\n\t\t\t'postal_code': 'postcode',\n\t\t\t'locality': 'city',\n\t\t};\n\t\tlet result_type = result.types.find( type => db_fields[type] );\n\t\tif( result_type ) {\n\t\t\tlet result_data = result.address_components.find( component => component.types.includes( result_type ) );\n\t\t\treturn {\n\t\t\t\tcode: result_data.short_name,\n\t\t\t\tname: result_data.long_name,\n\t\t\t\tfield: db_fields[result_type],\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}", "function addressToAensPointee (address) {\n const key = {\n ak: 'AENS.AccountPt',\n ct: 'AENS.ContractPt',\n ok: 'AENS.OraclePt',\n ch: 'AENS.ChannelPt',\n }[address.substring(0, 2)];\n return { [key]: [`ak${address.substring(2)}`] }\n }", "function geocode(lat, lon, callback) {\n if (!lat || !lon) {\n return callback(new Error(\"Both Latitude and Longitude MUST be submitted.\"));\n }\n //\n var longitute = parseFloat(lon);\n var latitute = parseFloat(lat);\n\n geocoder.reverseGeocode(latitute, longitute, function(err, data) {\n if (!err) {\n var geocodedAddress = (data.results && data.results[0] ? data.results[0].formatted_address : \"\");\n return callback(null, geocodedAddress);\n }\n\telse{\n\t\treturn callback(err);\n\t}\n });\n}", "function codeAddress(address) {\n\n geocoder.geocode({\n 'address': address,\n 'componentRestrictions': {\n 'country': 'US'\n }\n }, function (results, status) {\n var codedLat\n var codedLng\n\n if (status == google.maps.GeocoderStatus.OK) {\n mapCenter = results[0].geometry.location\n // map.setCenter(mapCenter);\n // map.setZoom(10);\n codedLat = results[0].geometry.location.lat();\n codedLng = results[0].geometry.location.lng();\n findResults(codedLat, codedLng);\n } else {\n console.log(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n \n}", "function evmWordToAddress(hex) {\n if (!hex) {\n throw Error('Input not defined');\n }\n chai_1.assert.equal(hex.slice(0, 26), '0x000000000000000000000000');\n return ethers_1.utils.getAddress(hex.slice(26));\n}", "function codeAddress() {\n //we reinitialize each time this is called, so it recenters on the world\n //I did this since it is difficult to zoom based on the lat/lngs\n initialize();\n \n //get the locations from the input box\n var address = document.getElementById(\"address\").value;\n \n //convert the input box into an array\n address_array=convert_terms_to_array(address)\n \n //iterate over the addresses and append the \"loc:\" tag to the beginning\n //which overwrites google point of interest detector\n saved_address_array=new Array();\n for (var i=0; i<address_array.length-1; i++){\n if (address_array[i] != ''){\n address_array[i]='loc:'+address_array[i].replace(/^loc:/i, '')\n saved_address_array[i]='loc:'+address_array[i].replace(/^loc:/i, '')\n }else if (address_array[i] == '' && address_array[i-1]!=''){\n address_array[i]=address_array[i-1]\n saved_address_array[i]=address_array[i-1]\n }else{\n saved_address_array[i]=address_array[i]\n }\n }\n\n //get a unique list of the address\n unique_addresses=unique(address_array)\n \n //no longer needed since we are re-initializing\n //clearOverlays();\n \n latitude=new Array();\n longitude=new Array();\n elevation=new Array();\n var latlong\n var iterator=0;\n timer_ms=0;\n if (geocoder) {\n \n //give status updates\n document.getElementById(\"loading_status\").innerHTML='Loading coordinates'\n \n //iterate over the addresses and append a timing event, since google\n //has a query limit per second\n for (var i=0; i<unique_addresses.length; i++){\n if (unique_addresses[i]!=''){\n var lat2=setTimeout('geocode_results('+i+')',timer_ms)\n timer_ms+=700\n }\n }\n //append to the status after all points should have loaded\n setTimeout(\"document.getElementById('loading_status').innerHTML='Completed'\",timer_ms) \n }\n}", "function Address (streetAddress, city, province, zipcode) {\n this.streetAddress = streetAddress;\n this.city = city;\n this.province = province;\n this.zipcode = zipcode;\n this.deliveryAddress = (streetAddress + \" \" + city + \", \" + province + \" \" + zipcode);\n}", "function getAddress() { \n \t\n \t coords = [];\n \t geocoder = new google.maps.Geocoder();\n \t \n \t var address = document.getElementById('address').value;\n \t geocoder.geocode( { 'address': address}, function(results, status) {\n \t if (status == 'OK') {\n \t \t\n \t \n \t \t coords.latitude = results[0].geometry.location.lat();\n \t \t coords.longitude = results[0].geometry.location.lng();\n \t \t coords.deliveryAddress = address;\n \t \n \t \t\n \t \t// put the lat and lng unto the index hidden fields\n \t \t var java_lat = coords.latitude;\n \t \t $(\"#googleLat\").attr(\"value\",java_lat);\n \t \t \n \t \t var java_lng = coords.longitude;\n \t \t $(\"#googleLng\").attr(\"value\",java_lng);\n \t \t \n \t \t \n \t \t var java_address = coords.deliveryAddress;\n \t\t \t $(\"#deliveryAddress\").attr(\"value\",java_address);\n \t \t\n \t \t\n \t } else {\n \t alert('Geocode was not successful for the following reason: ' + status);\n \t }\n \t });\n \t }", "function userInput2Address (state, city, zip, street){\n var address = street.trim()+\"%20\"+zip.trim()+\"%20\"+city.trim()+\"%20\"+state.trim();\n var address2 = address.replace(/ /g, \"%20\");\n return address2;\n}", "function mapClickStreetAddress() {\n\tlet geocode;\n\tmap.addEventListener('click', function (event) {\n\t\tgeocode = [event.latlng.lat, event.latlng.lng].toString()\n\t\tlet prox = `${event.latlng.lat.toString()},`\n\t\tprox += `${event.latlng.lng.toString()}, 100`\n\n\t\tlet reverseGeocodingParameters = {\n\t\t\tprox: prox, // (example)prox: '52.5309,13.3847,150',\n\t\t\tmode: 'retrieveAddresses',\n\t\t\tmaxresults: 1\n\t\t};\n\n\t\tgeocoder.reverseGeocode(reverseGeocodingParameters, onSuccess, function (error) {\n\t\t\tconsole.log('mapClickStreetAddress: error: ', error);\n\t\t});\n\t})\n\tfunction onSuccess(result) {\n\t\tlet address = result.Response.View[0].Result[0].Location.Address\n\t\tconsole.log('the address_string: ', address.Label);\n\n\t\t// let obj = {\n\t\tlet audioFile = {\n\t\t\taddress_string: address.Label,\n\t\t\tstreet_number: address.HouseNumber,\n\t\t\tstreet_name: address.Street,\n\t\t\tcity: address.City,\n\t\t\tstate: address.State,\n\t\t\tpostal_code: address.PostalCode,\n\t\t\tgeocode: geocode\n\t\t}\n\n\t\t// a valid LatLng does NOT mean we have a valid street address ...\n\t\tif (!audioFile.street_number || !audioFile.street_name) {\n\t\t\tresetAddressForm()\n\n\t\t\t$('#geocode').html('<p>Please click again, there is no valid address within 100 meters of where you clicked.</p>').css('background-color', 'pink')\n\t\t\treturn;\n\t\t} else {\n\n\t\t\t// if we have a valid street address, the data is replaced on the DOM, in the address form, for User to edit/accept.\n\t\t\tloadDataToAddressForm(audioFile)\n $('#geocode-label').show()\n\t\t\t$('#voter-preference-form-div').css(\"background-color\", \"rgb(183, 240, 160)\");\n\t\t\t$('#submit-vote-preference-button').css(\"background-color\", \"rgb(183, 240, 160)\");\n\t\t\t$('#geocode').html(`<p>${audioFile.geocode}</p>`)\n\t\t}\n\t}\n}", "function GetAddress(address) {\n return ParseAddress(address)[1];\n}", "addressChange(e){\n var change = Object.assign({}, this.state);\n change.modValues[0].address = e.target.value;\n this.setState(change);\n }", "function geocode(address){\n return new Promise(function(fulfill,reject){\n request('https://maps.googleapis.com/maps/api/geocode/json?' +\n 'address=' + encodeURIComponent(address) +\n '&key=' + googleGeoCodeKey\n ,function(err,res){\n if(!err) fulfill(JSON.parse(res.body).results[0].geometry)\n if(err) reject(err)\n })\n })\n}", "function geoCodeAddress(addr,txt,callback){\n\t// example: http://maps.googleapis.com/maps/api/geocode/json?address=350+5th+Avenue+New+York%2C+NY&sensor=false\n\tvar url = \"http://maps.googleapis.com/maps/api/geocode/json?address=\";\n\turl += encodeURIComponent(addr);\n\turl += \"&sensor=false\";\n\t$.ajax({\n type: 'GET',\n url: url,\n // Add markers to the map for each bathroom location\n success: function(response){ \n \tvar lat = response.results[0].geometry.location.lat;\n \tvar lng = response.results[0].geometry.location.lng;\n \t\n\t \t\t// send back the lat/long info\n\t \t\tcallback({la:lat,lo:lng,location_name:txt});\n }\n });\n}", "validateAddress() {\n // Remove white space from start and end\n let newAddress = this.addressInput.node.textContent.trim();\n // Remove initial @ sign if necessary\n const atStringNumber = newAddress.search(\"@\");\n if (atStringNumber === 0) {\n newAddress = newAddress.substring(1);\n }\n return newAddress;\n }", "function revGeocode(pos){\n\t\tvar defer = $q.defer();\n\t\tvar latLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);\n\t\tvar geocoder = new google.maps.Geocoder;\n\t\tgeocoder.geocode({'location': latLng}, function(posData, st){\n\t\t\tif(st == google.maps.GeocoderStatus.OK){\n\t\t\t\tdefer.resolve(posData[1].formatted_address);\n\t\t\t} else {\n\t\t\t\tdefer.reject('Error: Geocoder failed');\n\t\t\t}\n\t\t});\n\t\treturn defer.promise;\n\t}" ]
[ "0.6537228", "0.6524817", "0.6375113", "0.6339711", "0.6301076", "0.62485355", "0.6243433", "0.6216092", "0.6061961", "0.60589576", "0.6034297", "0.60336286", "0.59991384", "0.5974818", "0.5944917", "0.5928608", "0.5919886", "0.5919287", "0.5917513", "0.591317", "0.5908015", "0.5904743", "0.5903001", "0.5889344", "0.5874189", "0.58667827", "0.5866034", "0.5856735", "0.5850713", "0.5849026", "0.5848623", "0.5841161", "0.5832129", "0.5822822", "0.582098", "0.58173263", "0.5816997", "0.5815905", "0.58155507", "0.5815467", "0.5803506", "0.57990843", "0.5792479", "0.57734835", "0.57677007", "0.5766326", "0.5764469", "0.5763895", "0.5759374", "0.57587445", "0.5757979", "0.57576555", "0.57493097", "0.5741651", "0.573056", "0.57245755", "0.57053477", "0.5703978", "0.5684307", "0.5683024", "0.5680926", "0.5674228", "0.56510085", "0.56491506", "0.5644771", "0.5640379", "0.56396514", "0.5638573", "0.5634976", "0.5633562", "0.56136966", "0.5604974", "0.5598814", "0.55984795", "0.5597278", "0.55962425", "0.55949724", "0.5594872", "0.55851847", "0.5581064", "0.5578663", "0.5577272", "0.5568235", "0.55679744", "0.5561713", "0.5558596", "0.5558078", "0.55527455", "0.5546245", "0.55433494", "0.5542365", "0.55413735", "0.5540406", "0.55401605", "0.55392915", "0.55356884", "0.55315465", "0.5522606", "0.551624", "0.55123293", "0.5509156" ]
0.0
-1
Season function with calendar and show titles and dates
function Season() { let [allShows, setAllShows] = useState(null) async function seeAllShows() { const showsRef = firestore.collection('shows') const showSnapshot = await showsRef.where('status', '!=', 'Proposal').get() const allShowsArray = showSnapshot.docs.map(collectAllIdsAndDocs) if (!allShows) { console.log('allShowsArray =', allShowsArray) setAllShows(allShowsArray) } } seeAllShows() return ( <div className="season_container"> <h1>Season 2020</h1> { allShows ? allShows.map(show => { return <SeasonEvent key={show.id} id={show.id} title={show.title} dates={show.dates} type={show.type} artist={show.artist} blurb={show.blurb} artist={show.displayName} imageLg={show.imageLg} ></SeasonEvent> }) : 'loading' } </div> ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function DrawSeasonCalendar() {\n let ourDate = BackendHelper.Filter.CalendarDate;\n let firstDayOfMonthDate = new C_YMD(ourDate.Year, ourDate.Month, 1);\n let firstDayOfMonthDayOfWeek = firstDayOfMonthDate.DayOfWeek();\n\n CalendarModalDate = ourDate;\n $('#vitasa_modal_calendar_date')[0].innerText = MonthNames[ourDate.Month - 1] + \" - \" + ourDate.Year.toString();\n //$('#vitasa_cal_date')[0].innerText = MonthNames[OurDate.Month - 1] + \" - \" + OurDate.Year.toString();\n\n for(let x = 0; x !== 7; x++) {\n for(let y = 0; y !== 7; y++) {\n let calSelector = \"#vitasa_cal_\" + x.toString() + y.toString();\n let calCel = $(calSelector)[0];\n let dn = x * 7 + (y - firstDayOfMonthDayOfWeek + 1);\n\n if (x === 0) {\n if (y < firstDayOfMonthDayOfWeek) {\n calCel.bgColor = CalendarColor_Site_NotADate;\n calCel.innerText = \"\";\n }\n else {\n //let thisdate = new C_YMD(ourDate.Year, ourDate.Month, dn);\n calCel.bgColor = CalendarColor_Site_SiteClosed;\n calCel.innerText = dn.toString();\n }\n }\n else {\n let date = new C_YMD(ourDate.Year, ourDate.Month, dn);\n let daysInMonth = date.DaysInMonth();\n\n if (date.Day <= daysInMonth) {\n calCel.bgColor = CalendarColor_Site_SiteClosed;\n calCel.innerText = dn.toString();\n }\n else {\n calCel.bgColor = CalendarColor_Site_NotADate;\n calCel.innerText = \"\";\n }\n }\n }\n }\n}", "function changeSeason() {\n var seasonAndEpisodePatterns = {\n '<b>Season $1</b> ': /s(\\d\\d)/gi,\n '<b>- Episode $1</b>': /e(\\d\\d)/gi\n };\n $.each(seasonAndEpisodePatterns, function(title, pattern) {\n $('.detLink').html(function () {\n return $(this).html().replace(pattern, title);\n });\n });\n }", "function getSeason() {\n month = d.getMonth() + 1;\n if (3 <= month && month <= 5) {\n return 'spring';\n }\n else if (6 <= month && month <= 8) {\n return 'summer';\n }\n else if (9 <= month && month <= 11) {\n return 'fall';\n }\n else{\n return 'winter';\n }\n }", "function setSeasons(daynumber)\n{ \n //December Solstice to March Equinox\n if(daynumber >= 355 || daynumber < 79)\n {\n PIEchangeDisplayText(northSeason, winterSeason);\n PIEchangeDisplayText(southSeason, summerSeason);\n }\n //March Equinox to June Solstice\n else if(daynumber >= 79 && daynumber < 172)\n {\n PIEchangeDisplayText(northSeason, springSeason);\n PIEchangeDisplayText(southSeason, autumnSeason);\n }\n //June Solstice to September Equinox\n else if(daynumber >= 172 && daynumber < 265)\n {\n PIEchangeDisplayText(northSeason, summerSeason);\n PIEchangeDisplayText(southSeason, winterSeason);\n }\n //September Equinox to December Solstice\n else\n {\n PIEchangeDisplayText(northSeason, autumnSeason);\n PIEchangeDisplayText(southSeason, springSeason);\n }\n}", "function DisplaySeasons(props) {\n let dispArr = [];\n\n clothing.season.forEach(element => {\n dispArr.push(<StyledP> {element} </StyledP>);\n });\n\n return (\n <SeasonsStyle>{dispArr}</SeasonsStyle>\n );\n }", "function SetDateInputOnSeasons(season) {\n //Gets todays date.\n var todaysDate = new Date();\n var startDate;\n var endDate;\n //Determens the start- and endDate determent by what season is chosen.\n switch (season) {\n case 'Forår':\n startDate = new Date(2021, 3, 1);\n endDate = new Date(2021, 5, 30);\n break;\n case 'Sommer':\n startDate = new Date(2021, 3, 1);\n endDate = new Date(2021, 8, 30);\n break;\n case 'Efterår':\n startDate = new Date(2021, 7, 15);\n endDate = new Date(2021, 9, 31);\n break;\n case 'Vinter':\n startDate = new Date(2021, 9, 1);\n endDate = new Date(2021, 2, 31);\n break;\n }\n //Is that start date of the season has already passed then the date will pass to the next year.\n while (startDate < todaysDate) {\n startDate.setFullYear(startDate.getFullYear() + 1);\n endDate.setFullYear(endDate.getFullYear() + 1);\n }\n //Sets the inputs to the date determined by what season is chosen.\n document.getElementById('MainContent_startDate').value = ConvertDateFormat(startDate);\n document.getElementById('MainContent_endDate').value = ConvertDateFormat(endDate);\n}", "function addMonthSeason(image) { \n image = ee.Image(image);\n \n // set month\n var month = ee.Number.parse(image.date().format('M'));\n image = image.set({month: month});\n \n // set season (1=winter, 2=spring, 3=summer, 4=autumn)\n var s = ee.Algorithms.If(month.eq(ee.Number(1)),ee.Number(1),\n ee.Algorithms.If(month.eq(ee.Number(2)),ee.Number(1),\n ee.Algorithms.If(month.eq(ee.Number(3)),ee.Number(2),\n ee.Algorithms.If(month.eq(ee.Number(4)),ee.Number(2),\n ee.Algorithms.If(month.eq(ee.Number(5)),ee.Number(2),\n ee.Algorithms.If(month.eq(ee.Number(6)),ee.Number(3),\n ee.Algorithms.If(month.eq(ee.Number(7)),ee.Number(3),\n ee.Algorithms.If(month.eq(ee.Number(8)),ee.Number(3),\n ee.Algorithms.If(month.eq(ee.Number(9)),ee.Number(4),\n ee.Algorithms.If(month.eq(ee.Number(10)),ee.Number(4),\n ee.Algorithms.If(month.eq(ee.Number(11)),ee.Number(4),\n ee.Algorithms.If(month.eq(ee.Number(12)),ee.Number(1)))))))))))));\n \n image = image.set({season: s});\n \n return image;\n }", "function displayDates(month, year) {\n datesRegion.innerHTML = `\n <div class=\"row\" id=\"days\">\n <span class=\"day\">SUN</span>\n <span class=\"day\">MON</span>\n <span class=\"day\">TUES</span>\n <span class=\"day\">WED</span>\n <span class=\"day\">THURS</span>\n <span class=\"day\">FRI</span>\n <span class=\"day\">SAT</span>\n </div>\n `\n let n = numberOfDays[month];\n if(year%4==0 && year%100!=0 && month==1)\n n=29;\n let firstDay = `${monthList[month]} 1 ${year}`;\n let dateStart = new Date(firstDay);\n let counter = 1;\n let monthStart = dateStart.getDay();\n let output = '<div class=\"row date-row\">';\n for(let i=0; i<monthStart; i++)\n {\n output+=`\n <span class=\"date\"></span>\n `\n }\n for(let i=0; i<7-monthStart; i++)\n {\n output+=`\n <span class=\"date date-val\">${counter}</span>\n `\n counter++;\n }\n for(let i=0;;i++)\n {\n if(counter==n+1)\n break;\n else {\n if(i%7==0) {\n output+=\n `\n </div><div class=\"row date-row\">\n `\n }\n }\n output+= `<span class=\"date date-val\">${counter}</span>`;\n counter++;\n }\n let extra = 7-((n-(7-monthStart))%7);\n if(extra!=7) {\n while(extra--) {\n output+=`\n <span class=\"date\"></span>\n `\n }\n }\n datesRegion.innerHTML+= output;\n addSelectableProperty();\n}", "function getSeasonIndex() {\n var date = new Date();\n var month = date.getMonth();\n if (month == 9 || month == 10 || month == 11) {\n return 1;\n } else {\n return 0;\n }\n}", "function checkSeason(month) {\n if (month === 9) {\n console.log(\"The season is Autumn.\");\n } else if (month === 8) {\n console.log(\"The season is Autumn.\");\n } else if (month === 7) {\n console.log(\"The season is Autumn.\");\n } else if (month === 10) {\n console.log(\"The season is Winter.\");\n } else if (month === 11) {\n console.log(\"The season is Winter.\");\n } else if (month === 12) {\n console.log(\"The season is Winter.\");\n } else if (month === 1) {\n console.log(\"The season is Spring.\");\n } else if (month === 2) {\n console.log(\"The season is Spring.\");\n } else if (month === 3) {\n console.log(\"The season is Spring.\");\n } else {\n console.log(\"The season is Summer.\");\n }\n}", "function seasonActualizer() {\n let date = new Date\n let month = (date.getMonth() + 1) % 12;\n const summer = [6, 7, 8];\n const fall = [9, 10, 11];\n const winter = [12, 1, 2];\n const spring = [3, 4, 5];\n\n if (summer.includes(month)) {\n return 3;\n } else if (fall.includes(month)) {\n return 4;\n } else if (winter.includes(month)) {\n return 1;\n } else if (spring.includes(month)){\n return 2;\n } else {\n return 1\n }\n }", "function renderCalendar() {\r\n calendar.innerHTML = '';\r\n var dateCounter = new Date(pickerElement.value);\r\n var month = dateCounter.getMonth();\r\n\r\n dateCounter.setDate(1);\r\n\r\n while (dateCounter.getMonth() === month) {\r\n var dayObject = document.createElement('SPAN');\r\n dayObject.classList.add('vjsdate-day' + dateCounter.getDate());\r\n if (dateCounter < startDate || dateCounter > endDate) dayObject.classList.add('vjsdate-day-disabled');\r\n dayObject.innerHTML = dateCounter.getDate();\r\n calendar.appendChild(dayObject);\r\n if (new Date(pickerElement.value).getDate() === dateCounter.getDate()) dayObject.classList.add('vjsdate-day-selected');\r\n\r\n if (parseInt(dayObject.innerHTML) == 1) {\r\n /*If we are the first date, we need to make N spacers for Nth day of the week*/\r\n for (i = 0; i < dateCounter.getDay(); i++) {\r\n var daySpacer = document.createElement('SPAN');\r\n daySpacer.classList.add('vjsdate-day');\r\n dayObject.parentElement.insertBefore(daySpacer, dayObject);\r\n }\r\n }\r\n dateCounter.setDate(dateCounter.getDate() + 1);\r\n }\r\n }", "function animeSeasonSelect(season){\n\tconsole.log(\"Season is \" + season)\n\tvar section\n\tif (season == 1){\n\t\tsection = \"SymphogearSeasonOneAnimeData\"\n\t}\n\telse if(season == 2){\n\t\tsection = \"SymphogearSeasonTwoAnimeData\"\n\t}\n\telse if(season == 3){\n\t\tsection = \"SymphogearSeasonThreeAnimeData\"\n\t}\n\telse if(season == 4){\n\t\tsection = \"SymphogearSeasonFourAnimeData\"\n\t}\n\telse if(season == 5){\n\t\tsection = \"SymphogearSeasonFiveAnimeData\"\n\t}\n\treturn section\n}", "function showCalendar(month, year, event) {\n\n let today = new Date();\n let firstDay = new Date(year, month).getDay();\n let totalDays = 32 - new Date(year, month, 32).getDate();\n // Calendar container with monthly numbers of days\n let calendarCont = document.querySelector('.month-num');\n // 'month - year' in selection of previous and nest \n let monthYear = document.querySelector('.month-year');\n let viewedMonth = monthsArr[month]; // test\n console.log(viewedMonth);\n monthYear.innerHTML = `${monthsArr[month]} ${year}`;\n calendarCont.innerHTML = \"\";\n // scheduled events for a specific month of the year\n let theseEvents = event.filter(even => even.date.getFullYear() == year && even.date.getMonth() == month);\n console.log(theseEvents); // test\n\n let date = 1;\n\n for (let i = 0; i < 6; i++) {\n let week = document.createElement('div');\n week.classList.add('weeks');\n\n for (let j = 0; j < 7; j++) {\n\n if (i == 0 && j < firstDay) {\n let emptyCell = document.createElement('div');\n emptyCell.classList.add('empty');\n week.appendChild(emptyCell);\n\n } else if (date <= totalDays) {\n let numCell = document.createElement('div');\n numCell.classList.add('num');\n\n if (date == today.getDate() && month == today.getMonth() && year == today.getFullYear()) {\n numCell.classList.add('today');\n };\n\n let numCellEvent = \"\";\n\n let w = window.innerWidth;\n let eventPlan = document.querySelector('.event-plan');\n let leftSideBlue = document.querySelector('.blue');\n let rightSideRed = document.querySelector('.red');\n\n if (theseEvents.length) {\n let todayEvent = theseEvents.filter(eve => eve.date.getDate() == date);\n console.log(todayEvent); // test\n\n if (todayEvent.length && w > 992) {\n numCell.classList.add('event');\n\n todayEvent.forEach(ev => {\n numCellEvent += `<div class=\"eve\" style=\"border-left:4px solid ${ev.bgColor}\"><div>${ev.title}</div><div>${ev.time}</div><div>${ev.day}</div></div><span style=\"color:white !important\">${date}</span>`;\n numCell.style.backgroundColor = ev.bgColor;\n numCell.style.color = ev.color;\n });\n };\n\n // extra for tablet and mobile start \n\n if (todayEvent.length && w < 993) {\n numCell.classList.remove('event');\n\n todayEvent.forEach(ev => {\n console.log(todayEvent); // test\n if (ev.date.getMonth() == monthsArr.indexOf(viewedMonth)) {\n console.log(monthsArr.indexOf(viewedMonth)); // test 4 i ne se menuva, juni vo 5\n eventPlan.style.display = 'block';\n console.log(ev.date.getMonth()); // test 4\n\n if (ev.bgColor == 'blue') {\n leftSideBlue.innerHTML += `<div class=\"left-event\">\n <p class=\"date\">${ev.date.getDate()}/${ev.date.getMonth()}/${ev.date.getFullYear()}</p>\n <h5 class=\"title\">${ev.title}</h5>\n <p class=\"hours\">${ev.time}ч</p>\n </div>`;\n numCell.style.backgroundColor = ev.bgColor;\n numCell.style.color = ev.color;\n }\n\n if (ev.bgColor == 'red') {\n rightSideRed.innerHTML += `<div class=\"right-event\">\n <p class=\"date\">${ev.date.getDate()}/${ev.date.getMonth()}/${ev.date.getFullYear()}</p>\n <h5 class=\"title\">${ev.title}</h5>\n <p class=\"hours\">${ev.time}ч</p>\n </div>`;\n numCell.style.backgroundColor = ev.bgColor;\n numCell.style.color = ev.color;\n }\n\n if (ev.bgColor == 'orange') {\n leftSideBlue.innerHTML += `<div class=\"left-event-orange\">\n <p class=\"date\">${ev.date.getDate()}/${ev.date.getMonth()}/${ev.date.getFullYear()}</p>\n <h5 class=\"title\">${ev.title}</h5>\n <p class=\"hours\">${ev.time}ч</p>\n </div>`;\n numCell.style.backgroundColor = ev.bgColor;\n numCell.style.color = ev.color;\n }\n\n }\n\n });\n\n };\n\n } else if (!theseEvents.length) { // ova raboti \n leftSideBlue.innerHTML = '';\n rightSideRed.innerHTML = '';\n eventPlan.style.display = 'none';\n };\n // extra for tablet and mobile ends here\n\n numCell.innerHTML = (numCellEvent == \"\") ?\n `<span>${date}</span>` : numCellEvent;\n\n week.appendChild(numCell);\n\n date++;\n\n } else if (date > totalDays) {\n let emptyCell = document.createElement('div');\n emptyCell.classList.add('empty');\n week.appendChild(emptyCell);\n };\n\n };\n\n calendarCont.appendChild(week);\n };\n\n}", "function showEvent(day,month,year){\n dia_ult = day;\n mes_ult = month;\n ano_ult = year;\n showListCalen(4,day,month,year);\n}", "function fourSeasons(d){\n if (d > 365) {\n return 'The year flew by!';\n }\n const springStart = 79;\n const summerStart = 171;\n const autumnStart = 263;\n const winterStart = 354;\n\n switch(true) {\n case (d > springStart && d <= summerStart):\n return 'Spring Season';\n case (d > summerStart && d <= autumnStart):\n return 'Summer Season';\n case (d > autumnStart && d <= winterStart):\n return 'Autumn Season';\n case (d > winterStart || d <= springStart):\n return 'Winter Season';\n }\n}", "function seasonsOnClick () {\n module.exports.internal.stateManager.showState('main-branch', 'season-stats')\n}", "getGames () {\n let schedule = this.year + `${View.SPACE()}` + this.title + ` Draw ${View.NEWLINE()}`\n for (let aWeek of this.allGames) {\n schedule += 'Week:' + aWeek[0].week + `${View.NEWLINE()}`\n for (let aGame of aWeek) {\n// to get the date type, e.g. Mon, Jul 16 2018\n let newDate = new Date(aGame.dateTime).toDateString()\n// adding that date\n schedule += newDate + `${View.SPACE()}`\n// getting time like 7:35PM\n// was gonna use navigator.language instead of en-US but it comes up with korean\n// even thought default language is ENG\n let newTime = new Date(aGame.dateTime).toLocaleTimeString('en-US', {hour: 'numeric', minute: 'numeric'})\n schedule += newTime + `${View.SPACE()}`\n\n// getting name for home team from rank\n schedule += 'Team: ' + this.allTeams[aGame.homeTeamRank - 1].name + `${View.SPACE()}` + 'vs' + `${View.SPACE()}` + this.allTeams[aGame.awayTeamRank - 1].name + `${View.SPACE()}` + 'At: ' + this.allTeams[aGame.homeTeamRank - 1].venue + ', ' + this.allTeams[aGame.homeTeamRank - 1].city + `${View.NEWLINE()}`\n }\n }\n return schedule\n }", "function displayDates() {\n //Display right year\n var year = x.getFullYear();\n document.getElementById(\"thisYear\").innerText = year;\n //Display right month\n const months = {\n 0: \"January\", 1: \"February\", 2: \"March\", 3: \"April\", 4: \"May\", 5: \"June\", 6: \"July\",\n 7: \"August\", 8: \"September\", 9: \"October\", 10: \"November\", 11: \"December\"\n };\n var idmonth = document.getElementById(\"month\");\n var month = x.getMonth();\n idmonth.innerText = months[month];\n idmonth.style.fontSize = \"20px\";\n idmonth.style.letterSpacing = \"3px\";\n idmonth.style.textTransform = \"uppercase\";\n //Create days for display\n const dNumb = [];\n var ul = document.getElementById(\"days\");\n var lom = { 0: 31, 1: 28, 2: 31, 3: 30, 4: 31, 5: 30, 6: 31, 7: 31, 8: 30, 9: 31, 10: 30, 11: 31 };\n var ulSize = ul.getElementsByTagName(\"li\").length;\n var leapYear = getLeapYear(year);\n if (leapYear == true) {\n lom[1] = 29;\n }\n //Add days to calendar\n if (ulSize != 0) {\n ul.innerHTML = '';\n }\n var dim = lom[month];\n const rightDate = new Date(year, month, 1);\n for (let i = 1; i <= dim; i++) {\n dNumb.push(i);\n }\n if (rightDate.getDay() != 1) {\n if (rightDate.getDay() == 0) {\n for (var i = 0; i < 6; i++) {\n dNumb.unshift(\"\");\n }\n } else {\n for (var i = 0; i < (rightDate.getDay() - 1); i++) {\n dNumb.unshift(\"\");\n }\n }\n }\n for (let i = 0; i < dNumb.length; i++) {\n var li = document.createElement(\"li\");\n var btn = document.createElement(\"button\");\n btn.innerHTML = dNumb[i];\n btn.onclick = nextView;\n li.appendChild(btn);\n ul.appendChild(li);\n }\n //Display today\n const dayslist = ul.getElementsByTagName('li');\n for (var i = 0; i <= dayslist.length; i++) {\n if (dayslist[i].innerText == (x.getDate())) {\n dayslist[i].style.backgroundColor = \"#1abc9cd6\";\n }\n }\n}", "function setup_calendar_title_and_nav_buttons() {\n // Calendar month title\n document.getElementById(\"month_title\").innerHTML = formatted_date(calendar_date);\n\n // Previous month arrow button on click event\n document.getElementById(\"previous_month\").addEventListener(\"click\", function () {\n advance_month(-1);\n })\n\n // Next month arrow button on click event\n document.getElementById(\"next_month\").addEventListener(\"click\", function () {\n advance_month(1);\n })\n}", "function displayCalendar_Fall2013_Fall2014(numberOfMonths) {\n\n from_semester_title.innerHTML = \"Fall 2013\";\n to_semester_title.innerHTML = \"Fall 2014\";\n\n $(\"#weekNumber\").html(\"1\");\n\n $(\"#dateoutput1\").html(\"9 Sep, Mon\");\n $(\"#dateoutput2\").html(\"2 Sep, Tue\");\n\n\n function highlightDays(date) {\n var a = new Date(2013, 8, 9); // September 9, 2013\n var b = new Date(2014, 8, 2); // September 2, 2014\n\n if (a <= date && date <= b) {\n return [true, 'highlight'];\n }\n\n return [true, ''];\n\n }\n\n\n $(\"#datepicker_Fall2013_Fall2014\").datepicker({\n /*\n dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n */\n\n inline: true,\n showOtherMonths: true,\n defaultDate: '09-09-13',\n numberOfMonths: numberOfMonths,\n dateFormat: \"dd-mm-yy\",\n\n\n beforeShowDay: highlightDays,\n\n\n onSelect: function (dateText, inst) {\n var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);\n var dateText1 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n date.setDate(date.getDate() + 358);\n var dateText2 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n\n var newDate = date.getDate();\n var newMonth = date.getMonth();\n\n /*\n console.log(\"date: \" + date);\n console.log(\"newDate: \" + newDate);\n console.log(\"newMonth: \" + newMonth);\n */\n\n var weekNumber;\n var weekDays = 6;\n var wk1_start = 2;\n var wk1_end = wk1_start + weekDays;\n\n var wk2_start = 9;\n var wk2_end = wk2_start + weekDays;\n\n var wk3_start = 16;\n var wk3_end = wk3_start + weekDays;\n\n var wk4_start = 23;\n var wk4_end = wk4_start + weekDays;\n\n var wk5_start = 30;\n var wk5_end = 6;\n\n var wk6_start = 7;\n var wk6_end = wk6_start + weekDays;\n\n var wk7_start = 14;\n var wk7_end = wk7_start + weekDays;\n\n var wk8_start = 21;\n var wk8_end = wk8_start + weekDays;\n\n var wk9_start = 28;\n var wk9_end = 3;\n\n var wk10_start = 4;\n var wk10_end = wk10_start + weekDays;\n\n var wk11_start = 11;\n var wk11_end = wk11_start + weekDays;\n\n var wk12_start = 18;\n var wk12_end = wk12_start + weekDays;\n\n var wk13_start = 25;\n var wk13_end = 1;\n\n\n var September = 8;\n var October = 9;\n var November = 10;\n var December = 11;\n\n /* console.log(\"newDate: \" + newDate); */\n\n if ((newDate >= wk1_start && newDate <= wk1_end) && (newMonth == September)) {\n weekNumber = 1;\n }\n\n else if ((newDate >= wk2_start && newDate <= wk2_end) && (newMonth == September)) {\n weekNumber = 2;\n }\n\n else if ((newDate >= wk3_start && newDate <= wk3_end) && (newMonth == September)) {\n weekNumber = 3;\n }\n\n else if ((newDate >= wk4_start && newDate <= wk4_end) && (newMonth == September)) {\n weekNumber = 4;\n }\n\n else if (((newDate == wk5_start) && (newMonth == September)) || ((newDate <= wk5_end) && (newMonth == October))) {\n weekNumber = 5;\n }\n\n else if ((newDate >= wk6_start && newDate <= wk6_end) && (newMonth == October)) {\n weekNumber = 6;\n }\n\n else if ((newDate >= wk7_start && newDate <= wk7_end) && (newMonth == October)) {\n weekNumber = 7;\n }\n\n else if ((newDate >= wk8_start && newDate <= wk8_end) && (newMonth == October)) {\n weekNumber = 8;\n }\n\n else if (((newDate >= wk9_start && newDate <= 31) && (newMonth == October)) || ((newDate <= wk9_end) && (newMonth == November))) {\n weekNumber = 9;\n }\n\n\n else if ((newDate >= wk10_start && newDate <= wk10_end) && (newMonth == November)) {\n weekNumber = 10;\n }\n\n else if ((newDate >= wk11_start && newDate <= wk11_end) && (newMonth == November)) {\n weekNumber = 11;\n }\n\n else if ((newDate >= wk12_start && newDate <= wk12_end) && (newMonth == November)) {\n weekNumber = 12;\n }\n\n\n else if (((newDate >= wk13_start && newDate <= 30) && (newMonth == November)) || ((newDate == 1) && (newMonth == December))) {\n weekNumber = 13;\n }\n\n\n else {\n weekNumber = 'N/A';\n }\n\n\n $(\"#weekNumber\").html(weekNumber);\n\n $(\"#dateoutput1\").html(dateText1);\n $(\"#dateoutput2\").html(dateText2);\n\n\n }\n\n\n\n });\n\n\n}", "function getCurrentSeason(date){\n var mm, yyyy, dd;\n\n if(!date){\n // No date was set, use the current date\n var today = timezone().tz(\"America/Vancouver\").format(\"L\");\n mm = today.slice(0,2);\n dd = today.slice(3,5);\n yyyy = today.slice(6);\n }else{\n // Date was passed as a parameter use it to determine the current season\n yyyy = date.slice(0,4);\n mm = date.slice(4,6);\n dd = date.slice(6);\n }\n\n var currentSeason;\n\n if(parseInt(mm) >= 9){\n // September is a safe bet for start of new season - usually starts around mid to late October\n var nextYear = parseInt(yyyy) + 1;\n currentSeason = yyyy + \"-\" + nextYear + \"-regular\";\n }else{\n // then we are looking back at the previous year - either in progress or offseason\n var prevYear = parseInt(yyyy) -1;\n currentSeason = prevYear + \"-\" + yyyy + \"-regular\";\n }\n return currentSeason;\n}", "function displayCalendar_Spring2014_Summer2014(numberOfMonths) {\n\n from_semester_title.innerHTML = \"Spring 2014\";\n to_semester_title.innerHTML = \"Summer 2014\";\n\n $(\"#weekNumber\").html(\"1\");\n\n $(\"#dateoutput1\").html(\"13 Jan, Mon\");\n $(\"#dateoutput2\").html(\"5 May, Mon\");\n\n\n function highlightDays(date) {\n //month starts as 0\n var a = new Date(2014, 0, 13); // first day of FROM semester - September 9, 2013 - 2014, January 13\n var b = new Date(2014, 3, 11); // last day of FROM semester - December 6, 2013 - 2014, April 11\n\n if (a <= date && date <= b) {\n return [true, 'highlight'];\n }\n\n return [true, ''];\n\n }\n\n $(\"#datepicker_Spring2014_Summer2014\").datepicker({\n\n inline: true,\n showOtherMonths: true,\n defaultDate: '13-01-14', //09-09-13 dd-mm-yy\n numberOfMonths: numberOfMonths,\n dateFormat: \"dd-mm-yy\",\n\n beforeShowDay: highlightDays,\n\n onSelect: function (dateText, inst) {\n var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);\n var dateText1 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n date.setDate(date.getDate() + 112); //old - 126\n var dateText2 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n\n var newDate = date.getDate();\n var newMonth = date.getMonth();\n\n /*\n console.log(\"-----------------------\");\n console.log(\"next semester full date: \" + date);\n console.log(\"next semester Date: \" + newDate);\n console.log(\"next semester Month: \" + newMonth);\n */\n\n //List starting week days of the new semester\n var weekNumber;\n var weekDays = 4;\n\n var wk1_start = 5;\n var wk1_end = wk1_start + weekDays;\n\n var wk2_start = 12;\n var wk2_end = wk2_start + weekDays;\n\n var wk3_start = 19;\n var wk3_end = wk3_start + weekDays;\n\n var wk4_start = 26;\n var wk4_end = wk4_start + weekDays;\n\n var wk5_start = 2;\n var wk5_end = wk5_start + weekDays;\n\n var wk6_start = 9;\n var wk6_end = wk6_start + weekDays;\n\n var wk7_start = 16;\n var wk7_end = wk7_start + weekDays;\n\n var wk8_start = 23;\n var wk8_end = wk8_start + weekDays;\n\n var wk9_start = 30;\n var wk9_end = 4;\n\n var wk10_start = 7;\n var wk10_end = wk10_start + weekDays;\n\n var wk11_start = 14;\n var wk11_end = wk11_start + weekDays;\n\n var wk12_start = 21;\n var wk12_end = wk12_start + weekDays;\n\n var wk13_start = 28;\n var wk13_end = 1;\n\n\n var Month4_2014 = 4;\n var Month5_2014 = 5;\n var Month6_2014 = 6;\n var Month7_2014 = 7;\n\n\n if ((newDate >= wk1_start && newDate <= wk1_end) && (newMonth == Month4_2014)) {\n weekNumber = 1;\n }\n\n else if ((newDate >= wk2_start && newDate <= wk2_end) && (newMonth == Month4_2014)) {\n weekNumber = 2;\n }\n\n else if ((newDate >= wk3_start && newDate <= wk3_end) && (newMonth == Month4_2014)) {\n weekNumber = 3;\n }\n\n else if ((newDate >= wk4_start && newDate <= wk4_end) && (newMonth == Month4_2014)) {\n weekNumber = 4;\n }\n\n else if ((newDate >= wk5_start && newDate <= wk5_end) && (newMonth == Month5_2014)) {\n weekNumber = 5;\n }\n\n else if ((newDate >= wk6_start && newDate <= wk6_end) && (newMonth == Month5_2014)) {\n weekNumber = 6;\n }\n\n else if ((newDate >= wk7_start && newDate <= wk7_end) && (newMonth == Month5_2014)) {\n weekNumber = 7;\n }\n\n else if ((newDate >= wk8_start && newDate <= wk8_end) && (newMonth == Month5_2014)) {\n weekNumber = 8;\n }\n\n else if ((newDate == wk9_start) && (newMonth == Month5_2014)) {\n weekNumber = 9;\n }\n\n else if ((newDate <= wk9_end) && (newMonth == Month6_2014)) {\n weekNumber = 9;\n }\n\n else if ((newDate >= wk10_start && newDate <= wk10_end) && (newMonth == Month6_2014)) {\n weekNumber = 10;\n }\n\n else if ((newDate >= wk11_start && newDate <= wk11_end) && (newMonth == Month6_2014)) {\n weekNumber = 11;\n }\n\n else if ((newDate >= wk12_start && newDate <= wk12_end) && (newMonth == Month6_2014)) {\n weekNumber = 12;\n }\n\n //adjusting criteria for weeks that have days in multiple months\n\n else if ((newDate >= wk13_start && newDate <= (wk13_start + 3)) && (newMonth == Month6_2014)) {\n weekNumber = 13;\n }\n\n else if (newDate == wk13_end && newMonth == Month7_2014) {\n weekNumber = 13;\n }\n\n\n else {\n weekNumber = 'N/A';\n }\n\n\n $(\"#weekNumber\").html(weekNumber);\n\n $(\"#dateoutput1\").html(dateText1);\n $(\"#dateoutput2\").html(dateText2);\n\n\n /*\n console.log(\" ~~~~~~~> wk9_start: \" + wk9_start);\n console.log(\" ~~~~~~~> wk9_end: \" + wk9_end);\n */\n\n }\n\n\n });\n\n}", "function displayCalendar_Fall2013_Spring2014(numberOfMonths) {\n\n from_semester_title.innerHTML = \"Fall 2013\";\n to_semester_title.innerHTML = \"Spring 2014\";\n\n $(\"#weekNumber\").html(\"1\");\n\n $(\"#dateoutput1\").html(\"9 Sep, Mon\");\n $(\"#dateoutput2\").html(\"13 Jan, Mon\");\n\n function highlightDays(date) {\n var a = new Date(2013, 8, 9); // September 9, 2013\n var b = new Date(2013, 11, 6); // December 6, 2013\n\n if (a <= date && date <= b) {\n return [true, 'highlight'];\n }\n\n return [true, ''];\n\n }\n\n\n $(\"#datepicker_Fall2013_Spring2014\").datepicker({\n /*\n dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n */\n\n inline: true,\n showOtherMonths: true,\n defaultDate: '09-09-13',\n numberOfMonths: numberOfMonths,\n dateFormat: \"dd-mm-yy\",\n\n\n beforeShowDay: highlightDays,\n\n\n onSelect: function (dateText, inst) {\n var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);\n var dateText1 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n date.setDate(date.getDate() + 126);\n var dateText2 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n\n var newDate = date.getDate();\n var newMonth = date.getMonth();\n\n /*\n console.log(\"date: \" + date);\n console.log(\"newDate: \" + newDate);\n console.log(\"newMonth: \" + newMonth);\n */\n\n var weekNumber;\n var weekDays = 4;\n var wk1_start = 13;\n var wk1_end = wk1_start + weekDays;\n\n var wk2_start = 20;\n var wk2_end = wk2_start + weekDays;\n\n var wk3_start = 27;\n var wk3_end = wk3_start + weekDays;\n\n var wk4_start = 3;\n var wk4_end = wk4_start + weekDays;\n\n var wk5_start = 10;\n var wk5_end = wk5_start + weekDays;\n\n var wk6_start = 17;\n var wk6_end = wk6_start + weekDays;\n\n var wk7_start = 24;\n var wk7_end = wk7_start + weekDays;\n\n var wk8_start = 3;\n var wk8_end = wk8_start + weekDays;\n\n var wk9_start = 10;\n var wk9_end = wk9_start + weekDays;\n\n var wk10_start = 17;\n var wk10_end = wk10_start + weekDays;\n\n var wk11_start = 24;\n var wk11_end = wk11_start + weekDays;\n\n var wk12_start = 31;\n var wk12_end = 4;\n\n var wk13_start = 7;\n var wk13_end = wk13_start + weekDays;\n\n\n var January = 0;\n var February = 1;\n var March = 2;\n var April = 3;\n\n /* console.log(\"newDate: \" + newDate); */\n\n if ((newDate >= wk1_start && newDate <= wk1_end) && (newMonth == January)) {\n weekNumber = 1;\n }\n\n else if ((newDate >= wk2_start && newDate <= wk2_end) && (newMonth == January)) {\n weekNumber = 2;\n }\n\n else if ((newDate >= wk3_start && newDate <= wk3_end) && (newMonth == January)) {\n weekNumber = 3;\n }\n\n else if ((newDate >= wk4_start && newDate <= wk4_end) && (newMonth == February)) {\n weekNumber = 4;\n }\n\n else if ((newDate >= wk5_start && newDate <= wk5_end) && (newMonth == February)) {\n weekNumber = 5;\n }\n\n else if ((newDate >= wk6_start && newDate <= wk6_end) && (newMonth == February)) {\n weekNumber = 6;\n }\n\n else if ((newDate >= wk7_start && newDate <= wk7_end) && (newMonth == February)) {\n weekNumber = 7;\n }\n\n else if ((newDate >= wk8_start && newDate <= wk8_end) && (newMonth == March)) {\n weekNumber = 8;\n }\n\n else if ((newDate >= wk9_start && newDate <= wk9_end) && (newMonth == March)) {\n weekNumber = 9;\n }\n\n else if ((newDate >= wk10_start && newDate <= wk10_end) && (newMonth == March)) {\n weekNumber = 10;\n }\n\n else if ((newDate >= wk11_start && newDate <= wk11_end) && (newMonth == March)) {\n weekNumber = 11;\n }\n\n else if (newDate == wk12_start && newMonth == March) {\n weekNumber = 12;\n /* console.log(\"newDate: \" + newDate + \"\\n newMonth: \" + newMonth ); */\n }\n\n else if (newDate <= wk12_end && newMonth == April) {\n weekNumber = 12;\n /* console.log(\"newDate: \" + newDate + \"\\n newMonth: \" + newMonth ); */\n }\n\n\n else if ((newDate >= wk13_start && newDate <= wk13_end) && (newMonth == April)) {\n weekNumber = 13;\n }\n\n\n else {\n weekNumber = 'N/A';\n }\n\n\n $(\"#weekNumber\").html(weekNumber);\n\n $(\"#dateoutput1\").html(dateText1);\n $(\"#dateoutput2\").html(dateText2);\n\n\n }\n\n\n\n });\n\n\n}", "function Calendar( options, playedDays ) {\n var date = new Date();\n\n this.year = date.getFullYear();\n this.month = date.getMonth() + 1;\n $.extend(this, options);\n this.playedDays = playedDays ? playedDays : [];\n this.weeks = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];\n this.monthTable = ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'];\n \n Calendar.prototype.setPlayedDays = function( playedDays ) {\n this.playedDays = playedDays;\n }\n\n Calendar.prototype.display = function() { \n var html = this.showChangeDate ();\n html += '<table class=\"session-calendar-table\">';\n html += this.showWeeks ();\n html += this.showDays(this.year, this.month);\n html += '</table>';\n\n return html;\n };\n\n Calendar.prototype.showWeeks = function() {\n var html = '<thead><tr class=\"session-calendar-weeks\">';\n\n for (var title in this.weeks) {\n html += '<th>' + this.weeks[title] + '</th>'\n }\n html += '</tr></thead>';\n \n return html;\n }\n \n Calendar.prototype.showDays = function( year, month ) {\n var firstDay, starDay, days, html, flag = false;\n\n firstDay = new Date(year, month, 1, 0, 0, 0);\n starDay = firstDay.getDay()\n days = new Date(year, month, 0).getDate();\n html = '<tr>';\n\n for (var i = 0; i < starDay; i++) {\n html += '<td>&nbsp;</td>';\n }\n \n for (var j = 1; j <= days; j++) {\n i++;\n\n for (var index = 0; index < this.playedDays.length; index++) {\n if (j == this.playedDays[index]) {\n html += '<td class=\"played-day\">' + j + '</td>';\n flag = true;\n break;\n } \n }\n \n if (!flag) {\n html += '<td>' + j + '</td>';\n } else {\n flag = false;\n }\n \n if (i % 7 == 0) {\n html += '</tr><tr>';\n }\n }\n \n html += '</tr>';\n \n return html;\n }\n \n Calendar.prototype.showChangeDate = function() {\n\n var html, prevMonthIndex, crrentIndex, nextMonthIndex;\n prevMonthIndex = (this.month + 10) % 12;\n crrentIndex = (this.month - 1) % 12;\n nextMonthIndex = this.month % 12;\n\n html = '<div class=\"overflow-hidden\"><a class=\"js-calendar-prev-month change-date-btn prev-month-btn pull-left\">' + this.monthTable[prevMonthIndex].substr(0, 3) + '</a>';\n html += '<div class=\"js-current-month current-month pull-left\" data-month=\"' + this.month +'\"><span class=\"js-current-year\" data-year=\"' + this.year + '\"></span>' + this.monthTable[crrentIndex] + '</div>';\n html += '<a class=\"js-calendar-next-month change-date-btn pull-right next-month-btn\">' + this.monthTable[nextMonthIndex].substr(0, 3) + '</a>';\n html += '</div>';\n\n return html;\n }\n\n Calendar.prototype.prevMonth = function( year, month ) {\n if (month == 1) {\n month = 12;\n year = (year <= 1970) ? 1970 : year - 1;\n } else {\n month --;\n }\n \n this.year = year;\n this.month = month;\n }\n \n Calendar.prototype.nextMonth = function( year, month ) {\n if (month == 12) {\n month = 1;\n year = (year >= 2038) ? 2038 : parseInt(year) + 1;\n } else {\n month ++;\n }\n\n this.year = year;\n this.month = month;\n }\n }", "function switchSeasons() {\n\tcurrentSeasonSelected =event.target.value;\n\tprintToDom();\n}", "function getSeason(title) {\n\n //ispraznimo epizode kako bi prikazali nove\n $(\"#episodes\").empty();\n\n //pokupimo vrijednost iz selecta o sezoni koja nam je potrebna za GET zahtjev\n let val = $(\"#select-episodes\").val();\n\n //select uvijek vrace vrijednost sezone u obliku (nprm '1', '2') sto ne odgovara zahtjevu\n //pa je potrebno izbrisati navodnike koji se uvijek nalaze na prvom i poslednjem mjestu stringa\n let season = val.substring(1, val.length - 1);\n\n //ajax request prema API-ju koji vraca podatke o epizodama\n $.ajax({\n\n type: \"GET\",\n url: \"https://www.omdbapi.com/?apikey=39c93cf7&t=\" + title + \"&season=\" + season,\n success: (response) => {\n\n let season = response.Episodes;\n\n //prodjemo kroz niz epizoda koji smo dobili i prikazujemo jednu po jednu\n season.forEach(episode => {\n\n $('#episodes').append(\n '<p>' + episode.Episode + '. <a href=\"#\" class=\"episode-link\" onClick=\"openEpisode(\\'' + response.Title + '\\', \\'' + response.Season + '\\', \\'' + episode.Episode + '\\')\">' + episode.Title + '</a>, ' + episode.Released + ', ' + episode.imdbRating + '/10</p>'\n )\n\n })\n }\n })\n}", "function createCalendar(){\n // display the current month and year at the top of the calendar\n calendarHeader.innerHTML = `<h1>${monthInfo[dateInfo.currentMonth][0]} ${dateInfo.currentYear}</h1>`;\n checkLeapYear();\n addDaysFromPastMonth();\n addDaysFromCurrentMonth();\n addDaysFromNextMonth();\n}", "function showDate() {\n\n let tempCalendarDate = new Date(theYear, theMonth, 1);\n let tempYear = tempCalendarDate.getFullYear();\n let tempDate = tempCalendarDate.getDate();\n let tempDay = tempCalendarDate.getDay();\n let tempMonth = tempCalendarDate.getMonth();\n\n dayDiv.innerHTML = \"<!--innerHTML-->\"\n\n\n loopWeekDady: for (let i = 0; i < 6; i++) {\n\n\n // make there is enough rows for showing weeks.\n // porvide an extra row when the month span 6 weeks\n if (i == 5) {\n document.getElementById(\"id-dates\").style.height = \"270px\";\n document.getElementById(\"calendar\").style.height = \"405px\";\n\n\n\n\n } else {\n document.getElementById(\"id-dates\").style.height = \"225px\";\n document.getElementById(\"calendar\").style.height = \"360px\";\n }\n\n\n\n loopDate: for (let j = 0; j < 7; j++) {\n\n\n let tempId = \"\" + tempYear + \"y\" + tempMonth + \"m\" + tempDate + \"d\";\n\n\n if (tempDay == j) {\n dayDiv.innerHTML = dayDiv.innerHTML + \"<div \" + \"id=\" + tempId + \" class= \\\"small-box\\\" \" + \" onclick=\\\"chooseDate('\" + tempId + \"')\\\"\" + \" data-value=\" + \"\\\"\" + tempDate + \"\\\" \" + \">\" + \"<p>\" + tempDate + \"</p\" +\n \" class= \\\"date\\\" \" + \">\" + \"</div>\";\n\n tempCalendarDate.setDate(tempDate + 1);\n tempDay = tempCalendarDate.getDay();\n tempDate = tempCalendarDate.getDate();\n\n } else {\n dayDiv.innerHTML = dayDiv.innerHTML + \"<div class= \\\"small-box\\\" >\" + \"<p>\" + \" \" + \"</p>\" + \"</div>\";\n }\n if (tempMonth != tempCalendarDate.getMonth()) {\n tempMonth = tempCalendarDate.getMonth();\n break loopWeekDady;\n }\n\n }\n\n }\n\n document.getElementById(theDateId).style.fontWeight = 700;\n}", "function displayCalendar_Fall2014_Spring2015(numberOfMonths) {\n\n from_semester_title.innerHTML = \"Fall 2014\";\n to_semester_title.innerHTML = \"Spring 2015\";\n\n $(\"#weekNumber\").html(\"1\");\n\n $(\"#dateoutput1\").html(\"2 Sep, Tue\");\n $(\"#dateoutput2\").html(\"6 Jan, Tue\");\n\n function highlightDays(date) {\n var a = new Date(2014, 8, 2); // September 2, 2014\n var b = new Date(2014, 11, 8); // December 8, 2014\n\n if (a <= date && date <= b) {\n return [true, 'highlight'];\n }\n\n return [true, ''];\n\n }\n\n\n $(\"#datepicker_Fall2014_Spring2015\").datepicker({\n /*\n dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n */\n\n inline: true,\n showOtherMonths: true,\n defaultDate: '02-09-14',\n numberOfMonths: numberOfMonths,\n dateFormat: \"dd-mm-yy\",\n\n\n beforeShowDay: highlightDays,\n\n\n onSelect: function (dateText, inst) {\n var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);\n var dateText1 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n date.setDate(date.getDate() + 126);\n var dateText2 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n\n var newDate = date.getDate();\n var newMonth = date.getMonth();\n\n /*\n console.log(\"date: \" + date);\n console.log(\"newDate: \" + newDate);\n console.log(\"newMonth: \" + newMonth);\n */\n\n var weekNumber;\n var weekDays = 6;\n var wk1_start = 6;\n var wk1_end = wk1_start + weekDays;\n\n var wk2_start = 13;\n var wk2_end = wk2_start + weekDays;\n\n var wk3_start = 20;\n var wk3_end = wk3_start + weekDays;\n\n var wk4_start = 27;\n var wk4_end = 2;\n\n var wk5_start = 3;\n var wk5_end = wk5_start + weekDays;\n\n var wk6_start = 17;\n var wk6_end = wk6_start + weekDays;\n\n var wk7_start = 24;\n var wk7_end = 2;\n\n var wk8_start = 3;\n var wk8_end = wk8_start + weekDays;\n\n var wk9_start = 10;\n var wk9_end = wk9_start + weekDays;\n\n var wk10_start = 17;\n var wk10_end = wk10_start + weekDays;\n\n var wk11_start = 24;\n var wk11_end = wk11_start + weekDays;\n\n var wk12_start = 31;\n var wk12_end = 6;\n\n var wk13_start = 7;\n var wk13_end = wk13_start + weekDays;\n\n\n var January = 0;\n var February = 1;\n var March = 2;\n var April = 3;\n\n /* console.log(\"newDate: \" + newDate); */\n\n if ((newDate >= wk1_start && newDate <= wk1_end) && (newMonth == January)) {\n weekNumber = 1;\n }\n\n else if ((newDate >= wk2_start && newDate <= wk2_end) && (newMonth == January)) {\n weekNumber = 2;\n }\n\n else if ((newDate >= wk3_start && newDate <= wk3_end) && (newMonth == January)) {\n weekNumber = 3;\n }\n\n else if ((newDate >= wk4_start) && (newMonth == January)) {\n weekNumber = 4;\n }\n else if ((newDate <= wk4_end) && (newMonth == February)) {\n weekNumber = 4;\n }\n\n else if ((newDate >= wk5_start && newDate <= wk5_end) && (newMonth == February)) {\n weekNumber = 5;\n }\n\n else if ((newDate >= wk6_start && newDate <= wk6_end) && (newMonth == February)) {\n weekNumber = 6;\n }\n\n else if ((newDate >= wk7_start) && (newMonth == February)) {\n weekNumber = 7;\n }\n\n else if ((newDate <= wk7_end) && (newMonth == March)) {\n weekNumber = 7;\n }\n\n\n else if ((newDate >= wk8_start && newDate <= wk8_end) && (newMonth == March)) {\n weekNumber = 8;\n }\n\n else if ((newDate >= wk9_start && newDate <= wk9_end) && (newMonth == March)) {\n weekNumber = 9;\n }\n\n else if ((newDate >= wk10_start && newDate <= wk10_end) && (newMonth == March)) {\n weekNumber = 10;\n }\n\n else if ((newDate >= wk11_start && newDate <= wk11_end) && (newMonth == March)) {\n weekNumber = 11;\n }\n\n else if (newDate == wk12_start && newMonth == March) {\n weekNumber = 12;\n }\n\n else if (newDate <= wk12_end && newMonth == April) {\n weekNumber = 12;\n }\n\n\n else if ((newDate >= wk13_start && newDate <= wk13_end) && (newMonth == April)) {\n weekNumber = 13;\n }\n\n\n else {\n weekNumber = 'N/A';\n }\n\n\n $(\"#weekNumber\").html(weekNumber);\n\n $(\"#dateoutput1\").html(dateText1);\n $(\"#dateoutput2\").html(dateText2);\n\n\n }\n\n\n\n });\n\n\n}", "function displayCalendar_Fall2014_Spring2015_5(numberOfMonths) {\n\n from_semester_title.innerHTML = \"Fall 2014\";\n to_semester_title.innerHTML = \"Spring 2015\";\n\n\n $(\"#weekNumber\").html(\"1\");\n\n $(\"#dateoutput1\").html(\"2 Sep, Tue\");\n $(\"#dateoutput2\").html(\"5 Jan, Mon\");\n\n function highlightDays(date) {\n var a = new Date(2014, 8, 2); // September 2, 2014\n var b = new Date(2014, 11, 8); // December 8, 2014\n\n if (a <= date && date <= b) {\n return [true, 'highlight'];\n }\n\n return [true, ''];\n\n }\n\n\n $(\"#datepicker_Fall2014_Spring2015_5\").datepicker({\n /*\n dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n */\n\n inline: true,\n showOtherMonths: true,\n defaultDate: '02-09-14',\n numberOfMonths: numberOfMonths,\n dateFormat: \"dd-mm-yy\",\n\n\n beforeShowDay: highlightDays,\n\n\n onSelect: function (dateText, inst) {\n var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);\n var dateText1 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n date.setDate(date.getDate() + 125);\n var dateText2 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n\n var newDate = date.getDate();\n var newMonth = date.getMonth();\n\n /*\n console.log(\"date: \" + date);\n console.log(\"newDate: \" + newDate);\n console.log(\"newMonth: \" + newMonth);\n */\n\n var weekNumber;\n var weekDays = 4;\n var wk1_start = 5;\n var wk1_end = wk1_start + weekDays;\n\n var wk2_start = 12;\n var wk2_end = wk2_start + weekDays;\n\n var wk3_start = 19;\n var wk3_end = wk3_start + weekDays;\n\n var wk4_start = 26;\n var wk4_end = wk4_start + weekDays;\n\n var wk5_start = 2;\n var wk5_end = wk5_start + weekDays;\n\n var wk6_start = 16;\n var wk6_end = wk6_start + weekDays;\n\n var wk7_start = 23;\n var wk7_end = wk7_start + weekDays;\n\n var wk8_start = 2;\n var wk8_end = wk8_start + weekDays;\n\n var wk9_start = 9;\n var wk9_end = wk9_start + weekDays;\n\n var wk10_start = 16;\n var wk10_end = wk10_start + weekDays;\n\n var wk11_start = 23;\n var wk11_end = wk11_start + weekDays;\n\n var wk12_start = 30;\n var wk12_end = 3;\n\n var wk13_start = 6;\n var wk13_end = wk13_start + weekDays;\n\n\n var January = 0;\n var February = 1;\n var March = 2;\n var April = 3;\n\n /* console.log(\"newDate: \" + newDate); */\n\n if ((newDate >= wk1_start && newDate <= wk1_end) && (newMonth == January)) {\n weekNumber = 1;\n }\n\n else if ((newDate >= wk2_start && newDate <= wk2_end) && (newMonth == January)) {\n weekNumber = 2;\n }\n\n else if ((newDate >= wk3_start && newDate <= wk3_end) && (newMonth == January)) {\n weekNumber = 3;\n }\n\n else if ((newDate >= wk4_start && newDate <= wk4_end) && (newMonth == January)) {\n weekNumber = 4;\n }\n\n else if ((newDate >= wk5_start && newDate <= wk5_end) && (newMonth == February)) {\n weekNumber = 5;\n }\n\n else if ((newDate >= wk6_start && newDate <= wk6_end) && (newMonth == February)) {\n weekNumber = 6;\n }\n\n else if ((newDate >= wk7_start && newDate <= wk7_end) && (newMonth == February)) {\n weekNumber = 7;\n }\n\n\n else if ((newDate >= wk8_start && newDate <= wk8_end) && (newMonth == March)) {\n weekNumber = 8;\n }\n\n else if ((newDate >= wk9_start && newDate <= wk9_end) && (newMonth == March)) {\n weekNumber = 9;\n }\n\n else if ((newDate >= wk10_start && newDate <= wk10_end) && (newMonth == March)) {\n weekNumber = 10;\n }\n\n else if ((newDate >= wk11_start && newDate <= wk11_end) && (newMonth == March)) {\n weekNumber = 11;\n }\n\n else if (newDate >= wk12_start && newMonth == March) {\n weekNumber = 12;\n }\n\n else if (newDate <= wk12_end && newMonth == April) {\n weekNumber = 12;\n }\n\n\n else if ((newDate >= wk13_start && newDate <= wk13_end) && (newMonth == April)) {\n weekNumber = 13;\n }\n\n\n else {\n weekNumber = 'N/A';\n }\n\n\n $(\"#weekNumber\").html(weekNumber);\n\n $(\"#dateoutput1\").html(dateText1);\n $(\"#dateoutput2\").html(dateText2);\n\n\n }\n\n\n\n });\n\n\n}", "getReplaySeason() {\n //Constant array to hold episode numbers that each season begins with\n // excluding the first season which is assumed to start at episode 1\n // NOTE: Could use episode titles in the future if episode number is unreliable\n const replaySeasonStartEpisodes = [107, 268, 385, 443, 499]; // [S2, S3, S4, S5, S6]\n\n // Season\n let season = 0;\n for (let index = 0; index < replaySeasonStartEpisodes.length; index++) {\n if (this.episodeNumber < replaySeasonStartEpisodes[index]) {\n season = index + 1;\n break;\n }\n // If reached end of loop, assign last season\n if (index == replaySeasonStartEpisodes.length - 1) {\n season = replaySeasonStartEpisodes.length + 1;\n }\n }\n\n // Season Episode\n let seasonEpisode = (season == 1) ? this.episodeNumber\n : this.episodeNumber - replaySeasonStartEpisodes[season - 2] + 1;\n\n // Return both season and seasonEpisode number\n return [season, seasonEpisode];\n }", "_renderCalendarMonth() {\n let i = 0;\n let calendarWrapper = document.getElementById('calendarWrapper');\n let calendarMonth = document.getElementById('calendarMonth');\n let iteratingDate =1;\n this.numberOfDaysInMonth = this.daysInMonth(this.monthIndex,this.year);\n // Set date to the 1st of current month\n this.startOfMonthDate = new Date(this.year,this.monthIndex,1);\n this.dayAtStartOfMonth = this.startOfMonthDate.getDay();\n calendarWrapper.innerHTML = '';\n // Changes month and year displayed\n calendarMonth.innerHTML = '';\n calendarMonth.innerHTML += `${this.month} ${this.year}`; \n var myRequest = new Request('../months.json');\n fetch(myRequest)\n .then(function(response) {return response.json();})\n .then(function(months) {\n let colour = 'light-grey';\n let colourTwo = \"\";\n let text = \"\";\n for (var i=1; i<=42;i++ ){\n if (i>=dayArray[calendar.dayAtStartOfMonth] && iteratingDate<=calendar.numberOfDaysInMonth){\n if (`${iteratingDate}` in months[`${calendar.year}`][calendar.monthIndex]){\n colour = months[`${calendar.year}`][calendar.monthIndex][`${iteratingDate}`].colour;\n if (`text` in months[`${calendar.year}`][calendar.monthIndex][`${iteratingDate}`]){\n text = months[`${calendar.year}`][calendar.monthIndex][`${iteratingDate}`].text;\n }\n if (`colourTwo` in months[`${calendar.year}`][calendar.monthIndex][`${iteratingDate}`]){\n colourTwo = months[`${calendar.year}`][calendar.monthIndex][`${iteratingDate}`].colourTwo;\n } \n }\n if (colourTwo !== \"\"){\n calendarWrapper.innerHTML +=`<div><div class=\"grid-two-col\"><div class=\"${colour}\"></div><div class= \"${colourTwo}\"><p class=\"calendar-number\">${iteratingDate}</p></div></div><p class=\"calendar-text\">${text}</p></div>`;\n colourTwo = \"\"; \n } else {\n calendarWrapper.innerHTML +=`<div><div class=\"grid-two-col\"><div class=\"${colour}\"></div><div class= \"${colour}\"><p class=\"calendar-number\">${iteratingDate}</p></div></div><p class=\"calendar-text\">${text}</p></div>`;\n }\n iteratingDate++;\n text=\"\";\n } else {\n calendarWrapper.innerHTML += `<div><p class=\"calendar-text\"></p></div>`;\n }\n } \n });\n }", "function display(){\n\t$(\"#month\").html(getMonthName(currentDate.getMonth()));\n\t$(\"#year\").html(currentDate.getFullYear());\n\tfor(i=0;i<7;i++){\n\t\tif(week[i].getDate()==currentDate.getDate()){ //Add active class to day active\n\t\t\t$('#day'+i).html('<div class=\"day-active mx-auto\" >'+week[i].getDate()+'</div>');\n\t\t}else{\n\t\t\t$('#day'+i).html(week[i].getDate());\n\t\t}\n\t}\n\tgetWeekDescription()\t\n}", "function displayCalendar_Summer2014_Fall2014(numberOfMonths) {\n\n from_semester_title.innerHTML = \"Summer 2014\";\n to_semester_title.innerHTML = \"Fall 2014\";\n\n $(\"#weekNumber\").html(\"1\");\n\n $(\"#dateoutput1\").html(\"5 May, Mon\");\n $(\"#dateoutput2\").html(\"2 Sep, Tue\");\n\n function highlightDays(date) {\n var a = new Date(2014, 4, 5); // May 5, 2014\n var b = new Date(2014, 8, 2); // September 2, 2014\n\n if (a <= date && date <= b) {\n return [true, 'highlight'];\n }\n\n return [true, ''];\n\n }\n\n\n $(\"#datepicker_Summer2014_Fall2014\").datepicker({\n /*\n dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n */\n\n inline: true,\n showOtherMonths: true,\n defaultDate: '05-05-14',\n numberOfMonths: numberOfMonths,\n dateFormat: \"dd-mm-yy\",\n\n\n beforeShowDay: highlightDays,\n\n\n onSelect: function (dateText, inst) {\n var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);\n var dateText1 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n date.setDate(date.getDate() + 120);\n var dateText2 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n\n var newDate = date.getDate();\n var newMonth = date.getMonth();\n\n /*\n console.log(\"date: \" + date);\n console.log(\"newDate: \" + newDate);\n console.log(\"newMonth: \" + newMonth);\n */\n\n var weekNumber;\n var weekDays = 6;\n var wk1_start = 2;\n var wk1_end = wk1_start + weekDays;\n\n var wk2_start = 9;\n var wk2_end = wk2_start + weekDays;\n\n var wk3_start = 16;\n var wk3_end = wk3_start + weekDays;\n\n var wk4_start = 23;\n var wk4_end = wk4_start + weekDays;\n\n var wk5_start = 30;\n var wk5_end = 6;\n\n var wk6_start = 7;\n var wk6_end = wk6_start + weekDays;\n\n var wk7_start = 14;\n var wk7_end = wk7_start + weekDays;\n\n var wk8_start = 21;\n var wk8_end = wk8_start + weekDays;\n\n var wk9_start = 28;\n var wk9_end = 3;\n\n var wk10_start = 4;\n var wk10_end = wk10_start + weekDays;\n\n var wk11_start = 11;\n var wk11_end = wk11_start + weekDays;\n\n var wk12_start = 18;\n var wk12_end = wk12_start + weekDays;\n\n var wk13_start = 25;\n var wk13_end = 1;\n\n\n var September = 8;\n var October = 9;\n var November = 10;\n var December = 11;\n\n /* console.log(\"newDate: \" + newDate); */\n\n if ((newDate >= wk1_start && newDate <= wk1_end) && (newMonth == September)) {\n weekNumber = 1;\n }\n\n else if ((newDate >= wk2_start && newDate <= wk2_end) && (newMonth == September)) {\n weekNumber = 2;\n }\n\n else if ((newDate >= wk3_start && newDate <= wk3_end) && (newMonth == September)) {\n weekNumber = 3;\n }\n\n else if ((newDate >= wk4_start && newDate <= wk4_end) && (newMonth == September)) {\n weekNumber = 4;\n }\n\n else if (((newDate == wk5_start) && (newMonth == September)) || ((newDate <= wk5_end) && (newMonth == October))) {\n weekNumber = 5;\n }\n\n else if ((newDate >= wk6_start && newDate <= wk6_end) && (newMonth == October)) {\n weekNumber = 6;\n }\n\n else if ((newDate >= wk7_start && newDate <= wk7_end) && (newMonth == October)) {\n weekNumber = 7;\n }\n\n else if ((newDate >= wk8_start && newDate <= wk8_end) && (newMonth == October)) {\n weekNumber = 8;\n }\n\n else if (((newDate >= wk9_start && newDate <= 31) && (newMonth == October)) || ((newDate <= wk9_end) && (newMonth == November))) {\n weekNumber = 9;\n }\n\n\n else if ((newDate >= wk10_start && newDate <= wk10_end) && (newMonth == November)) {\n weekNumber = 10;\n }\n\n else if ((newDate >= wk11_start && newDate <= wk11_end) && (newMonth == November)) {\n weekNumber = 11;\n }\n\n else if ((newDate >= wk12_start && newDate <= wk12_end) && (newMonth == November)) {\n weekNumber = 12;\n }\n\n\n else if (((newDate >= wk13_start && newDate <= 30) && (newMonth == November)) || ((newDate == 1) && (newMonth == December))) {\n weekNumber = 13;\n }\n\n\n else {\n weekNumber = 'N/A';\n }\n\n\n $(\"#weekNumber\").html(weekNumber);\n\n $(\"#dateoutput1\").html(dateText1);\n $(\"#dateoutput2\").html(dateText2);\n\n\n }\n\n\n\n });\n\n\n}", "function updateCalendar(){\n //events = [];\n document.getElementById(\"display_events\").innerHTML = \"\";\n //document.getElementById(\"days\").innerHTML = \"\";\n $(\"#days\").empty();\n\tlet weeks = currentMonth.getWeeks();\n \n const data = {'month': currentMonth.month+1, 'year': currentMonth.year};\n eventsDay(data);\n //console.log(currentMonth);\n let index = 0;\n\tfor(let w in weeks){\n\t\tlet days = weeks[w].getDates();\n index++;\n\t\t// days contains normal JavaScript Date objects.\n\t\t//alert(\"Week starting on \"+days[0]); \n\t\t//$(\"#days\").append(\"<div class='calendar__week'>\");\n\t\tfor(let d in days){ \n\t\t\t// You can see console.log() output in your JavaScript debugging tool, like Firebug,\n\t\t\t// WebWit Inspector, or Dragonfly.\n const dayRegex = /(\\d{2})/g;\n const dayMatch = dayRegex.exec(days[d])[1];\n //const data = {'day': dayMatch, 'month': currentMonth.month+1, 'year': currentMonth.year};\n let name =\"\";\n let namearray = [];\n let count = 0;\n for (let i = 0; i < eventclass.length; ++i) {\n //console.log(eventclass[i].name);\n //console.log(eventclass[i].day + \" \" + dayMatch);\n const c = eventclass[i].tag;\n let color;\n if (c == 'holiday') {\n color = 'green';\n }\n else if (c == 'birthday') {\n color = 'pink';\n }\n else if (c == 'exam') {\n color = 'blue';\n }\n else if (c == 'important') {\n color = 'red';\n }\n else {\n color = '#aab2b8';\n }\n //console.log(eventclass[i].name + \" \" + eventclass[i].month);\n \n if (eventclass[i].day == dayMatch && currentMonth.month+1 == eventclass[i].month && currentMonth.year == eventclass[i].year) {\n //console.log(\"entered\");\n if (eventclass[i].day < 7) {\n if(index > 1) {\n //console.log(\"less than 1\");\n //\n }\n else {\n name= name.concat(\"<div id='eventbox'><span style='color:\"+color+\";'>\" + eventclass[i].name + \"</span> <button class='mod' id='modify_btn' value=\" + eventclass[i].id +\">Edit</button> <button class='del' id='delete_btn' value=\" + eventclass[i].id +\">Delete</button> <button class='time' id='time_btn' value=\" + eventclass[i].id +\">View Details</button></div>\");\n name = name.concat(\"<br>\");\n //console.log(eventclass[i].month);\n //console.log(\"greater\");\n }\n \n }\n else if (eventclass[i].day > 23) {\n if(index < 3) {\n //\n }\n else {\n name= name.concat(\"<div id='eventbox'><span style='color:\"+color+\";'>\" + eventclass[i].name + \"</span> <button class='mod' id='modify_btn' value=\" + eventclass[i].id +\">Edit</button> <button class='del' id='delete_btn' value=\" + eventclass[i].id +\">Delete</button> <button class='time' id='time_btn' value=\" + eventclass[i].id +\">View Details</button></div>\");\n name = name.concat(\"<br>\");\n \n }\n }\n else {\n //sname = name.concat(eventclass[i].name);\n // name= name.concat(\"<button class='mod' id='modify_btn' value=\" + eventclass[i].id +\">\" + eventclass[i].name + \"</button><p>\");\n name= name.concat(\"<div id='eventbox'><span style='color:\"+color+\";'>\" + eventclass[i].name + \"</span> <button class='mod' id='modify_btn' value=\" + eventclass[i].id +\">Edit</button> <button class='del' id='delete_btn' value=\" + eventclass[i].id +\">Delete</button> <button class='time' id='time_btn' value=\" + eventclass[i].id +\">View Details</button></div>\");\n name = name.concat(\"<br>\");\n //console.log(\"work\");\n //name = name + \"\\n\" + \"\\n\";\n //namearray[count] = name;\n //count ++;\n }\n\n }\n }\n if(name == \"\"){\n $(\"#days\").append(\"<li><div class='box'>\" + dayMatch + \"</div></li>\");\n } else {\n \n $(\"#days\").append(\"<li><div class='box'>\" + dayMatch + \"<br>\" +name + \"</div></li>\");\n }\n }\n\t}\n const mod_buttons = document.getElementsByClassName('mod');\n const del_buttons = document.getElementsByClassName('del');\n const time_buttons = document.getElementsByClassName('time');\n for ( let j in Object.keys( mod_buttons ) ) {\n mod_buttons[j].addEventListener(\"click\", modifyEvents, false);\n }\n for ( let k in Object.keys( del_buttons ) ) {\n del_buttons[k].addEventListener(\"click\", deleteEvents, false);\n }\n for ( let m in Object.keys( time_buttons ) ) {\n time_buttons[m].addEventListener(\"click\", viewtime, false);\n }\n \n}", "function calendar(dates) {\n // grab the year, month, and day\n let year = dates.year;\n let month = dates.month;\n let day = dates.day;\n let dayOfWeek = dates.dayOfWeek;\n let monthOfYear = dates.monthOfYear;\n // get the timezone\n let timezone = dates.timezone;\n\n // find the month of year\n let months = ['January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December'];\n for (let i = 0; i < months.length; i++) {\n if (i === month) {\n monthOfYear = months[i];\n };\n };\n // find the day of the week\n let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];\n for (let i = 0; i < days.length; i++) {\n if (i === dayOfWeek) {\n dayOfWeek = days[i];\n };\n };\n\n // display the date on the application\n document.getElementById(\"date-numbers\").innerHTML = dayOfWeek + \" \" + monthOfYear + \" \" + day + \", \" + year;\n document.getElementById(\"timezone\").innerHTML = timezone;\n // month = month + 1;\n // document.getElementById(\"header-title\").innerHTML += \" \" + month + \"/\" + day + \"/\" + year;\n}", "function calendar(year) {\n console.log(\"creating calendar\")\n for (var monthCount = 0; monthCount < 13; monthCount++) {\n var newList = $(\"<ul>\");\n newList.addClass(\"main\");\n for (var dayCount = 0; dayCount < 32; dayCount++) {\n\n if (dayCount===0 && monthCount===0) {\n var newListItem = $(\"<li>\")\n newListItem.addClass(\"cEmpty\")\n // newListItem.addClass(\"cLabel\");\n newList.append(newListItem)\n }\n else if (monthCount ===0)\n {\n var newListItem = $(\"<li>\");\n newListItem.addClass(\"cEmpty\");\n var labelDiv = $(\"<div>\")\n labelDiv.addClass(\"cLabel\");\n labelDiv.text(dayCount);\n newListItem.append(labelDiv);\n newList.append(newListItem);\n\n } else if (dayCount ===0) {\n var monthName = moment(monthCount, \"M\").format(\"MMM\")\n var newListItem = $(\"<li>\");\n newListItem.addClass(\"cEmpty\");\n var labelDiv = $(\"<div>\");\n labelDiv.addClass(\"cLabel\");\n labelDiv.text(monthName.substring(0,1));\n newListItem.append(labelDiv);\n newList.append(newListItem)\n } else {\n\n var newListItem = $(\"<li>\")\n\n var dateDiv = $(\"<div>\")\n var date = String(monthCount) + \"/\" + String(dayCount) + \"/\" + year\n var dateFormat = \"M/D/YYYY\"\n var convertedDate = moment(date, dateFormat)\n var dayOfTheWeek = convertedDate.format(\"d\") // sunday =0\n\n\n\n if (!convertedDate.isValid()) {\n newListItem.addClass(\"cEmpty\")\n } else {\n dateDiv.addClass(\"cDate\")\n dateDiv.addClass(date)\n dateDiv.text(convertedDate.format(\"MM/DD/YY\"));\n newListItem.append(dateDiv)\n\n var location = $(\"<div>\")\n location.addClass(\"cLocation\")\n location.text(\"Gary, IN\")\n newListItem.append(location)\n\n var mood = Math.floor(Math.random() * (9 - 1)) + 1\n newListItem.addClass(\"type-\" + mood)\n newListItem.addClass(\"cat-\" + dayOfTheWeek)\n }\n\n\n\n newList.append(newListItem)\n }\n }\n $(\".wrapper\").append(newList)\n }\n }", "renderDateTitle(date) {\n return moment(date).format(\"dddd\") + \", \" + moment(date).format(\"MMMM Do\");\n }", "displaySeason() {\r\n if(this.state.serie !== undefined) {\r\n return this.state.serie.seasons_details.map(season => {\r\n return <div className=\"seasons\" key={season.id} onClick={ (e) => {this.episodeslist(season.number)}}>\r\n Saison {season.number}\r\n </div>\r\n })\r\n }\r\n }", "function displayCalendar_Fall2013_Int2_Summer2014_Int2(numberOfMonths) {\n\n from_semester_title.innerHTML = \"Fall 2013 Int 2\";\n to_semester_title.innerHTML = \"Summer 2014 Int 2\";\n\n $(\"#weekNumber\").html(\"1\");\n\n $(\"#dateoutput1\").html(\"28 Oct, Mon\");\n $(\"#dateoutput2\").html(\"23 Jun, Mon\");\n\n function highlightDays(date) {\n var a = new Date(2013, 9, 28); // 2013, October (10-1) 28\n var b = new Date(2013, 11, 6); // 2013, December (12-1) 6\n\n if (a <= date && date <= b) {\n return [true, 'highlight'];\n }\n\n return [true, ''];\n\n }\n\n\n $(\"#datepicker_Fall2013_Int2_Summer2014_Int2\").datepicker({\n /*\n dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n */\n\n inline: true,\n showOtherMonths: true,\n defaultDate: '28-10-13',\n numberOfMonths: numberOfMonths,\n dateFormat: \"dd-mm-yy\",\n\n\n beforeShowDay: highlightDays,\n\n\n onSelect: function (dateText, inst) {\n var date = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);\n var dateText1 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n date.setDate(date.getDate() + 238);\n var dateText2 = $.datepicker.formatDate(\"d M, D\", date, inst.settings);\n\n var newDate = date.getDate();\n var newMonth = date.getMonth();\n\n /*\n console.log(\"date: \" + date);\n console.log(\"newDate: \" + newDate);\n console.log(\"newMonth: \" + newMonth);\n */\n\n var weekNumber;\n var weekDays = 4;\n var wk1_start = 23;\n var wk1_end = wk1_start + weekDays;\n\n var wk2_start = 30;\n var wk2_end = 4;\n\n var wk3_start = 7;\n var wk3_end = wk3_start + weekDays;\n\n var wk4_start = 14;\n var wk4_end = wk4_start + weekDays;\n\n var wk5_start = 21;\n var wk5_end = wk5_start + weekDays;\n\n var wk6_start = 28;\n var wk6_end = 1;\n\n\n var June = 5;\n var July = 6;\n var August = 7;\n\n /* console.log(\"newDate: \" + newDate); */\n\n if ((newDate >= wk1_start && newDate <= wk1_end) && (newMonth == June)) {\n weekNumber = 1;\n }\n\n else if ((newDate == wk2_start) && (newMonth == June)) {\n weekNumber = 2;\n }\n\n else if ((newDate <= wk2_end) && (newMonth == July)) {\n weekNumber = 2;\n }\n\n else if ((newDate >= wk3_start && newDate <= wk3_end) && (newMonth == July)) {\n weekNumber = 3;\n }\n\n else if ((newDate >= wk4_start && newDate <= wk4_end) && (newMonth == July)) {\n weekNumber = 4;\n }\n\n else if ((newDate >= wk5_start && newDate <= wk5_end) && (newMonth == July)) {\n weekNumber = 5;\n }\n\n else if ((newDate >= wk6_start ) && (newMonth == July)) {\n weekNumber = 6;\n }\n\n else if ((newDate == wk6_end) && (newMonth == August)) {\n weekNumber = 6;\n }\n\n\n else {\n weekNumber = 'N/A';\n }\n\n\n $(\"#weekNumber\").html(weekNumber);\n\n $(\"#dateoutput1\").html(dateText1);\n $(\"#dateoutput2\").html(dateText2);\n\n\n }\n\n\n\n });\n\n\n}", "function renderCalendar() {\n // render month title\n renderMonthTitle(currentMonth, monthTitleEl);\n\n // render days\n renderDays(currentMonth, daysContainerEl);\n }", "function displayOclinics () {\n\n var d = new Date();\n\tvar month = d.getMonth();\n\tvar date = d.getDate();\n var may = Object.keys(Oclinicsmay);\n var june = Object.keys(Oclinicsjune);\n for (var i = 0; i < (may.length + june.length); i++) {\n $(\"#oevents\" + i).html('');\n }\n // see if there are any Officials Clinics in May and display them ---------\n if (may.length > 0) {\n\n for (var i = 0; i < may.length; i++) {\n $(\"#oevents\" + i).html(\"<div class='month1'>May \" + may[i] + \":</div><div class='officialsclinics'>\" + Oclinicsmay[may[i]]+ \"</div>\");\n }\n counter = (may.length - 1); // adjust ids used for May clinics\n }\n // Display Officials Clinics in June ----------------------------\n for (var i = 0; i < june.length; i++) {\n counter ++;\n $(\"#oevents\" + counter).html(\"<div class='month1'>June \" + june[i] + \":</div><div class='officialsclinics'>\" + Oclinicsjune[june[i]]+ \"</div>\");\n }\n //delete unused cells ---------------------------------------------\n\n if (counter+1 <= 5) {\n\n for (var i = counter+1; i < 9; i++) {\n $(\"#oclinics\" + i).css('display', 'none');\n }\n }\n // add strike through when date passes\n var z = findEvent(date, june);\n if ((month === 4 && date > parseInt(may[may.length-1])) || month > 4) {\n for (var i = 0; i < may.length; i++) {\n $(\"#oevents\" + i).html(\"<s><div class='month1'>May \" + may[i] + \":</div><div class='officialsclinics'>\" + Oclinicsmay[may[i]]+ \"</div></s>\");\n }\n }\n if (month === 5 ) {\n counter = (may.length - 1);\n for (var i = 0; i < z; i++) {\n counter ++;\n $(\"#oevents\" + counter).html(\"<s><div class='month1'>June \" + june[i] + \":</div><div class='officialsclinics'>\" + Oclinicsjune[june[i]]+ \"</div></s>\");\n }\n }\n if (month === 5 && date > parseInt(june[june.length-1]) || month > 5) {\n counter = (may.length - 1);\n for (var i = 0; i <= june.length; i++) {\n counter ++;\n $(\"#oevents\" + counter).html(\"<s><div class='month1'>June \" + june[i] + \":</div><div class='officialsclinics'>\" + Oclinicsjune[june[i]]+ \"</div></s>\");\n }\n }\n}", "function fillCalendar() {\n console.log(\"inside the fill calendar\");\n // for (let i = 0; i < events.length; i++) {\n // console.log(events[i].title);\n // }\n let currentMonth = date.getMonth()+1;\n let dateComp = new Date(date.getFullYear()+yearCounter, currentMonth-1+monthCounter, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());\n let year = new Date(date.getFullYear()+yearCounter, currentMonth+monthCounter, 0).getFullYear();\n let month = new Date(date.getFullYear()+yearCounter, currentMonth+monthCounter, 0).getMonth();\n let numDaysInMonth = new Date(date.getFullYear()+yearCounter, currentMonth+monthCounter, 0).getDate();\n let monthStartingDay = new Date(date.getFullYear()+yearCounter, currentMonth+-1+monthCounter, 1).getDay();\n let numDaysLastMonth = new Date(date.getFullYear()+yearCounter, currentMonth+monthCounter-1, 0).getDate();\n let monthStartingDayCopy = monthStartingDay;\n let counter = 1;\n let counter2 = 0;\n let counter3 = 0;\n let counter4 = 1;\n //\n //prints month and year above calendar\n //\n $(\"#month\").html(`${months[month]}`);\n $(\"#year\").html(`${year}`);\n //\n //clears all day boxes on calendar\n //\n $(\".day-box\").html(\" \"); \n // while loop fills in boxes for last month\n // first for-loop fills in first row for curreny month\n // second for-loop fills in the rest of the rows for current month\n // third for-loop fills in the rest of the rows for next month\n while (counter2 < monthStartingDay) {\n $(`#c${counter2}`).append(`<span class=\"faded\">${numDaysLastMonth-monthStartingDayCopy+1}</span>`);\n counter2++;\n monthStartingDayCopy--;\n }\n for (let j = monthStartingDay; j < 7; j++) {\n $(`#c${j}`).append(`<span class=\"bold\">${counter}</span>`);\n for (let i = 0 ; i < events.length; i++) {\n //\n // If the current date is equal to the date generated by fillCalender()\n // then highlight current day's box to lightgreen using currentDay class\n //\n if (currentMonth + monthCounter == parseInt(events[i].startMonth) && counter == parseInt(events[i].startDay)) {\n $(`#c${j}`).append(`<p class=\"event ${events[i].tag}\">${events[i].startHour}:${events[i].startMinutes} ${events[i].title}</p>`);\n }\n }\n counter++;\n }\n for (let j = 7; counter <= numDaysInMonth; j++) {\n $(`#c${j}`).append(`<span class=\"bold\">${counter}</span>`);\n if (date.getMonth() == dateComp.getMonth() && date.getDate() == dateComp.getDate() && date.getFullYear() == dateComp.getFullYear()) {\n currentDayIDNum = date.getDate()-monthStartingDay+1;\n $(`#c${currentDayIDNum}`).find(\"span\").addClass(\"currentDay\");\n } else {\n $(`#c${currentDayIDNum}`).find(\"span\").removeClass(\"currentDay\");\n }\n for (let i = 0 ; i < events.length; i++) {\n // console.log(\"Event index: \" + i)\n if (currentMonth + monthCounter == parseInt(events[i].startMonth) && counter == parseInt(events[i].startDay)) {\n $(`#c${j}`).append(`<p class=\"event ${events[i].tag}\">${events[i].startHour}:${events[i].startMinutes} ${events[i].title}</p>`);\n }\n }\n counter++;\n counter3 = j+1;\n }\n for (j = counter3; j < 42; j++) {\n $(`#c${j}`).append(`<span class=\"faded\">${counter4}</span>`);\n counter3++;\n counter4++;\n }\n console.log(\"Outside fill calendar\");\n}", "function ChangeDate(sens) { \n if(sens === 2){//mois précédent\n monthIndex = monthIndex - 1;\n\n if(monthIndex < 0){\n monthIndex = 11;\n dataCalendar.year = dataCalendar.year - 1;\n } \n }\n\n if(sens === 1){//mois d'après\n monthIndex = monthIndex + 1;\n\n if(monthIndex >= 12){\n monthIndex = 0;\n dataCalendar.year = dataCalendar.year + 1;\n } \n \n }\n dataCalendar.monthNames = monthNames[monthIndex]; \n ResetCalendar(); \n InitCalendar();\n}", "function DisplaySchedule()\n{\nHTMLCode = \"<table cellspacing=0 cellpadding=3 border=3 bgcolor=purple bordercolor=#000033>\";\nQueryDay = DefDateDay(QueryYear,QueryMonth,QueryDate);\nWeekRef = DefWeekNum(QueryDate);\nWeekOne = DefWeekNum(1);\nHTMLCode += \"<tr align=center><td colspan=8 class=Titre><b>\" + MonthsList[QueryMonth] + \" \" + QueryYear + \"</b></td></tr><tr align=center>\";\n\nfor (s=1; s<8; s++)\n{\nif (QueryDay == s) { HTMLCode += \"<td><b><font color=#ff0000>\" + DaysList[s] + \"</font></b></td>\"; }\nelse { HTMLCode += \"<td><b>\" + DaysList[s] + \"</b></td>\"; }\n}\n\nHTMLCode += \"<td><b><font color=#888888>Sem</font></b></td></tr>\";\na = 0;\n\nfor (i=(1-DefDateDay(QueryYear,QueryMonth,1)); i<MonthLength[QueryMonth]; i++)\n{\nHTMLCode += \"<tr align=center>\";\nfor (j=1; j<8; j++)\n{\nif ((i+j) <= 0) { HTMLCode += \"<td>&nbsp;</td>\"; }\nelse if ((i+j) == QueryDate) { HTMLCode += \"<td><b><font color=#ff0000>\" + (i+j) + \"</font></b></td>\"; }\nelse if ((i+j) > MonthLength[QueryMonth]) { HTMLCode += \"<td>&nbsp;</td>\"; }\nelse { HTMLCode += \"<td>\" + (i+j) + \"</td>\"; }\n}\n\nif ((WeekOne+a) == WeekRef) { HTMLCode += \"<td><b><font color=#00aa00>\" + WeekRef + \"</font></b></td>\"; }\nelse { HTMLCode += \"<td><font color=#888888>\" + (WeekOne+a) + \"</font></td>\"; }\nHTMLCode += \"</tr>\";\na++;\ni = i + 6;\n}\n\nCalendrier.innerHTML = HTMLCode + \"</table>\";\n}", "function getSeasonName() {\n if (SEASONS.indexOf(SEASON) === SEASONS.length - 1) {\n return 'latest'\n } else {\n return SEASON\n }\n}", "function getSeasonName () {\n if (SEASONS.indexOf(SEASON) === SEASONS.length - 1) {\n return 'latest'\n } else {\n return SEASON\n }\n}", "function NumberDayShow(){\n var date = new Date(\"\"+dataCalendar.year+\"-\"+(monthIndex+1)+\"-01\"); \n return NumberDay(date.getDay())-1;//nombre de jour à afficher\n}", "getTitle() {\n return IsMorning(this.date) ? \"Sunrise - \" + this.date.toLocaleString() : \"Sunset - \" + this.date.toLocaleString();\n }", "function parseSched() {\n var schedule = {};\n var days = document.getElementsByClassName('current-day');\n\n // Here we'd iteratre through each day..\n\n var todaysDate = new Date();\n var dd = todaysDate.getDate();\n var mm = todaysDate.getMonth()+1; //January is 0!\n var yyyy = todaysDate.getFullYear();\n\n if(dd<10) {\n dd='0'+dd\n } \n\n if(mm<10) {\n mm='0'+mm\n } \n\n todaysDate = yyyy + \"/\" + mm+'/'+dd;\n\n var dates = [todaysDate];\n var datesMenu = document.getElementsByClassName('daytue');\n for (date in datesMenu) { \n if (parseInt(date)) { \n dates.push(datesMenu[date].getAttribute('data-ldate')) \n }\n };\n\n // var daysData = doc /ument.\n\n for (dateIndex in dates) {\n var day = days[dateIndex];\n var thisDate = dates[dateIndex]\n if (day != null) {\n console.log(\"day is ... \" + day )\n shows = day.getElementsByClassName('data');\n schedule[thisDate] = [];\n\n // now we'd iterate through the shows.\n for (i in shows) {\n show = {};\n s = shows[i];\n if (s.constructor.name == \"HTMLDivElement\") {\n console.log(\"Day: \" + day + \" - s is \" + s + \" A type...\" + s.constructor.name);\n minute = s.getElementsByClassName('minute')[0].innerHTML;\n hour = s.getElementsByClassName('hour')[0].innerHTML;\n dayhalf = s.getElementsByClassName('dayhalf')[0].innerHTML;\n if (dayhalf == \"pm\") {\n hour = (parseInt(hour) + 12);\n }\n show['airtime'] = new Date(hour + \":\" + minute + \":00 \" + thisDate); \n show['series'] = s.getElementsByClassName('name')[0].getElementsByTagName('span')[1].innerHTML.trim();\n show['episode'] = s.getElementsByClassName('name')[0].getElementsByTagName('span')[1].innerHTML.trim();\n schedule[thisDate].push(show);\n }\n }\n }\n }\n\n return schedule\n}", "numberCalendar() {\n \n // update this.monthInfo\n this.monthInfo.firstDayOfWeek = new Date (this.year, this.month, 1).getDay();\n this.monthInfo.daysLast = new Date (this.year, this.month, 0).getDate();\n this.monthInfo.daysThis = new Date (this.year + parseInt((this.month + 1) / 12), (this.month + 1), 0).getDate();\n \n // declare variable that will hold the day info\n var dateToDisplay;\n\n // get all of the day squares\n var daySquares = C('day-square');\n\n // loop through all of the day squares\n for (var i = 0; i < 42; i++) {\n\n // calculate the day with respect to the first of the month\n // not adjusted for month lengths (i.e. last month's dates are negative,\n // next month's dates start at [last day of this month] + 1)\n dateToDisplay = daySquares[i].children[0].innerHTML = i - this.monthInfo.firstDayOfWeek + 1;\n\n // adjust the date and day square if it is part of the previous month\n if (dateToDisplay <= 0) {\n dateToDisplay += this.monthInfo.daysLast;\n daySquares[i].classList.add('not-month');\n }\n \n // adjust the date and day square if it is part of the next month\n else if (dateToDisplay > this.monthInfo.daysThis) {\n dateToDisplay -= this.monthInfo.daysThis;\n daySquares[i].classList.add('not-month');\n }\n \n // make all other days have regular formatting\n else {\n daySquares[i].classList.remove('not-month');\n }\n\n // set dateToDisplay to be in the <p> tag of the proper daySquare\n daySquares[i].children[0].innerHTML = dateToDisplay;\n\n }\n\n // if the last week of the calendar is not needed, hide it\n if (O('last-sunday').classList.contains('not-month')) {\n O('last-week').classList.add('hidden');\n }\n\n // if the last week of the calendar is needed, show it\n else {\n O('last-week').classList.remove('hidden');\n }\n\n }", "function whichMonths(season) {\n let monthsInSeason;\n let enun;\n //DEPOIS DA ATIVIDADE USANDO ENUN EM VEZ DE SWITCH\n let Season;\n (function (Season) {\n Season[\"Fall\"] = \"September to November\";\n Season[\"Winter\"] = \"December to February\";\n Season[\"Spring\"] = \"March to May\";\n Season[\"Summer\"] = \"June to August\";\n })(Season || (Season = {}));\n /*\n ANTES DA ATIVADE\n \n switch (season) {\n case \"Fall\":\n monthsInSeason = \"September to November\";\n break;\n case \"Winter\":\n monthsInSeason = \"December to February\";\n break;\n case \"Spring\":\n monthsInSeason = \"March to May\";\n break;\n case \"Summer\":\n monthsInSeason = \"June to August\";\n }*/\n // return monthsInSeason;\n return Season.Fall;\n}", "function showEvents(month, year) {\n let events = Store.getEvents();\n if (events) {\n events.forEach((event) => {\n if (\n Number(event.date.slice(0, 2)) - 1 === month &&\n Number(event.date.slice(6)) === year\n ) {\n setEventBackground(event.date, event.url);\n }\n });\n }\n}", "function renderDate(){\n // Show current day\n var today = moment().format('Do MMMM YYYY');\n $(\".date0\").text(today);\n let dayArray = []\n for (i = 1 ; i < 5 ; i++){\n dayArray[i] = moment().add(i,'days').format('Do MMMM YYYY');\n $(\".date\"+i).text(dayArray[i]);\n }\n \n }", "function renderEvent () {\n const daysContainer = document.querySelectorAll(\".current-month-day\");\n const currentMonth = date.getMonth() + 1;\n const currentYear = date.getFullYear();\n //* Calendar days divs pass by\n for (let div of daysContainer) {\n const dayNumber = div.firstChild.innerHTML;\n //* checking that day has events\n if (!!eventsByDate[`${currentYear}-${currentMonth}-${dayNumber}`]) {\n //* Looping thru events in array\n for (let eventObjectId of eventsByDate[`${currentYear}-${currentMonth}-${dayNumber}`]){\n //* Access to event data\n const eventTitle = eventsById[eventObjectId].title;\n const eventType = eventsById[eventObjectId].eventType;\n //* Create of the event element\n let newEvent = document.createElement(\"div\");\n newEvent.classList.add(\"event-in-calendar\");\n newEvent.innerHTML = eventTitle;\n newEvent.setAttribute(\"divEventId\", eventObjectId);\n //* choosing event color depending of event type\n switch (eventType) {\n case 'Study':\n newEvent.classList.add(\"blue-event\");\n break;\n case 'Meeting':\n newEvent.classList.add(\"green-event\");\n break;\n case 'Personal':\n newEvent.classList.add(\"orange-event\");\n break;\n default:\n break;\n }\n newEvent.addEventListener('click', eventModal);\n //* Insert element in DOM\n div.firstChild.insertAdjacentElement('afterend',newEvent);\n }\n }\n }\n}", "function onLoad(){\r\n\r\n\t var d = new Date();\r\n\t var month_name = ['January','February','March','April','May','June','July','August','September','October','November','December'];\r\n\t var month = d.getMonth(); //0-11\r\n\t var year = d.getFullYear(); //2017\r\n\t var first_date = month_name[month] + \" \" + 1 + \" \" + year;\r\n\t //Nov 1 2017\r\n\t var tmp = new Date(first_date).toDateString();\r\n\t //Wed Nov 01 2017 ...\r\n\t var first_day = tmp.substring(0, 3); //Wed\r\n\t var day_name = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];\r\n\t var day_no = day_name.indexOf(first_day); //1\r\n\t var days = new Date(year, month+1, 0).getDate(); //30\r\n\t //Wed Nov 01 2017 ...\r\n\t var calendar = get_calendar(day_no, days);\r\n\t document.getElementById(\"calendar-month-year\").innerHTML = month_name[month]+\" \"+year;\r\n\t document.getElementById(\"calendar-dates\").appendChild(calendar);\r\n\t}", "function getSemesterName( season, year ) {\n return season + \" \" + year;\n}", "function updateTitleText(newDateArray) {\n if (!newDateArray) {\n title.text(\"NYC Crimes (select a time range)\");\n } else {\n var from = (newDateArray[0].getMonth() + 1) + \"/\" +\n (newDateArray[0].getDay() + 1) + \"/\" +\n newDateArray[0].getFullYear(),\n to = (newDateArray[1].getMonth() + 1) + \"/\" +\n (newDateArray[1].getDay() + 1) + \"/\" +\n newDateArray[1].getFullYear();\n title.text(\"NYC Crimes \" + from + \" - \" + to);\n }\n}", "function getNavigation(month, year) {\n if (language == 'lv-lv') {\n monthTitle = `<h2>${year}. gada ${months[month - 1]}</h2>`;\n } else {\n monthTitle = `<h2>${months[month - 1]} of ${year}</h2>`;\n }\n resultHTML = `<div class=\"pc-month-title\"><i id=\"prev_date\" class=\"fa fa-chevron-left\"></i>` +\n monthTitle +\n `<i id=\"next_date\" class=\"fa fa-chevron-right\"></i></div><div class=\"date-range\">` +\n getDateRange() + `</div>`;\n return resultHTML;\n}", "function printCalendar(year, month, iday, setdays) {\r\n var daysInMonth = getDaysInMonth(year, month + 1 ); // number of days\r\n var firstDayOfMonth = (new Date(year, month, 1)).getDay(); // 0-6 for Sun to Sat\r\n\r\n if(month > 11){\r\n month = 0;\r\n year++;\r\n }\r\ncMonth = getMonthByName(month);\r\n\r\n var tableInnerHTML = \"<caption class='heads'>\"+ year +\"</caption><caption>\"+ cMonth +\"</caption><tr><th class='heads'>Sun</th><th class='heads'>Mon</th><th class='heads'>Tue</th>\"\r\n + \"<th class='heads'>Wed</th><th class='heads'>Thu</th><th class='heads'>Fri</th><th class='heads'>Sat</th></tr>\";\r\n \r\n var tdCellCount = 0; // count of table's <td> cells\r\n var diasd = parseInt(iday);\r\n \r\n var setday = parseInt(setdays) -1;\r\n\r\n if ((isLeapYear(year)) && (month == 1)){\r\n daysInMonth = 29;\r\n } else if (month == 1){\r\n daysInMonth = 28;\r\n }\r\n \r\n if (firstDayOfMonth !== 0) { // Leave these cells blank\r\n tableInnerHTML += \"<tr><td colspan='\" + firstDayOfMonth + \"'></td>\";\r\n tdCellCount = firstDayOfMonth;\r\n }\r\n\r\n for (var day = 1 ; day <= daysInMonth; day++) {\r\n if (tdCellCount % 7 === 0) { // new table row\r\n tableInnerHTML += \"<tr>\";\r\n }\r\n if ((day < iday) || (day > diasd + setday )){\r\n tableInnerHTML += \"<td class ='disa'>\" + day + \"</td>\";\r\n } else if (day == 1){\r\n tableInnerHTML += \"<td class='firstday'>\" + day + \"</td>\";\r\n } else if ((tdCellCount % 7 === 0) || (tdCellCount % 7 === 6)){\r\n tableInnerHTML += \"<td class='weekend'>\" + day + \"</td>\";\r\n } else {\r\n tableInnerHTML += \"<td class='week'>\" + day + \"</td>\";\r\n } \r\n\r\n tdCellCount++;\r\n if (tdCellCount % 7 === 0) {\r\n tableInnerHTML += \"</tr>\";\r\n }\r\n }\r\n // print the remaining cells and close the row\r\n var remainingCells = 7 - tdCellCount % 7;\r\n if (remainingCells < 7) {\r\n tableInnerHTML += \"<td colspan='\" + remainingCells + \"'></td></tr>\";\r\n }\r\n\r\n var node = document.createElement(\"TABLE\"); \r\n var linebreak = document.createElement(\"p\");\r\n\r\n node.innerHTML = tableInnerHTML; \r\n linebreak.innerHTML = \" <br>Continue...<br><br> \";\r\n\r\n if (diasd + setday >daysInMonth){\r\n \r\n day = diasd + setday - daysInMonth; \r\n\r\n document.getElementById(\"tableCalendar\").appendChild(node); \r\n document.getElementById(\"tableCalendar\").appendChild(linebreak);\r\n printCalendar(year, month + 1, 1,day);\r\n\r\n } else {\r\n document.getElementById(\"tableCalendar\").appendChild(node);\r\n }\r\n\r\n}", "function init(month, year) {\n monthDisplay.innerHTML = `${monthList[month]}, ${year}`; \n populateCalender();\n}", "function createCalendar() {\n addCalendar();\n displayDates();\n}", "function getSeasonDetails() {\n let episodesDetails = [];\n episodesList._embedded?.episodes.forEach(episode => {\n if (episode.season == selectedSeason) {\n let details = {\n episodeTitle: '',\n episodeNumber: 0,\n episodeAirDate: ''\n };\n details['episodeTitle'] = episode?.name;\n details['episodeNumber'] = episode?.number;\n details['episodeAirDate'] = episode?.airdate;\n episodesDetails.push(details);\n }\n });\n\n return (\n <div className=\"episodes-container\">\n <div className=\"show-details-container\">\n <div class=\"img-container\"><img src={episodesList.image?.medium ? `${episodesList.image?.medium}` : null} alt=\"\"></img></div>\n <h3>{episodesList.name}</h3>\n <p>{episodesList.summary}</p>\n <p>Creator:{episodesList._embedded?.crew.find(current => current.type == 'Producer')?.person.name}</p>\n <p>Cast:{episodesList._embedded?.cast.find(current => current.type == 'Producer')?.person.name}</p>\n </div>\n\n {episodesDetails.map(episodeDetail => {\n return (\n <div className=\"episode\" id={episodeDetail.id}>\n <div className=\"episode-container__left-block\">{episodeDetail.episodeNumber}</div>\n <div className=\"episode-container__right-block\">\n <div className=\"episode-title\">{episodeDetail.episodeTitle}</div>\n <div className=\"episode-rating-airdate\">{`${episodeDetail.episodeAirDate} | 7.5 `}</div>\n </div>\n </div>\n )\n })\n }\n </div>\n );\n }", "function relatedEssays(data) {\n var contentES = '<div class=\"related-essays\">';\n\n $.each(data.descriptions, function(rInd, rElm) {\n var monthNames = [ \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\" ];\n var createdDate = new Date(Date.parse(rElm.created_at));\n var showDate = monthNames[createdDate.getMonth()] + ' ' + createdDate.getDate() + ', ' + createdDate.getFullYear();\n contentES += '<h6>' + rElm.title + ' <small>by ' + rElm.author.fullname + ' (' + showDate + ')</small>' + '</h6>';\n contentES += rElm.content;\n });\n\n contentES += '</div>';\n\n $(\"#tab-essays\").append(contentES);\n\n}", "function display() {\n var thisDay = today.getDay();// lấy thứ theo số thứ tự của mảng 0-6, lưu giá trị hiển thị\n var thisMonth = today.getMonth();// lấy tháng theo index 0-11, lưu giá trị hiển thị\n var thisYear = today.getFullYear();// lấy năm đủ 4 chữ số, lưu giá trị hiển thị\n var thisDate = today.getDate();// lấy ra ngày 1-31, lưu giá trị hiển thị\n var nowDate = now.getDate();// lay ngay\n console.log(nowDate);\n var nowMonth = now.getMonth();// lay thang\n var nowYear = now.getFullYear();// lay nam\n var text = \"\";\n\n if (nowYear % 4 == 0) month_day[1]=29;\n console.log(nowYear);\n var first_date = new Date(thisYear, thisMonth, 1);// trả về kết quả đầy đủ h, ngày 1 tháng năm ở thời điểm được trỏ tới\n var first_day = first_date.getDay();// trả về thứ của ngày mùng 1 = so\n console.log(first_day);\n title = month_name[thisMonth] + ' ' + thisYear;\n document.getElementById('title').innerHTML = title;\n text += '<table border = 2 style=\"height: 300px;width: 440px;\">';\n text += '<tr><td style=\"color: orangered;\">' + \"Sunday\" + '</td><td style=\"color: orangered;\">' + \"Monday\" + '</td><td style=\"color: orangered;\">' + \"Tuesday\" + '</td><td style=\"color: orangered;\">' + \"Wednesday\" + '</td><td style=\"color: orangered;\">' + \"Thursday\" + '</td><td style=\"color: orangered;\">' + \"Friday\" + '</td><td style=\"color: orangered;\">' + \"Saturday\" + '</td></tr>';\n text+='<tr>';\n for (i = 0; i < first_day; i++) {\n console.log(i);\n console.log(first_day);\n text += \"<td> </td>\";\n }\n date = 1;\n while (date <= month_day[nowMonth]){\n for (j = first_day; j < 7; j++) {\n if ( date <= month_day[thisMonth]){\n if (nowDate == date && nowMonth == thisMonth && nowYear == thisYear){\n text +='<td id = \"nowDate\"><b style=\"color: orangered;\">' + date + '</b></td>';\n }else {\n text +='<td class = \"date\">' + date + '</td>';\n }\n } else {\n text += \"&nbsp\";\n }\n date++;\n }\n text += '</tr>';\n first_day = 0;\n }\n text += '</table>';\n document.getElementById(\"display\").innerHTML = text;\n}", "function visData(){\r\n\tvar days=new Array(\"Domenica\",\"Luned&igrave;\",\"Marted&igrave;\",\"Mercoled&igrave;\",\"Gioved&igrave;\",\"Venerd&igrave;\",\"Sabato\");\r\n\tvar months=new Array(\"Gennaio\",\"Febbraio\",\"Marzo\",\"Aprile\",\"Maggio\",\"Giugno\",\"Luglio\",\"Agosto\",\"Settembre\",\"Ottobre\",\"Novembre\",\"Dicembre\");\r\n\tvar dateObj=new Date();\r\n\tvar lmonth=months[dateObj.getMonth()];\r\n\tvar anno=dateObj.getFullYear();\r\n\tvar date=dateObj.getDate();\r\n\tvar wday=days[dateObj.getDay()];\r\n\tdocument.write(\" \" + wday + \" \" + date + \" \" + lmonth + \" \" + anno);\r\n}", "function Season() {\n return <h2>Ummm, I am also a Season!</h2>;\n}", "function calendar() {\n var monthNames = [\"Январь\", \"Февраль\", \"Март\", \"Апрель\", \"Май\", \"Июнь\", \"Июль\", \"Август\", \"Сентябрь\", \"Октябрь\", \"Ноябрь\", \"Декабрь\"];\n\n var dayNames = [\"Пн\", \"Вт\", \"Ср\", \"Чт\", \"Пт\", \"Сб\", \"Вс\"];\n\n var events = [\n {\n date: \"8/3/2013\",\n title: 'Двойной заказ',\n link: '',\n linkTarget: '_blank',\n color: '',\n //content: 'Два заказа, один на выезде, другой в городе ',\n class: 'tripleOutdore',\n displayMonthController: true,\n displayYearController: true,\n nMonths: 6\n }\n ];\n\n $('#calendari_lateral1').bic_calendar({\n //list of events in array\n events: events,\n //enable select\n enableSelect: true,\n //enable multi-select\n multiSelect: false, //set day names\n dayNames: dayNames,\n //set month names\n monthNames: monthNames,\n //show dayNames\n showDays: true,\n //show month controller\n displayMonthController: true,\n //show year controller\n displayYearController: false,\n //set ajax call\n reqAjax: {\n type: 'get',\n url: 'http://fierydream.com/js/someJSON/events.json'\n }\n });\n }", "function monthdisplay(){\n\tvar td0 = getElementsByClassName(document, \"table\", \"wp-calendar\");\n\tfor(j=0;j<td0.length;j++){\n\t\tvar td1 = td0[j].getElementsByTagName('td');\n\t\tfor(i=0;i<td1.length;i++){\n\t\t\tvar listevent = td1[i].getElementsByTagName('li');\n\t\t\tif(listevent.length != 0){\n\t\t\t\tif (listevent.length > 4){\n\t\t\t\t\tvar how_many_more = listevent.length - 4;\n\t\t\t\t\tfor( var d=4; d<listevent.length; d++){\n\t\t\t\t\t\tlistevent[d].style.display = 'none';\n\t\t\t\t\t}\n\t\t\t\t\tcreateButton(\"+\"+how_many_more+\" more\", td1[i], showMoreEvents, \"more_event\");\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcreateButton(\"full view\", td1[i], showMoreEvents, \"more_event\");\n\t\t\t\t}\n\t\t\t\tfor (k=0;k<listevent.length;k++){\n\t\t\t\tvar listText = listevent[k].getElementsByTagName('a');\n\t\t\t\t\tfor(x=0; x<listText.length; x++){\n\t\t\t\t\t truncate(listText[x], '12');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function displayDate() {\n var currentDay = new Date();\n var month;\n var date = currentDay.getDate();\n var year = currentDay.getFullYear();\n \n switch (currentDay.getMonth()) {\n case 0:\n month = \"January\";\n break;\n case 1:\n month = \"February\";\n break;\n case 2:\n month = \"March\";\n break;\n case 3:\n month = \"April\";\n break;\n case 4:\n month = \"May\";\n break;\n case 5:\n month = \"June\";\n break;\n case 6:\n month = \"July\";\n break;\n case 7:\n month = \"August\";\n break;\n case 8:\n month = \"September\";\n break;\n case 9:\n month = \"October\";\n break;\n case 10:\n month = \"November\";\n break;\n case 11:\n month = \"December\";\n break;\n }\n var dateDiv = document.getElementById('date');\n dateDiv.innerText = month + \" \" + date + \", \" + year;\n }", "function createDemoEvents() {\n // Date for the calendar events (dummy data)\n var date = new Date();\n var d = date.getDate(),\n m = date.getMonth(),\n y = date.getFullYear();\n\n return [\n {\n title: 'All Day Event',\n start: new Date(y, m, 1),\n backgroundColor: '#f56954', //red \n borderColor: '#f56954' //red\n },\n {\n title: 'Long Event',\n start: new Date(y, m, d - 5),\n end: new Date(y, m, d - 2),\n backgroundColor: '#f39c12', //yellow\n borderColor: '#f39c12' //yellow\n },\n {\n title: 'Meeting',\n start: new Date(y, m, d, 10, 30),\n allDay: false,\n backgroundColor: '#0073b7', //Blue\n borderColor: '#0073b7' //Blue\n },\n {\n title: 'Lunch',\n start: new Date(y, m, d, 12, 0),\n end: new Date(y, m, d, 14, 0),\n allDay: false,\n backgroundColor: '#00c0ef', //Info (aqua)\n borderColor: '#00c0ef' //Info (aqua)\n },\n {\n title: 'Birthday Party',\n start: new Date(y, m, d + 1, 19, 0),\n end: new Date(y, m, d + 1, 22, 30),\n allDay: false,\n backgroundColor: '#00a65a', //Success (green)\n borderColor: '#00a65a' //Success (green)\n },\n {\n title: 'Open Google',\n start: new Date(y, m, 28),\n end: new Date(y, m, 29),\n url: '//google.com/',\n backgroundColor: '#3c8dbc', //Primary (light-blue)\n borderColor: '#3c8dbc' //Primary (light-blue)\n }\n ];\n }", "function getSeasons(episodesList) {\n let seasons = [];\n episodesList[0]._embedded.episodes.forEach(episode => {\n if (!seasons.includes(episode.season)) {\n seasons.push(episode.season);\n }\n })\n return seasons;\n }", "function runDate() {\n\t\tvar el = document.getElementsByClassName(\"date-span\");\n\t\t// var dateString = get_Date();\n\t\tvar dateString = getSmallDate();\n\t\tfor(var i in el) {\n\t\t\tel[i].innerHTML = \" \" + dateString;\n\t\t}\n\t}", "function formatEpisodeSeason(value) {\n if (value > 0 && value <= 9) {\n if (value.includes('0')) {\n value = `${parseInt(value)}`;\n }\n value = `0${value}`;\n } else {\n while (value.substring(0, 1) === '0') {\n value = value.substring(1, value.length);\n }\n }\n return value;\n}", "function renderDate() {\n // The class name \"content\" does not have any relevance for our js file, and is only used for creating overview of the div section.\n\n dt.setDate(1);\n// set.Date is a javascript function we use so the date is equal to the weekday. We use the parameter (1) because (0) is equal to the first day of the last month, and we want to get the first day of this month.\n// (\"JavaScript setDate\" s.d)\n var day = dt.getDay();\n\n // this is consoled log, so we can see how many dates from last month we have.\n console.log(dt.getDay());\n\n var endDate = new Date(\n dt.getFullYear(),\n dt.getMonth()+1,0\n ).getDate();\n\n // Test, where we should get the last day of the month. That happens because we in getMonth use +1 besides the parameter, and furthermore use 0 which represents the last day of the last month.\n // This object constructor will also be relevant in a later for loop.\n console.log(endDate);\n\n var prevDate = new Date(\n dt.getFullYear(),\n dt.getMonth(),0).getDate();\n// This variable refers to the HTML arrow symbol and the function executes with an onClick. We use date:0; because that is the last month\n var today = new Date();\n console.log(today);\n // This console log consoles the date of today via a javascript method\n // We declare this variable because we want to use it in or for loop, that via HTML should print all the dates of the month.\n console.log(prevDate);\n // Here we test that the prevDate we just created is the last day of the last month.\n\n// But firstly an array of all the months.\n var months = [\"January\",\"February\",\"March\",\"April\",\"May\", \"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"];\n\n// We here use a object constructor function, which prints the date to our paragraph in html.\n// \"\"JaveScript | date.toDateString\" s.d)/\n document.getElementById(\"date_str\").innerHTML = 1 + \"/\" + (dt.getMonth() + 1) + \"/\" + dt.getFullYear();\n\n// We use our dt variable new date to get the month.\n document.getElementById(\"month\").innerHTML = months[dt.getMonth()];\n\n cells = \"\";\n\n for(x = day; x > 0; x--){\n cells += \"<div class='prev_date'>\" + (prevDate - x + 1) + \"</div>\";\n }\n\n// This for loop connects with our div class \"'prev_date\" it starts out by saying our previous date, which is the last day of the last month=30. Then it says - x = the days that is represented from last month. It then plus with 1 so we get 29, and the loop repeats.\n\n// This for loop is for all the days of the relevant month. We again use a for loop, ad break out of the loop when i is less than our equal to the last day of the month\n\n for (i = 1; i <= endDate; i++){\n if(i == today.getDate() && dt.getMonth() == today.getMonth()){\n //var newDate = \"day\" + i;\n cells += \"<div class='day' id ='\" + i + \"' value ='\" + i + \"'>\" + i + \"</div>\";\n\n } else{\n\n cells += \"<div class='day' id ='\" + i + \"' value ='\" + i + \"'>\" + i + \"</div>\";\n\n// If the date is not equal to today's date, we use the conditional else statement, until we hit todays date. Then the if statement will be used. The break happens at the endDate\n\n }\n }\n\n // Here we use innerHTML to print the cells we have declared above, in the user interface.\n document.getElementsByClassName(\"days\")[0].innerHTML = cells;\n one++;\n console.log( \"første tæller\" + one)\n // add onclick functions to every day with addDateChecker();\n addDateChecker();\n}", "function renderDay() {\n currentDay.innerHTML = `<h1>${moment().format('MMMM Do YYYY, h:mm:ss a')}</h1>`\n setInterval(renderDay, 1000);\n}", "function printHolidays(date){\r\n // chiamata al server del calendario 2018\r\n $.ajax(\r\n {\r\n \"url\": \"https://flynn.boolean.careers/exercises/api/holidays?year=2018&month=0\",\r\n \"data\": {\r\n \"year\": 2018,\r\n \"month\": date.format(\"M\")-1\r\n },\r\n \"method\": \"GET\",\r\n \"success\": function(data){\r\n var holidays = data.response;\r\n for (var i = 0; i < holidays.length; i++) {\r\n var holidaysDate = holidays[i].date;\r\n var holidaysName = holidays[i].name;\r\n\r\n $(\".day[data-date = '\"+ holidaysDate +\"']\").addClass(\"redHoliday\");\r\n $(\".day[data-date = '\"+ holidaysDate +\"'] span\").text(holidaysName);\r\n }\r\n },\r\n \"error\": function(){\r\n alert(\"Errore!\");\r\n }\r\n }\r\n );\r\n}", "function generateYear(year) {\r\n var h2 = document.createElement(\"h2\");\r\n h2.innerText = year;\r\n calendar.appendChild(h2);\r\n for (var i = 0; i < monthDays.length; i++) {\r\n calendar.appendChild(generateMonth(i, year));\r\n }\r\n if (calendarData[year] === undefined) {\r\n calendarData[year] = { colors: {}, text: {} };\r\n }\r\n}", "function showCalendar() {\n loadDropdownContent();\n $('#login-logo').hide();\n $('nav').show();\n\n // show calendar section\n $('section').hide();\n $('nav li').removeClass('active');\n $('#reservation-content input').val('');\n $(CALENDAR_NAVLINK).addClass('active');\n $(CALENDAR_CONTENT).show();\n $(TIMETABLE_CONTENT).show();\n}", "function printCalendar(year = defaultYearValue, month = defaultMonthValue) { //set defaults for parameters to today's year and date if not provided\n var thisDate = new Date (year, month);\n var thisYear = thisDate.getFullYear();\n var thisMonth = thisDate.getMonth();\n var dateValue = thisDate.getDate(); //returns 1-31\n var dayValue = thisDate.getDay(); //returns 0-6\n var firstDate = new Date(year, month, 1);\n var firstDayValue = firstDate.getDay(); //to know which day on first row to start on\n var numberOfDaysInMonth = new Date(year, month + 1, 0).getDate();\n\n /*console.log(\"month in print cal: \" + month);\n console.log(\"year in print cal: \" + year);*/\n\t\n /*Print moth name & year*/\n document.getElementById(\"monthLabel\").innerHTML = monthNameArray[month];\n document.getElementById(\"yearLabel\").innerHTML = thisYear;\n /*Add an extra row to table if needed*/\n if(numberOfDaysInMonth + firstDayValue > 35){\n \tvar row = table.insertRow(6);\n \tvar cellIdBase = parseInt(35, 10);\n \tvar numberCellsToAdd = (numberOfDaysInMonth + firstDayValue) - 35;\n \tfor (var i=0; i< numberCellsToAdd; i++){\n \t\tvar newCellId = cellIdBase + i;\n \t\trow.insertCell(i).setAttribute(\"id\", \"c\" + newCellId);\n \t}\n }\n /*Populate calendar dates*/\n var i=0;\n do {\n document.getElementById(\"c\" + firstDayValue).innerHTML = i+1;\n dateHolder.push(i+1);\n i++;\n firstDayValue++;\n } while (i<numberOfDaysInMonth);\n}", "function displayTvList() {\n $.ajax({\n url: `http://api.tvmaze.com/shows/${$show_id}/seasons`,\n type: \"GET\",\n dataType: \"json\",\n }).done(function (response) {\n\n $season_number.text(`Seassons (${response.length})`);\n response.forEach(element => {\n if (element.premiereDate !== null && element.endDate !== null) {\n $show_list.append(`<li>${element.premiereDate} - ${element.endDate}</li>`);\n } else {\n $show_list.append(`<li>TBD</li>`);\n }\n\n });\n\n });\n\n}", "function updateCalendar(){\r\n\tlet weeks = currentMonth.getWeeks();\r\n\tlet dayArray=[];\r\n\tlet arrayIndex=0;\r\n\tlet previous=0;\r\n\t\r\n\tfor(var w in weeks){\r\n\t\tlet days = weeks[w].getDates();\r\n\t\t// days contains normal JavaScript Date objects.\r\n\t\t\r\n\t\t//alert(\"Week starting on \"+days[0]);\r\n\t\t\r\n\t\tfor(var d in days){\r\n\t\t\tlet str= days[d].toString();\r\n\t\t\tlet strSplit=str.split(\" \");\r\n\t\t\t\r\n\t\t\tconsole.log(parseInt(strSplit[2]));\r\n\t\t\t\r\n\t\t\tif (parseInt(strSplit[2])-1 == previous)\r\n\t\t\t{\r\n\t\t\t\tdocument.getElementById(arrayIndex.toString()).innerText=parseInt(strSplit[2]);\r\n\t\t\t\tprevious++;\r\n\t\t\t}\r\n\t\t\tarrayIndex++;\r\n\t\t\t// You can see console.log() output in your JavaScript debugging tool, like Firebug,\r\n\t\t\t// WebWit Inspector, or Dragonfly.\r\n\t\t}\r\n\t}\r\n}", "function display_month(data_moment){\n //svuoto il calendario\n $('#calendario').empty();\n\n //clono l'oggetto moment per usarlo per il data-day\n var date = data_moment.clone();\n\n //numero giorni del mese da visualizzare\n var days_of_month = date.daysInMonth();\n //mese testuale\n var text_month = date.format('MMMM');\n text_month = text_month.charAt(0).toUpperCase() + text_month.slice(1);\n //giorno della settimana in numero\n var day_of_week = date.day();\n //mese in numero\n var month = date.month();\n //anno in numero\n var year = date.year();\n\n //popolo dinaminamente il mese che appare come titolo\n $('#current_month').text(text_month);\n\n //devo stampare dei li vuoti per i giorni mancanti dall'inizio\n display_empty_block(day_of_week);\n //devo stampare i giorni\n display_days(days_of_month, date);\n //richiamo funzione per stampare le festività\n display_holiday(start_moment);\n }", "function calendar(){\n var dateobj=document.getElementById('calendar').value;\n var dateobj= new Date(dateobj);\n var month = dateobj.getMonth() + 1;\n var year = dateobj.getFullYear();\n var day = dateobj.getDate()+1;\n console.log(month);\n console.log(year);\n console.log(day);\nvar montharray = ['January','February','March','April','May','June','July','August','September','October','November','December'];\nvar month1 = dateobj.getMonth();\nif(month1 ==0){\n month1 = montharray[0];\n console.log(month1);\n}\nelse if(month1 ==1){\n month1 = montharray[1];\n console.log(month1);\n}\nelse if(month1 ==2){\n month1 = montharray[2];\n console.log(month1);\n}\nelse if(month1 ==3){\n month1 = montharray[3];\n console.log(month1);\n}\nelse if(month1 ==4){\n month1 = montharray[4];\n console.log(month1);\n}\nelse if(month1 ==5){\n month1 = montharray[5];\n console.log(month1);\n}\nelse if(month1 ==6){\n month1 = montharray[6];\n console.log(month1);\n}\nelse if(month1 ==7){\n month1 = montharray[7];\n console.log(month1);\n}\nelse if(month1 ==8){\n month1 = montharray[8];\n console.log(month1);\n}\nelse if(month1 ==9){\n month1 = montharray[9];\n console.log(month1);\n}\nelse if(month1 ==10){\n month1 = montharray[10];\n console.log(month1);\n}\nelse if(month1 ==11){\n month1 = montharray[11];\n console.log(month1);\n}\nelse if(month1 ==12){\n month1 = montharray[12];\n console.log(month1);\n}\n\nif (year > 2020 || year < 2019){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" falls outside the range of dates for which data is available.\";\n}\nelse if (year==2019 && month>=1 && month<=8){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" falls outside the range of dates for which data is available.\";\n}\nelse if(year==2020 && month>8){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" falls outside the range of dates for which data is available.\";\n}\nelse if(month<9 && year==2019){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" falls outside the range of dates for which data is available.\";\n }\n else{\n console.log('valid');\n if(month>8 && year==2020){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" falls outside the range of dates for which data is available.\";\n }\n else {\n console.log('valid');\n }\n if(month==9){\n if(day==2){\n document.getElementById('output').innerHTML = \"September 2, 2019 is Labor Day. This is an NYU Holiday. No Classes Scheduled.\";\n document.images[4].src=\"img/laborday.jpg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://www.grammarly.com/blog/why-do-we-call-it-labor-day/]\"\n }\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n }\n else if(month==10){\n if(day==14){\n document.getElementById('output').innerHTML = \"October 14, 2019 is Fall Recess. This is an NYU Holiday. No classes scheduled.\";\n document.images[4].src=\"img/fallrecess.jpg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://www.swedesboro-woolwich.com/site/default.aspx?PageType=3&ModuleInstanceID=5611&ViewID=7b97f7ed-8e5e-4120-848f-a8b4987d588f&RenderLoc=0&FlexDataID=10845&PageID=1]\"\n }\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\"\n }\n }\n else if(month==11){\n if(day==27){\n document.getElementById('output').innerHTML = \"November 27, 2019 is Thanksgiving Recess. No Classes Scheduled.\";\n document.images[4].src=\"img/thanksgiving.jpg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://www.theholidayspot.com/thanksgiving/]\"\n }\n else if(day == 28 || day == 29){\n document.getElementById('output').innerHTML = \"November \"+day+\", 2019 is Thanksgiving Recess. This is an NYU Holiday. No Classes Scheduled. \";\n document.images[4].src=\"img/thanksgiving.jpg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://www.theholidayspot.com/thanksgiving/]\"\n }\n else {\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\"\n }\n }\n else if(month==12){\n if(day>20 && day<32){\n document.getElementById('output').innerHTML = \"December \"+day+ \", 2019 is Winter Recess. This is an NYU Holiday. No Classes Scheduled\";\n document.images[4].src=\"img/winter.png\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://www.smoothusa.com/2018/12/21/winter-recess-has-begun/]\"\n }\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\"\n\n }\n }\n else if(month==1){\n if(day==1){\n document.getElementById('output').innerHTML = \"January 1, 2019 is Winter Recess. This is an NYU Holiday. No Classes Scheduled.\";\n document.images[4].src=\"img/winter.png\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://www.smoothusa.com/2018/12/21/winter-recess-has-begun/]\"\n }\n else if(day>1 && day<6){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is Winter Recess. However, the University is open. No Classes Scheduled.\";\n document.images[4].src=\"img/winter.png\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://www.smoothusa.com/2018/12/21/winter-recess-has-begun/]\"\n }\n else if(day==20){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is Martin Luther King Day. This is an NYU Holiday. No Classes Scheduled.\";\n document.images[4].src=\"img/mlk.jpg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://wpde.com/news/local/martin-luther-king-jr-day-local-events]\"\n }\n\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n }\n else if (month==2){\n if(day==17){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+ \" is President's Day. This is an NYU Holiday. No Classes Scheduled.\";\n document.images[4].src=\"img/presidents.jpeg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://www.wflx.com/2019/02/18/heres-what-is-open-closed-presidents-day/]\"\n\n }\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n }\n else if (month==3){\n if (day>15 && day<23){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is Spring Break. No Classes Scheduled.\";\n document.images[4].src=\"img/spring.png\";\n document.getElementById('output2').innerHTML = \"[Image obtained from http://clipart-library.com/spring-break-cliparts.html]\"\n\n }\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n\n }\n else if (month==4){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n else if (month==5){\n if (day ==25){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is Memorial Day. This is an NYU holiday. No classes scheduled.\";\n document.images[4].src=\"img/memorial.jpeg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from http://mentalfloss.com/article/27858/10-things-remember-about-memorial-day]\"\n\n }\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n }\n else if (month==6){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n else if (month==7){\n if (day==3){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is the observance of Independence Day. This is an NYU holiday. No classes scheduled.\";\n document.images[4].src=\"img/independence.jpg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://kvoa.com/news/local-news/2019/07/04/list-of-4th-of-july-events/]\"\n\n }\n else if (day==4){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is Independence Day.\";\n document.images[4].src=\"img/independence.jpg\";\n document.getElementById('output2').innerHTML = \"[Image obtained from https://kvoa.com/news/local-news/2019/07/04/list-of-4th-of-july-events/]\"\n\n }\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n }\n else if (month==8){\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n else{\n document.getElementById('output').innerHTML = month1+\" \"+day+\", \"+year+\" is not a school holiday at NYU.\";\n }\n }\n\n }", "displaySchedule(schedule) {\n // helper-function: add leading Zero to Numbers < 10\n function addZero(i) {\n if (i < 10) {\n i = \"0\" + i;\n }\n return i;\n }\n\n let today = new Date();\n let target = document.querySelector(\"#wrapper\");\n let dayNames = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\n let tempDay = -1;\n // for each entry\n for (let i in schedule) {\n // get start & end Date\n let start = new Date(parseInt(schedule[i].start) * 1000);\n let end = new Date(parseInt(schedule[i].end) * 1000);\n\n // if course is in the past -> skip\n if (\n start.getDate() < today.getDate() &&\n start.getMonth() < today.getMonth() &&\n start.getFullYear() <= today.getFullYear()\n ) {\n console.log(\n start.getDate(),\n today.getDate(),\n start.getMonth(),\n today.getMonth()\n );\n console.log(\"skip\");\n continue;\n }\n\n let dayforAriaLabel = \"\";\n // insert once per Day\n if (tempDay == -1 || tempDay != start.getDate()) {\n if (\n start.getDate() == today.getDate() &&\n start.getMonth() == today.getMonth() &&\n start.getFullYear() == today.getFullYear()\n ) {\n target.innerHTML += `\n <div class=\"schedule_day\">TODAY!</div>\n `;\n dayforAriaLabel = \"Today\";\n } else {\n target.innerHTML += `\n <div class=\"schedule_day\">${start.getDate()}.${start.getMonth() + 1} - ${dayNames[start.getDay()]}</div>\n `;\n\n dayforAriaLabel = `${dayNames[start.getDay()]} the ${start.getDate()}.${start.getMonth() + 1}`;\n }\n\n tempDay = start.getDate();\n }\n\n // Template\n target.innerHTML += `<div class=\"entry\" tabindex=\"0\" aria-label=\"${dayforAriaLabel}, ${schedule[i].title} in Room ${schedule[i].location} with ${schedule[i].lecturer} from ${addZero(start.getHours())}:${addZero(start.getMinutes())} to ${addZero(end.getHours())}:${addZero(end.getMinutes())}\">\n <div class=\"time\">\n ${addZero(start.getHours())}:${addZero(start.getMinutes())} - ${addZero(end.getHours())}:${addZero(end.getMinutes())}\n </div>\n <div class=\"detail\">\n ${schedule[i].title} / ${schedule[i].type} / ${schedule[i].lecturer} / ${schedule[i].location}\n </div>\n </div>\n `;\n }\n }", "updateCalendar() {\n /*\n get the correct month\n number the calendar\n get future events\n * show the events\n highlight current date\n */\n\n this.updateMonth();\n this.updateYear();\n this.numberCalendar();\n this.highlightToday();\n this.updateEvents();\n }", "async function getCurrentSeasonDate(){\n const league_details = await axios.get(\n `https://soccer.sportmonks.com/api/v2.0/leagues/${league_utils.LEAGUE_ID}`,\n {\n params: {\n include: \"season\",\n api_token: process.env.api_token,\n },\n }\n );\n \n let current_season_date = league_details.data.data.season.data.name.split(\"/\");\n return current_season_date.map(date => {return parseInt(date)}) \n }", "function changeMonth(direction, currentMonth){\n // changing month/year value\n //document.getElementById(\"month_year_label\").textContent = currentMonth.month + \" \" + currentMonth.year;\n\n if (direction == \"next\"){\n currentMonth = currentMonth.nextMonth();\n updateCalendar();\n\n } else if (direction == \"previous\"){\n currentMonth = currentMonth.prevMonth();\n updateCalendar();\n\n } else{\n updateCalendar();\n }\n\n function getMonthName(month_num){\n switch(month_num){\n case 0:\n return \"January\";\n break;\n case 1:\n return \"February\";\n break;\n case 2:\n return \"March\";\n break;\n case 3:\n return \"April\";\n break;\n case 4:\n return \"May\";\n break;\n case 5:\n return \"June\";\n break;\n case 6:\n return \"July\";\n break;\n case 7:\n return \"August\";\n break;\n case 8:\n return \"September\";\n break;\n case 9:\n return \"October\";\n break;\n case 10:\n return \"November\";\n break;\n case 11:\n return \"December\";\n break;\n }\n }\n\n // update the calendar whenever we need to\n // sorry bout it\n function updateCalendar(){\n \tvar weeks = currentMonth.getWeeks();\n\n var x = getMonthName(currentMonth.month);\n\n document.getElementById(\"month_year_label\").textContent = x + \" \" + currentMonth.year;\n\n\n\n //console.log(currentMonth.month);\n console.log(\"pressed\");\n\n \tfor(var w in weeks){\n //days is an array with each day in a week\n \t var days = weeks[w].getDates();\n var week_number = parseInt(w);\n //console.log(w);\n var week_id = \"week-\" + week_number;\n //console.log(week_id);\n \t// days contains normal JavaScript Date objects.\n //console.log()\n var week1_node = document.getElementById(week_id).getElementsByClassName(\"calendar-day\");\n\n \t\tfor(var d in days){\n\n \t\t\t// You can see console.log() output in your JavaScript debugging tool, like Firebug,\n \t\t\t// WebWit Inspector, or Dragonfly.\n // for(int i = 0; i < week1_node.childNodes.length-1; i++){\n week1_node[d].innerHTML = \"<div class='month-day-calendar' value=\" + days[d].getDate() + \"> <div>\" + days[d].getDate() + \"</div></div>\";\n week1_node[d].setAttribute(\"value\", days[d]);\n //week1_node.childNodes[7].textContent = d;\n\n // }\n \t\t\t//console.log(days[d].toISOString());\n \t\t}\n\n \t}\n // if 6 weeks (0-5 weeks) (length = 6) update everything, else 5 weeks (0-4 weeks) (length = 5) and don't show last week (hidden)\n if (weeks.length == 5) {\n // clear sixth week (week-5)\n var week_six_node = document.getElementById(\"week-5\").getElementsByClassName(\"calendar-day\");\n // days = weeks[4].getDates();\n\n for (i = 0; i < week_six_node.length; i++) {\n // var apple = document.getElementById(\"my-list\").getElementsByClassName(\"fruits\")[0];\n // document.getElementById(\"my-list\").removeChild(apple);\n week_six_node[i].style.visibility = \"hidden\";\n }\n\n } else {\n // clear sixth week (week-5)\n var week_six_node = document.getElementById(\"week-5\").getElementsByClassName(\"calendar-day\");\n // days = weeks[4].getDates();\n\n for (i = 0; i < week_six_node.length; i++) {\n // var apple = document.getElementById(\"my-list\").getElementsByClassName(\"fruits\")[0];\n // document.getElementById(\"my-list\").removeChild(apple);\n week_six_node[i].style.visibility = \"visible\";\n }\n }\n\n\n }\n}", "function overviewChartMonthDisplay() {\n\t\tlet monthDisplay = document.getElementById('overviewChartMonth');\n\t\t\n\t\t// Year Display\n\t\tlet currentDate = new Date();\n\t\t\n\t\t// If month is December then show only the current year \n\t\tif(currentDate.getMonth() == 11) {\n\t\t\tmonthDisplay.innerText = currentDate.getFullYear();\n\t\t} else {\n\t\t\tmonthDisplay.innerText = (Number(currentDate.getFullYear()) - 1) + ' - ' + currentDate.getFullYear()\n\t\t}\n\t}", "function charSeasonSelect(season){\n\tconsole.log(\"Season is \" + season)\n\tvar section\n\tif (season == 1){\n\t\tsection = \"SymphogearSeasonOneCharacterData\"\n\t}\n\telse if(season == 2){\n\t\tsection = \"SymphogearSeasonTwoCharacterData\"\n\t}\n\telse if(season == 3){\n\t\tsection = \"SymphogearSeasonThreeCharacterData\"\n\t}\n\telse if(season == 4){\n\t\tsection = \"SymphogearSeasonFourCharacterData\"\n\t}\n\telse if(season == 5){\n\t\tsection = \"SymphogearSeasonFiveCharacterData\"\n\t}\n\treturn section\n}", "function display_days(days_of_month, date) {\n //ciclo for per stampare i giorni del mese e data-day\n for (var i = 1; i <= days_of_month; i++) {\n // console.log(i + ' ' + text_month + ' ' + year);\n //uso template per appendere giorno corrente in html e data-day ad ogni giorno\n var context = {\n 'day': i,\n 'date': date.format('YYYY-MM-DD')\n };\n var html_finale = template_function(context);\n $('#calendario').append(html_finale);\n //aggiungo un giorno all'oggetto moment che ho clonato\n date.add(1, 'days');\n }\n }", "function renderCalendar() {\n\n function renderCalendarViewRender(view, element) {\n scheduled.currentViewType = view.type;\n // this event fires once the calendar has completed loading and when the date is changed - thus calling the new events\n var start = moment(view.start).format('DD-MM-YYYY');\n var end = moment(view.end).format('DD-MM-YYYY');\n if(scheduled.currentViewType == 'month') {\n // if the current 'start' date of the selected month is not the same as the actual month then set the scheduled.calendarDate to the first of the proper month\n var currentStartMonth = moment(start, 'DD-MM-YYYY').format('MM-YYYY');\n var currentMonth = moment(view.title, 'MMMM YYYY').format('MM-YYYY');\n if(currentStartMonth != currentMonth) {\n scheduled.calendarDate = moment(view.title, 'MMMM YYYY').startOf('month').format('DD-MM-YYYY');\n }\n else {\n scheduled.calendarDate = start;\n }\n } else {\n scheduled.calendarDate = start;\n }\n updateCalendar(start, end);\n }\n\n\n $('#schedule-calendar').fullCalendar({\n header: {\n left: 'prev,next today',\n center: 'title',\n right: 'month,agendaWeek,agendaDay',\n },\n eventRender: function (event, element) {\n //Show tooltip when hovering over an event title\n var toolTipContent = '<strong>' + event.title + '</strong><br/>' + moment(event.start).format('MMMM D, YYYY') + ' ' + moment(event.start).format('h:mma');\n /*element.qtip({\n content: toolTipContent,\n hide: {fixed: true, delay: 200},\n style: 'qtip-light',\n position: {\n my: 'bottom center',\n at: 'top center',\n target: 'mouse',\n viewport: $('#fullcalendar'),\n adjust: {\n x: 0,\n y: -10,\n mouse: false,\n scroll: false,\n },\n },\n });*/\n },\n\n viewRender: renderCalendarViewRender,\n\n timeFormat: 'h:mma',\n firstDay: 1,\n aspectRatio: 2,\n defaultView: scheduled.currentViewType,\n fixedWeekCount: false,\n editable: false,\n lazyFetch: false,\n defaultDate: moment(scheduled.calendarDate, 'DD-MM-YYYY')\n });\n\n log.info('calendar start date ' + moment(scheduled.calendarDate, 'DD-MM-YYYY').format('DD-MM-YYYY'))\n }", "function drawMonth() {\n console.log(\"Drawing month for \" + selectedDay.toISOString());\n $('#jump_month_title').html(selectedDay.toString(\"MMM yyyy\"));\n\n days.reset();\n var startTime = new Date();\n startTime.setTime(selectedDay.getTime());\n startTime.moveToFirstDayOfMonth();\n var endTime = new Date();\n endTime.setTime(selectedDay.getTime());\n endTime.moveToLastDayOfMonth();\n // Loop from start to end\n for (loopCount = 1; loopCount <= endTime.getDate(); loopCount += 1) {\n var dateText = loopCount + \".\" + (startTime.getMonth() + 1) + \".\" + startTime.getFullYear();\n //console.log(\"Draw day \" + loopCount + \":\" + dateText);\n var loopDate = Date.parseExact(dateText, \"d.M.yyyy\");\n var day = new Day({id:loopCount, day_no:loopCount, date:loopDate.toString(\"d.M.yyyy\")});\n days.add(day);\n }\n}", "function getCalendar(semester, year, callback) {\n var term_in = year;\n\n switch (semester) {\n case \"Winter\": {\n term_in = term_in.concat(\"10\");\n break;\n }\n case \"Summer\": {\n term_in = term_in.concat(\"20\");\n break;\n\n }\n case \"Fall\": {\n term_in = term_in.concat(\"30\");\n break;\n }\n }\n\n //Grab the HTML page of the calendar and pass it to the parseCalendarHTML\n request.post({ url: VIEW_CALENDAR_URL, form:{ 'term_in': term_in } }, function (err, resp) {\n parseCalendarHTML(resp.body, function(object) {\n callback(object);\n });\n });\n}", "function GetEvents(year,month){\n\n\t/* this should be returned from api, number of day and html */\n\t return {13 : '', 18 : ''};\n }", "function renderDaysOfMonth(month, year) {\n $('#currentMonth').text(d3CalendarGlobals.monthToDisplayAsText() + ' ' + d3CalendarGlobals.yearToDisplay());\n // We get the days for the month we need to display based on the number of times the user has pressed\n // the forward or backward button.\n var daysInMonthToDisplay = d3CalendarGlobals.daysInMonth();\n var cellPositions = d3CalendarGlobals.gridCellPositions;\n\n // All text elements representing the dates in the month are grouped together in the \"datesGroup\" element by the initalizing\n // function below. The initializing function is also responsible for drawing the rectangles that make up the grid.\n d3CalendarGlobals.datesGroup \n .selectAll(\"text\")\n .data(daysInMonthToDisplay)\n .attr(\"x\", function (d,i) { return cellPositions[i][0]; })\n .attr(\"y\", function (d,i) { return cellPositions[i][1]; })\n .attr(\"dx\", 20) // right padding\n .attr(\"dy\", 20) // vertical alignment : middle\n .attr(\"transform\", \"translate(\" + d3CalendarGlobals.gridXTranslation + \",\" + d3CalendarGlobals.gridYTranslation + \")\")\n .text(function (d) { return d[0]; }); // Render text for the day of the week\n\n d3CalendarGlobals.calendar\n .selectAll(\"rect\")\n .data(daysInMonthToDisplay)\n // Here we change the color depending on whether the day is in the current month, the previous month or the next month.\n // The function that generates the dates for any given month will also specify the colors for days that are not part of the\n // current month. We just have to use it to fill the rectangle\n .style(\"fill\", function (d) { return d[1]; }); \n\n }", "function showGames(schedule, day, rotation) {\n // Set the day header\n document.getElementById(\"dayHeader\").innerHTML = day.charAt(0).toUpperCase() + day.slice(1);\n // Get the gameListContainer and clear it\n var gameListContainer = document.getElementById(\"gameListContainer\");\n gameListContainer.innerHTML = \"\";\n gameListContainer.scrollTop = 0;\n \n // Loop through the games\n var gameNo = (schedule[day]) ? schedule[day].length : 0;\n for (let i = 0; i < gameNo; i++) {\n // Generate headers\n const headers = generateHeaders(schedule[day][i]);\n \n // Generate div\n gameListContainer.innerHTML += `<div class='gameContainer'>\n <h1>` + headers[\"gameHeader\"] + `</h1>\n <h2>` + headers[\"subHeaderText\"] + `</h2>\n </div>`;\n }\n\n // Display message if there are no games that day\n if (gameNo == 0) {\n gameListContainer.innerHTML += `<div class='gameContainer'>\n <h1> No games today </h1>\n </div>`;\n }\n\n // Adds fake game containers for testing purposes\n gameNo = insertFakeGames(0, gameNo, gameListContainer);\n\n // Add page indicators\n document.getElementById(\"gamePageIndicatorContainer\").innerHTML = `\n <div id=\"dot1\" class=\"dot open\"></div> <div id=\"dot2\" class=\"dot open\"></div> <div id=\"dot3\" class=\"dot open\"></div>\n `;\n\n // Indicate correct indicator\n var dotId;\n switch(day) {\n case \"yesterday\":\n dotId = \"dot1\";\n break;\n case \"today\":\n dotId = \"dot2\";\n break;\n default:\n dotId = \"dot3\";\n }\n document.getElementById(dotId).classList = \"dot\";\n\n // Slide all divs in\n slideIn(gameNo, function () {\n // Sroll if necessary and then slide out after 7 seconds\n preSlideDelayTimer = setTimeout(function () {\n scroll(gameNo, function () {\n slideOut(schedule, day, rotation);\n });\n }, 7000);\n });\n\n\n}", "function createDemoEvents() {\n // Date for the calendar events (dummy data)\n var date = new Date();\n var d = date.getDate(),\n m = date.getMonth(),\n y = date.getFullYear();\n\n return [\n {\n title: 'All Day Event',\n start: new Date(y, m, 1),\n backgroundColor: '#f56954', //red\n borderColor: '#f56954' //red\n },\n {\n title: 'Long Event',\n start: new Date(y, m, d - 5),\n end: new Date(y, m, d - 2),\n backgroundColor: '#f39c12', //yellow\n borderColor: '#f39c12' //yellow\n },\n {\n title: 'Meeting',\n start: new Date(y, m, d, 10, 30),\n allDay: false,\n backgroundColor: '#0073b7', //Blue\n borderColor: '#0073b7' //Blue\n },\n {\n title: 'Lunch',\n start: new Date(y, m, d, 12, 0),\n end: new Date(y, m, d, 14, 0),\n allDay: false,\n backgroundColor: '#00c0ef', //Info (aqua)\n borderColor: '#00c0ef' //Info (aqua)\n },\n {\n title: 'Birthday Party',\n start: new Date(y, m, d + 1, 19, 0),\n end: new Date(y, m, d + 1, 22, 30),\n allDay: false,\n backgroundColor: '#00a65a', //Success (green)\n borderColor: '#00a65a' //Success (green)\n },\n {\n title: 'Open Google',\n start: new Date(y, m, 28),\n end: new Date(y, m, 29),\n url: '//google.com/',\n backgroundColor: '#3c8dbc', //Primary (light-blue)\n borderColor: '#3c8dbc' //Primary (light-blue)\n }\n ];\n }", "function initialiseCalendar() { \r\n\tdocument.getElementById(\"canvas\").style.display = \"block\";\r\n\tdocument.getElementById(\"color-fade\").style.display = \"block\";\r\n\tselectMonth = selectDate.getMonth();\r\n\tselectYear = selectDate.getFullYear();\r\n\tvar startDay = 1;\t\t\t\t\t\t// default show from 1st of month\r\n\tif (selectDate < today) \r\n\t\tselectDate = today;\r\n\tselectDay = selectDate.getDate();\r\n\tdocument.getElementById(\"year\").innerHTML = months[selectMonth] + \" \" + selectYear;\r\n\t/*\r\n\t/ do not show previous button, if the month is before the current month\r\n\t*/\r\n\tif ((selectDate.getYear() <= today.getYear())&&(selectDate.getMonth() <= today.getMonth())) {\r\n\t\tdocument.getElementById(\"previous\").style.display = \"none\";\r\n\t} else {\r\n\t\tdocument.getElementById(\"previous\").style.display = \"block\";\r\n\t}\r\n\t/*\r\n\t/ do not show next button, if the month is after one year into the future\r\n\t*/\r\n\tif ((selectDate.getYear() > today.getYear())&&(selectMonth >= today.getMonth())) {\r\n\t\tdocument.getElementById(\"next\").style.display = \"none\";\r\n\t} else {\r\n\t\tdocument.getElementById(\"next\").style.display = \"block\";\r\n\t}\r\n\t// get the first day of the month, so know what day of the week to start adding day of month numbers\r\n\tvar dateText = selectYear + \"-\" + twoDigit(selectMonth+1) + \"-01\";\r\n //firstOfMonth = new Date(selectYear+\"-\"+(selectMonth+1)+\"-01\");\r\n\tfirstOfMonth = new Date(\"2019-08-01\");\r\n\tfirstOfMonth=new Date(selectYear + \"-\" + twoDigit(selectMonth+1) + \"-01\");\t// get Date object for the first day of the current month\r\n\tif (firstOfMonth < today) \t\t\t\t// if first of month is before current date (today)\r\n\t\tstartDay = currentDay;\t\t\t\t// then do not show days before current date (today)\r\n\tvar firstDayOfMonth = firstOfMonth.getDay();\r\n\tvar selectDay = firstOfMonth.getDate();\r\n\t// create the table of days of month\r\n\tvar tbl = document.getElementById(\"month\");\r\n\ttbl.innerHTML = \"\";\t\t// body of the calendar\r\n\t/*\r\n\t// create and add the header for the days of the week\r\n\t*/\r\n\tvar row = document.createElement(\"tr\");\r\n\tfor (var i=0; i < 7; i++) {\r\n\t\tvar cell = document.createElement(\"th\");\r\n\t\tvar cellText = document.createTextNode(days[i]);\r\n\t\tcell.appendChild(cellText);\r\n row.appendChild(cell);\r\n\t}\r\n\ttbl.appendChild(row);\r\n\t/*\r\n\t/ next, write out the first row of days of the month\r\n\t*/\r\n\trow = document.createElement(\"tr\");\r\n\tvar day;\r\n\tfor (var i=0;i<firstDayOfMonth; i++) {\r\n\t\tcell = document.createElement(\"th\");\r\n\t\trow.appendChild(cell);\r\n\t}\r\n\tfor (var i=firstDayOfMonth; i < 7; i++) {\r\n\t\tif (selectDay < startDay) {\r\n\t\t\tcell = document.createElement(\"th\");\r\n\t\t\tcell.style.color = \"rgb(0,0,153)\";\r\n\t\t} else {\r\n\t\t\tcell = document.createElement(\"td\");\r\n\t\t}\t\t\r\n\t\tcellText = document.createTextNode(selectDay);\r\n\t\tcell.appendChild(cellText);\r\n row.appendChild(cell);\r\n\t\tselectDay++;\r\n\t}\r\n\ttbl.appendChild(row);\r\n\t/*\r\n\t/ then write out the next 3 rows of days of the month\r\n\t*/\r\n\tfor (var i = 0; i < 3; i++) {\r\n\t\trow = document.createElement(\"tr\");\r\n\t\t// create each cell in table of month dates\r\n\t\tfor (var j=0; j<7; j++) {\r\n\t\t\tif (selectDay < startDay) {\r\n\t\t\t\tcell = document.createElement(\"th\");\r\n\t\t\t\tcell.style.color = \"rgb(0,0,153)\";\r\n\t\t\t} else {\r\n\t\t\t\tcell = document.createElement(\"td\");\r\n\t\t\t}\r\n\t\t\tcellText = document.createTextNode(selectDay);\r\n\t\t\tcell.appendChild(cellText);\r\n\t\t\trow.appendChild(cell);\r\n\t\t\tselectDay++;\r\n\t\t}\r\n\t\ttbl.appendChild(row);\r\n\t}\r\n\t\r\n\tselectDate = new Date(selectYear+\"-\"+twoDigit(selectMonth+1)+\"-\"+selectDay);\r\n\trow = document.createElement(\"tr\");\r\n\t// create each cell in table of month days\r\n\tfor (var j=0; j<7; j++) {\r\n\t\tday = selectDate.getDate();\r\n\t\tcellText = document.createTextNode(day);\t\t\r\n\t\tif ( (day < 7) || (day < startDay) ) {\r\n\t\t\tcell = document.createElement(\"th\");\r\n\t\t\tcell.style.color = \"rgb(0,0,153)\";\r\n\t\t} else {\r\n\t\t\tcell = document.createElement(\"td\");\r\n\t\t}\r\n\t\tcell.appendChild(cellText);\r\n\t\trow.appendChild(cell);\r\n\t\tselectDate.setDate(selectDate.getDate() + 1);\r\n\t}\r\n\t// add the new row to the table\r\n\ttbl.appendChild(row);\r\n}", "function seasonToColour(season) {\n switch (season) {\n case 0:\n return \"winter\";\n case 1:\n return \"spring\";\n case 2:\n return \"summer\";\n case 3:\n return \"autumn\";\n default:\n return \"black\";\n }\n}" ]
[ "0.77897084", "0.6939122", "0.6911409", "0.68985325", "0.66730314", "0.6661029", "0.6644443", "0.66373426", "0.6617695", "0.6465469", "0.6412799", "0.6267902", "0.62401795", "0.6238997", "0.6215198", "0.6127396", "0.61130023", "0.60675347", "0.6067287", "0.60525984", "0.60314846", "0.60303915", "0.60138667", "0.5986715", "0.59851277", "0.5983146", "0.5977988", "0.5976973", "0.59714067", "0.59689784", "0.5957141", "0.59553003", "0.5943513", "0.59420437", "0.5940877", "0.5937934", "0.5933851", "0.5923214", "0.59150803", "0.5898241", "0.58892363", "0.585598", "0.58524084", "0.58257544", "0.5824537", "0.5822757", "0.5818714", "0.58182126", "0.58125126", "0.5796707", "0.57870424", "0.5774023", "0.57729685", "0.57470715", "0.57210475", "0.5717951", "0.5705762", "0.57025504", "0.5697153", "0.56935203", "0.5692011", "0.56847394", "0.56797695", "0.56540334", "0.5646559", "0.5642011", "0.5637769", "0.5633035", "0.56298", "0.5626755", "0.5621521", "0.5619868", "0.561706", "0.561533", "0.5601601", "0.5596273", "0.558815", "0.5581221", "0.5578588", "0.5577944", "0.5575062", "0.5562727", "0.5560608", "0.55558527", "0.55510986", "0.55445796", "0.5537416", "0.55360526", "0.553411", "0.5533034", "0.55323523", "0.55295175", "0.55288726", "0.5524827", "0.5521556", "0.55214965", "0.551243", "0.5505495", "0.5499853", "0.54966253", "0.5490976" ]
0.0
-1
k: products[i].length === 20 s: searchWord.length === 1000 sol 1) knslogs
function add(obj, key, value) { if (! (key in obj)) obj[key] = [value]; else { obj[key].push(value) obj[key].sort() if (obj[key].length === 4) { obj[key].pop() } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function checkForKeyWords(arsTest) {\n console.log(\"arstest, \", arsTest);\n arsKeyWords = [];\n arsKeyTot = [];\n bCheck = false;\n for (var i = 0; i < arsTest.length; i++) {\n arsKeyWords = [];\n var nStartCheck, nEndCheck;\n console.log(\"sStartIndexForEachLength: \", sStartIndexForEachLength);\n for (var j = 0; j < arsTest[i].length; j++) { //LOOP THROUGH EMAIL BODY\n if ((arsTest[i][j].length - 3) > 0 && (arsTest[i][j].length + 3) <= sStartIndexForEachLength.length - 1) {\n nStartCheck = sStartIndexForEachLength[arsTest[i][j].length - 3][1];\n nEndCheck = sStartIndexForEachLength[arsTest[i][j].length + 3][1];\n } else if ((arsTest[i][j].length - 3) <= 0) {\n nStartCheck = sStartIndexForEachLength[1][1];\n nEndCheck = sStartIndexForEachLength[arsTest[i][j].length + 3][1];\n } else if (((arsTest[i][j].length+3)>sStartIndexForEachLength.length-1) && arsTest[i][j].length<sStartIndexForEachLength.length) { \n nStartCheck = sStartIndexForEachLength[arsTest[i][j].length - 3][1];\n nEndCheck = sStartIndexForEachLength[sStartIndexForEachLength.length - 1][1];\n } else{\n nStartCheck = 0;\n nEndCheck = 0;\n }\n //console.log(\"arsTest[i][j]: \", arsTest[i][j],\" arsTest[i][j].length: \", arsTest[i][j].length, \" nStartCheck: \", nStartCheck, \" nEndcheck: \", nEndCheck, \" klfdalkadj \", ((arsTest[i][j].length+3)>sStartIndexForEachLength.length-1), \" daf \", arsTest[i][j].length<sStartIndexForEachLength.length);\n for (var k = parseInt(nStartCheck); k <= parseInt(nEndCheck); k++) { \n //console.log(\"arsTest[i][j]: \", arsTest[i][j],\" arsTest[i][j].length: \", arsTest[i][j].length, \" nStartCheck: \", nStartCheck, \" nEndcheck: \", nEndCheck, \" arsWords[k]: \", arsWords[k], \" arsWords[k].indexOf(arsTest[i][j]): \", arsWords[k].indexOf(arsTest[i][j]));\n if (arsWords[k].indexOf(arsTest[i][j]) > -1) {\n arsKeyWords.push(arsWords[k][0]);\n break;\n }\n }\n }\n /*CHECK FOR PEOPLE WHO USE SPACES IN RANDOM WAYS*/\n for (var j = 0; j < arsKeyWords.length - 1; j++) {\n if (arsKeyWords[j] === \"play\") {\n if (arsKeyWords[j + 1] === \"list\") {\n arsKeyWords[j] = \"playlist\";\n }\n }\n if (arsKeyWords[j] === \"will\") {\n if (arsKeyWords[j + 1] === \"not\") {\n arsKeyWords[j] = \"wont\";\n }\n }\n if (arsKeyWords[j] === \"not\") {\n if (arsKeyWords[j + 1] === \"available\") {\n arsKeyWords[j] = 'unavailable';\n }\n }\n\n if (arsKeyWords[j] === \"get\") {\n if (arsKeyWords[j + 1] === \"rid\") {\n arsKeyWords[j] = \"delete\";\n }\n }\n if (arsKeyWords[j] === \"not\") {\n if (arsKeyWords[j + 1] === \"able\") {\n arsKeyWords[j] = \"cant\";\n }\n }\n if (arsKeyWords[j] === \"unable\") {\n arsKeyWords[j] = \"cannot\";\n }\n if (arsKeyWords[j] === \"video\") {\n if (arsKeyWords[j + 1] === \"stream\") {\n arsKeyWords[j] = \"videostream\";\n }\n }\n }\n if (arsKeyWords.length > 0) {\n console.log(\"Checking if seen before arsKeyWords: \", arsKeyWords);\n // console.log(\"Checking if seen before arsKeyTot: \", arsKeyTot);\n // checkifseenbefore(arsKeyTot);\n checkifseenbefore(arsKeyWords);\n testwords(arsKeyWords);\n arsKeyTot = arsKeyTot.concat(arsKeyWords);\n if (sAns.length > 0) {\n bCheck = true;\n }\n console.log(\"Answer - in check for keywords: \", sAns);\n }\n }\n if (sAns.length === 0 || sAns === \"Super sorry! I don't quite understand your question! Do you mind giving me a bit more information? If possible, screenshots would be appreciated :) \\n \\n Cheers!\") {\n checkifseenbefore(arsKeyTot);\n testwords(arsKeyTot);\n }\n if (sAns.length > 0) {\n bCheck = true;\n return;\n }\n}", "function genSearch() {\r\n buildMatrices(); // initialize grid and taken matrices\r\n\r\n genAnswers(); // add answers to the grid and update taken matrix\r\n\r\n displayWordSearch(); // display finished product\r\n}", "function findKeywords() {\n\t\tvar skipwords = getSkipWords();\n\t\tvar inputwords = getInputWords();\n\t\tvar inputwordscount = inputwords.length;\n\n\t\tvar finaloutput = '';\n\t\t\n\t\tfinaloutput = findKeywordPhrases({\n\t\t\t'inputwords':inputwords,\n\t\t\t'inputwordscount':inputwordscount,\n\t\t\t'skipwords':skipwords,\n\t\t});\n\t\t\n\t\tvar wordcounts = getSingleKeywordCounts({\n\t\t\t'wordcount':inputwordscount,\n\t\t\t'words':inputwords,\n\t\t\t'skipwords':skipwords,\n\t\t});\n\t\t\n\t\tvar wordcountsbynumber = sortKeywords({'wordcounts':wordcounts});\n\t\tfinaloutput += displayKeywords({'keywords':wordcountsbynumber});\n\t\t\n\t\t$('.output-area').val(finaloutput);\n\t\t$('.output-area').change();\n\t\t$('#status-text').text(waitingForUserText());\n\t\t\n\t\treturn true;\n\t}", "function findKeywordPhrases(args) {\n\t\tvar inputwords = args['inputwords'];\n\t\tvar inputwordscount = args['inputwordscount'];\n\t\tvar skipwords = args['skipwords'];\n\t\t\n\t\tvar finaloutput = '';\n\t\t\n\t\tvar separator = getKeywordSectionSeparator();\n\t\t\n\t\tif($('.include-phrases').is(':checked')) {\n\t\t\t\t// Six-Word Phrases\n\t\t\tvar sixwordphrases = getSixWordPhraseCounts(args);\n\t\t\tvar sixwordphrasessorted = sortKeywords({'wordcounts':sixwordphrases});\n\t\t\tvar sixwordphrasetext = displayKeywords({'keywords':sixwordphrasessorted});\n\t\t\t\n\t\t\tif(sixwordphrasetext.length !== 0) {\n\t\t\t\tfinaloutput += sixwordphrasetext + separator;\n\t\t\t}\n\t\t\t\n\t\t\t\t// Five-Word Phrases\n\t\t\tvar fivewordphrases = getFiveWordPhraseCounts(args);\n\t\t\tvar fivewordphrasessorted = sortKeywords({'wordcounts':fivewordphrases});\n\t\t\tvar fivewordphrasetext = displayKeywords({'keywords':fivewordphrasessorted});\n\t\t\t\n\t\t\tif(fivewordphrasetext.length !== 0) {\n\t\t\t\tfinaloutput += fivewordphrasetext + separator;\n\t\t\t}\n\t\t\t\n\t\t\t\t// Four-Word Phrases\n\t\t\tvar fourwordphrases = getFourWordPhraseCounts(args);\n\t\t\tvar fourwordphrasessorted = sortKeywords({'wordcounts':fourwordphrases});\n\t\t\tvar fourwordphrasetext = displayKeywords({'keywords':fourwordphrasessorted});\n\t\t\t\n\t\t\tif(fourwordphrasetext.length !== 0) {\n\t\t\t\tfinaloutput += fourwordphrasetext + separator;\n\t\t\t}\n\t\t\t\n\t\t\t\t// Three-Word Phrases\n\t\t\tvar threewordphrases = getThreeWordPhraseCounts(args);\n\t\t\tvar threewordphrasessorted = sortKeywords({'wordcounts':threewordphrases});\n\t\t\tvar threewordphrasetext = displayKeywords({'keywords':threewordphrasessorted});\n\t\t\t\n\t\t\tif(threewordphrasetext.length !== 0) {\n\t\t\t\tfinaloutput += threewordphrasetext + separator;\n\t\t\t}\n\t\t\t\n\t\t\t\t// Two-Word Phrases\n\t\t\tvar twowordphrases = getTwoWordPhraseCounts(args);\n\t\t\tvar twowordphrasessorted = sortKeywords({'wordcounts':twowordphrases});\n\t\t\tvar twowordphrasetext = displayKeywords({'keywords':twowordphrasessorted});\n\t\t\t\n\t\t\tif(twowordphrasetext.length !== 0) {\n\t\t\t\tfinaloutput += twowordphrasetext + separator;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn finaloutput;\n\t}", "function doTF(tf)\r\n{\r\n termfrequency = {};\r\n var word = tf.split(' '); // individual words\r\n var count=0;\r\n \r\n for(var i = 0;i<tf.length;i++)\r\n {\r\n if(termfrequency.hasOwnProperty(word[i]))\r\n {\r\n // the word is already in the database:\r\n termfrequency[word[i]]++;\r\n arrfrequency++;\r\n }\r\n else\r\n {\r\n // the word is new:\r\n termfrequency[word[i]]=1;\r\n arrfrequency++;\r\n \r\n }\r\n for (var j = 0; j < arr.length; j++) {\r\n if (arr[j] == word[i]) {\r\n count++;\r\n } }\r\n}\r\n \r\n \r\n \r\n console.log(termfrequency);\r\n console.log(arrfrequency);\r\n console.log(word);\r\n console.log(count); \r\n return count;\r\n }", "function invertedIndexing(){\n document.getElementById('response-box').innerHTML = \"\";\n searchWord = document.getElementById('input_search_word').value;\n searchWord = searchWord.toLowerCase();\n //get 10 instances of highest occurrence of the word\n occ_freq = Object.keys(index[searchWord]);\n occ_freq = occ_freq.map(Number);\n occ_freq.reverse();\n if(occ_freq.length > 10){\n occ_freq = occ_freq.slice(0,10);\n }\n occ_doc = getTopTen(searchWord, occ_freq);\n \n //display the results in the response box\n document.getElementById('response-box').insertAdjacentHTML('beforeend', \"\\nOccurrences of \\\"\"+searchWord+\"\\\"\\n\\n\");\n for(let [c,did] of occ_doc.entries()){\n var freq_count = occ_freq[c];\n var parah_no = document_id[did];\n var occ_string = String(freq_count)+\" times in \"+did+\": \";\n document.getElementById('response-box').insertAdjacentHTML('beforeend', occ_string + orig_parahs[parah_no]+'\\n\\n');\n }\n}", "handleSearch(event) {\n const { inputText, words } = this.state;\n let textToMatch = inputText.split(\" \");\n \n let searchedWordsArray = words.map((word) => word.toLowerCase());\n \n for (let i=0; i <= searchedWordsArray.length-1; i++){\n for (let j=0; j <= textToMatch.length-1; j++ ){\n let parkArray = searchedWordsArray[i].split(\" \");\n let subInputTextArray = textToMatch.slice(j, j+parkArray.length);\n if(parkArray.compare(subInputTextArray)){\n for (let k=0; k <=parkArray.length-1 ; k++){\n textToMatch[j+k] = `<Strong>${textToMatch[j+k]}</Strong>`\n }\n }\n }\n this.setState({outputText: textToMatch.join(' ')})\n }\n\n event.preventDefault();\n }", "function wordCountEnginePt2(document) {\n // your code goes here\n const frequencyCnt = {};\n document\n .toLowerCase()\n .split(' ')\n .forEach((word, index) => {\n word = word.replace(/[^a-z]/gi, '');\n if (word) {\n if (frequencyCnt[word]) {\n frequencyCnt[word] = {\n count: frequencyCnt[word].count + 1,\n index: Math.min(index, frequencyCnt[word].index),\n };\n } else {\n frequencyCnt[word] = { count: 1, index };\n }\n }\n });\n\n // [[word, {index, count}]]\n const returnArr = Object.keys(frequencyCnt).map(key => [\n key,\n frequencyCnt[key],\n ]);\n returnArr.sort(([_a, a], [_b, b]) => {\n if (b.count === a.count) {\n return a.index - b.index;\n } else {\n return b.count - a.count;\n }\n });\n\n return returnArr\n .map(innerArr => innerArr)\n .map(([key, { count }]) => [key, `${count}`]);\n}", "_fiterByWordCount() {\n let entitesCopy = [...this.state.entities];\n let filteredArray = [];\n let { pfa, cfa } = this.state;\n if(!pfa && !cfa) {\n filteredArray = entitesCopy;\n } else {\n let secondFilterArray = [];\n entitesCopy.forEach( entrie => {\n let titleLength = entrie.title.split(' ').length;\n if(cfa && titleLength > 5) {\n secondFilterArray.push(entrie);\n } else if(pfa && titleLength <= 5) {\n secondFilterArray.push(entrie);\n }\n });\n filteredArray = this._fiterByPoitsOrComm( cfa, secondFilterArray );\n };\n return filteredArray;\n }", "function shortestWords(words) {\n // Code here\n var newWords = \"\";\n for (var x = 0; x < words.length; x++) {\n newWords = newWords + words[x].toLowerCase();\n // console.log(newWords)\n //toLowerCase digunakan agar tidak muncul dua kata yang sama dikarenakan huruf kapital. \n }\n // Lakukan split untuk agar var splitWords bisa di cek menggunakan looping.\n var splitWords = newWords.split(\" \");\n // Buat array kosong untuk menampung pengulangan dari looping.\n // console.log(splitWords)\n var tampungLength = [];\n\n for (var a = 0; a < splitWords.length; a++) {\n var cekKata = \"\";\n for (var b = 0; b < splitWords[a].length; b++) {\n cekKata = b;\n }\n tampungLength.push(cekKata);\n }\n // console.log(tampungLength);\n // Mengecek panjang huruf var words.\n\n // Gunakan looping untuk mencari kata yang paling jarang muncul.\n var angkaTerkecil = tampungLength[0];\n\n for (var c = 0; c < tampungLength.length; c++) {\n if (angkaTerkecil > tampungLength[c]) {\n angkaTerkecil = tampungLength[c];\n }\n }\n // console.log(angkaTerkecil)\n\n var tampungHasil = [];\n for (var i = 0; i < tampungLength.length; i++) {\n if (tampungLength[i] == angkaTerkecil) {\n tampungHasil.push(splitWords[i]);\n }\n }\n // console.log(tampungHasil)\n\n var hasil = [];\n for (var j = 0; j < tampungHasil.length; j++) {\n if (hasil.indexOf(tampungHasil[j]) === -1) {\n hasil.push(tampungHasil[j]);\n if (tampungHasil[j] === 'i') {\n hasil[0] = tampungHasil[j].toUpperCase();\n }\n }\n }\n return hasil;\n}", "function uniqueFinder(sentence) {\r\n //your code here\r\n //kondisi untuk nilai array kosong\r\n if (sentence.length === 0) {\r\n return 'NO WORDS';\r\n }\r\n \r\n //coding untuk split, space (' ');\r\n sentence += ' ';\r\n const tampungWords = [];\r\n let tampungKata = '';\r\n for (let i = 0; i < sentence.length; i++) {\r\n if (sentence[i] === ' ') {\r\n tampungWords.push(tampungKata.toLowerCase());\r\n tampungKata = ' ';\r\n } else {\r\n tampungKata += sentence[i];\r\n }\r\n }\r\n //console.log(tampungWords);\r\n \r\n const results = [];\r\n //looping untuk splitted\r\n for (let p = 0; p< tampungWords.length; p++){\r\n //looping untuk check words yg sama\r\n //console.log('Kata I : ' +tampungWords[p]);\r\n for (let q = p + 1; q< tampungWords.length; q++){\r\n //console.log('kata II ' +tampungWords[q]);\r\n let exist = false;\r\n \r\n //looping untuk check udah masuk result or belum\r\n for (let r = 0; r< results.length; r++) {\r\n //console.log('kata III : ' +results);\r\n if (tampungWords[p] === results[r]) {\r\n exist = true ;\r\n }\r\n }\r\n \r\n if (tampungWords[p] === tampungWords[q] && !exist ) {\r\n results.push(tampungWords[p]);\r\n }\r\n }\r\n } \r\n //console.log(results);\r\n return results;\r\n\r\n}", "function SearchingChallenge1(str) {\n const array = [...str];\n const k = Number(array.shift());\n\n let substring = [];\n let n = 1;\n\n let index = 0;\n\n let res = [];\n\n while (index < array.length) {\n if (substring === [] || substring.includes(array[index])) {\n substring.push(array[index]);\n index++;\n console.log(\"substring\", substring);\n } else if (!substring.includes(array[index]) && n <= k) {\n substring.push(array[index]);\n n++;\n index++;\n console.log(\"substring\", substring);\n } else {\n res.push(substring.join(\"\"));\n console.log(\"res during\", res);\n substring = [];\n n = 1;\n index--;\n console.log(\"substring after []\", substring.length);\n }\n }\n\n res.push(substring.join(\"\"));\n\n console.log(\"res final\", res);\n\n const lengths = res.map((e) => e.length);\n\n return res[lengths.indexOf(Math.max(...lengths))];\n}", "countBigWords(input) {\n // Split the input\n let arr = input.split(\" \");\n // Start counter from 0\n let count = 0;\n //if array contains more than 6 lettes word, add 1 otherwise neglect word and keep moving further\n //until whole string input is completed\n arr.forEach(word =>{\n if (word.length > 6){\n count++;\n }\n \n });\n\n // return the count of all words with more than 6 letters\n return count;\n }", "function filterLongWords(words, i) {\n\n}", "function getSixWordPhraseCounts(args) {\n\t\tvar inputwords = args['inputwords'];\n\t\tvar inputwordscount = args['inputwordscount'];\n\t\tvar skipwords = args['skipwords'];\n\t\t\n\t\tvar sixwordphrases = {};\n\t\t\n\t\tfor(i = 0; i - 5 < inputwordscount; i++) {\n\t\t\tvar currentword = inputwords[i];\n\t\t\tvar nextword = inputwords[i + 1];\n\t\t\tvar thirdword = inputwords[i + 2];\n\t\t\tvar fourthword = inputwords[i + 3];\n\t\t\tvar fifthword = inputwords[i + 4];\n\t\t\tvar sixthword = inputwords[i + 5];\n\t\t\tif(currentword && nextword && thirdword && fourthword && fifthword && sixthword) {\n\t\t\t\tif(\n\t\t\t\t\t(!skipwords[currentword] && !skipwords[nextword]) ||\n\t\t\t\t\t(!skipwords[currentword] && !skipwords[thirdword]) ||\n\t\t\t\t\t(!skipwords[currentword] && !skipwords[fourthword]) ||\n\t\t\t\t\t(!skipwords[currentword] && !skipwords[fifthword]) ||\n\t\t\t\t\t(!skipwords[currentword] && !skipwords[sixthword]) ||\n\t\t\t\t\t(!skipwords[nextword] && !skipwords[thirdword]) ||\n\t\t\t\t\t(!skipwords[nextword] && !skipwords[fourthword]) ||\n\t\t\t\t\t(!skipwords[nextword] && !skipwords[fifthword]) ||\n\t\t\t\t\t(!skipwords[nextword] && !skipwords[sixthword]) ||\n\t\t\t\t\t(!skipwords[thirdword] && !skipwords[fourthword]) ||\n\t\t\t\t\t(!skipwords[thirdword] && !skipwords[fifthword]) ||\n\t\t\t\t\t(!skipwords[thirdword] && !skipwords[sixthword]) ||\n\t\t\t\t\t(!skipwords[fourthword] && !skipwords[fifthword]) ||\n\t\t\t\t\t(!skipwords[fourthword] && !skipwords[sixthword]) ||\n\t\t\t\t\t(!skipwords[fifthword] && !skipwords[sixthword])\n\t\t\t\t) {\n\t\t\t\t\tvar phrase = currentword + ' ' + nextword + ' ' + thirdword + ' ' + fourthword + ' ' + fifthword + ' ' + sixthword;\n\t\t\t\t\tif(sixwordphrases[phrase]) {\n\t\t\t\t\t\tsixwordphrases[phrase]++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsixwordphrases[phrase] = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn sixwordphrases;\n\t}", "function FindWords(letters, finalsolutions){\n\tvar letters_or = getOrdered(letters); \n\tif (letters_or in wordhash){\t// check if ordered version has words\n\t\tfor (var i=0; i<wordhash[letters_or].length; i++){\n\t\t\tfinalsolutions.push(wordhash[letters_or][i]);\t// grab each mapped word\n\t\t}\n\t}\n\treturn finalsolutions;\n\n\n\n\n}", "function searchRecom() {\n\t// store keyword in localSession\n\twindow.localStorage.setItem('kw', keyWord);\n\t// Fuse options\t\t\t\t\n\tvar options = {\n\t\tshouldSort: true,\n\t\ttokenize: true,\n\t\tthreshold: 0.2,\n\t\tlocation: 0,\n\t\tdistance: 100,\n\t\tincludeScore: true,\n\t\tmaxPatternLength: 32,\n\t\tminMatchCharLength: 2,\n\t\tkeys: [\"title.recommendation_en\",\n\t\t\t \"title.title_recommendation_en\",\n\t\t\t \"topic.topic_en\"]\n\t};\n\t//Fuse search\n\tvar fuse = new Fuse(recommends, options); //https://fusejs.io/\n\tconst results = fuse.search(keyWord);\n\treturn results;\n}", "function filterLongWords(words, i){\n //...\n}", "function s2(beginWord, endWord, wordList) {\n /* \n make forms hashmap\n '*ot': [ 'hot', 'dot', 'lot' ],\n 'h*t': [ 'hot' ],\n 'ho*': [ 'hot' ],\n 'd*t': [ 'dot' ],\n 'do*': [ 'dot', 'dog' ],\n '*og': [ 'dog', 'log', 'cog' ],\n 'd*g': [ 'dog' ],\n 'l*t': [ 'lot' ],\n 'lo*': [ 'lot', 'log' ],\n 'l*g': [ 'log' ],\n 'c*g': [ 'cog' ],\n 'co*': [ 'cog' ]\n */\n\n // time, o(nm2), o(length of wordlist * length of word * length of word)\n // word of m length, will appear in m forms (3 letter word will appear 3 times in the graph)\n // will be at most nm entries in graph\n // BETTER THAN ABOVE if length of wordlist is greater than the length of the word (ASSUMING ALL SAME LENGTH)\n\n // space, o(nm2)\n const graph = makeGraph();\n console.log(graph);\n\n function makeGraph() {\n const out = {};\n for (let i = 0; i < beginWord.length; i++) {\n const form = `${beginWord.substring(0, i)}*${beginWord.substring(i + 1)}`;\n out[form] ? out[form].push(beginWord) : (out[form] = [beginWord]);\n }\n for (let word of wordList) {\n for (let i = 0; i < word.length; i++) {\n const form = `${word.substring(0, i)}*${word.substring(i + 1)}`;\n out[form] ? out[form].push(word) : (out[form] = [word]);\n }\n }\n return out;\n }\n\n const set = new Set();\n set.add(beginWord);\n const q = [[beginWord, 0]];\n while (q.length) {\n console.log(q);\n const [word, level] = q.shift();\n if (word === endWord) return level;\n for (let i = 0; i < word.length; i++) {\n const form = `${word.substring(0, i)}*${word.substring(i + 1)}`;\n for (let nextWord of graph[form]) {\n if (!set.has(nextWord)) {\n set.add(nextWord);\n q.push([nextWord, level + 1]);\n }\n }\n }\n }\n}", "function naiveSearch(long, short){\n let count = 0;\n let test;\n for(let i = 0; i<long.length; i++){\n test = long.slice(i,i+short.length)\n console.log(test)\n if(test === short )count++\n }\n return count;\n}", "function search(in_data) {\n var data = in_data;\n var temp = data;\n var words = new Array();\n words = temp.split(\" \");\n words = tolower(words);\n\n var uniqueWords = new Array();\n var count = new Array();\n var wordArray = new Array();\n\n // calculate each word frequency\n // console.log(words.length);\n for (var i = 0; i < words.length; i++) {\n var freq = 0;\n for (j = 0; j < uniqueWords.length; j++) {\n if (words[i] == uniqueWords[j]) {\n count[j] = count[j] + 1;\n freq = 1;\n }\n }\n if (freq == 0) {\n count[i] = 1;\n uniqueWords[i] = words[i];\n }\n }\n\n for (var i=0; i<uniqueWords.length; i++) {\n if (count[i] > 0) {\n wordArray.push({word: uniqueWords[i], freq: count[i]});\n }\n }\n\n // sorting\n wordArray.sort(function(first,second) {\n return second.freq - first.freq;\n });\n\n//printing the before deletion\n // console.log(\"BEFORE DELETION\")\n // for (var i=0; i<wordArray.length; i++) {\n // console.log(wordArray[i]);\n // }\n\n // eliminating pronouns\n // for (var i=0; i<wordArray.length; i++) {\n // for (var j=0; j<pronouns.length; j++) {\n // if (wordArray[i].word == pronouns[j]) {\n // console.log(\"deleting: \" + wordArray[i].word);\n // wordArray.splice(i,1);\n // }\n // }\n // }\n\n for (var i= wordArray.length - 1; i >=0; i--) {\n if (set.has(wordArray[i].word)) {\n // console.log(\"deleting: \" + wordArray[i].word);\n wordArray.splice(i,1);\n }\n }\n\n // console.log(\"AFTER DELETION\")\n // for (var i=0; i<wordArray.length; i++) {\n // console.log(wordArray[i]);\n // }\n \n //this process the cloud:\n var to_process = wordArray.slice(0, 250);\n // console.log(\"this is the arraysize \"+ to_process.length);\n processCloud(to_process);\n}", "function Search(case_sentences_for_indexing) {\n\n //Configuring options for Fuse library\n var fuse_options = {\n shouldSort: true,\n includeScore: false,\n threshold: 0.6,\n location: 0,\n distance: 100,\n maxPatternLength: 200,\n minMatchCharLength: 1,\n keys: [\n \"title\"\n ]\n };\n\n\n //TEST DATA//\n //STOPWORDS are words we don't want to be included in search\n const STOPWORDS = [\"a\", \"about\", \"above\", \"after\", \"again\", \"against\", \"all\", \"am\", \"an\", \"and\", \"any\",\"are\",\"aren't\",\"as\",\"at\",\"be\",\"because\",\"been\",\"before\",\"being\",\"below\",\"between\",\"both\",\"but\",\"by\",\"can't\",\"cannot\",\"could\",\"couldn't\",\"did\",\"didn't\",\"do\",\"does\",\"doesn't\",\"doing\",\"don't\",\"down\",\"during\",\"each\",\"few\",\"for\",\"from\",\"further\",\"had\",\"hadn't\",\"has\",\"hasn't\",\"have\",\"haven't\",\"having\",\"he\",\"he'd\",\"he'll\",\"he's\",\"her\",\"here\",\"here's\",\"hers\",\"herself\",\"him\",\"himself\",\"his\",\"how\",\"how's\",\"i\",\"i'd\",\"i'll\",\"i'm\",\"i've\",\"if\",\"in\",\"into\",\"is\",\"isn't\",\"it\",\"it's\",\"its\",\"itself\",\"let's\",\"me\",\"more\",\"most\",\"mustn't\",\"my\",\"myself\",\"no\",\"nor\",\"not\",\"of\",\"off\",\"on\",\"once\",\"only\",\"or\",\"other\",\"ought\",\"our\",\"ours\",\"ourselves\",\"out\",\"over\",\"own\",\"same\",\"shan't\",\"she\",\"she'd\",\"she'll\",\"she's\",\"should\",\"shouldn't\",\"so\",\"some\",\"such\",\"than\",\"that\",\"that's\",\"the\",\"their\",\"theirs\",\"them\",\"themselves\",\"then\",\"there\",\"there's\",\"these\",\"they\",\"they'd\",\"they'll\",\"they're\",\"they've\",\"this\",\"those\",\"through\",\"to\",\"too\",\"under\",\"until\",\"up\",\"very\",\"was\",\"wasn't\",\"we\",\"we'd\",\"we'll\",\"we're\",\"we've\",\"were\",\"weren't\",\"what\",\"what's\",\"when\",\"when's\",\"where\",\"where's\",\"which\",\"while\",\"who\",\"who's\",\"whom\",\"why\",\"why's\",\"with\",\"won't\",\"would\",\"wouldn't\",\"you\",\"you'd\",\"you'll\",\"you're\",\"you've\",\"your\",\"yours\",\"yourself\",\"yourselves\"];\n \n // Sentences that are being searched through\n var caseSentences = case_sentences_for_indexing;\n\n removeStopwordsFromCaseSentences();\n\n //Initializing Fuse search library\n var fuse = new Fuse(caseSentences, fuse_options);\n\n\n // String -> String\n function removeStopwordsFromSentence(sentence){\n sentenceWordList = sentence.split(\" \");\n for (var i = 0; i < STOPWORDS.length; i++) {\n sentenceWordList = sentenceWordList.filter(word => word != STOPWORDS[i]);\n }\n //console.log(sentenceWordList);\n trimmedSentence = sentenceWordList.join(\" \")\n //console.log(trimmedSentence);\n return trimmedSentence;\n }\n\n function removeStopwordsFromCaseSentences(){\n for (var i = 0; i<caseSentences.length; i++) {\n caseSentences[i] = removeStopwordsFromSentence(caseSentences[i]);\n }\n }\n\n\n\n this.find_sentence_in_case = function(sentence_to_be_found) {\n trimmedSentence = removeStopwordsFromSentence(sentence_to_be_found);\n var result = fuse.search(trimmedSentence);\n //console.log(result[0]);\n return result[0];\n }\n \n}", "function searchProducts(request,response){\n const page=request.query.page;\n const limit=request.query.limit;\n const startIndex=(page-1)*limit;\n const endIndex=limit;\n let splitStr=[];\n let searchQuery = request.body.searchString;\n splitStr = searchQuery.split(\" \");\n console.log(splitStr)\n console.log(request.body.searchString)\n let sqlQuery=\"SELECT * FROM milk_comparison RIGHT JOIN milk ON milk.id=milk_comparison.milk_id WHERE \";\n if(page!=null && limit!=null){\n for(let i=0;i<splitStr.length;i++){\n if(i!=splitStr.length-1){\n // console.log(\"adding to the sql query\")\n sqlQuery+=\"searchString LIKE '%\"+splitStr[i]+\"%' AND \"\n }else{\n sqlQuery+=\"searchString LIKE '%\"+splitStr[i]+\"%' \"\n // console.log(\"last bit added to the search query\")\n }\n }\n sqlQuery+=\"LIMIT \"+startIndex+\",\"+endIndex;\n\n}else if(page==null&limit==null){\n for(let i=0;i<splitStr.length;i++){\n if(i!=splitStr.length-1){\n sqlQuery+=\"searchString LIKE '%\"+splitStr[i]+\"%' AND \"\n }else{\n sqlQuery+=\"searchString LIKE '%\"+splitStr[i]+\"%' \"\n }\n }\n}\n connectionPool.query(sqlQuery,(err,result)=>{\n if (err) {//Check for errors\n console.error(\"Error executing query: \" + JSON.stringify(err));\n response.send(\"error\");\n }\n else {\n let obj=JSON.stringify(result);\n console.log(\"this is the object sent from server\"+obj);\n console.log(\"object length\"+obj.length)\n if(obj.length==2){\n // if object empty search in cheese\n \n sqlQuery=\"SELECT * FROM cheeses_comparison RIGHT JOIN cheeses ON cheeses.id=cheeses_comparison.cheese_id WHERE \";\n if(page!=null && limit!=null){\n for(let i=0;i<splitStr.length;i++){\n if(i!=splitStr.length-1){\n // console.log(\"adding to the sql query\")\n sqlQuery+=\"searchString LIKE '%\"+splitStr[i]+\"%' AND \"\n }else{\n sqlQuery+=\"searchString LIKE '%\"+splitStr[i]+\"%' \"\n // console.log(\"last bit added to the search query\")\n }\n }\n sqlQuery+=\"LIMIT \"+startIndex+\",\"+endIndex;\n \n }else if(page==null&limit==null){\n for(let i=0;i<splitStr.length;i++){\n if(i!=splitStr.length-1){\n sqlQuery+=\"searchString LIKE '%\"+splitStr[i]+\"%' AND \"\n }else{\n sqlQuery+=\"searchString LIKE '%\"+splitStr[i]+\"%' \"\n }\n }\n }\n connectionPool.query(sqlQuery,(err,result)=>{\n if (err) {//Check for errors\n console.error(\"Error executing query: \" + JSON.stringify(err));\n response.send(\"error\");\n }\n else {\n obj=JSON.stringify(result); \n response.send(obj);\n console.log(\"This is cheese:\"+obj)\n }\n });\n }else{\n response.send(obj);\n }\n }\n });\n\n}", "usedPhrases ({start, end}) {\n const filterRow = row => row.date >= start && row.date < end\n const phrases = new Set()\n // load all the unique phrases\n for (let n = 1; n <= this.options.maxN; n++) {\n this.ngrams[n].filter(filterRow).forEach(row => {\n phrases.add(row.ngram)\n })\n }\n return [...phrases]\n }", "function searchProducts(){\n var searchWords = $(\"#search\").val();\n var searchArray = searchWords.split(\"\")\n if (searchWords == \"\"){\n readAll()\n }else{\n var count = 1;\n\n var formData = {};\n \n for (var j=0; j<searchArray.length; j++){\n formData[\"product\"+count] = searchArray[j];\n count += 1;\n }\n \n // console.log(formData);\n // for(var pair of formData.entries()) {\n // console.log(pair[0]+ ', '+ pair[1]); \n // }\n \n $.ajax({\n type: \"POST\",\n url: \"search.php\",\n data: {\n \"word\" : searchWords,\n },\n success: function (data, status) {\n //var products = JSON.parse(data);\n // console.log(data);\n $(\"#contents\").html(data);\n //console.log(products.status == \"success\");\n }\n });\n }\n\n\n \n\n}", "function wordCountEngine(doc) {\n const map = new Map();\n const wordList = doc.split(' ');\n let largestCount = 0;\n\n// for i from 0 to wordList.length-1:\n// # convert each token to lowercase\n// word = wordList[i].toLowerCase()\n for (let i = 0; i < wordList.length; i++) {\n const word = wordList[i].toLowerCase();\n const charArray = [];\n for (let char of word) {\n if (char >= 'a' && char <= 'z') {\n charArray.push(char);\n }\n \n }\n const cleanWord = charArray.join('');\n let count = 0;\n if (map.has(cleanWord)) {\n count = map.get(cleanWord);\n count++;\n } else {\n count = 1;\n }\n if (count > largestCount) {\n largestCount = count\n }\n map.set(cleanWord,count);\n }\n // const result = [];\n // for (let key of map) {\n // key[1] = key[1].toString()\n // result.push(key);\n \n // }\n // // result.sort((a,b) => b[1] - a[1])\n // return result;\n const counterList = new Array(largestCount + 1);\n for (word of map.keys()) {\n counter = map.get(word);\n wordCounterList = counterList[counter]\n console.log(counterList)\n if (wordCounterList == null) {\n wordCounterList = [];\n }\n wordCounterList.push(word);\n counterList[counter] = wordCounterList;\n }\n// # init the word counter list of lists.\n// # Since, in the worst case scenario, the\n// # number of lists is going to be as\n// # big as the maximum occurrence count,\n// # we need counterList's size to be the\n// # same to be able to store these lists.\n// # Creating counterList will allow us to\n// # “bucket-sort” the list by word occurrences\n// counterList = new Array(largestCount+1)\n// for j from 0 to largestCount:\n// counterList[j] = null\n\n// # add all words to a list indexed by the\n// # corresponding occurrence number.\n// for word in wordMap.keys():\n// counter = wordMap[word]\n// wordCounterList = counterList[counter]\n\n// if (wordCounterList == null):\n// wordCounterList = []\n\n// wordCounterList.push(word)\n// counterList[counter] = wordCounterList\n\n// # iterate through the list in reverse order\n// # and add only non-null values to result\n// result = []\n// for l from counterList.length-1 to 0:\n// wordCounterList = counterList[l]\n// if (wordCounterList == null):\n// continue\n\n// stringifiedOccurrenceVal = toString(l)\n// for m from 0 to wordCounterList.length-1:\n// result.push([wordCounterList[m], stringifiedOccurrenceVal])\n\n// return result\n\n}", "function longPlaneteerCalls(words){\nfor(let i = 0 ; i < words.length; i++){\nif(words[i].length > 4){\nreturn true\n}\n}\nreturn false\n}", "function ngram(arr, minwords, maxwords) {\n var keys = [, ];\n var results = [];\n maxwords++; //for human logic, we start counting at 1 instead of 0\n for (var i = 1; i <= maxwords; i++) {\n keys.push({});\n }\n for (var i = 0, arrlen = arr.length, s; i < arrlen; i++) {\n s = arr[i];\n keys[1][s] = (keys[1][s] || 0) + 1;\n for (var j = 2; j <= maxwords; j++) {\n if (i + j <= arrlen) {\n s += \" \" + arr[i + j - 1];\n keys[j][s] = (keys[j][s] || 0) + 1;\n } else break;\n }\n }\n //collect results\n for (var k = 0; k < maxwords; k++) {\n var key = keys[k];\n for (var i in key) {\n if (key[i] >= minwords) results.push(i);\n }\n }\n return results\n }", "function searching() {\n\n //tomo el valor que se está introduciendo y lo convierto en mayúscula para que sea más fácil el matcheo\n var letra = document.getElementById(\"buscador\").value.toUpperCase();\n\n let htmlContentToAppend = \"\";\n for (let i = 0; i < currentProductsArray.length; i++) {\n let product = currentProductsArray[i];\n //saco el nombre del auto y lo convierto en mayúscula para que sea más fácil el matcheo\n var nombre = product.name.toUpperCase();\n var descrip = product.description.toUpperCase();\n //verifica si está contenido en el nombre o la descripción \n if (nombre.includes(letra) || descrip.includes(letra)) {\n\n htmlContentToAppend += ` <\n a href = \"product-info.html\"\n class = \"list-group-item list-group-item-action\" >\n <\n div class = \"row\" >\n <\n div class = \"col-3\" >\n <\n img src = \"` + product.imgSrc + `\"\n alt = \"` + product.description + `\"\n class = \"img-thumbnail\" >\n <\n /div> <\n div class = \"col\" >\n <\n div class = \"d-flex w-100 justify-content-between\" >\n <\n h4 class = \"mb-1\" > ` + product.name + ` < /h4> <\n small class = \"text-muted\" > ` + product.soldCount + `\n Vendidos < /small> <\n /div> <\n p class = \"mb-1\" > ` + product.description + ` < /p> <\n p class = \"mb-1\" > ` + product.currency + \": \" + product.cost + ` < /p> <\n /div> <\n /div> <\n /a>\n `\n }\n document.getElementById(\"cat-list-container\").innerHTML = htmlContentToAppend;\n }\n\n}", "function wordsRepetition(words) {\n let uniqueWords = [...new Set(words)];\n let wordRepetition = [];\n // Finding how many times each word repeat in quaries\n function frequency(word) {\n let counter = 0;\n for (let i = 0; i < words.length; i++) {\n if (words[i] === word) counter++;\n }\n return counter;\n }\n // Calculate impr/click of the word\n function imprOrClick(type, word) {\n let value = 0;\n for (let i = 0; i < inputData.length; i++) {\n if (inputData[i].query.includes(word) === true) value += inputData[i][type];\n }\n return value;\n }\n\n // Calculate total impr/click of the URL\n function totalImprOrClick(type) {\n let value = 0;\n for (let i = 0; i < inputData.length; i++) {\n value += inputData[i][type];\n }\n return value;\n }\n \n let totalImpr = totalImprOrClick(\"impr\");\n let totalClick = totalImprOrClick(\"click\");\n let inputDataLen = inputData.length;\n\n\n for (let i = 0; i < uniqueWords.length; i++) {\n wordRepetition[i] = {\n word: uniqueWords[i],\n weight: (frequency(uniqueWords[i]) * imprOrClick(\"impr\", uniqueWords[i]) * Math.pow(uniqueWords[i].length, 2)),\n freq: frequency(uniqueWords[i]),\n freqPercent: frequency(uniqueWords[i]) / inputDataLen,\n impr: imprOrClick(\"impr\", uniqueWords[i]),\n imprPercent: imprOrClick(\"impr\", uniqueWords[i]) / totalImpr,\n click: imprOrClick(\"click\", uniqueWords[i]),\n clickPercent: imprOrClick(\"click\", uniqueWords[i]) / totalClick,\n wordsInPhrase: uniqueWords[i].split(\" \").length\n }\n }\n\n function weightSum(arr) {\n let sum = 0;\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i][\"weight\"];\n }\n return sum;\n }\n\n let totalWeight = weightSum(wordRepetition);\n\n for (let i = 0; i < wordRepetition.length; i++) {\n wordRepetition[i][\"weightPercent\"] = wordRepetition[i][\"weight\"] / totalWeight;\n }\n\n return wordRepetition;\n}", "function lookup(i) {\n if(i<words.length){\n var wrd = words[i].replace(/[\\.,-\\/#!$%\\^&\\*;:{}=\\-_`~()\\\"\\']/g,\"\"),\n stem = wrd.stem();\n console.log(\"\\n=====================\\nLooking up: \"+ words[i] + \" -> \"+wrd+ \" -> \"+stem);\n wordnet.lookup(wrd, function(results) {\n var trueCount = 0;\n results.forEach(function(result) {\n if(result.pos===\"a\" || result.pos===\"s\" || result.pos===\"r\") {\n trueCount++;\n console.log(\"true: \" + trueCount + \" times\");\n } \n //More checks for importance here!\n });\n if(trueCount/results.length>0.7){\n //marked=true;\n console.log(\"True percentage: \"+trueCount/results.length);\n console.log(\"- Very likely an Adj or Adv\");\n resultStr+=' <span class=\"unimportant1\" style=\"color:#dedede\"> '+words[i]+'</span>';\n } \n else if(trueCount/results.length>0.49){\n //marked=true;\n console.log(\"True percentage: \"+trueCount/results.length);\n console.log(\"- Possibly an Adj or Adv\");\n resultStr+=' <span class=\"unimportant2\" style=\"color:#999\"> '+words[i]+'</span>';\n }\n else {\n console.log(\"- Possibly not an Adj or Adv\");\n resultStr+=' '+words[i];\n }\n lookup(i+1);\n });\n } else {\n connection.sendUTF(resultStr);\n }\n \n }", "function calculateIndex(){\n orig_parahs = Object.assign([], parahs);\n for(let i=0; i<parahs.length; i++){\n //remove special characters and convert to lower case\n var tempString = parahs[i].replace(/[123]|[`~!@#$%^&*()_|+\\-=?;:'\",.<>\\{\\}\\[\\]\\\\\\/]/gi, '');\n parahs[i] = tempString.toLowerCase();\n }\n\n //for each paragraph, update word_count with the frequency of words\n for(let [count, doc] of parahs.entries()){\n word_count = {};\n wordlist = doc.split(' ');\n wordCount();\n //use word_count for the paragraph to add/update frequency and occurrence of index[word]\n for(let [c,word] of wordlist.entries()){\n if(get(index, word, \"false\")===\"false\"){\n var freq = word_count[word];\n var idp = Object.keys(document_id)[count];\n //index is of the form {word:{freq:doc_id}}\n index[word] = {};\n index[word][freq] = idp;\n }\n else{\n var freq = word_count[word];\n var idp = Object.keys(document_id)[count];\n index[word][freq] = idp;\n }\n }\n }\n}", "function filterLongWords(arr, i) {\n let longWordArray = [];\n for (let test = 0; test < arr.length; test++) {\n if (arr[test].length > i) {\n longWordArray += arr[test];\n }\n }\n return longWordArray;\n}", "function search_algo(f, term) {\r\n var mach = 0;\r\n var srch = searchEntities(term);\r\n var name = searchEntities(f.name);\r\n _.each(srch, function (s) {\r\n s = jQuery.trim(s)\r\n _.each(name, function (n) {\r\n n = jQuery.trim(n)\r\n if (n.indexOf(s) != -1) {mach++;}\r\n if (n.indexOf(s) === 0) {mach++;}\r\n if (n == s) {mach++;}\r\n if (f.id == s) {mach += 2;}\r\n });\r\n });\r\n if (mach > 0 && !f.server) mach++;\r\n return mach;\r\n}", "function sensorSentence ( sentence, words ) {\n var panjangWords = words.length-1\n \n var result= ''\n for(var i=0;i<sentence.length;i++){\n if(sentence[i] == words[0] && sentence[i+panjangWords] == words[panjangWords]){\n var awalsensor = i\n var ahirsensor = i+panjangWords\n }\n if(i>= awalsensor && i<=ahirsensor) result+= '*'\n else result+= sentence[i]\n }\n\n return result\n}", "function funcDetectProduct(str) {\n let a=detect(str,CT.knowledgeBaseFull);\n if(a.moreThanTwo){return \"more than two\"} \n if (!a.detected){return \"not found\"} \n return (!isNaN(parseInt(str)) && str.length===8) ? a.founded[\"Descriptive Code\"] : a.founded[\"Item Number\"]\n }", "countBigWords(input) {\n // code goes here\n //break string into separate words\n let words = input.split(\" \");\n //create a count\n let counter = 0;\n //iterate through each word in the string\n for (let i = 0; i < words.length; i++) {\n //check if each word's length is greater that 6\n //if it is increase the counter by 1\n if (words[i].length > 6) {\n counter++;\n }\n }\n\n //return the counter\n\n return counter;\n }", "async find(terms) {\n //TODO\n terms = terms.toString().replace(/,1/g, \"\");\n let results;\n let score;\n let docName = \"\";\n let arrayItems = [];\n let arrayResults = [];\n let ret;\n let line;\n let startIndex;\n let endIndex;\n let document = [];\n terms = terms.split(\",\");\n for(let term of terms) {\n arrayItems.length = 0;\n await db.collection(docs_table).find({ words: term }).forEach(function(items){\n arrayItems.push(items);\n });\n for(let item of arrayItems){\n score = item.score;\n startIndex = endIndex = item.offset;\n docName = item.docs;\n ret = await db.collection(docContent_table).findOne(\n {docN: docName} );\n while(ret.content.charAt(startIndex) !== '\\n'){\n if(startIndex === 0){break;};\n startIndex--;\n }\n while(ret.content.charAt(endIndex) !== '\\n'){\n endIndex++;\n }\n line = ret.content.substring(startIndex, endIndex);\n if(document.indexOf(docName) >= 0) {\n arrayResults.find(obj => obj.name === docName).score += score;\n if (arrayResults.find(obj => obj.name === docName).lines !== line) {\n arrayResults.find(obj => obj.name === docName).lines += \"\\n\" + line;\n }\n }else {\n document.push(docName);\n results = new Result(docName, score, line);\n arrayResults.push(results);\n }\n }\n }\n arrayResults.sort(compareResults);\n return arrayResults;\n }", "function filterLongWords (arr, i) {\n var ret = [];\n arr.forEach(function(s){\n if (s.length > i) {\n ret += [s];\n }\n });\n debugger;\n return ret;\n}", "function filtrarProductosXEtiqueta() {\n let textoIngresado = $(\"#txtFiltroProductos\").val();\n textoIngresado = textoIngresado.toLowerCase();\n let arrayFiltrados = { data: Array(), error: \"\" };\n for (let i = 0; i < productos.length; i++) {\n let unProd = productos[i];\n let unaEtiqueta = unProd.etiquetas;\n let x = 0;\n let encontrado = false;\n while (!encontrado && x < unaEtiqueta.length) {\n let etiquetaX = unaEtiqueta[x];\n if (etiquetaX.includes(textoIngresado)) {\n arrayFiltrados.data.push(unProd);\n encontrado = true;\n }\n x++;\n }\n }\n crearListadoProductos(arrayFiltrados);\n}", "function voiceCheck(search) {\n //save found words in found array variable.\n var found = [];\n\n //loop through the length of user inputed words and check to see IF they match gigVoice object keys.\n //if found, push that particular key to found array variable.\n for (var i = 0; i < search.length; i++) {\n var myArray = keys.filter(function(word) {\n if (word == search[i]) {\n found.push(gigVoice[search[i]]);\n //list out to DOM all the found words with their mathing object value.\n display.innerHTML += \"<li class='list-group-item list-group-item-action'>\" + search[i] + \" : \" + gigVoice[search[i]] + \"</li>\";\n }\n });\n }\n\n //if 0 items found then display red list alert, otherwise green list alert.\n if (found.length === 0) {\n //display in stats DOM location the number of found words compared to the number of words entered by user.\n stats.innerHTML = \"<li class='list-group-item list-group-item-danger'> Found \" + found.length + \" of \" + search.length + \"</li>\";\n } else {\n //display in stats DOM location the number of found words compared to the number of words entered by user.\n stats.innerHTML = \"<li class='list-group-item list-group-item-success'> Found \" + found.length + \" of \" + search.length + \"</li>\";\n }\n\n\n //default the input box placeholder.\n document.getElementById('searchInput').value = '';\n }", "function updateKWIC() {\n // kwic = RiTa.kwic(theText.join('\\n'), word, {\n // ignorePunctuation: true,\n // ignoreStopWords: true,\n // wordCount: 200\n // });\n kwic = RiTa.kwic(theTextCopy, word, {\n ignorePunctuation: true,\n // ignoreStopWords: true,\n wordCount: 10\n });\n // console.log(kwic);\n if (kwic.length == 0) {\n // textAlign(CENTER);\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textSize(14);\n text(\"Context word not found\", width / 1.7, height / 4);\n } else {\n\n var tw = textWidth(word);\n\n for (var i = 0; i < kwic.length; i++) {\n\n //console.log(display[i]);\n var parts = kwic[i].split(word);\n var x = width / 1.7,\n y = i * 20 + 115;\n\n if (y > height - 20) return;\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textSize(14);\n // fill(0);\n textAlign(RIGHT);\n text(parts[0], x - tw/1.5, y);\n\n fill(200, 0, 0);\n textFont(\"Lucida Console\");\n textAlign(CENTER);\n text(word, x, y);\n\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textAlign(LEFT);\n text(parts[1], x + tw/1.5, y);\n }\n }\n}", "function createIndex(word,times,and) {\t\n\t// Handle word as an array\n\tif (typeof(word) === 'object') {\n\t\tvar info = [];\n\t\t$.each(word,function(index,value) {\t\t\t\n\t\t\tvar new_info = createIndex(value.toLowerCase(),times);\n\t\t\tif (info.length == 0) info = new_info;\n\t\t\telse {\n\t\t\t\tvar l1 = new_info.length;\n\t\t\t\tloop1:\n\t\t\t\tfor (var i=0; i<l1; ++i) {\n\t\t\t\t\tvar new_id = new_info[i].ID;\n\t\t\t\t\tvar l0 = info.length;\n\t\t\t\t\tfor (var j=0; j<l0; ++j) {\n\t\t\t\t\t\tif (info[j].ID == new_id) {\n\t\t\t\t\t\t\tif (and) info[j].hits = Math.min(info[j].hits,new_info[i].hits);\n\t\t\t\t\t\t\telse info[j].hits += new_info[i].hits;\n\t\t\t\t\t\t\tcontinue loop1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!and) info.push(new_info[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t// Create Index page\n\t\t$('.Z3').remove();\n\t\t$('body').append('<div class=\"outer Z3\"></div>');\n\t\tvar Z3 = $('.Z3');\n\t\tvar title = 'Index: Sections containing \"' + word + '\"';\n\t\tif (typeof(times) === 'number' && times) {\n\t\t\ttitle += ' ' + times + ' times';\n\t\t\tif (!and) title += ' at least one of them';\n\t\t}\n\t\telse {\n\t\t\tif (and) title += ' (gcf)';\n\t\t\telse title += ' (sum)';\n\t\t}\n\t\tZ3.append('<h3>' + title + '</h3>');\n\t}\n\telse {\n\t\tword = word.toLowerCase();\n\t\t// Create Index page\n\t\t$('.Z3').remove();\n\t\t$('body').append('<div class=\"outer Z3\"></div>');\n\t\tvar Z3 = $('.Z3');\n\t\tvar title = 'Index: Sections containing \"' + word + '\"';\n\t\tif (typeof(times) === 'number' && times) title += ' ' + times + ' times';\n\t\telse times = 1;\n\t\tZ3.append('<h3>' + title + '</h3>');\n\t\t\n\t\tvar info = [];\n\t\t// Find pages containing word\n\t\t$('.inner').not('.outer').each(function(i) {\n\t\t\tvar string = this.innerHTML.toLowerCase();\n\t\t\tvar test = string.indexOf(word);\n\t\t\t// Count how many times word appears on page\n\t\t\tfor (var j=0; test != -1; ++j) {\n\t\t\t\tstring = string.substr(test+1);\n\t\t\t\tif (typeof(word) === 'object') {\n\t\t\t\t\t$.each(word,function(index,value) {\n\t\t\t\t\t\tvar spot = string.indexOf(value);\n\t\t\t\t\t\tif (test == -1 || (spot != -1 && spot < test)) test = spot;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse test = string.indexOf(word);\n\t\t\t}\n\t\t\tif (j >= times) test = 0;\n\t\t\tif (test != -1) {\n\t\t\t\tvar classes = this.className.split(/\\s/);\n\t\t\t\tvar new_id = classes[classes.length-1];\n\t\t\t\tinfo.push({ 'ID': new_id, 'hits': j });\n\t\t\t}\n\t\t});\n\t}\n\t// Sort pages by how many times they contain word\n\tinfo.sort(function(a,b) { return b.hits - a.hits; });\n\tvar length = info.length;\n\t// Put page summaries in index page\n\tfor (var k=0; k < length; ++k) {\n\t\tvar new_id = info[k].ID;\n\t\tif (new_id) {\n\t\t\t// Code for Preview Text\n\t\t\tvar obj = $('#' + String.fromCharCode(new_id.charCodeAt(0)-1) + new_id.substr(1)).clone();\n\t\t\tobj.children('.delete,.handle').remove();\n\t\t\tvar content = obj.html();\n\t\t\tcontent = /*'<button class=\"preview_exit\">&times;</button>*/'<p style=\"margin:0px 6px;\">' + content + '</p>';\n\t\t\tcontent = '<button class=\"preview_main\">*<br/><span>' + info[k].hits + '</span></button>' + /*'<button class=\"preview_split\">&raquo;</button>' +*/ content;\n\t\t\tcontent = '<div id=_' + new_id +' class=\"preview_window\">' + content + '</div>';\n\t\t\t\n\t\t\t$('.preview_window#_' + new_id).remove();\n\t\t\tZ3.append(content);\n\t\t}\n\t}\n\t// Go to index page\n\tvar index = workspace.indexOf('Z3');\n\tif (index != -1) {\n\t\tZ3.attr('id','Z3');\n\t\tswitch_tab(index);\n\t}\n\telse explore_tangent('Z3');\n\t$(window).resize();\n\treturn info;\n}", "function filterLongWord(arr, i){\n var q=[];\n var k =0;\n arr.map(function(p,c){\n if(p.split('').length>i) q[k++]=p;\n });\n return q;\n }", "function searchProduct(){\r\n \r\n var go = \"Thing(?i)\";\r\n \r\n submitProduct(go); \r\n \r\n }", "function createGoodness() {\n\n var numPhrases = 100\n\n //get starting word\n var newShit = getNewWord()\n \n\n //Save last word for key \n var lastWord = newShit\n \n\n for(var i = 0; i < numPhrases - 1; i++) {\n\n var newWord = \"\"\n\n if(words.has(lastWord)) {\n newWord = words.get(lastWord).getWord()\n }\n else {\n var newWord = getNewWord()\n }\n\n newShit += \" \"\n newShit += newWord\n lastWord = newWord\n \n }\n\n //console.log(newShit)\n document.getElementById(\"MarkovText\").innerHTML = newShit\n\n var longest = 0\n words.forEach(item => {\n if(item.getNumFollowers() > longest) {\n longest = item.getNumFollowers() \n }\n })\n\n console.log(longest)\n}", "function searchwords(){var wd=jQuery.trim($('#searchwrods').val()).replace(/\\./g,''); if(''==wd || '客官要点什么'==wd){$('#searchwrods').attr('placeholder','客官还没点呢');return;}querywords(wd);}", "function findMatches(wordToMatch, products) {\n\treturn products.filter(product=>{\n\t\tconst regex = new RegExp(wordToMatch,'gi');\n\t\treturn product.title.match(regex) || product.filtertags.country.match(regex)\n\t})\n}", "function countWords() {\n //get display location into variable.\n var ul = document.getElementById(\"display\", \"stats\");\n\n //remove any unordered list in DOM.\n while (ul.firstChild) ul.removeChild(ul.firstChild);\n\n //turn user input to UpperCase since all gigVoice keys are upper case. For easy matching for now.\n //will need to find a fix for apostrophe characters in a word.\n var w = document.getElementById(\"searchInput\").value.toUpperCase();\n\n //remove end spacing\n w = w.replace(/(^\\s*)|(\\s*$)/gi, \"\");\n\n //gather 2 or more spacing to 1\n w = w.replace(/[ ]{2,}/gi, \" \");\n\n //exclude new line with start spacing\n w = w.replace(/\\n /, \"\\n\");\n\n //split string\n w = w.split(' ')\n return voiceCheck(w);\n\n }", "function solution_1 (words) {\r\n\r\n // SOLUTION 1 [\r\n // O(nl time (n is # of words, l is longest length. the first few steps of the algo are n time, but the biggest time sink is the queue. if each of your n words has l letters, then\r\n // your queue will go through l \"major cycles\" (such that each major cycle adds up to n or fewer iterations) since 1 letter gets removed each time. thus, n*l),\r\n // O(nl) space (prereqs object is arguably constant because at most 26 letters, 25 prereqs each. similarly, all sets/arrays such as lettersSeen or noPrereqs will have no more\r\n // than 26 elements. however, the queue matters. n is # of words, l is longest length. the first element in queue takes up n*l characters in total. those words will be distributed \r\n // in some way into potentially 26 buckets, but it will still be at most n words, each of which will be at most (l - 1) length. whenever anything is added to the queue, the amount\r\n // added will always be less than amount recently shifted out, so the space occupied by the queue should not exceed the initial nl)\r\n // ]:\r\n // in this solution we create a prereqs object where every unique letter found inside the alien dictionary will eventually be a key in prereqs, and the values will be sets containing\r\n // any letter that must go before the corresponding key. to build this, we will use a queue, where every element in the queue will be a subarray of words that have an equal basis of\r\n // comparison prior to its first letter. thus, the initial input will be the first element in the queue. (thereafter, all words beginning with the same letter will go into their own\r\n // subarrays and be added to the queue.)\r\n // (1) when analyzing a particular subarray of words, the first order of business is to make sure that the words within are properly grouped by first\r\n // letter. in other words, you shouldn't have something like ['axx', 'ayy', 'bxxx', 'azz'] because the a...b...a is invalid (a cannot be both before and after b).\r\n // if a violation is found we can immediately return '' because the entire alien dictionary is invalid.\r\n // (2) next, we iterate through the subarray of words. since we know the words are properly grouped by their first letters, we just need to iterate through the words, and every time\r\n // we encounter a new first letter, we will add all previously seen first letters to the prerequisite of the current first letter. additionally, we should start creating new\r\n // subarrays for each new first letter to enter the queue, and we should push in each word.slice(1) into that subarray, for future processing. for example, if the current block is\r\n // ['axx', 'byy', 'bzz'] we want to push in ['xx'] (for the a) followed by ['yy', 'zz'] (for the b).\r\n // after doing all of that, the prereqs object has now been properly constructed. this is now effectively a graph! the final step is to start building the output string. while the\r\n // output string has a length less than the total number of unique letters in the dictionary, we keep going. for every iteration, we search the prereqs object for letters that have no\r\n // prerequisites (set size is 0). we add these letters to a list of processedLetters, we delete the entries for those letters from the prereqs object, and we add that letter to the end\r\n // of output. if we find that no letters had zero prerequisites (i.e. the list of processedLetters is empty) then there must be a cycle in the graph, because every letter depends on\r\n // something else, and so the alien dictionary is invalid - return ''. otherwise, we simply run through the prereqs object a second time, removing all processedLetters from the sets\r\n // of all remaining letters.\r\n // eventually, if and when the while loop exits, then the alien dictionary is valid and the output string has been built out, so we return the output string as required.\r\n\r\n // INITIALIZE prereqs GRAPH\r\n const prereqs = {}; // keys are letters, and values are a set of prerequisite letters that must go before the given letter\r\n \r\n // CONFIGURE prereqs OBJECT. EACH SET OF ENTRIES FROM THE QUEUE HAS EQUAL BASIS OF COMPARISON PRIOR TO ITS FIRST LETTER\r\n const queue = [words]; // initialize with all words\r\n while (queue.length) {\r\n // shift out currentWords from queue\r\n const currentWords = queue.shift();\r\n \r\n // identical first letters must be adjacent. check for something like a...b...a which would invalidate the entire dictionary\r\n const lettersSeen = new Set();\r\n for (let i = 0; i < currentWords.length; i++) {\r\n if (i && currentWords[i][0] === currentWords[i - 1][0]) continue; // same letter as previous? skip\r\n if (lettersSeen.has(currentWords[i][0])) return ''; // else, it's a new letter. make sure you haven't seen it yet\r\n lettersSeen.add(currentWords[i][0]); // add this letter to the list of letters seen\r\n }\r\n \r\n // update the prerequisites\r\n lettersSeen.clear(); // this now represents all letters seen so far for each new block\r\n for (let i = 0; i < currentWords.length; i++) {\r\n const char = currentWords[i][0];\r\n if (!i || char !== currentWords[i - 1][0]) { // if new letter...\r\n if (!(char in prereqs)) prereqs[char] = new Set(); // (initialize prereqs entry if necessary)\r\n prereqs[char] = new Set([...prereqs[char], ...lettersSeen]); // add all letters seen so far in this block to the prereqs for this char\r\n lettersSeen.add(char); // add this char to letters seen so far in this block\r\n queue.push([]); // set up new subarray (new queue entry) for this letter. it's possible this will be empty, but that's fine\r\n }\r\n if (currentWords[i].length > 1) { // whether or not new letter, if and only if there are letters after current char\r\n queue[queue.length - 1].push(currentWords[i].slice(1)); // then push those remaining letters into the latest queue entry (there will always be something)\r\n }\r\n }\r\n }\r\n \r\n // BUILD output STRING BASED ON prereqs OBJECT\r\n let output = '';\r\n const totalLetters = Object.keys(prereqs).length; // this is simply the number of unique letters found anywhere in the dictionary. each letter should have a prereqs entry\r\n while (output.length < totalLetters) {\r\n const noPrereqs = []; // this holds letters with no prerequisites, which can therefore be added to output\r\n for (const letter in prereqs) { // pass 1: find and process all letters with no prereqs\r\n if (!prereqs[letter].size) { // if a letter has no prereqs, then process it\r\n noPrereqs.push(letter);\r\n output += letter;\r\n delete prereqs[letter];\r\n }\r\n }\r\n if (!noPrereqs.length) return ''; // if you didn't find any prereqs, then you have a cycle in the graph - invalid!\r\n for (const letter in prereqs) { // pass 2: delete all processed letters from the prereqs of all remaining letters\r\n for (const processedLetter of noPrereqs) {\r\n prereqs[letter].delete(processedLetter);\r\n }\r\n }\r\n }\r\n\r\n return output;\r\n}", "function searchMaxprod(searchMaxvalue) {\r\n if(searchMaxprod > 1000) {\r\n let searchedMaxprod = products.filter(function(product,index){\r\n\r\n return product.price.indexOf(searchMaxvalue) !=-1 ;\r\n });\r\n\r\n }\r\n else {\r\n return false;\r\n }\r\n\r\n displayProducts(searchedMaxprod);\r\n\r\n}", "function BOT_tagWords() {\r\n\tBOT_lemTagList = [];\r\n\tvar w,t;\r\n\tfor(var i in BOT_lemWordList) {\r\n\t\tw = BOT_lemWordList[i];\t\r\n\t\tt = \"TXT\";\t\t\t\t\t\t\t// default\r\n\t\tres = w; \t\t\t\t\t\t\t\t// default\r\n\t\tif(w == \"_possibility\") t = \"POS\";\r\n\t\telse if(BOT_wordIsPer(w,i)) t = \"PER\";\t// i = position in sentence\r\n\t\telse if(BOT_wordIsSep(w)) t = \"SEP\";\r\n\t\telse if(BOT_wordIsPss(w)) t = \"PSS\";\r\n\t\telse if(BOT_wordIsEqu(w)) t = \"EQU\";\r\n\t\telse if(BOT_wordIsFee(w)) t = \"FEE\";\r\n\t\telse if(BOT_wordIsJud(w)) t = \"JUD\";\r\n\t\telse if(BOT_wordIsStr(w)) t = \"STR\";\t// stresser\r\n\t\telse if(BOT_wordIsVal(w,i)) t = \"VAL\";\t// supersede the rest\r\n\t\telse if(BOT_wordIsAct(w)) t = \"ACT\";\r\n\t\telse if(BOT_wordIsRel(w)) t = \"REL\";\r\n\t\telse if(BOT_wordIsRef(w)) { t = \"REF\"; res = BOT_wordIsRef(w) }\r\n\t\telse if(BOT_wordIsKey(w) ) {\r\n\t\t\tt = \"KEY\";\r\n\t\t\tif(i>0) { // if no performative \r\n\t\t\t\t// Composed keys\r\n\t\t\t\tvar pred = BOT_lemTagList[i-1];\r\n\t\t\t\tif(i != 0 && pred[0] == \"KEY\") {\t // two keys\r\n\t\t\t\t\tt = \"KYS\";\r\n\t\t\t\t\tres = [pred[1],w];\r\n\t\t\t\t\tBOT_lemTagList[i-1] = \"_$_\";\t // used locally\r\n\t\t\t\t}\r\n\t\t\t\telse if(pred[0] == \"KYS\") {\t\t\t // more than two keys\r\n\t\t\t\t\tt = \"KYS\";\r\n\t\t\t\t\tres = pred[1].concat([w]);\r\n\t\t\t\t\tBOT_lemTagList[i-1] = \"_$_\";\t // used locally\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tBOT_lemTagList = BOT_lemTagList.concat([[t,res]]);\r\n\t}\r\n\t// delete first of composed keys\r\n\tBOT_lemTagList = BOT_delete(BOT_lemTagList,\"_$_\");\r\n}", "function getTopTen(searchWord, arr){\n occ_doc = []\n for(let [c,key] of arr.entries()){\n occ_doc.push(index[searchWord][key]);\n }\n return occ_doc;\n}", "function filterLongWords(arr,i) {\n let word = \"\";\n for (let i = 0; i < arr.length; i++) {\n if (word.length < arr[i].length) {\n word = arr[i];}\n }\n return word;\n // finds the length of the longest word \n }", "function doSearch()\n{\n var searchTerm = document.searchbox.searchterm.value;\n var productOne = 'Young Titan: The Making of Winston Churchill';\n var productTwo = 'Animal Farm';\n var productThree = 'The Mysterious Island [Paperback]';\n \n if (checkSearchTerm(productOne, searchTerm))\n {\n \tbuildProduct('Young Titan: The Making of Winston Churchill', 'bob smith','978-1451609912','Biography of Winston Churchill\\'s career from 1901 through 1915.');\n }\n else if (checkSearchTerm(productTwo, searchTerm))\n {\n buildProduct('Animal Farm', 'George Orwell', '978-1412811903', 'George Orwell\\'s famous fabel of a workers revolution gone awry');\n }\n else if (checkSearchTerm(productThree, searchTerm)) \n {\n buildProduct('The Mysterious Island [Paperback]', 'Jules Verne', '978-1613822364','Verne\\'s classic tale of five Americans who are stranded on an uncharted island.');\n }\n\telse\n\t{\n productarea.document.writeln('Invalid search term entered: ' + searchTerm + '. Please try again');\n productarea.document.close();\n } // end of switch statement\n\n} // end of function doSearch", "function searchEntities(word, contin) {\n //console.log('im here2: ' + word + \" caller: \" + arguments.callee.caller);\n if (entities.length > projectLimit) {\n return;\n }\n $.ajax({\n dataType: \"json\",\n async: true,\n url: 'http://wikidata.org/w/api.php?action=wbsearchentities&search=' + word + '&limit=50continue=' + contin + '&language=en&format=json&callback=?'\n\n }).done(function (data) {\n //console.log(data);\n for (var i = 0; i < data.search.length; i++) {\n //entities[Object.keys(entities).length + 1] = {'id': i, 'name': data.search[i].label};\n entities.push(data.search[i].label);\n }\n if (data.search.length < 50) {\n return;\n }\n if (entities.length < 100) {\n searchEntities(def, entities.length);\n } else if ($('#theme_name').val() !== '') {\n //console.log(theme);\n searchEntities($('#theme_name').val(), entities.length);\n }\n //console.log(entities);\n //console.log(entities.length);\n });\n\n}", "function filteredShoes() {\n let searchTerm = \"shoe\";\n console.log(searchTerm);\n console.log(products);\n let searchedProducts = products.filter((product) => \n product.product_type.toLowerCase().includes(searchTerm.toLowerCase())\n \n );\n console.log(searchedProducts);\n make_products(searchedProducts);\n\n}", "function getCounts() {\n kwordArr.sort();\n let currentWord = null;\n let cnt = 0;\n for (var i = 0; i < kwordArr.length; i++) {\n if (kwordArr[i] !== currentWord) {\n if (cnt > 0) {\n let word = {\n \"value\": currentWord,\n \"count\": cnt,\n }\n dataArray.push(word);\n }\n currentWord = kwordArr[i];\n cnt = 1;\n } else {\n cnt++;\n }\n }\n if (cnt > 0) {\n let word = {\n \"value\": currentWord,\n \"count\": cnt,\n }\n dataArray.push(word);\n }\n }", "static get wordsMap() {\n return {\n 0: { word: \"Zero\" },\n 1: { word: \"One\" },\n 2: { word: \"Two\" },\n 3: { word: \"Three\" },\n 4: { word: \"Four\" },\n 5: { word: \"Five\" },\n 6: { word: \"Six\" },\n 7: { word: \"Seven\" },\n 8: { word: \"Eight\" },\n 9: { word: \"Nine\" },\n 10: { word: \"Ten\" },\n 11: { word: \"Eleven\" },\n 12: { word: \"Twelve\" },\n 13: { word: \"Thirteen\" },\n 14: { word: \"Fourteen\" },\n 15: { word: \"Fifteen\" },\n 16: { word: \"Sixteen\" },\n 17: { word: \"Seventeen\" },\n 18: { word: \"Eighteen\" },\n 19: { word: \"Nineteen\" },\n 20: { word: \"Twenty\" },\n 30: { word: \"Thirty\" },\n 40: { word: \"Fourty\" },\n 50: { word: \"Fifty\" },\n 60: { word: \"Sixty\" },\n 70: { word: \"Seventy\" },\n 80: { word: \"Eighty\" },\n 90: { word: \"Ninty\" },\n 100: { word: \"Hundred\", isCountable: true },\n 1000: { word: \"Thousand\", isCountable: true },\n 100000: { word: \"Lakh\", isCountable: true },\n 10000000: { word: \"Crore\", isCountable: true }\n };\n }", "function frequentngram(ngram)\n{\n \n \n \n\n}", "function findWords(){\n if(options.isOn == false){\n options.isOn = true;\n options.timer.check(\"Traverse Grid\");\n result = traverseGrid();\n options.isOn = false;\n loading.stop();\n options.timer.check(\"Display Results\");\n displayResults(result);\n options.timer.stop()\n displayTime();\n }\n }", "doSearch() {\n this.setState(\n (prevState, props) => {\n var count = this.state.seacrchText.length * 3;\n return {\n seacrchCount: prevState.seacrchCount + 1,\n resultCount: count\n };\n }\n );\n }", "function getKeywords(dataObj, minWordLen, minFreq) {\n var fdist = dataObj.fdist;\n var keywords = [];\n for (var i = 0; i < fdist.length; i++) {\n if (fdist[i][1] >= minFreq && fdist[i][0].length >= minWordLen) \n {\n if ( fdist[i][0]!= \"Prof.\")\n keywords.push(fdist[i][0]); \n }\n }\n return keywords;\n}", "function buscarProducto(keyword){\n\tif(keyword.length >= 3){\n\t\tkeyword = encodeURIComponent(keyword);\n\t\thttpGet(`/api/search/${keyword}`, results => {\n\t\t\ttry{\n\t\t\t\tresults = JSON.parse(results);\n\t\t\t}catch(e){\n\t\t\t\tresults = null;\n\t\t\t}\n\t\t\tq('#buscador-sugerencias').firstChild.innerHTML = '';\n\t\t\tif(results != null && results != undefined){\n\t\t\t\tq('#buscador-sugerencias').children[0].innerHTML = generarResultadosBusquedaHTML(results);\n\t\t\t\tacortarTextoResultadosBusqueda();\n\t\t\t}else{\n\t\t\t\t//Si no hay resultados, ocultar la barra de results\n\t\t\t\tq('#buscador-sugerencias').style.display = 'none';\n\t\t\t}\n\t\t});\n\t}else{\n\t\tq('#buscador-sugerencias').style.display = 'none';\n\t}\n}", "function createW(total_results, product_id, degree_connection, relationship_desc) {\n\n var deferred = Q.defer();\n var results = total_results;\n var id = product_id;\n var connection = degree_connection;\n var desc = relationship_desc;\n\n var definitions = results[results.length - 1];\n results.pop();\n\n var resultsArray = JSON.stringify(results);\n var resultsLength = results.length;\n\n //console.log(\"Total number of word suggestions found before filtering: \" + resultsLength);\n\n // validation\n db.words.findOne({ search_word: id, relationship: connection},\n function (err, word) {\n if (err) deferred.reject(err.name + ': ' + err.message);\n\n if (word) {\n // word already exists in database\n deferred.reject('Word \"' + results._id + '\" is already in database');\n }\n else {\n createWord();\n }\n });\n\n function createWord() {\n var newMeta = [];\n\n //Want to check for duplicates in newMeta array and slice the repitition off the results at the index of repitition\n newMeta = convertToDoubleMeta(results, id);\n var arrayBlacklist = containsAndRemove(newMeta, newMeta, results, id);\n\n var i = 0;\n var index = 0;\n\n var string_data = JSON.stringify(results); //outputs string from JSON\n var json_array1 = JSON.parse(string_data);\n\n //Removes words from blacklist array\n for (i = 0; i < results.length; i++) {\n if (containsAndRemoveObject(arrayBlacklist, results[i], json_array1, index) === false) {\n index++;\n }\n }\n db.words.insert({ search_word: id, relationship: connection, defs: definitions, links: json_array1 },\n function (err, doc) {\n if (err) deferred.reject(err.name + ': ' + err.message);\n\n deferred.resolve();\n });\n } //end of createWord\n\n return deferred.promise;\n}", "function filterLongWords(words, i)\n{\n\n\n\n\nvar x = words.filter(function(word){\n\n\treturn word.length > i;\n}); \nreturn x;\n}", "getText(numWords = 100) {\n const objKeys = Object.keys(this.markovChain);\n // console.log(\"objKeys = \", objKeys);\n let chosenWord;\n let currNumWords = text.length;\n let randomKeyIdx = this._getRandomNum(objKeys);\n let key = objKeys[randomKeyIdx];\n let text = [];\n\n while (chosenWord !== null && currNumWords <= numWords) {\n console.log(\"key = \", key);\n let wordList = this.markovChain[key];\n console.log(\"wordlist = \", wordList);\n let randomWordIdx = this._getRandomNum(wordList);\n\n if (wordList.length === 1) chosenWord = wordList[0];\n \n chosenWord = wordList[randomWordIdx];\n // console.log(\"chosenWord = \", chosenWord);\n \n key = chosenWord;\n text.push(chosenWord);\n currNumWords = text.length;\n }\n console.log(\"text = \", text.join(' '));\n return text.join(' ');\n }", "function suggest(keywords,key,object)\n{\n //alert(\"line 19=\"+object.id);\nvar results = document.getElementById(\"results\");\n \n if(keywords != \"\")\n {\n var terms = get_data(); // sort? -- data should be alphabetical for best results\n\n var ul = document.createElement(\"ul\");\n var li;\n var a;\n \n if ((key.keyCode == '40' || key.keyCode == '38' || key.keyCode == '13'))\n {\n navigate(key.keyCode,object);\n }\n else\n {\n var kIndex = -1;\n \n for(var i = 0; i < terms.length; i++)\n { \n kIndex = terms[i].activity.toLowerCase().indexOf(keywords.toLowerCase());\n \n if(kIndex >= 0) \n {\n li = document.createElement(\"li\");\n \n // setup the link to populate the search box\n a = document.createElement(\"a\");\n a.href = \"javascript://\"; \n \n a.setAttribute(\"rel\",terms[i].val);\n a.setAttribute(\"rev\", getRank(terms[i].activity.toLowerCase(), keywords.toLowerCase()));\n a.setAttribute(\"ref\",terms[i].val2);\n \n if(!document.all) a.setAttribute(\"onclick\",\"populate(this,object);\");\n else a.onclick = function() { populate(this,object); }\n \n \n \n a.appendChild(document.createTextNode(\"\"));\n \n if(keywords.length == 1) \n {\n var kws = terms[i].activity.toLowerCase().split(\" \");\n //alert(\"line 68=\"+kws+terms[i].val2);\n\n var firstWord = 0;\n \n for(var j = 0; j < kws.length; j++)\n {\n // if(kws[j].toLowerCase().charAt(0) == keywords.toLowerCase()) {\n \n ul.appendChild(li);\n \n if(j != 0) {\n kIndex = terms[i].activity.toLowerCase().indexOf(\" \" + keywords.toLowerCase());\n kIndex++;\n }\n \n break;\n // }\n }\n }\n else if(keywords.length > 1) {\n ul.appendChild(li);\n }\n else continue;\n\n \n var before = terms[i].activity.substring(0,kIndex);\n var after = terms[i].activity.substring(keywords.length + kIndex, terms[i].activity.length);\n \n a.innerHTML = before + \"<strong>\" + keywords.toLowerCase() + \"</strong>\" + after;\n \n li.appendChild(a);\n\n }\n } \n \n if(results.hasChildNodes()) results.removeChild(results.firstChild);\n \n // position the list of suggestions\n var s = document.getElementById(object.id);\n var xy = findPos(s);\n \n results.style.left = xy[0] + \"px\";\n results.style.top = xy[1] + s.offsetHeight + \"px\";\n results.style.width = s.offsetWidth + \"px\";\n \n // if there are some results, show them\n if(ul.hasChildNodes()) {\n results.appendChild(filterResults(ul));\n \n if(results.firstChild.childNodes.length == 1) results.firstChild.firstChild.getElementsByTagName(\"a\")[0].className = \"hover\";\n \n }\n\n }\n }\n else\n {\n if(results.hasChildNodes()) results.removeChild(results.firstChild);\n }\n}", "function findSubstrings(words, parts) {\n function leaf(x) {\n this.value = x;\n this.end = false;\n this.children = []\n }\n function createTree(root,parts){\n if(!parts.length){\n return []\n }\n\n var childArray = [];\n //var endArray = []\n var children = [];\n parts.forEach((ele,i)=>{\n var index = children.indexOf(ele[0]);\n if (index == -1){\n root.children.push(new leaf(ele[0]))\n children.push(ele[0]);\n if(ele.length>1){\n childArray.push([ele.substr(1)])\n }else{\n root.children[root.children.length-1].end = true;\n //this.end = true;\n childArray.push([])\n }\n }else{\n if(ele[0] == \"i\"){\n console.log(ele[0])\n //root.children[root.children.length-1]\n }\n if(ele.length>1){\n childArray[index].push(ele.substr(1))\n }else{\n //console.log(root.children[index])\n root.children[index].end =true;\n }\n }\n })\n //console.log(childArray);\n root.children.forEach((ele,index) =>{\n if (childArray[index].length>0){\n createTree(ele,childArray[index])\n }\n })\n }\n var root = new leaf('');\n //createTree(root,[\"a\", \"mel\", \"lon\", \"el\", \"An\"]);\n createTree(root,parts);\n //console.log(root)\n function search(word,tree){\n var startIndex = 0,maxLength=-1;\n for(var start=0; start<word.length;start++){\n var root = tree;\n for(var i = start; i< word.length ;i++){\n // console.log(word[i] + ' ' + start)\n var index = root.children.findIndex(ele=>{\n return ele.value == word[i] })\n if(index==-1){\n break;\n }else{\n //console.log(root);\n root = root.children[index];\n if(\"myopic\" == word){\n // console.log(root.value);\n // console.log(root.end);\n }\n\n if(root.end == true && ((i-start)> maxLength)){//&& startIndex<start\n startIndex = start;\n maxLength = i-start;\n }\n }\n }\n }\n //console.log(maxLength + \" \" + startIndex)\n if(maxLength!=-1){\n word = word.substr(0,startIndex) + '[' + word.substr(startIndex,maxLength+1) + \"]\" + word.substr(startIndex+maxLength+1)\n }\n return word;\n }\n //search('Watermelon',root)\n // console.log(tree);\n words.forEach((ele,index)=>{\n words[index] = search(ele,root);\n })\n return words;\n}", "productSearch() {\n let query = this.addableProduct.product.name;\n delete this.addableProduct.product.id; // Such that a user cannot input a name for a specific product_id\n\n if (query === undefined || query.length <= 1) {\n this.searchProductsList = [];\n } else {\n this.searchProductsList = this.unreceivedProducts.filter( item => {\n return (item.product.name.match(new RegExp(query, 'i')) !== null) ||\n (item.product.article.match(new RegExp(query, 'i')) !== null);\n })\n }\n }", "function naiveSearchString(longString, shortString) {\n let count = 0;\n\n for (let i = 0; i < longString.length; i++) {\n for (let j = 0; j < shortString.length; j++) {\n if (shortString[j] !== longString[i + j]) break;\n if (j === shortString.length - 1) count++;\n }\n }\n return console.log(\"count is: \", count);\n}", "function doubleSearch () {}", "function getAnadiplosisCount() {\r\n text = workarea.textContent;\r\n search_string = \"[a-zA-Zа-яА-ЯёЁ]+[.?!;]{1,3}\\\\s[a-zA-Zа-яА-ЯёЁ]+\";\r\n middle_words = text.match(/[a-zA-Zа-яА-ЯёЁ]+[.?!;]{1,3}\\s[a-zA-Zа-яА-ЯёЁ]+/g);\r\n new_phrases = [];\r\n result = [];\r\n if(middle_words != null) {\r\n for (i=0; i < middle_words.length; i++) {\r\n phrase = middle_words[i];\r\n phrase = phrase.toLowerCase();\r\n near_space = phrase.match(/[.?!;]{1,3}\\s/)[0];\r\n phrase = phrase.split(near_space);\r\n if(phrase[0] == phrase[1]) {\r\n new_phrases.push(middle_words[i]);\r\n }\r\n }\r\n result = new_phrases;\r\n\r\n tmp = [];\r\n for(key in result) {\r\n if(tmp.indexOf(result[key]) == -1) {\r\n tmp.push(result[key]);\r\n }\r\n }\r\n result = tmp;\r\n count = 0;\r\n\r\n search_string = \"([a-zA-Zа-яА-ЯёЁ]+\\\\s){0}\" + search_string + \"(\\\\s[a-zA-Zа-яА-ЯёЁ]+){0}\";\r\n while(new_phrases.length != 0) {\r\n\r\n middle_words = [];\r\n count++;\r\n search_reg = new RegExp(\"\\\\{\"+(count-1)+\"\\\\}\", 'g');\r\n search_string = search_string.replace(search_reg, \"{\"+count+\"}\");\r\n middle_words = text.match(new RegExp(search_string,\"g\"));\r\n new_phrases = [];\r\n if(middle_words != null) {\r\n for (i=0; i < middle_words.length; i++) {\r\n phrase = middle_words[i];\r\n phrase = phrase.toLowerCase();\r\n near_space = phrase.match(/[^a-zA-Zа-яА-ЯёЁ]{1,3}\\s/)[0];\r\n phrase = phrase.split(near_space);\r\n temp = middle_words[i].split(near_space);\r\n for(j=0; j<phrase.length-1; j++) {\r\n if(phrase[j] == phrase[j+1]) {\r\n new_phrases.push(temp[j] + near_space + temp[j+1]);\r\n } \r\n }\r\n }\r\n\r\n for(key in new_phrases) {\r\n result.push(new_phrases[key]);\r\n }\r\n }\r\n\r\n }\r\n tmp = [];\r\n for(key in result) {\r\n if(tmp.indexOf(result[key]) == -1) {\r\n tmp.push(result[key]);\r\n }\r\n }\r\n result = tmp;\r\n }\r\n return result.length;\r\n}", "function searchData() {\r\n var searchKeyword = document.getElementById(\"navSearch\").value.toUpperCase();\r\n console.log(searchKeyword);\r\n var searchResult = productData.filter((searchItem) => searchItem.product.toUpperCase().includes(searchKeyword));\r\n console.log(searchResult);\r\n cards(searchResult);\r\n}", "function searchResults(){\n let resultDocs = [];\n \n queryWords = tokenizer.tokenize(query);\n queryWords.forEach((word)=>{\n \n word = stemmer.stem(word.toLowerCase());\n word = stopwords.includes(word) ? \"\" : word;\n \n if(word){\n let newDocs = wordDocs(word);\n \n // union of both document arrays\n // resultDocs = [...new Set([...resultDocs, ...newDocs])];\n\n // resultDocs = resultDocs.concat( resultDocs.filter(x => !newDocs.includes(x)) );\n\n if(newDocs.length && resultDocs.length){\n resultDocs = resultDocs.filter(x => !newDocs.includes(x));\n }else{\n resultDocs = newDocs;\n }\n }\n });\n\n\n return resultDocs;\n }", "function stringSearch(long, short){\n let counter = 0;\n\n for (let i = 0; i < long.length; i ++){\n for (let j = 0; j < short.length; j ++){\n console.log(short[j], long[i+j])\n if (short[j] !== long[i+j]){\n console.log(\"BREAK!!!\")\n break;\n }\n if (j === short.length -1){\n console.log(\"FOUND ONE!!\");\n counter ++\n }\n }\n }\n\n return counter\n}", "function search() {\n var input, filter, searchItem = [];\n input = document.getElementById(\"search-item\");\n filter = input.value.toLowerCase();\n console.log(\"filter \" + filter);\n products.forEach((item, index) => {\n console.log(\"filter \" + filter + \"\" + item.name.indexOf(filter));\n if (item.name.indexOf(filter) != -1) {\n searchItem.push(item);\n const storeItem = document.getElementById(\"store-items\");\n storeItem.innerHTML = \"\"\n loadHtml(searchItem);\n }\n })\n}", "function sameVocalsQuantity(text) {\n let result = false;\n let words = text.split(\" \"); // ['oi', 'ei'];\n for (let i = 0; i < words.length - 1; i++) {\n let word = words[i];\n let nextWord = words[i + 1];\n\n if (vocalsQuantity(word) === vocalsQuantity(nextWord)) {\n result = true;\n break;\n }\n }\n\n return result;\n}", "function findShort(s){\nvar split = s.split(' ')\ncounter = 100\n\nfor (var i=0; i<split.length; i++){\n if (split[i].length < counter){\n \tcounter = split[i].length\n word = split[i]\n \t}\n }\n return counter;\n}", "async getWords(startWord='', maxLength=30) {}", "function wordComp(str, k) {\n // loop through the string\n let ar = str.split('')\n let start;\n let counter = 1;\n for (let i = 0; i < ar.length; i++) {\n //keep track of which letter (i) you're currently on\n //if i == i + 1, add one to the counter, keep track of which letter i you're\n //currently on\n if (ar[i] !== ar[i - 1]) {\n start = ar[i];\n }\n \n for (let j = 1; j < ar.length; j++) {\n \n if (ar[i] === ar[j]) {\n counter ++;\n }\n if (ar[i] !== ar[j]) {\n counter = 1;\n }\n }\n if (counter === k) {\n ar.splice(start, k);\n }\n \n }\n return ar.join('')\n}", "function searchTerm(){\n \n }", "function Word() {\n \n //normal words from English words on TV and movies https://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/TV/2006/1-1000\n this.normalWords = ['course','against','ready','daughter','work','friends','minute','though','supposed','honey','point','start','check','alone','matter','office','hospital','three','already','anyway','important','tomorrow','almost','later','found','trouble','excuse','hello','money','different','between','every','party','either','enough','year','house','story','crazy','mind','break','tonight','person','sister','pretty','trust','funny','gift','change','business','train','under','close','reason','today','beautiful','brother','since','bank','yourself','without','until','forget','anyone','promise','happy','bake','worry','school','afraid','cause','doctor','exactly','second','phone','look','feel','somebody','stuff','elephant','morning','heard','world','chance','call','watch','whatever','perfect','dinner','family','heart','least','answer','woman','bring','probably','question','stand','truth','problem','patch','pass','famous','true','power','cool','last','fish','remote','race','noon','wipe','grow','jumbo','learn','itself','chip','print','young','argue','clean','remove','flip','flew','replace','kangaroo','side','walk','gate','finger','target','judge','push','thought','wear','desert','relief','basic','bright','deal','father','machine','know','step','exercise','present','wing','lake','beach','ship','wait','fancy','eight','hall','rise','river','round','girl','winter','speed','long','oldest','lock','kiss','lava','garden','fight','hook','desk','test','serious','exit','branch','keyboard','naked','science','trade','quiet','home','prison','blue','window','whose','spot','hike','laptop','dark','create','quick','face','freeze','plug','menu','terrible','accept','door','touch','care','rescue','ignore','real','title','city','fast','season','town','picture','tower','zero','engine','lift','respect','time','mission','play','discover','nail','half','unusual','ball','tool','heavy','night','farm','firm','gone','help','easy','library','group','jungle','taste','large','imagine','normal','outside','paper','nose','long','queen','olive','doing','moon','hour','protect','hate','dead','double','nothing','restaurant','reach','note','tell','baby','future','tall','drop','speak','rule','pair','ride','ticket','game','hair','hurt','allow','oven','live','horse','bottle','rock','public','find','garage','green','heat','plan','mean','little','spend','nurse','practice','wish','uncle','core','stop','number','nest','magazine','pool','message','active','throw','pull','level','wrist','bubble','hold','movie','huge','ketchup','finish','pilot','teeth','flag','head','private','together','jewel','child','decide','listen','garbage','jealous','wide','straight','fall','joke','table','spread','laundry','deep','quit','save','worst','email','glass','scale','safe','path','camera','excellent','place','zone','luck','tank','sign','report','myself','knee','need','root','light','sure','page','life','space','magic','size','tape','food','wire','period','mistake','full','paid','horrible','special','hidden','rain','field','kick','ground','screen','risky','junk','juice','human','nobody','mall','bathroom','high','class','street','cold','metal','nervous','bike','internet','wind','lion','summer','president','empty','square','jersey','worm','popular','loud','online','something','photo','knot','mark','zebra','road','storm','grab','record','said','floor','theater','kitchen','action','equal','nice','dream','sound','fifth','comfy','talk','police','draw','bunch','idea','jerk','copy','success','team','favor','open','neat','whale','gold','free','mile','lying','meat','nine','wonderful','hero','quilt','info','radio','move','early','remember','understand','month','everyone','quarter','center','universe','name','zoom','inside','label','yell','jacket','nation','support','lunch','twice','hint','jiggle','boot','alive','build','date','room','fire','music','leader','rest','plant','connect','land','body','belong','trick','wild','quality','band','health','website','love','hand','okay','yeah','dozen','glove','give','thick','flow','project','tight','join','cost','trip','lower','magnet','parent','grade','angry','line','rich','owner','block','shut','neck','write','hotel','danger','impossible','illegal','show','come','want','truck','click','chocolate','none','done','bone','hope','share','cable','leaf','water','teacher','dust','orange','handle','unhappy','guess','past','frame','knob','winner','ugly','lesson','bear','gross','midnight','grass','middle','birthday','rose','useless','hole','drive','loop','color','sell','unfair','send','crash','knife','wrong','guest','strong','weather','kilometer','undo','catch','neighbor','stream','random','continue','return','begin','kitten','thin','pick','whole','useful','rush','mine','toilet','enter','wedding','wood','meet','stolen','hungry','card','fair','crowd','glow','ocean','peace','match','hill','welcome','across','drag','island','edge','great','unlock','feet','iron','wall','laser','fill','boat','weird','hard','happen','tiny','event','math','robot','recently','seven','tree','rough','secret','nature','short','mail','inch','raise','warm','gentle','glue','roll','search','regular','here','count','hunt','keep','week']\n \n //harder words from vocabulary.com\n this.hardWords = [\"abject\", \"aberration\", \"abjure\", \"abnegation\", \"abrogate\", \"abscond\", \"abstruse\", \"accede\", \"accost\", \"accretion\", \"acumen\", \"adamant\", \"admonish\", \"adumbrate\", \"adverse\", \"advocate\", \"affluent\", \"aggrandize\", \"alacrity\", \"alias\", \"ambivalent\", \"amenable\", \"amorphous\", \"anachronistic\", \"anathema\", \"annex\", \"antediluvian\", \"antiseptic\", \"apathetic\", \"antithesis\", \"apocryphal\", \"approbation\", \"arbitrary\", \"arboreal\", \"arcane\", \"archetypal\", \"arrogate\", \"ascetic\", \"aspersion\", \"assiduous\", \"atrophy\", \"bane\", \"bashful\", \"beguile\", \"bereft\", \"blandishment\", \"bilk\", \"bombastic\", \"cajole\", \"callous\", \"calumny\", \"camaraderie\", \"candor\", \"capitulate\", \"carouse\", \"carp\", \"caucus\", \"cavort\", \"circumlocution\", \"circumscribe\", \"circumvent\", \"clamor\", \"cleave\", \"cobbler\", \"cogent\", \"cognizant\", \"commensurate\", \"complement\", \"compunction\", \"concomitant\", \"conduit\", \"conflagration\", \"congruity\", \"connive\", \"consign\", \"constituent\", \"construe\", \"contusion\", \"contrite\", \"contentious\", \"contravene\", \"convivial\", \"corpulence\", \"covet\", \"cupidity\", \"dearth\", \"debacle\", \"debauch\", \"debunk\", \"defunct\", \"demagogue\", \"denigrate\", \"derivative\", \"despot\", \"diaphanous\", \"didactic\", \"dirge\", \"disaffected\", \"discomfit\", \"disparate\", \"dispel\", \"disrepute\", \"divisive\", \"dogmatic\", \"dour\", \"duplicity\", \"duress\", \"eclectic\", \"edict\", \"ebullient\", \"egregious\", \"elegy\", \"elicit\", \"embezzlement\", \"emend\", \"emollient\", \"empirical\", \"emulate\", \"enervate\", \"enfranchise\", \"engender\", \"ephemeral\", \"epistolary\", \"equanimity\", \"equivocal\", \"espouse\", \"evanescent\", \"evince\", \"exacerbate\", \"exhort\", \"execrable\", \"exigent\", \"expedient\", \"expiate\", \"expunge\", \"extraneous\", \"extol\", \"extant\", \"expurgate\", \"fallacious\", \"fatuous\", \"fetter\", \"flagrant\", \"foil\", \"forbearance\", \"fortuitous\", \"fractious\", \"garrulous\", \"gourmand\", \"grandiloquent\", \"gratuitous\", \"hapless\", \"hegemony\", \"heterogenous\", \"iconoclast\", \"idiosyncratic\", \"impecunious\", \"impetuous\", \"impinge\", \"impute\", \"inane\", \"inchoate\", \"incontrovertible\", \"incumbent\", \"inexorable\", \"inimical\", \"injunction\", \"inoculate\", \"insidious\", \"instigate\", \"insurgent\", \"interlocutor\", \"intimation\", \"inure\", \"invective\", \"intransigent\", \"inveterate\", \"irreverence\", \"knell\", \"laconic\", \"largesse\", \"legerdemain\", \"libertarian\", \"licentious\", \"linchpin\", \"litigant\", \"maelstrom\", \"maudlin\", \"maverick\", \"mawkish\", \"maxim\", \"mendacious\", \"modicum\", \"morass\", \"mores\", \"munificent\", \"multifarious\", \"nadir\", \"negligent\", \"neophyte\", \"noisome\", \"noxious\", \"obdurate\", \"obfuscate\", \"obstreperous\", \"officious\", \"onerous\", \"ostensible\", \"ostracism\", \"palliate\", \"panacea\", \"paradigm\", \"pariah\", \"partisan\", \"paucity\", \"pejorative\", \"pellucid\", \"penchant\", \"penurious\", \"pert\", \"pernicious\", \"pertinacious\", \"phlegmatic\", \"philanthropic\", \"pithy\", \"platitude\", \"plaudit\", \"plenitude\", \"plethora\", \"portent\", \"potentate\", \"preclude\", \"predilection\", \"preponderance\", \"presage\", \"probity\", \"proclivity\", \"profligate\", \"promulgate\", \"proscribe\", \"protean\", \"prurient\", \"puerile\", \"pugnacious\", \"pulchritude\", \"punctilious\", \"quaint\", \"quixotic\", \"quandary\", \"recalcitrant\", \"redoubtable\", \"relegate\", \"remiss\", \"reprieve\", \"reprobate\", \"rescind\", \"requisition\", \"rife\", \"sanctimonious\", \"sanguine\", \"scurrilous\", \"semaphore\", \"serendipity\", \"sobriety\", \"solicitous\", \"solipsism\", \"spurious\", \"staid\", \"stolid\", \"subjugate\", \"surfeit\", \"surreptitious\", \"swarthy\", \"tangential\", \"tome\", \"toady\", \"torpid\", \"travesty\", \"trenchant\", \"trite\", \"truculent\", \"turpitude\", \"ubiquitous\", \"umbrage\", \"upbraid\", \"utilitarian\", \"veracity\", \"vestige\", \"vicissitude\", \"vilify\", \"virtuoso\", \"vitriolic\", \"vituperate\", \"vociferous\", \"wanton\", \"winsome\", \"yoke\", \"zephyr\", \"wily\", \"tirade\"];\n \n this.guesses = [];\n this.currentWord;\n this.guessList = document.getElementById('guesses');\n this.userInput = document.getElementById('user-input');\n this.counter = 0;\n this.winner = false;\n this.init();\n}", "getCount(word) {\n return this.dict[word];\n }", "function filterLongWords (words, i) {\r\n let arr = words.filter(elem=>elem.length>i);\r\n return arr;\r\n}", "function getWords(i) {\n\t\treturn wordsizeset[i];\n\t // return words[i]\n\t // .replace(/[!\\.,:;\\?]/g, '')\n\t // .split(' ')\n\t // .map(function(d) {\n\t // return {text: d, size: 10 + Math.random() * 60};\n\t // })\n\t}", "function WordCloud() {\n\tvar colors = ['colorCat_1', 'colorCat_2', 'colorCat_3', 'colorCat_4', 'colorCat_5', 'colorCat_6'],\n\t\tmargin = { top: 70, right: 10, bottom: 10, left: 40 },\n\t\twidth = 960,\n\t\theight = 320,\n\t\ts = d3.scale.linear(),\n\t\tlayout = d3.layout.cloud()\n\t\t\t\t\t.timeInterval(10)\n\t\t\t\t\t.spiral(\"archimedean\") // archimedean or rectangular\n\t\t\t\t\t.padding(0.5)\n\t\t\t\t\t.rotate(function(d) { return d.term.length > 5 ? 0 : ~~(Math.random() * 2) * 90; })\n\t\t\t\t\t.font(\"Impact\")\n\t\t\t\t\t.fontSize(function(d) { return s(Math.floor(+d.tf_idf)); })\n\t\t\t\t\t.text(function(d) { return d.term; })\n\t\t\t\t\t.on(\"end\", draw),\n\t\tfill = d3.scale.quantize().range(colors),\n\t\ttransitionTime = 2000,\n\t\tevent = d3.dispatch(\"click\", \"cloudend\"),\n\t\tmaxWords = 100,\n\t\twordsShowing = 0,\n\t\tfullWords = undefined,\n\t\tsvg = undefined;\n\n\tfunction chart (selection) {\n\t\t// Do the charting\n\t\tselection.each(function(data) {\t\t\n\t\t\t// Create the svg element if it doesnt exist\n\t\t\tsvg = d3.select(this).selectAll(\"svg\").data([data]);\n\t\t\tsvg.enter().append(\"svg\").append(\"g\").attr(\"transform\", \"translate(\" + [width >> 1, height >> 1] + \")\");\n\n\t\t\t// Update the outer dimensions\n\t\t\tsvg.attr(\"width\", width).attr(\"height\", height);//.attr('x', margin.left);\n\n\t\t\t// Refresh the layout size and scales\n\t\t\tlayout.size([width, height]);\n\t\t\ts.range([20, 80]);\n\t\t\tfill.domain(s.range());\n\n\t\t\t// Calculate the x and y points for each word based on layout\n\t\t\tfullWords = data.slice(0, Math.min(maxWords, data.length - 1));\n\n\t\t\t// Refresh the word size calculator scale\n\t\t\ts.domain(d3.extent(fullWords, function (d) { return Math.floor(+d.tf_idf); }));\n\n\t\t\t// Fade out all existing words\n\t\t\tsvg.selectAll(\"text\").transition(transitionTime)\n\t\t\t\t.style(\"font-size\", \"1px\")\n\t\t\t\t.style(\"opacity\", 0)\n\t\t\t\t.attr(\"transform\", \"translate(0,0)\");\n\n\t\t\tlayout.stop().words(fullWords).start();\n\t\t});\n\t}\n\n\tfunction draw (words, bounds) {\n\t\twordsShowing = words.length;\n\n\t\tvar scale = bounds ? Math.min(width / Math.abs(bounds[1].x - width / 1), width / Math.abs(bounds[0].x - width / 1), height / Math.abs(bounds[1].y - height / 1), height / Math.abs(bounds[0].y - height / 1)) / 1 : 1;\n\t\tvar g = svg.select(\"g\");\n\n\t\t// Update existing texts\n\t\tvar p = g.selectAll(\"text\")\n\t .data(words)\n\t //.data(fullWords)\n\t .attr(\"class\", \"\");\n\n\t\t// Insert new texts\n\t\tp.enter().append(\"text\")\n\t\t .style(\"font-family\", \"Impact\")\n\t .attr(\"text-anchor\", \"middle\")\n\t .attr(\"class\", \"\")\n\t .on(\"click\", onClick);\n\n\t // Fade in the words\n\t p.text(function(d) { return d.text; })\n\t \t.transition(transitionTime)\n\t .style(\"font-size\", function(d) { return d.size + \"px\"; })\n\t .style(\"opacity\", 1)\n\t .attr(\"class\", function(d) { return \"cloudText \" + fill(d.size); })\n\t .attr(\"transform\", function(d) { return \"translate(\" + [d.x, d.y] + \")rotate(\" + d.rotate + \")\"; });\n\n\t\t// Delete extra texts\n\t p.exit().remove();\n\n\t // Scale the world cloud to show all words\n\t\tg.transition()\n\t\t .delay(transitionTime)\n\t\t .attr(\"transform\", \"translate(\" + [width >> 1, height >> 1] + \")scale(\" + scale + \")\");\n\n\t\tonEnd();\n\t}\n\n\tfunction onClick (word) {\n\t\tevent.click(word.text);\n\t}\n\n\tfunction onEnd ()\n\t{\n\t\tevent.cloudend();\n\t}\n\n\n\tchart.margin = function (value) {\n \tif (!arguments.length) return margin;\n \tmargin = value;\n \treturn chart;\n };\n\n chart.width = function (value) {\n \tif (!arguments.length) return width;\n \twidth = value;\n \treturn chart;\n };\n\n chart.height = function (value) {\n \tif (!arguments.length) return height;\n \theight = value;\n \treturn chart;\n };\n\n chart.maxWords = function (value) {\n \tif (!arguments.length) return maxWords;\n \tmaxWords = value;\n \treturn chart;\n };\n\n chart.wordsShowing = function() {\n \treturn wordsShowing;\n }\n\n\treturn d3.rebind(chart, event, \"on\");\n}", "function search(input){\r\n console.log(data);\r\n for(var i=0; i<data.length; i++){\r\n //ith reaction\r\n //array of elts\r\n console.log(i);\r\n var elt = data[i].elt.split(\",\");\r\n var elt_en = data[i].elt_en.split(\",\");\r\n var res = 1;\r\n for(var j=0; j<input.length; j++){\r\n //check jth input\r\n var find = 0; //not find\r\n for(var m=0; m<elt.length; m++){\r\n if(input[j].trim().localeCompare(elt[m].toLowerCase().trim())==0){\r\n find = 1;\r\n break;\r\n }\r\n }\r\n for(var m=0; m<elt_en.length; m++){\r\n if(input[j].trim().localeCompare(elt_en[m].toLowerCase().trim())==0){find = 1;break;}}\r\n if(find == 0){\r\n res = 0;break;}\r\n }\r\n if(res == 1){\r\n results.push(data[i].id);\r\n } \r\n }\r\n}", "function build_input(results) {\n var ret = results.map(function (result) {\n if (result[1].length <= 0) { // the word is not a top10k one\n // narraw random values down into range (-.25, .25]\n rmatrix = [];\n for (i = 0; i < VECTOR_LENGTH; i++) {\n //rmatrix.push((Math.random()-0.5)/2);\n rmatrix.push(0);\n }\n return rmatrix;\n }\n\n return result[1];\n });\n\n return ret;\n}", "function word() {\n let type = document.getElementById('selectAlgorithm').value;\n // Get user word and convert to lowercase\n let userWord = document.getElementById(\"word\").value;\n userWord = userWord.toLowerCase();\n\n let searchResult = search(dictionary, userWord, type);\n if (searchResult == -1) {\n document.getElementById(\"word-result\").innerHTML = \"Linear Search: \" + userWord + \" is NOT in the dictionary.\";\n } else {\n document.getElementById(\"word-result\").innerHTML = \"Linear Search: \" + userWord + \" IS in the dictionary.\";\n }\n\n}", "function filterLongWords(words, i){\n \"use strict\";\n\n}", "function wordSearchChecker(txt) {\n var userKeyWord = document.getElementById('userKeyWord').value;\n var wordSearch = '';\n var array = txt.match(new RegExp(userKeyWord, 'gi'));\n\n if (array == null) {\n \n wordSearch = \"<h4>\" + userKeyWord + \"</h4> \" + \" does not appear in this file.\";\n\n } else if (array.length == 1) {\n wordSearch = \"<h4>\" + userKeyWord + \"</h4> \" + \" appears \" + array.length + \" time.\";\n wordSearch += \"<br/>\";\n wordSearch += \"<br/>\";\n wordSearch += txt.replace(new RegExp(userKeyWord, 'gi'), \"<strong class='btn btn-warning'>\" + userKeyWord + \"</strong>\");\n } else {\n wordSearch = \"<h4>\" + userKeyWord + \"</h4> \" + \" appears \" + array.length + \" times.\";\n wordSearch += \"<br/>\";\n wordSearch += \"<br/>\";\n wordSearch += txt.replace(new RegExp(userKeyWord, 'gi'), \"<strong class='btn btn-warning'>\" + userKeyWord + \"</strong>\");\n }\n\n return wordSearch;\n }", "function wordsComplex() {\n\n}", "static postSearchedProduct(req, res, next){\n if(req.body.searchData){\n const val = req.body.searchData\n var regVal = new RegExp(val.charAt(0).toUpperCase() + val.slice(1))\n var arrLong = []\n ProductSchema.find({}, function(err, products){\n if(err) throw err\n products.map(prod=>{\n if(regVal.test(prod.productName)){\n arrLong.push(prod) \n }\n })\n res.send([arrLong])\n }) \n } else {\n res.send([\"error\"])\n }\n\n }", "function filterLongWord(arr, n){\n let arr1=[];\n for(i=0; i<arr.length; i++){\n if(arr[i].length>n)\n arr1.push(arr[i]);\n }\n return arr1;\n }", "generateQuery (ignoreSuperterms) {\n // 1. Get appropriate terms\n let keywords = this.getTermsWithThreshold(true)\n let mergedKeywords = []\n\n if (ignoreSuperterms) {\n mergedKeywords = keywords\n } else {\n // 3. + 4. Discard all subterms and put all superterms at the position of their first subterm\n for (let i = 0; i < keywords.length; i++) {\n let current = keywords[i]\n let { stemmedTerm } = current\n // iterate over remaining terms in search for parents\n let searchForParent = SearchTermExtractor.largestParent(keywords.map(kw => kw.stemmedTerm), stemmedTerm, false)\n let parent = searchForParent ? keywords[searchForParent.index] : null\n // iterate over mergedKeywords in search for parents\n let candidate = parent ? parent : current\n let searchForMergedParent = SearchTermExtractor.largestParent(\n mergedKeywords.map(kw => kw.stemmedTerm), \n candidate.stemmedTerm, \n true)\n if (!searchForMergedParent) {\n mergedKeywords.push(candidate)\n }\n }\n }\n\n // 2. Select the two query terms\n let requestKeywords = mergedKeywords.slice(0, 2)\n let requestTerms = requestKeywords.map(kw => (kw.canonicalTerm || kw.originalTerms[0]))\n let keywordsString = concatStrings(requestTerms, ' ')\n let requestString = keywordsString\n // 5. Shorten the query if neccessary\n if (keywordsString.split(' ').length > 3) {\n let firstLength = requestTerms[0] ? requestTerms[0].split(' ').length : 0\n let secondLength = requestTerms[1] ? requestTerms[1].split(' ').length : 0\n let diff = firstLength - secondLength\n if (diff < 0) {\n requestString = requestTerms[1]\n } else if (diff > 0 || (diff == 0 && requestTerms[0])) {\n requestString = requestTerms[0]\n }\n }\n // 6. Phew.\n return requestString.toLowerCase()\n }", "function wordMatchCount(tweet, target_tier) {\n //put # here and get rid of createKeywordTier ?\n var normalized_text = tweet.text.toLowerCase().replace(/[\\.,-\\/!$#%\\^&\\*;:{}=\\-_`~()]/g,\"\");\n var words = normalized_text.split(' ');\n var count = 0; \n\n for(var i=0; i < words.length; i++) {\n if(target_tier[words[i]]) {\n //console.log(words[i]);\n count++;\n }\n }\n return count;\n}", "function topK(workIds, k, language, lemmatized, removeStopWords, frequency) {\r\n\t$.ajax({\r\n\t\ttype: \"POST\",\r\n\t\turl: 'https://s-lib024.lib.uiowa.edu/greekandlatincanons/' + language + '/search_function/inc/api.php',\r\n\t\tdata: {\r\n\t\t\t'functionName': 'topKWords',\r\n\t\t\t'workList': workIds,\r\n\t\t\t'k': k,\r\n\t\t\t'lemmatized': lemmatized,\r\n\t\t\t'removeStopWords': removeStopWords,\r\n\t\t\t'frequency': frequency\r\n\t\t},\r\n\t\tsuccess: function(res) {\r\n\t\t\tconsole.log(JSON.stringify(res));\r\n\t\t},\r\n\t\terror: function(err) {\r\n\t\t\tconsole.log(JSON.stringify(e));\r\n\t\t}\r\n\t});\r\n}", "function contains(words, token)\n{\n\ttoken = token.toLowerCase()\n\tfor (var i = 0; i < words.length; i++)\n\t{\n\t\tvar w = words[i].toLowerCase()\n\t\t//console.log(w)\n\t\t//console.log(w + \" \" + token + \" \" + token.replace(\"/\\W/g\", '') + \" \" + levenstein(w, token) + \" \" + levenstein(w, token.replace(/\\W/g, '')))\n\t\tif (token == w) return i + 1\n\t\tif (levenstein(w, token) <= 0.3 || levenstein(w, token.replace(/\\W/g, '')) <= 0.3)\n\t\t{\n\t\t\tif (token.length > 2)\n\t\t\t\treturn i + 1 // || levenstein(w, token.replace(/\\W/g, '')) <= 0.3) return true\n\t\t}\n\t}\n\n\treturn false\n}", "calculateTermFrequency(term, doc) {\n let numOccurences = 0;\n for (let i = 0; i < doc.length; i++){\n if (doc[i].toLowerCase() == term.toLowerCase()){\n numOccurences++;\n }\n }\n return (numOccurences * 1.0 / (doc.length + 1))\n }", "function dictionary(initial, words) {\n console.log('initial', initial)\n const outputArr = []\n for (var i = 0; i < words.length; i++) {\n var len = initial.length\n const word = words[i]\n // console.log('word', word)\n const tempArr = []\n for (var y = 0; y < len; y++) {\n const letter = word[y]\n // console.log('letter', letter)\n tempArr.push(letter)\n }\n // console.log('tempArr-', tempArr)\n const wordStart = tempArr.join('') // first x letters of word, where x = initial.length\n // console.log('wordstart::', wordStart)\n if (wordStart === initial) {\n outputArr.push(word)\n }\n }\n console.log('outputArr', outputArr)\n return outputArr\n}" ]
[ "0.6051526", "0.5920228", "0.58063376", "0.5695481", "0.5681347", "0.56718266", "0.5662377", "0.5650793", "0.5596862", "0.55857015", "0.5581462", "0.5572365", "0.55683625", "0.556427", "0.55636114", "0.5531635", "0.5526469", "0.5520329", "0.551112", "0.55066603", "0.55022603", "0.55014604", "0.54997444", "0.5478948", "0.54695815", "0.5466136", "0.54319245", "0.5430773", "0.5395462", "0.53788775", "0.5371005", "0.5368471", "0.53655064", "0.53606564", "0.5360058", "0.53548855", "0.53509265", "0.5350004", "0.53348565", "0.5334345", "0.53327954", "0.5328941", "0.5324877", "0.5318706", "0.5310545", "0.5302838", "0.5293332", "0.5290028", "0.52819866", "0.5274016", "0.5265694", "0.5263695", "0.5259454", "0.5248501", "0.5244072", "0.5230147", "0.5224483", "0.522274", "0.5222283", "0.52189124", "0.52185464", "0.52165574", "0.5215849", "0.5212521", "0.52087426", "0.5202092", "0.5200429", "0.5197937", "0.519668", "0.5192026", "0.5183847", "0.5177909", "0.51777273", "0.51751024", "0.5167916", "0.5166819", "0.516323", "0.51586217", "0.5157622", "0.5137732", "0.5136846", "0.51367736", "0.5129407", "0.51269037", "0.5125363", "0.51208687", "0.5119806", "0.51141196", "0.5113141", "0.51087326", "0.5106285", "0.51062465", "0.5103805", "0.5103342", "0.50995946", "0.5092904", "0.5089867", "0.50879425", "0.5078415", "0.5070269", "0.50696117" ]
0.0
-1
Bind to relay events. Capture emitted events by the relay and send via websocket.
initSockets() { this.relay.on('requests satisfied', (data) => { const sockets = this.channel('relay'); if (!sockets) return; this.to('relay', 'relay requests satisfied', data); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_bindEvents () {\n this.channel.on('route', this.navigate)\n }", "function bindPusherEvents() {\n var pusher = new Pusher('bf3b73f9a228dfef0913');\n var channel = pusher.subscribe(divvy.channel);\n\n channel.bind('commentWasDeleted', commentWasDeleted);\n channel.bind('commentWasLeft', commentWasLeft);\n channel.bind('commentWasModified', commentWasModified);\n }", "function bindPusherEvents() {\n var pusher = new Pusher('bf3b73f9a228dfef0913');\n var channel = pusher.subscribe(divvy.channel);\n\n channel.bind('subtaskWasModified', subtaskWasModified);\n channel.bind('subtaskWasDeleted', subtaskWasDeleted);\n channel.bind('subtaskWasCompleted', subtaskWasCompleted);\n channel.bind('subtaskWasIncomplete', subtaskWasIncomplete);\n }", "bindEvents () {\n if (this.bound) {\n this.log.warn('trails-app: Someone attempted to bindEvents() twice! Stacktrace below.')\n this.log.warn(console.trace())\n return\n }\n\n this.once('trails:error:fatal', err => this.stop(err))\n\n process.on('exit', () => {\n this.log.verbose('Event loop is empty. I have nothing else to do. Shutting down')\n })\n process.on('uncaughtException', err => this.stop(err))\n\n this.bound = true\n }", "bind() {\n\t\tthis.armband.on(this.options.triggerEvent, this.snapHandler.bind(this));\n\t}", "_bindEventHandlers(){\n if ( this._server !== null ){\n // TODO\n }\n }", "_bindEvents () {\n this.listenTo(this, 'sync', this._syncModels.bind(this))\n this.listenTo(this, 'request', this._requestModels.bind(this))\n }", "function WanwanRelay() {\n this.signals = {};\n}", "function bindPusherEvents() {\n var pusher = new Pusher('bf3b73f9a228dfef0913');\n var channel = pusher.subscribe(divvy.channel);\n\n channel.bind('discussionWasModified', discussionWasModified);\n channel.bind('discussionWasDeleted', discussionWasDeleted);\n }", "bind () {\n for (const event in this._virtuals) {\n document.body.addEventListener(event, this._handlers[event])\n }\n }", "run () {\n this._client.on('messageCreate', this.onMessageCreateEvent.bind(this))\n this._client.on('messageReactionAdd', this.onMessageReactionEvent.bind(this))\n this._client.on('messageReactionRemove', this.onMessageReactionEvent.bind(this))\n }", "function bindPusherEvents() {\n var pusher = new Pusher('bf3b73f9a228dfef0913');\n var channel = pusher.subscribe(divvy.channel);\n\n channel.bind('taskWasIncomplete', taskWasIncomplete);\n channel.bind('projectCompletionChanged', projectProgressChanged);\n channel.bind('updateActivityLog', updateActivityLog);\n channel.bind('taskWasCompleted', taskWasCompleted);\n channel.bind('taskModified', taskModified);\n channel.bind('memberJoinedProject', memberJoinedProject);\n channel.bind('memberRemovedFromProject', memberRemovedFromProject);\n channel.bind('taskWasDeleted', taskWasDeleted);\n channel.bind('taskAddedToProject', taskAddedToProject);\n channel.bind('projectWasRemoved', projectWasRemoved);\n channel.bind('projectWasModified', projectWasModified);\n }", "function bindPusherEvents() {\n var pusher = new Pusher('bf3b73f9a228dfef0913');\n var channel = pusher.subscribe(divvy.channel);\n\n channel.bind('taskCompletionChanged', taskProgressChanged);\n channel.bind('updateActivityLog', updateActivityLog);\n channel.bind('subtaskAddedToTask', subtaskAddedToTask);\n channel.bind('subtaskWasDeleted', subtaskWasDeleted);\n channel.bind('subtaskWasModified', subtaskWasModified);\n channel.bind('subtaskWasCompleted', subtaskWasCompleted);\n channel.bind('subtaskWasIncomplete', subtaskWasIncomplete)\n channel.bind('discussionStartedInTask', discussionStartedInTask);\n channel.bind('discussionWasDeleted', discussionWasDeleted);\n channel.bind('discussionWasModified', discussionWasModified);\n channel.bind('taskModified', taskModified);\n channel.bind('taskWasDeleted', taskWasDeleted);\n channel.bind('taskWasCompleted', taskWasCompleted);\n channel.bind('commentWasLeftOnSubtask', commentWasLeftOnSubtask);\n channel.bind('commentWasLeftOnDiscussion', commentWasLeftOnDiscussion);\n channel.bind('commentWasDeletedOnSubtask', commentWasDeletedOnSubtask);\n channel.bind('commentWasDeletedOnDiscussion', commentWasDeletedOnDiscussion);\n }", "function bindPusherEvents() {\n if (typeof window.divvy != 'undefined') {\n var pusher = new Pusher('bf3b73f9a228dfef0913');\n var channel = pusher.subscribe(divvy.userChannel);\n\n channel.bind('notifyUsers', notifyUsers);\n }\n }", "function bindPusherEvents() {\n var pusher = new Pusher('bf3b73f9a228dfef0913');\n var channel = pusher.subscribe(divvy.channel);\n\n channel.bind('projectWasRemoved', projectWasRemoved);\n channel.bind('projectWasModified', projectWasModified);\n }", "bind() {\n this.onData = this.onData.bind(this);\n this.onConnect = this.onConnect.bind(this);\n this.onMessage = this.onMessage.bind(this);\n this.onError = this.onError.bind(this);\n this.onClose = this.onClose.bind(this);\n }", "function bindListener() {\n MxWcEvent.listenInternal('actived', performWhenActived);\n MxWcEvent.listenInternal('selecting', performWhenSelecting);\n MxWcEvent.listenInternal('completed', performWhenCompleted);\n MxWcEvent.listenInternal('idle', performWhenIdle);\n}", "_bindEvents () {\n this.listenTo(this.model.get('rats'), 'change sync', this._showRats)\n }", "_bindEvents() {\n this._internalWidget.bind(window.SC.Widget.Events.PLAY, this.props.onPlay);\n this._internalWidget.bind(window.SC.Widget.Events.PAUSE, this.props.onPause);\n this._internalWidget.bind(window.SC.Widget.Events.FINISH, this.props.onEnd);\n }", "function bindHandlers() {\n wss.bindHandlers(handlerMap);\n $log.debug('topo2 event handlers bound');\n }", "_bindEvents() {\n\t\t_.bindAll(\n\t\t\tthis,\n\t\t\t'_onClickPlay',\n\t\t\t'_onPlayerReceived',\n\t\t\t'_onInterval',\n\t\t\t'_onPlay',\n\t\t\t'_onPause',\n\t\t\t'_onEnded',\n\t\t\t'_onLoaded',\n\t\t\t'_onError',\n\t\t\t'_onReady'\n\t\t);\n\n\t\tthis.$el.on('click.' + this.options.eventNamespace, this.options.trigger, this._onClickPlay);\n\t}", "bindEvents() {\n }", "function _bindEventHandlers() {\n\t\t\n helper.bindEventHandlers();\n }", "function bind() {\r\n\r\n socket = new io.Socket(postmile.api.domain, { port: postmile.api.port, rememberTransport: false });\r\n\r\n socket.on('connect', function () {\r\n Y.log('Connected!');\r\n });\r\n\r\n socket.on('message', function (message) {\r\n handleStreamMessage(message);\r\n });\r\n\r\n socket.connect();\r\n\r\n Y.on(\"postmile:subscribeProject\", function (project) {\r\n subscribe(project);\r\n });\r\n\r\n }", "bindEventHandlers(events) {\n events.forEach(name => {\n const method = this[`on${name[0].toUpperCase()}${name.slice(1)}`];\n if (method) {\n this.slack.rtmClient.on(name, method.bind(this));\n }\n });\n }", "function onBindEvent(name)\n\t{\n\t\tswitch(name)\n\t\t{\n\t\t\tcase 'CONNECTION_STATUS_CHANGED' :\n\t\t\t\tthis.emit('CONNECTION_STATUS_CHANGED', this.connectionStatus);\n\t\t\tbreak;\n\t\t}\n\t}", "function _bindEvents() {\n // subscribe to 'peopleChanged' event\n // When received, fire setPeople\n app.events.on('peopleChanged', setPeople);\n }", "function bindWebSockets(server) {\n var sio = io.listen(server);\n\n // Convenience forwarder when the WS \"event\" is exactly the same\n // as the engine-emitted event.\n function justForward(call) {\n engine.on(call, function() {\n sio.sockets.emit.apply(sio.sockets, _.flatten([call, arguments]));\n });\n }\n\n // Quiz init: notify waiting clients (\"No active quiz yet…\" front screens)\n engine.on('quiz-init', function(quiz) {\n engine.getUsers(function(err, users) {\n if (err) throw err;\n sio.sockets.emit('quiz-init', _.pick(quiz, 'title', 'description', 'level'), users);\n });\n });\n\n // Quiz join: a new user comes in the engine while a quiz is at init stage.\n justForward('quiz-join');\n\n // Question start: a new question starts! (including quiz start)\n justForward('question-start');\n\n // Answers coming in (input)\n sio.sockets.on('connection', function(socket) {\n socket.on('answer', function(answer) {\n socket.set('userId', answer.userId);\n engine.handleAnswer(answer);\n });\n });\n\n // Answers getting in (output)\n justForward('new-answer');\n justForward('edit-answer');\n\n // Question ends!\n justForward('question-end');\n\n // Quiz ends!\n engine.on('quiz-end', function(scoreboard) {\n // For every socket, check whether it's a player, and if so get and send their scoring.\n sio.sockets.clients().forEach(function(socket) {\n socket.get('userId', function(err, userId) {\n var scoring = userId && _.findWhere(scoreboard, { id: userId });\n if (scoring) {\n scoring.rank = scoreboard.indexOf(scoring) + 1;\n }\n socket.emit('quiz-end', scoring);\n });\n });\n });\n}", "subscribeEvents()\n {\n on('debug.log', event => {\n this.screen.log(event.text);\n });\n\n // Check for battle after moving\n on('move.finish', () => { \n if (this.checkStartFight())\n {\n // switch to Battle state\n this.battleState();\n }\n });\n\n // Handle postbattle event; go to world screen after postbattle screen\n on('battle.over.win', args => { this.postBattleState(args) });\n }", "_addEventListeners () {\n this._socket.on(ConnectionSocket.EVENT_ESTABLISHED, this._handleConnectionEstablished.bind(this))\n this._socket.on(ConnectionSocket.EVENT_CLOSED, this._handleConnnectionClosed.bind(this))\n this._socket.on(ConnectionSocket.EVENT_PEER_CONNECTED, this._handlePeerConnected.bind(this))\n this._socket.on(ConnectionSocket.EVENT_PEER_PING, this._handlePingMessage.bind(this))\n this._socket.on(ConnectionSocket.EVENT_PEER_SIGNAL, (signal) => this._rtc.signal(signal))\n this._rtc.on(ConnectionRTC.EVENT_RTC_SIGNAL, (signal) => this._socket.sendSignal(signal))\n this._rtc.on(ConnectionRTC.EVENT_PEER_PING, this._handlePingMessage.bind(this))\n this._rtc.on(ConnectionRTC.EVENT_CLOSED, this._handleConnnectionClosed.bind(this))\n }", "function proxySocket() {\n\t\tproxyEvents.forEach(function(event){\n\t\t\tsocket.on(event, function(data) {\n\t\t\t\tamplify.publish('socket:'+event, data || null);\n\t\t\t});\n\t\t});\n\t\tsocket.on('connect', function() {\n\t\t\tsocket.emit('subscribe', user.token);\n\t\t\tamplify.publish('socket:connect');\n\t\t});\n\t\n\t}", "bindCallbacks() {\n this.socket.onopen = (event) => this.onopen(event);\n this.socket.onmessage = (event) => this.onmmessage(event);\n this.socket.onclose = (event) => this.onclose(event);\n this.socket.onerror = (event) => this.onerror(event);\n }", "connect() {\n window.addEventListener('message', this.onConnectionMessageHandler);\n }", "listen() {\r\n this.client.on('message', message => this.onMessage(message));\r\n }", "function bindEvents() {\n this.applyEventBindings('on');\n\n return this;\n }", "listen() {\n [\"change\"].forEach(name => {\n this.el_.addEventListener(name, this.handler_, false)\n })\n }", "function bindEvents(socket){\n\tsocket.on(\"sendUserJoinEvent\", function (formInfoObj){\n\t\tsendUserJoinEvent(formInfoObj);\t\t\n\t});\n\n\tsocket.on(\"sendWhiteboardDrawEvent\", function (formInfoObj){\n\t\tsendWhiteboardDrawEvent(formInfoObj);\t\t\n\t});\n\n\tsocket.on(\"sendWhiteboardUpdShapeEvent\", function (formInfoObj){\n\t\tsendWhiteboardUpdShapeEvent(formInfoObj);\t\t\n\t});\n\n\tsocket.on(\"createMeeting\", function (formInfoObj){\n\t\tcreateMeeting(formInfoObj);\t\t\n\t});\n\n\tsocket.on(\"sendJSON\", function (formInfoObj){\n\t\tsendJSON(formInfoObj);\t\t\n\t});\n\n\n}", "setupEvents() {\n this.eventEmitter\n .on('close', () => {\n this.botInterface.emit('close');\n })\n .on('connect', () => {\n this.loadSavedEvents();\n })\n .on('reconnect', () => {\n this.reconnect();\n })\n .on('shutdown', () => {\n this.botInterface.emit('shutdown');\n })\n .on('start', () => {\n this.botInterface.emit('start');\n })\n .on('ping', (args) => {\n this.dispatchMessage(...args);\n })\n .on('message', (args) => {\n this.handleMessage(...args);\n })\n .on('channel', (args) => {\n this.handleChannelEvents(...args);\n })\n .on('user', (args) => {\n this.handleUserEvents(...args);\n })\n .on('team', (args) => {\n this.handleTeamEvents(...args);\n })\n .on('presence', (args) => {\n this.handlePresenceEvents(...args);\n });\n }", "setupWebSocket() {\n\n let self = this;\n let filterImsi = self._nconf.get(\"udpRelayService:filterImsi\");\n self.socket.on('connect', function () {\n console.log(\"Connected to NB-IoT relay service\");\n });\n self.socket.on('message', function (data) {\n data.msgStr = new Buffer(data.data, 'base64').toString(\"ascii\");\n data.msgJSON = safelyParseJSON(data.msgStr) || {};\n\n // if set in the config.jsom the messages are filtered bei an imsi\n if (filterImsi === '' || filterImsi === data.imsi) {\n log.L2(dl, '########################');\n log.L2(dl, 'Received from: ' + data.imsi);\n log.L2(dl, \"Reveiced at: \" + data.timestamp);\n log.L2(dl, \"Direction: \" + data.direction);\n log.L2(dl, \"Message_raw: \" + data.msgStr);\n log.L2(dl, \"Message_json: \" + JSON.stringify(data.msgJSON, null, 4));\n log.L2(dl, '########################\\n\\n\\n');\n\n self.emit('jsonData', data);\n }\n });\n\n self.socket.on('disconnect', function () {\n log.L1(dl,\"Disconnected from NB-IoT relay service\");\n });\n\n self.socket.on('error', (error) => {\n log.Err(dl, error);\n });\n\n }", "onListening() {\n this.emit('ready');\n }", "onListening() {\n this.emit('ready');\n }", "static listenSocketEvents() {\n Socket.shared.on(\"wallet:updated\", (data) => {\n let logger = Logger.create(\"wallet:updated\");\n logger.info(\"enter\", data);\n\n Redux.dispatch(Wallet.actions.walletUpdatedEvent(data));\n });\n }", "setupHandlers () {\n this.rs.on('connected', () => this.eventHandler('connected'));\n this.rs.on('ready', () => this.eventHandler('ready'));\n this.rs.on('disconnected', () => this.eventHandler('disconnected'));\n this.rs.on('network-online', () => this.eventHandler('network-online'));\n this.rs.on('network-offline', () => this.eventHandler('network-offline'));\n this.rs.on('error', (error) => this.eventHandler('error', error));\n\n this.setEventListeners();\n this.setClickHandlers();\n }", "addEventListeners() {\n const self = this;\n\n this.ws.onopen = function() {\n self.onOpen();\n };\n this.ws.onclose = function() {\n self.onClose();\n };\n this.ws.onmessage = function(ev) {\n self.onData(ev.data);\n };\n this.ws.onerror = function(e) {\n self.onError(\"websocket error\", e);\n };\n }", "addEventListeners() {\n const self = this;\n\n this.ws.onopen = function() {\n self.onOpen();\n };\n this.ws.onclose = function() {\n self.onClose();\n };\n this.ws.onmessage = function(ev) {\n self.onData(ev.data);\n };\n this.ws.onerror = function(e) {\n self.onError(\"websocket error\", e);\n };\n }", "addEventListeners() {\n const self = this;\n\n this.ws.onopen = function() {\n self.onOpen();\n };\n this.ws.onclose = function() {\n self.onClose();\n };\n this.ws.onmessage = function(ev) {\n self.onData(ev.data);\n };\n this.ws.onerror = function(e) {\n self.onError(\"websocket error\", e);\n };\n }", "function _bindEvents() {\n _$sort.on(CFG.EVT.CLICK, _setSort);\n _$navbar.on(CFG.EVT.CLICK, _SEL_BUTTON, _triggerAction);\n _$search.on(CFG.EVT.INPUT, _updateSearch);\n _$clear.on(CFG.EVT.CLICK, _clearSearch);\n }", "function listen() {\r\n __sco.on(\"message\", react);\r\n }", "bindEvents() {\n Events.$on('modal::close', (_event, data) => this.closeModal(data))\n Events.$on('modal::open', (_event, data) => this.openModal(data))\n\n Events.$on('modal::bind', (_event, data) => this.customBind(data))\n }", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n\n if (self.isMobile) {\n setupMobile();\n return;\n }\n\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent)) bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\") onMouseOver(e.target);\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config[\"static\"]) bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined) bind(window.document, \"touchstart\", documentClick);else bind(window.document, \"mousedown\", onClick(documentClick));\n bind(window.document, \"focus\", documentClick, {\n capture: true\n });\n\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"mousedown\", onClick(self.open));\n }\n\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"mousedown\", onClick(onMonthNavClick));\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"mousedown\", onClick(selectDate));\n }\n\n if (self.timeContainer !== undefined && self.minuteElement !== undefined && self.hourElement !== undefined) {\n var selText = function selText(e) {\n return e.target.select();\n };\n\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, {\n capture: true\n });\n bind(self.timeContainer, \"mousedown\", onClick(timeIncrement));\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined) bind(self.secondElement, \"focus\", function () {\n return self.secondElement && self.secondElement.select();\n });\n\n if (self.amPM !== undefined) {\n bind(self.amPM, \"mousedown\", onClick(function (e) {\n updateTime(e);\n triggerChange();\n }));\n }\n }\n }", "bindMouseEvents ()\n {\n // Set drag scroll on the viewport object\n this.viewerState.viewportObject.classList.add('dragscroll');\n\n gestureEvents.onDoubleClick(this.viewerState.viewportObject, (event, coords) =>\n {\n debug('Double click at %s, %s', coords.left, coords.top);\n this.viewerState.viewHandler.onDoubleClick(event, coords);\n });\n }", "bind(source, handler) {\n if (source instanceof Listening) {\n //if no handler passed in, we assume the callback is just a re-render of the UI because of a change in state\n //handler passed in should be a JS callback that takes data and does something (data = new updated data)\n if (handler === undefined) {\n const defaultHandler = (data) => this.render(data);\n source.addHandler(defaultHandler)\n this.events = {source, defaultHandler};\n } else {\n source.addHandler(handler);\n this.events = {source, handler};\n }\n } else {\n throw 'Attempting to bind to an unknown object!';\n }\n }", "bind(source, handler) {\n if (source instanceof Listening) {\n //if no handler passed in, we assume the callback is just a re-render of the UI because of a change in state\n //handler passed in should be a JS callback that takes data and does something (data = new updated data)\n if (handler === undefined) {\n const defaultHandler = (data) => this.render(data);\n source.addHandler(defaultHandler)\n this.events = {source, defaultHandler};\n } else {\n source.addHandler(handler);\n this.events = {source, handler};\n }\n } else {\n throw 'Attempting to bind to an unknown object!';\n }\n }", "$bind() {\n this.$onopen = this.$onopen.bind(this);\n this.$onclose = this.$onclose.bind(this);\n this.$onmessage = this.$onmessage.bind(this);\n this.$onerror = this.$onerror.bind(this);\n this.$oncheck = this.$oncheck.bind(this);\n }", "function bindEvents() {\n\t\tself._handlers = [];\n\t\tself._animationLoop = [];\n\t\tif (self.config.wrap) {\n\t\t\t[\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n\t\t\t\tArray.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n\t\t\t\t\treturn bind(el, \"mousedown\", onClick(self[evt]));\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tif (self.isMobile) return setupMobile();\n\n\t\tself.debouncedResize = debounce(onResize, 50);\n\t\tself.triggerChange = function () {\n\t\t\ttriggerEvent(\"Change\");\n\t\t};\n\t\tself.debouncedChange = debounce(self.triggerChange, 300);\n\n\t\tif (self.config.mode === \"range\" && self.daysContainer) bind(self.daysContainer, \"mouseover\", function (e) {\n\t\t\treturn onMouseOver(e.target);\n\t\t});\n\n\t\tbind(window.document.body, \"keydown\", onKeyDown);\n\n\t\tif (!self.config.static) bind(self._input, \"keydown\", onKeyDown);\n\n\t\tif (!self.config.inline && !self.config.static) bind(window, \"resize\", self.debouncedResize);\n\n\t\tif (window.ontouchstart !== undefined) bind(window.document, \"touchstart\", documentClick);\n\n\t\tbind(window.document, \"mousedown\", onClick(documentClick));\n\t\tbind(self._input, \"blur\", documentClick);\n\n\t\tif (self.config.clickOpens === true) {\n\t\t\tbind(self._input, \"focus\", self.open);\n\t\t\tbind(self._input, \"mousedown\", onClick(self.open));\n\t\t}\n\n\t\tif (!self.config.noCalendar) {\n\t\t\tself.monthNav.addEventListener(\"wheel\", function (e) {\n\t\t\t\treturn e.preventDefault();\n\t\t\t});\n\t\t\tbind(self.monthNav, \"wheel\", debounce(onMonthNavScroll, 10));\n\t\t\tbind(self.monthNav, \"mousedown\", onClick(onMonthNavClick));\n\n\t\t\tbind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n\t\t\tbind(self.daysContainer, \"mousedown\", onClick(selectDate));\n\n\t\t\tif (self.config.animate) {\n\t\t\t\tbind(self.daysContainer, [\"webkitAnimationEnd\", \"animationend\"], animateDays);\n\t\t\t\tbind(self.monthNav, [\"webkitAnimationEnd\", \"animationend\"], animateMonths);\n\t\t\t}\n\t\t}\n\n\t\tif (self.config.enableTime) {\n\t\t\tvar selText = function selText(e) {\n\t\t\t\treturn e.target.select();\n\t\t\t};\n\t\t\tbind(self.timeContainer, [\"wheel\", \"input\", \"increment\"], updateTime);\n\t\t\tbind(self.timeContainer, \"mousedown\", onClick(timeIncrement));\n\n\t\t\tbind(self.timeContainer, [\"wheel\", \"increment\"], self.debouncedChange);\n\t\t\tbind(self.timeContainer, \"input\", self.triggerChange);\n\n\t\t\tbind([self.hourElement, self.minuteElement], \"focus\", selText);\n\n\t\t\tif (self.secondElement !== undefined) bind(self.secondElement, \"focus\", function () {\n\t\t\t\treturn self.secondElement.select();\n\t\t\t});\n\n\t\t\tif (self.amPM !== undefined) {\n\t\t\t\tbind(self.amPM, \"mousedown\", onClick(function (e) {\n\t\t\t\t\tupdateTime(e);\n\t\t\t\t\tself.triggerChange(e);\n\t\t\t\t}));\n\t\t\t}\n\t\t}\n\t}", "function bindPusherTaskEvents() {\n var pusher = new Pusher('bf3b73f9a228dfef0913');\n var channel = pusher.subscribe(divvy.taskChannel);\n\n channel.bind('taskWasDeleted', taskWasDeleted);\n channel.bind('taskWasCompleted', taskWasCompleted);\n }", "function bindEvents() {\n\t\tself._handlers = [];\n\t\tself._animationLoop = [];\n\t\tif (self.config.wrap) {\n\t\t\t[\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n\t\t\t\tArray.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n\t\t\t\t\treturn bind(el, \"mousedown\", onClick(self[evt]));\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tif (self.isMobile) return setupMobile();\n\n\t\tself.debouncedResize = debounce(onResize, 50);\n\t\tself.triggerChange = function () {\n\t\t\ttriggerEvent(\"Change\");\n\t\t};\n\t\tself.debouncedChange = debounce(self.triggerChange, 300);\n\n\t\tif (self.config.mode === \"range\" && self.daysContainer) bind(self.daysContainer, \"mouseover\", function (e) {\n\t\t\treturn onMouseOver(e.target);\n\t\t});\n\n\t\tbind(window.document.body, \"keydown\", onKeyDown);\n\n\t\tif (!self.config.static) bind(self._input, \"keydown\", onKeyDown);\n\n\t\tif (!self.config.inline && !self.config.static) bind(window, \"resize\", self.debouncedResize);\n\n\t\tif (window.ontouchstart !== undefined) bind(window.document, \"touchstart\", documentClick);\n\n\t\tbind(window.document, \"mousedown\", onClick(documentClick));\n\t\tbind(self._input, \"blur\", documentClick);\n\n\t\tif (self.config.clickOpens === true) bind(self._input, \"focus\", self.open);\n\n\t\tif (!self.config.noCalendar) {\n\t\t\tself.monthNav.addEventListener(\"wheel\", function (e) {\n\t\t\t\treturn e.preventDefault();\n\t\t\t});\n\t\t\tbind(self.monthNav, \"wheel\", debounce(onMonthNavScroll, 10));\n\t\t\tbind(self.monthNav, \"mousedown\", onClick(onMonthNavClick));\n\n\t\t\tbind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n\t\t\tbind(self.daysContainer, \"mousedown\", onClick(selectDate));\n\n\t\t\tif (self.config.animate) {\n\t\t\t\tbind(self.daysContainer, [\"webkitAnimationEnd\", \"animationend\"], animateDays);\n\t\t\t\tbind(self.monthNav, [\"webkitAnimationEnd\", \"animationend\"], animateMonths);\n\t\t\t}\n\t\t}\n\n\t\tif (self.config.enableTime) {\n\t\t\tvar selText = function selText(e) {\n\t\t\t\treturn e.target.select();\n\t\t\t};\n\t\t\tbind(self.timeContainer, [\"wheel\", \"input\", \"increment\"], updateTime);\n\t\t\tbind(self.timeContainer, \"mousedown\", onClick(timeIncrement));\n\n\t\t\tbind(self.timeContainer, [\"wheel\", \"increment\"], self.debouncedChange);\n\t\t\tbind(self.timeContainer, \"input\", self.triggerChange);\n\n\t\t\tbind([self.hourElement, self.minuteElement], \"focus\", selText);\n\n\t\t\tif (self.secondElement !== undefined) bind(self.secondElement, \"focus\", function () {\n\t\t\t\treturn self.secondElement.select();\n\t\t\t});\n\n\t\t\tif (self.amPM !== undefined) {\n\t\t\t\tbind(self.amPM, \"mousedown\", onClick(function (e) {\n\t\t\t\t\tupdateTime(e);\n\t\t\t\t\tself.triggerChange(e);\n\t\t\t\t}));\n\t\t\t}\n\t\t}\n\t}", "connectRelay() {\n var params, peer_ip, ref;\n dbg('Connecting to relay...');\n // Get a remote IP address from the PeerConnection, if possible. Add it to\n // the WebSocket URL's query string if available.\n // MDN marks remoteDescription as \"experimental\". However the other two\n // options, currentRemoteDescription and pendingRemoteDescription, which\n // are not marked experimental, were undefined when I tried them in Firefox\n // 52.2.0.\n // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/remoteDescription\n peer_ip = Parse.ipFromSDP((ref = this.pc.remoteDescription) != null ? ref.sdp : void 0);\n params = [];\n if (peer_ip != null) {\n params.push([\"client_ip\", peer_ip]);\n }\n var relay = this.relay = WS.makeWebsocket(this.relayAddr, params);\n this.relay.label = 'websocket-relay';\n this.relay.onopen = () => {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = 0;\n }\n log(relay.label + ' connected!');\n return snowflake.ui.setStatus('connected');\n };\n this.relay.onclose = () => {\n log(relay.label + ' closed.');\n snowflake.ui.setStatus('disconnected.');\n snowflake.ui.setActive(false);\n this.flush();\n return this.close();\n };\n this.relay.onerror = this.onError;\n this.relay.onmessage = this.onRelayToClientMessage;\n // TODO: Better websocket timeout handling.\n return this.timer = setTimeout((() => {\n if (0 === this.timer) {\n return;\n }\n log(relay.label + ' timed out connecting.');\n return relay.onclose();\n }), 5000);\n }", "function listen () {\n var _this = this\n\n this.handler = function () {\n _this.handleMessage.apply(_this, arguments)\n }\n\n if (window.addEventListener) {\n window.addEventListener('message', this.handler)\n }\n else {\n window.attachEvent('onmessage', this.handler)\n }\n}", "function bind(eventName, handler) {\n\t\t\t_this.on(eventName, handler);\n\t\t\tbindTuples.push([ eventName, handler ]);\n\t\t}", "function bind(eventName, handler) {\n\t\t\t_this.on(eventName, handler);\n\t\t\tbindTuples.push([ eventName, handler ]);\n\t\t}", "function bind(eventName, handler) {\n\t\t\t_this.on(eventName, handler);\n\t\t\tbindTuples.push([ eventName, handler ]);\n\t\t}", "function bind(eventName, handler) {\n\t\t\t_this.on(eventName, handler);\n\t\t\tbindTuples.push([ eventName, handler ]);\n\t\t}", "_BindPeer( peerSocket )\n {\n\n peerSocket.BindEvent( \"open\", this.Open.bind(this) );\n peerSocket.BindEvent( \"close\", this.Close.bind(this) );\n peerSocket.BindEvent( \"error\", this.Error.bind(this) );\n peerSocket.BindEvent( \"message\", this.Message.bind(this) );\n\n }", "function bindEventListeners() {\r\n //b.bind();\r\n}", "function _bindPageEvents() {\n \"use strict\";\n $('#js-start-broadcasting-button').click(function() {\n $(this).prop('disabled', true);\n participant.startBroadcasting($('video').get(0));\n });\n}", "setListeners(){\n let self = this;\n\n self.socketHub.on('connection', (socket) => {\n console.log(`SOCKET HUB CONNECTION: socket id: ${socket.id}`)\n self.emit(\"client_connected\", socket.id);\n socket.on(\"disconnect\", (reason)=>{\n console.log(\"Client disconnected: \" + socket.id)\n self.emit(\"client_disconnected\", socket.id)\n });\n\n socket.on('reconnect', (attemptNumber) => {\n self.emit(\"client_reconnected\", socket.id)\n });\n\n socket.on(\"ping\", ()=>{\n console.log(\"RECEIVED PING FROM CLIENT\")\n socket.emit(\"pong\");\n })\n\n socket.on(\"error\", (err)=>{\n Logger.error(`Client socket error: ${err.message}`, {stack: err.stack});\n })\n\n });\n\n self.dataSocketHub.on('connection', (socket)=>{\n console.log(\"File socket connected\");\n self.emit(\"data_channel_opened\", socket);\n console.log(\"After data_channel_opened emit\")\n socket.on(\"disconnect\", (reason)=>{\n self.emit(\"data_channel_closed\", socket.id);\n });\n\n socket.on(\"reconnect\", (attemptNumber) => {\n self.emit(\"data_channel_reconnection\", socket.id);\n })\n\n socket.on(\"error\", (err)=>{\n Logger.error(\"Data socket error: \" + err)\n })\n\n })\n }", "bindButtonEvents() {\n var self = this;\n\n this.button.addEventListener(\n 'click',\n self.onButtonClick.bind(self)\n );\n }", "bindSocketListeners() {\n //Remove listeners that were used for connecting\n this.netClient.removeAllListeners('connect');\n this.netClient.removeAllListeners('timeout');\n // The socket is expected to be open at this point\n this.isSocketOpen = true;\n this.netClient.on('close', () => {\n this.log('info', `Connection to ${this.endpointFriendlyName} closed`);\n this.isSocketOpen = false;\n const wasConnected = this.connected;\n this.close();\n if (wasConnected) {\n // Emit only when it was closed unexpectedly\n this.emit('socketClose');\n }\n });\n\n this.protocol = new streams.Protocol({ objectMode: true });\n this.parser = new streams.Parser({ objectMode: true }, this.encoder);\n const resultEmitter = new streams.ResultEmitter({objectMode: true});\n resultEmitter.on('result', this.handleResult.bind(this));\n resultEmitter.on('row', this.handleRow.bind(this));\n resultEmitter.on('frameEnded', this.freeStreamId.bind(this));\n resultEmitter.on('nodeEvent', this.handleNodeEvent.bind(this));\n\n this.netClient\n .pipe(this.protocol)\n .pipe(this.parser)\n .pipe(resultEmitter);\n\n this.writeQueue = new WriteQueue(this.netClient, this.encoder, this.options);\n }", "listen () {\n const url = 'ws://' + this._options.hostname + ':' + this._options.port\n this.ws = new WebSocket(url, { family: 4 })\n\n this.ws\n .on('error', (error) => {\n /** Emitted on error.\n * @event WsMonitor#error\n * @param {Error} error - The error.\n */\n this.emit('error', error)\n })\n .on('open', () => {\n /** Emitted when connection to web socket server is opened.\n * @event WsMonitor#listening\n * @param {string} url - The URL of the web socket server.\n */\n this.emit('listening', url)\n })\n .on('message', (data, flags) => {\n try {\n const obj = JSON.parse(data.toString())\n if (!this._options.raw) {\n if (obj.t === 'event') {\n switch (obj.e) {\n case 'changed':\n if (obj.r && obj.id && obj.state) {\n const resource = '/' + obj.r + '/' + obj.id + '/state'\n /** Emitted when a `changed` notification has been received.\n * @event WsMonitor#changed\n * @param {string} resource - The changed resource.<br>\n * This can be a `/lights`, `/groups`, or `/sensors`\n * resource for top-level attributes, or a `state` or\n * `config` sub-resource.\n * @param {object} attributes - The top-level, `state`,\n * `config`, or `capabilities` attributes.\n */\n this.emit('changed', resource, obj.state)\n return\n }\n if (obj.r && obj.id && obj.config) {\n const resource = '/' + obj.r + '/' + obj.id + '/config'\n this.emit('changed', resource, obj.config)\n return\n }\n if (obj.r && obj.id && obj.attr) {\n const resource = '/' + obj.r + '/' + obj.id\n this.emit('changed', resource, obj.attr)\n return\n }\n if (obj.r && obj.id && obj.capabilities) {\n const resource = '/' + obj.r + '/' + obj.id + '/capabilities'\n this.emit('changed', resource, obj.capabilities)\n return\n }\n break\n case 'added':\n if (obj.r && obj.id) {\n const resource = '/' + obj.r + '/' + obj.id\n /** Emitted when an `added` notification has been received.\n * @event WsMonitor#added\n * @param {string} resource - The added resource.\n * @param {object} attributes - The full attributes of the\n * added resource.\n */\n this.emit('added', resource, obj[obj.r.slice(0, -1)])\n return\n }\n break\n case 'scene-called':\n if (obj.gid && obj.scid) {\n const resource = '/groups/' + obj.gid + '/scenes/' + obj.scid\n /** Emitted when an `sceneRecall` notification has been received.\n * @event WsMonitor#sceneRecall\n * @param {string} resource - The scene resource.\n */\n this.emit('sceneRecall', resource)\n return\n }\n break\n default:\n break\n }\n }\n }\n /** Emitted when an unknown notification has been received, or when\n * `params.raw` was specified to the\n * {@link WsMonitor constructor}.\n * @event WsMonitor#notification\n * @param {object} notification - The raw notification.\n */\n this.emit('notification', obj)\n } catch (error) {\n this.emit('error', error)\n }\n })\n .on('close', () => {\n /** Emitted when the connection to the web socket server has been closed.\n * @event WsMonitor#closed\n * @param {string} url - The URL of the web socket server.\n */\n this.emit('closed', url)\n if (this._options.retryTime > 0) {\n setTimeout(this.listen.bind(this), this._options.retryTime * 1000)\n }\n })\n }", "bindButtonEvents() {\n var self = this;\n\n this.button.addEventListener('click', self.onButtonClick.bind(self));\n }", "_eventHandler(message) {\n // push to web client\n this._io.emit('service:event:' + message.meta.event, message.payload)\n this._io.emit('_bson:service:event:' + message.meta.event,\n this._gateway._connector.encoder.pack(message.payload))\n }", "registerPlayerEvents() {\n const socket = Game.socket;\n socket.on('update', this.onUpdate.bind(this));\n socket.on('command', this.onCommand.bind(this));\n socket.on('player:connected', this.onPlayerConnected.bind(this));\n socket.on('player:disconnected', this.onPlayerDisconnected.bind(this));\n }", "bindEvent() {\n chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {\n switch (request.eventName) {\n case 'parse':\n this.parse()\n break\n case 'revert':\n this.revert()\n break\n case 'switchThemeName':\n this.switchTheme(request.themeName)\n this.setThemeName(request.themeName)\n break\n case 'switchLangsPrefer':\n this.setLangsPrefer(request.langsPrefer)\n break\n }\n });\n }", "addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n\n this.onOpen();\n };\n\n this.ws.onclose = this.onClose.bind(this);\n\n this.ws.onmessage = ev => this.onData(ev.data);\n\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }", "bindEvents() {\n this.node.addEventListener('change', this.update.bind(this));\n this.node.addEventListener('input', this.update.bind(this));\n this.node.addEventListener('click', this.update.bind(this));\n this.node.addEventListener('touchend', this.update.bind(this));\n this.node.addEventListener('keyup', this.update.bind(this));\n }", "bindEvents() {\n this.node.addEventListener('rh-toggle', this.update.bind(this));\n }", "_bindEvents() {\n const thisObj = this;\n\n this._muteBtn\n .off()\n .on(\"click\", function () {\n if (thisObj._isMuted) {\n thisObj._unmute();\n } else {\n thisObj._mute();\n }\n });\n\n this._ackAllBtn\n .off()\n .on(\"click\", function () {\n if (!thisObj._ackAllBtn.hasClass(\"disabled\")) {\n thisObj.panelElem.trigger(NotifPanel.ACK_ALL_EVENT);\n }\n });\n\n this.bellElem\n .off()\n .on(\"click\", function () {\n thisObj._toggle();\n });\n }", "bindConnectEventListener(raw, baseUrl, resolve) {\n raw.on('connect', () => {\n this.handleSuccessfulConnect(raw, baseUrl, resolve);\n });\n }", "listen () {\n if (this._wss) return\n\n super.listen()\n\n this._wss = new WS.Server({\n perMessageDeflate: false,\n port: this._apiPort\n })\n\n this._clients = []\n this._wss.on('connection', this._onConnection.bind(this))\n\n debug('ws2 api server listening on port %d', this._apiPort)\n }", "listenWindow() {\n this.initDefaultUI();\n this.initFastClick();\n this.setMoblie();\n }", "function bindEvents() {\n\t\t\teManager.on('showForm', function() {\n\t\t\t\tshowForm();\n\t\t\t});\n\t\t\teManager.on('csvParseError', function() {\n\t\t\t\tshowError();\n\t\t\t});\n\t\t}", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n if (self.isMobile) {\n setupMobile();\n return;\n }\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))\n bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\")\n onMouseOver(getEventTarget(e));\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config.static)\n bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined)\n bind(window.document, \"touchstart\", documentClick);\n else\n bind(window.document, \"click\", documentClick);\n bind(window.document, \"focus\", documentClick, { capture: true });\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"click\", self.open);\n }\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"click\", onMonthNavClick);\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"click\", selectDate);\n }\n if (self.timeContainer !== undefined &&\n self.minuteElement !== undefined &&\n self.hourElement !== undefined) {\n var selText = function (e) {\n return getEventTarget(e).select();\n };\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, { capture: true });\n bind(self.timeContainer, \"click\", timeIncrement);\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined)\n bind(self.secondElement, \"focus\", function () { return self.secondElement && self.secondElement.select(); });\n if (self.amPM !== undefined) {\n bind(self.amPM, \"click\", function (e) {\n updateTime(e);\n triggerChange();\n });\n }\n }\n if (self.config.allowInput)\n bind(self._input, \"blur\", onBlur);\n }", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n if (self.isMobile) {\n setupMobile();\n return;\n }\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))\n bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\")\n onMouseOver(getEventTarget(e));\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config.static)\n bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined)\n bind(window.document, \"touchstart\", documentClick);\n else\n bind(window.document, \"click\", documentClick);\n bind(window.document, \"focus\", documentClick, { capture: true });\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"click\", self.open);\n }\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"click\", onMonthNavClick);\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"click\", selectDate);\n }\n if (self.timeContainer !== undefined &&\n self.minuteElement !== undefined &&\n self.hourElement !== undefined) {\n var selText = function (e) {\n return getEventTarget(e).select();\n };\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, { capture: true });\n bind(self.timeContainer, \"click\", timeIncrement);\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined)\n bind(self.secondElement, \"focus\", function () { return self.secondElement && self.secondElement.select(); });\n if (self.amPM !== undefined) {\n bind(self.amPM, \"click\", function (e) {\n updateTime(e);\n triggerChange();\n });\n }\n }\n if (self.config.allowInput)\n bind(self._input, \"blur\", onBlur);\n }", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n if (self.isMobile) {\n setupMobile();\n return;\n }\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))\n bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\")\n onMouseOver(e.target);\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config.static)\n bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined)\n bind(window.document, \"touchstart\", documentClick);\n else\n bind(window.document, \"mousedown\", onClick(documentClick));\n bind(window.document, \"focus\", documentClick, { capture: true });\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"mousedown\", onClick(self.open));\n }\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"mousedown\", onClick(onMonthNavClick));\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"mousedown\", onClick(selectDate));\n }\n if (self.timeContainer !== undefined &&\n self.minuteElement !== undefined &&\n self.hourElement !== undefined) {\n var selText = function (e) {\n return e.target.select();\n };\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, { capture: true });\n bind(self.timeContainer, \"mousedown\", onClick(timeIncrement));\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined)\n bind(self.secondElement, \"focus\", function () { return self.secondElement && self.secondElement.select(); });\n if (self.amPM !== undefined) {\n bind(self.amPM, \"mousedown\", onClick(function (e) {\n updateTime(e);\n triggerChange();\n }));\n }\n }\n }", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n if (self.isMobile) {\n setupMobile();\n return;\n }\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))\n bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\")\n onMouseOver(e.target);\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config.static)\n bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined)\n bind(window.document, \"touchstart\", documentClick);\n else\n bind(window.document, \"mousedown\", onClick(documentClick));\n bind(window.document, \"focus\", documentClick, { capture: true });\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"mousedown\", onClick(self.open));\n }\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"mousedown\", onClick(onMonthNavClick));\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"mousedown\", onClick(selectDate));\n }\n if (self.timeContainer !== undefined &&\n self.minuteElement !== undefined &&\n self.hourElement !== undefined) {\n var selText = function (e) {\n return e.target.select();\n };\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, { capture: true });\n bind(self.timeContainer, \"mousedown\", onClick(timeIncrement));\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined)\n bind(self.secondElement, \"focus\", function () { return self.secondElement && self.secondElement.select(); });\n if (self.amPM !== undefined) {\n bind(self.amPM, \"mousedown\", onClick(function (e) {\n updateTime(e);\n triggerChange();\n }));\n }\n }\n }", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n if (self.isMobile) {\n setupMobile();\n return;\n }\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))\n bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\")\n onMouseOver(e.target);\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config.static)\n bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined)\n bind(window.document, \"touchstart\", documentClick);\n else\n bind(window.document, \"mousedown\", onClick(documentClick));\n bind(window.document, \"focus\", documentClick, { capture: true });\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"mousedown\", onClick(self.open));\n }\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"mousedown\", onClick(onMonthNavClick));\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"mousedown\", onClick(selectDate));\n }\n if (self.timeContainer !== undefined &&\n self.minuteElement !== undefined &&\n self.hourElement !== undefined) {\n var selText = function (e) {\n return e.target.select();\n };\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, { capture: true });\n bind(self.timeContainer, \"mousedown\", onClick(timeIncrement));\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined)\n bind(self.secondElement, \"focus\", function () { return self.secondElement && self.secondElement.select(); });\n if (self.amPM !== undefined) {\n bind(self.amPM, \"mousedown\", onClick(function (e) {\n updateTime(e);\n triggerChange();\n }));\n }\n }\n }", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n if (self.isMobile) {\n setupMobile();\n return;\n }\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))\n bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\")\n onMouseOver(e.target);\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config.static)\n bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined)\n bind(window.document, \"touchstart\", documentClick);\n else\n bind(window.document, \"mousedown\", onClick(documentClick));\n bind(window.document, \"focus\", documentClick, { capture: true });\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"mousedown\", onClick(self.open));\n }\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"mousedown\", onClick(onMonthNavClick));\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"mousedown\", onClick(selectDate));\n }\n if (self.timeContainer !== undefined &&\n self.minuteElement !== undefined &&\n self.hourElement !== undefined) {\n var selText = function (e) {\n return e.target.select();\n };\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, { capture: true });\n bind(self.timeContainer, \"mousedown\", onClick(timeIncrement));\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined)\n bind(self.secondElement, \"focus\", function () { return self.secondElement && self.secondElement.select(); });\n if (self.amPM !== undefined) {\n bind(self.amPM, \"mousedown\", onClick(function (e) {\n updateTime(e);\n triggerChange();\n }));\n }\n }\n }", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n if (self.isMobile) {\n setupMobile();\n return;\n }\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))\n bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\")\n onMouseOver(getEventTarget(e));\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config.static)\n bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined)\n bind(window.document, \"touchstart\", documentClick);\n else\n bind(window.document, \"mousedown\", documentClick);\n bind(window.document, \"focus\", documentClick, {capture: true});\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"click\", self.open);\n }\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"click\", onMonthNavClick);\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"click\", selectDate);\n }\n if (self.timeContainer !== undefined &&\n self.minuteElement !== undefined &&\n self.hourElement !== undefined) {\n var selText = function (e) {\n return getEventTarget(e).select();\n };\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, {capture: true});\n bind(self.timeContainer, \"click\", timeIncrement);\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined)\n bind(self.secondElement, \"focus\", function () {\n return self.secondElement && self.secondElement.select();\n });\n if (self.amPM !== undefined) {\n bind(self.amPM, \"click\", function (e) {\n updateTime(e);\n triggerChange();\n });\n }\n }\n if (self.config.allowInput) {\n bind(self._input, \"blur\", onBlur);\n }\n }", "function bindDataChannelHandlers(dataChannel) {\n dataChannel.onopen = () => {\n print(\"%cRTCDataChannel now open and ready to receive messages\", \"color:blue;\");\n // for (let i = 0; i < 200; i++) {\n // dataChannel.send(\"hello!\");\n // }\n };\n dataChannel.onmessage = (event) => { // careful: both clients recieve message sent\n let message = event.data;\n print(\"RTCDataChannel recieved a message: \"+message);\n };\n dataChannel.onclose = () => {\n print(\"RTCDataChannel closed\");\n };\n dataChannel.onerror = () => {\n print(\"RTCDataChannel error!\");\n };\n}", "startEventListener() {\n Utils.contract.MessagePosted().watch((err, { result }) => {\n if(err)\n return console.error('Failed to bind event listener:', err);\n\n console.log('Detected new message:', result.id);\n this.fetchMessage(+result.id);\n });\n }", "addEventListeners() {\n this.ws.onopen = () => {\n if (this.opts.autoUnref) {\n this.ws._socket.unref();\n }\n this.onOpen();\n };\n this.ws.onclose = this.onClose.bind(this);\n this.ws.onmessage = ev => this.onData(ev.data);\n this.ws.onerror = e => this.onError(\"websocket error\", e);\n }", "function EventHandler() {\n this._binds = [];\n }", "_connectEvents () {\n this._socket.on('sensorChanged', this._onSensorChanged);\n this._socket.on('deviceWasClosed', this._onDisconnect);\n this._socket.on('disconnect', this._onDisconnect);\n }", "addChatListeners () {\n this.webSocket.onopen = () => console.log('open channel')\n this.webSocket.addEventListener('open', this.handleSocketConnection)\n this.webSocket.onmessage = (e) => this.handleMessage(JSON.parse(e.data))\n this.form.addEventListener('submit', this.handleSubmit)\n this.emojiIcon.addEventListener('click', this.toggleEmojis)\n }", "function bindClassEvents() {\n var resHandlr = this.responseHandler;\n this.on('ajaxable:on-ajax-before', resHandlr.beforeSend.bind(resHandlr), this);\n this.on('ajaxable:on-ajax-success', resHandlr.onSuccess.bind(resHandlr), this);\n this.on('ajaxable:on-ajax-error', resHandlr.onError.bind(resHandlr), this);\n this.on('ajaxable:on-ajax-complete', resHandlr.onComplete.bind(resHandlr), this);\n this.on('ajaxable:on-ajax-abort', resHandlr.onAbort.bind(resHandlr), this);\n this.on('ajaxable:on-ajax-timeout', resHandlr.onTimeout.bind(resHandlr), this);\n}", "bindEvents() {\n // Listen for global debounced resize.\n this.resizeId = OdoWindowEvents.onResize(this.update.bind(this));\n\n // Throttle scrolling because it doesn't need to be super accurate.\n this.scrollId = OdoWindowEvents.onFastScroll(this.handleScroll.bind(this));\n\n this.hasActiveHandlers = true;\n }", "function bindEvents() {\n if (self.config.wrap) {\n [\"open\", \"close\", \"toggle\", \"clear\"].forEach(function (evt) {\n Array.prototype.forEach.call(self.element.querySelectorAll(\"[data-\" + evt + \"]\"), function (el) {\n return bind(el, \"click\", self[evt]);\n });\n });\n }\n if (self.isMobile) {\n setupMobile();\n return;\n }\n var debouncedResize = debounce(onResize, 50);\n self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);\n if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))\n bind(self.daysContainer, \"mouseover\", function (e) {\n if (self.config.mode === \"range\")\n onMouseOver(e.target);\n });\n bind(window.document.body, \"keydown\", onKeyDown);\n if (!self.config.inline && !self.config.static)\n bind(window, \"resize\", debouncedResize);\n if (window.ontouchstart !== undefined)\n bind(window.document, \"touchstart\", documentClick);\n else\n bind(window.document, \"mousedown\", onClick(documentClick));\n bind(window.document, \"focus\", documentClick, { capture: true });\n if (self.config.clickOpens === true) {\n bind(self._input, \"focus\", self.open);\n bind(self._input, \"mousedown\", onClick(self.open));\n }\n if (self.daysContainer !== undefined) {\n bind(self.monthNav, \"mousedown\", onClick(onMonthNavClick));\n bind(self.monthNav, [\"keyup\", \"increment\"], onYearInput);\n bind(self.daysContainer, \"mousedown\", onClick(selectDate));\n }\n if (self.timeContainer !== undefined &&\n self.minuteElement !== undefined &&\n self.hourElement !== undefined) {\n var selText = function (e) {\n return e.target.select();\n };\n bind(self.timeContainer, [\"increment\"], updateTime);\n bind(self.timeContainer, \"blur\", updateTime, { capture: true });\n bind(self.timeContainer, \"mousedown\", onClick(timeIncrement));\n bind([self.hourElement, self.minuteElement], [\"focus\", \"click\"], selText);\n if (self.secondElement !== undefined)\n bind(self.secondElement, \"focus\", function () { return self.secondElement && self.secondElement.select(); });\n if (self.amPM !== undefined) {\n bind(self.amPM, \"mousedown\", onClick(function (e) {\n updateTime(e);\n triggerChange();\n }));\n }\n }\n }", "_bindEventListenerCallbacks() {\n this._onClickBound = this._onClick.bind(this);\n this._onKeydownBound = this._onKeydown.bind(this);\n }", "bind(object) {\n\t\t// remove old events\n\t\tfor (let name in this.events) {\n\t\t\tif (this.resolver.resolved[name]) continue;\n\t\t\tthis.node.removeEventListener(name, this.listener, false);\n\t\t\tdelete this.events[name];\n\t\t}\n\n\t\t// add new events\n\t\tfor (let name in this.resolver.resolved)\n\t\t{\n\t\t\tif (!this.events[name])\n\t\t\t{\n\t\t\t\tif (typeof this.resolver.resolved[name].method !== 'function') continue;\n\t\t\t\tthis.node.addEventListener(name, this.listener.bind(this), false);\n\t\t\t}\n\t\t\tthis.events[name] = this.resolver.resolved[name];\n\t\t}\n\t}" ]
[ "0.63512105", "0.6251112", "0.6139383", "0.6045059", "0.6021572", "0.6010052", "0.5994783", "0.59935796", "0.5982343", "0.596509", "0.5930961", "0.5929303", "0.59268016", "0.5896727", "0.588862", "0.5873009", "0.5872311", "0.5867207", "0.58462965", "0.5811057", "0.57656306", "0.5751278", "0.5734137", "0.5713873", "0.57071877", "0.56524736", "0.56081444", "0.5584363", "0.55763865", "0.55748767", "0.55612165", "0.5558383", "0.5555119", "0.5538465", "0.5525513", "0.5511861", "0.5504366", "0.54879093", "0.5484953", "0.5478841", "0.5478841", "0.547143", "0.5459057", "0.5458565", "0.5458043", "0.5458043", "0.5409348", "0.5391266", "0.5381898", "0.53788525", "0.53725255", "0.5357172", "0.5357172", "0.53391683", "0.53344774", "0.5322844", "0.5320399", "0.53201544", "0.5317057", "0.5310913", "0.5310913", "0.5310913", "0.5310913", "0.5308723", "0.5306931", "0.52956647", "0.52936214", "0.52907133", "0.52797425", "0.52797425", "0.5272766", "0.5271502", "0.52682424", "0.52483094", "0.52466047", "0.52442116", "0.52439654", "0.52399737", "0.5232035", "0.5227659", "0.522505", "0.522344", "0.52214974", "0.5221442", "0.5221001", "0.5221001", "0.5221001", "0.5221001", "0.52208066", "0.5217875", "0.52083987", "0.51907295", "0.5188195", "0.5186767", "0.5181987", "0.51800424", "0.5165777", "0.5163227", "0.516268", "0.5157509" ]
0.58158666
19
one or the other or both spends is valid if both the hash and the index are valid. pays is valid if pays is valid
function isValidRequestInput(options) { const {hash, index, pays} = options; let isSpendsValid = false; let isPaysValid = false; if ( Buffer.isBuffer(hash) && hash.length === 32 && typeof index === 'number' && (index >>> 0) === index ) isSpendsValid = true; // TODO: check for size if (Buffer.isBuffer(pays)) isPaysValid = true; return isSpendsValid || isPaysValid; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "isChainValid(){\n\n //not putting index in 0 cause GENESIS is the 0\n for(let i = 1; i <this.chain.length; i++){\n const currentBlock = this.chain[i];\n const previousBlock = this.chain[i -1];\n\n //check if the propely block are link together\n //1.- if the hash of the block still valid \n if(currentBlock.hash != currentBlock.calculateHash()){\n return false; \n }\n\n if(currentBlock.previousHash != previousBlock.hash){\n return false;\n }\n }\n return true;\n }", "checkChainValidity() {\n for (let i = 1; i < this.chain.length; i++){\n const currentBlock = this.chain[i];\n const previousBlock = this.chain[i - 1];\n if (currentBlock.hash !== currentBlock.calculateHash()) {\n //console.log(\"hash \" + i);\n return false;\n }\n if (currentBlock.previousHash !== previousBlock.hash) {\n //console.log(\"previousHash \" + i);\n return false;\n }\n }\n return true;\n }", "validateSaleBuyAcount() {\n let result = false;\n let acountID = this.saleAndBuy.acountID;\n let state = this.saleAndBuy.acountState;\n\n //Primero verifico que es una cuenta exsitente\n let acountExist = this.bank.players.some(p => p.id === acountID);\n\n if (acountExist) {\n state.reset();\n result = true;\n } else {\n state.hasError = true;\n }\n\n return result;\n }", "verifyHash(hash) {\n return (0, _sha2.default)(this.index + this.previousHash + this.timestamp + this.nonce) == hash;\n }", "isChainValid() {\n let invalidBlocks = [];\n for (let i = 1; i < this.chain.length; i++) {\n const currentBlock = this.chain[i];\n const previousBlock = this.chain[i - 1];\n\n // Current block's hash miscalculates\n if (currentBlock.hash !== currentBlock.calculateHash()) {\n invalidBlocks.push(i)\n }\n\n // Current block's previousHash doesn't match to the previous block's hash\n if (currentBlock.previousHash !== previousBlock.hash) {\n // TODO: Should check if this index has already been pushed but whatever for now\n invalidBlocks.push(i);\n }\n }\n\n if(invalidBlocks.length == 0){\n return {\n result: true\n };\n } else {\n return {\n result: false,\n invalidBlocks\n };\n }\n }", "isChainValid(chainToVerify) {\r\n if(chainToVerify==null){\r\n chainToVerify=this.chain;\r\n }\r\n for (let chainIndex = 1; chainIndex < chainToVerify.length; chainIndex++){\r\n let currentBlock = new Block(chainToVerify[chainIndex].index,chainToVerify[chainIndex].timeStamp,chainToVerify[chainIndex].data,chainToVerify[chainIndex].previousHash,false);\r\n currentBlock.hash=chainToVerify[chainIndex].hash;\r\n currentBlock.nonce=chainToVerify[chainIndex].nonce;\r\n let previousBlock = chainToVerify[chainIndex - 1];\r\n\r\n //either hash is not matching or previous hash is not matching\r\n if (currentBlock.hash !== currentBlock.calculateHash()\r\n || currentBlock.previousHash !== previousBlock.hash) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "checkValidLastTransaction(lastTransactionInSegment, lastTransactionToObtain) {\n if (lastTransactionToObtain.id === false || lastTransactionInSegment.id === false) {\n return 'noCheck';\n } else {\n let check = Transaction.prototype.transactionFromId(lastTransactionInSegment.id).checkEarlierLaterEqualThanId(lastTransactionToObtain.id);\n //if (check === 'equal' || check === 'later') {\n if (check === 'equal') {\n return true;\n } else {\n return false;\n }\n }\n }", "validateCosts() {\n for (const [[key1, key2], cost] of this.symbolPairCostMap.entries()) {\n if (key1 < key2) {\n this.symbolPairCostMap.set([key2, key1], cost);\n }\n if (cost < 0) {\n throw (new Error(\"Costs must be Positive.\"));\n }\n }\n for (const [key, cost] of this.symbolCostMap.entries()) {\n if (cost < 0) {\n throw (new Error(\"Costs must be Positive.\"));\n }\n }\n }", "validate() {\n for (let i=1 ; i < this.chain.length; i++) {\n const currentBlock = this.chain[i];\n const previousBlock = this.chain[i-1];\n\n if (!currentBlock.hasValidTransactions()) {\n return false;\n }\n \n //console.log(\"validate = currentBlock: \", this.chain[i] );\n if ( currentBlock.hash !== currentBlock.createHash()) {\n return false;\n }//end iffy\n \n if (currentBlock.previousHash !== previousBlock.hash ) {\n return false;\n }\n \n }//end for\n \n // if we reach here, the chain is valid\n return true;\n }", "function isAdjacentValid(index_1, index_2) {\n let pos_1 = toEncapsulated(index_1);\n let pos_2 = toEncapsulated(index_2);\n let dist_1 = Math.abs(pos_1[0] - pos_2[0]);\n let dist_2 = Math.abs(pos_1[1] - pos_2[1]);\n\n if((!dist_1 || !dist_2) && (dist_1 === 1 || dist_2 === 1)) {\n\n return dist_1 !== dist_2;\n\n }\n return false;\n}", "valid(index) { return (this.start<=index && index<this.end) }", "_checkDone() {\n\n // it's only for SIGHASH_ALL, if implement other - change it!\n if (this._data.claimProofs.length) throw new Error('Tx is already signed, you can\\'t modify it');\n }", "isAvailable(newStart, newEnd) {\n let plans = this.props.dailyPlans\n for (let i = 0; i < plans.length; i++) {\n let old = plans[i]\n\n if(old.fldOpRLogOn === true && old.fldOpRLogOut === true) continue\n\n let oldStart = this.createDate(old.fldOpRStartDate, old.fldOpRStartTime).getTime()\n let oldEnd = old.fldOpREndTime ? \n this.createDate(old.fldOpREndDate, old.fldOpREndTime).getTime() : null\n \n if (this.state.openEnded || !oldEnd) return true\n \n if (newStart <= oldEnd && oldStart <= newEnd) return\n } \n return true\n }", "isChainValid() \n{ \n for (let i = 1; i < this.chain.length; i++)\n { \n const currentBlock = this.chain[i]; \n const previousBlock = this.chain[i - 1]; \n\n if (currentBlock.hash !== currentBlock.calculateHash()) { \n return false; \n } \n\n if (currentBlock.previousHash !== previousBlock.hash) \n { \n return false; \n } \n } \n \n return true; \n}", "function checkAvailable(endIndex, schedule, startIndex) {\n for (var counter = startIndex; counter <= endIndex; counter++) {\n if (schedule[counter] != 0)\n return false;\n }\n return true;\n}", "isChainValid(){\n let currentBlock;\n let previousBlock;\n\n for (let i = 1; i <= this.length; i++){\n currentBlock = this.chain[i];\n previousBlock = this.chain[i -1];\n\n if(currentBlock.hash !== currentBlock.calculateHash()){\n return false;\n }\n\n if(currentBlock.previousHash !== previousBlock.hash){\n return false;\n }\n \n if(currentBlock.index === previousBlock.index){\n return false;\n }\n }\n return true;\n }", "function checkValid(index) {\r\n var tempBalance, tempValue;\r\n var tempInputs = document.getElementsByTagName(\"input\");\r\n var patt = /^\\d+$/;\r\n if (index == PARTS) {\r\n var total = 0;\r\n var i;\r\n for (i = 0; i < tempInputs.length; i++) {\r\n if (!(patt.test(tempInputs[i].value))) {\r\n document.getElementById(\"errMsg\").innerHTML = \"<p>Please enter a number for each part!</p>\";\r\n return;\r\n }\r\n total += parseInt(tempInputs[i].value);\r\n }\r\n tempValue = tempSupplies[index];\r\n tempSupplies[index] = total;\r\n tempBalance = supplies[MONEY] - ((price[OXEN_COST] * tempSupplies[OXEN]) + (price[CLOTHING_COST] * tempSupplies[CLOTHING]) + (price[FOOD_COST] * tempSupplies[FOOD]) + (price[BAIT_COST] * tempSupplies[BAIT]) + (price[WAGON_COST] * tempSupplies[PARTS]));\r\n if (tempBalance < 0) {\r\n tempSupplies[index] = tempValue;\r\n document.getElementById(\"errMsg\").innerHTML = \"<p>You do not have enough money to do that!</p>\";\r\n }\r\n else {\r\n tempParts[WHEEL] = parseInt(tempInputs[0].value);\r\n tempParts[AXLE] = parseInt(tempInputs[1].value);\r\n tempParts[TONGUE] = parseInt(tempInputs[2].value);\r\n initStore();\r\n }\r\n }\r\n else {\r\n if (patt.test(tempInputs[0].value)) {\r\n tempValue = tempSupplies[index];\r\n if (index == OXEN) tempSupplies[index] = parseInt(tempInputs[0].value) * 2;\r\n else if (index == BAIT) tempSupplies[index] = parseInt(tempInputs[0].value) * 20;\r\n else tempSupplies[index] = parseInt(tempInputs[0].value);\r\n tempBalance = supplies[MONEY] - ((price[OXEN_COST] * tempSupplies[OXEN]) + (price[CLOTHING_COST] * tempSupplies[CLOTHING]) + (price[FOOD_COST] * tempSupplies[FOOD]) + (price[BAIT_COST] * tempSupplies[BAIT]) + (price[WAGON_COST] * tempSupplies[PARTS]));\r\n if (tempBalance < 0) {\r\n tempSupplies[index] = tempValue;\r\n document.getElementById(\"errMsg\").innerHTML = \"<p>You do not have enough money to do that!</p>\";\r\n }\r\n else initStore();\r\n }\r\n else document.getElementById(\"errMsg\").innerHTML = \"<p>Please enter a number!</p>\";\r\n }\r\n}", "verifyChainIntegrity(){\n for(let i = 1; i < this.blockchain.length; i++){\n const currentBlock = this.blockchain[i];\n const precedingBlock= this.blockchain[i-1];\n\n if(currentBlock.hash !== currentBlock.calculateHash()){\n return false;\n }\n if(currentBlock.prevHash !== precedingBlock.hash)\n return false;\n }\n return true;\n }", "function validate(block, diff){\n return(block.hash<diff);\n}", "function isValid(prevIndex, index)\n{\n\t//0 1 2\n\t//3 4 5\n\t//6 7 8\n\tconst valid_moves = {\n\t\t0 : [1, 3, 4, -1, -1, -1, -1, -1], \n\t\t1 : [0, 2, 3, 4, 5, -1, -1, -1], \n\t\t2 : [1, 4, 5, -1, -1, -1, -1, -1], \n\t\t3 : [0, 1, 4, 6, 7, -1, -1, -1], \n\t\t4 : [0, 1, 2, 3, 5, 6, 7, 8], \n\t\t5 : [1, 2, 4, 7, 8, -1, -1, -1], \n\t\t6 : [3, 4, 7, -1, -1, -1, -1, -1], \n\t\t7 : [3, 4, 5, 6, 8, -1, -1, -1], \n\t\t8 : [4, 5, 7, -1, -1, -1, -1, -1]\n\t}; \n\n\tvar valid_spots = valid_moves[prevIndex]; \n\tfor(var i = 0; i < 8; i++)\n\t{\n\t\tif(valid_spots[i] === index)\n\t\t\treturn true; \n\t}\n\treturn false; \n}", "isValidChain(chain){\n //first element of incoming chain matches the genesis block\n //Stringyify the element to compare\n if (JSON.stringify(chain[0]) !== JSON.stringify(Block.genesis())) return false;\n\n\n \n //validation on each block after teh genesis block in the incoming chain\n for (let i = 1; i < chain.length; i++) {\n //current block\n const block = chain[i];\n \n //the last block\n const lastBlock = chain[i - 1];\n \n //the current block last hash must match the hash of the last block\n //if the block hash not equal to the generated hash (changed by any reason)\n if (block.lastHash !== lastBlock.hash ||\n block.hash !== Block.blockHash(block)) {\n return false;\n \n }\n }\n return true;\n \n }", "isChainValid(chain) {\n\t\tif (chain.length == 1) return true;\n\t\tlet prev_block = chain[1];\n\t\tfor (let i = 2; i < chain.lenght; i++) {\n\t\t\tlet cur_block = chain[i];\n\t\t\tif (cur_block.prev_hash !== this.hash(prev_block)) return false;\n\t\t\tlet prev_nonce = prev_block.nouce;\n\t\t\tlet cur_nonce = cur_block.nouce;\n\t\t\tif (sha256((Math.pow(cur_nonce, 2) - Math.pow(prev_nonce, 2)).toString()).slice(0, 4) !== '0000') return false;\n\t\t\tprev_block = cur_block;\n\t\t}\n\t\treturn true;\n\t}", "openCoinModal(e) {\n e.preventDefault();\n var key_btc_bal = 0;\n var key_safex_bal = 0;\n\n this.state.keys.map(key => {\n if (key.public_key === e.target.public_key.value) {\n key_btc_bal = key.btc_bal;\n key_safex_bal = key.safex_bal;\n }\n });\n\n if ((this.state.send_coin === 'safex' && this.state.send_fee > key_btc_bal) | (this.state.send_coin === 'btc' && this.state.send_total > key_btc_bal)) {\n alert('you do not have enough BTC to cover the fee');\n } else if (this.state.send_coin === 'safex' && this.state.send_amount > key_safex_bal) {\n alert('you do not have enough SAFEX to cover this transaction');\n } else if (this.state.send_coin === 'btc' && this.state.send_total > key_btc_bal) {\n alert('you do not have enough BTC to cover this transaction');\n } else if (e.target.destination.value === '') {\n alert('destination field is empty');\n } else {\n try {\n bitcore.Address.fromString(e.target.destination.value)\n this.setState({\n send_overflow_active: true,\n send_to: e.target.destination.value,\n send_keys: {\n public_key: e.target.public_key.value,\n private_key: e.target.private_key.value\n },\n dividend_active: false,\n affiliate_active: false\n })\n } catch (e) {\n alert('destination address is invalid');\n }\n }\n }", "function viable(sch){\n\tvar i;\n\tfor(i=1; i<sch.length; i++) if(sch[i].d == sch[i-1].d && (sch[i].s < sch[i-1].e || sch[i].s == sch[i-1].s)) return false;\n\treturn true;\n}", "_isValidIndex(index) {\n return index >= 0 && index < this.options.length;\n }", "_isValidIndex(index) {\n return index >= 0 && index < this.options.length;\n }", "isValid() {\n for(let i = 1; i < this.chain.length; i++) {\n let currentBlock = this.chain[i];\n let previousBlock = this.chain[i-1];\n let currentBlockHash = currentBlock.calculateHash();\n if (currentBlock.hash !== currentBlockHash) {\n return false;\n }\n if (currentBlock.previousHash !== previousBlock.hash) {\n return false;\n }\n }\n return true;\n }", "isValid () {\n return this.validHasGamblingDebt() &&\n this.validGamblingDebt()\n }", "function check_keyval(hash1, hash2) {\r\n\t\r\n\tvar v_exists = 0;\r\n\r\n\tObject.keys(hash1).forEach(function(key, index) {\r\n\t //console.log(this[key]+key);\r\n\t // 1 \r\n\t Object.keys(hash2).forEach(function(key2, index2) {\r\n\t // 2\r\n\t if (hash1[key]+key == hash2[key2]+key2) {\r\n\t //console.log(\"True: \" + hash1[key]+key + \" \" + hash2[key2]+key2);\r\n\t v_exists = v_exists + 1;\r\n\t } \r\n\t },hash1)\r\n\t });\r\n\t//3\r\n if (v_exists > 0) {return true;} else {return false;}\r\n}", "function checkbet(b) {\n var betid = b['id'];\n var betctr = b['betctr'];\n var cseed = pack('H*', b['cseed']);\n var fseed = pack('H*', b['fseed']);\n var sseed = pack('H*', b['sseed']);\n var shash = pack('H*', b['shash']);\n\n if (b['dseed'] == null) {\n dseed == null\n } else {\n var dseed = pack('H*', b['dseed'])\n }\n ;\n var dhash = pack('H*', b['dhash']);\n var user = b['user'];\n var game = b['game'].toLowerCase();\n var result = b['multiplier'];\n var tocheckres = b['multiplier'] * 100;\n tocheckres = Math.floor(tocheckres) / 100;\n var multiply = b['multiplier'];\n var param = b['param'];\n\n var checks = [];\n var my_dhash = null;\n var resulttocheck = multiply;\n checks['betid'] = betid;\n\n//===================================================================================\n// Verification happens here:\n checks['hashchain integrity'] = null;\n for (i = 0; i < dseeds.length; i++) {\n var line = dseeds[i];\n var fields = line.split(\"\\t\");\n\n if (typeof fdhash !== 'undefined') {\n var f_dseed = fdhash;\n }\n var fdhash = pack('H*', fields[1]);\n if (typeof f_dseed !== 'undefined') {\n if (checks['hashchain integrity'] == null) {\n checks['hashchain integrity'] = 'pass';\n }\n if (fields[1].toString() != CryptoJS.SHA256(CryptoJS.enc.Latin1.parse(f_dseed)).toString()) {\n checks['hashchain integrity'] = 'fail';\n\n } else {\n }\n }\n\n if (parseInt(fields[2].trim()) < betid && my_dhash == null) {\n my_dhash = fdhash;\n if (typeof f_dseed !== 'undefined') {\n my_dseed = f_dseed;\n }\n }\n }\n checks['this dhash = published dhash'] = dhash == my_dhash ? 'pass' : 'fail';\n endresult.dhash = checks['this dhash = published dhash'];\n\n\n\n if (dseed == null) {\n checks['sseed = hmac_sha256(username:betctr, dseed)'] = 'no data provided';\n checks['dhash = sha256(dseed)'] = 'no data provided';\n } else {\n var hash1 = CryptoJS.SHA256(CryptoJS.enc.Latin1.parse(dseed));\n hash1 = hash1.toString(CryptoJS.enc.Latin1);\n if (dhash == hash1) {\n checks['dhash = sha256(dseed)'] = 'pass';\n } else {\n checks['dhash = sha256(dseed)'] = 'fail';\n }\n var hmac = CryptoJS.HmacSHA256(user + ':' + betctr, CryptoJS.enc.Latin1.parse(dseed));\n hmac = hmac.toString(CryptoJS.enc.Latin1);\n checks['sseed = hmac_sha256(user:betctr,dseed)'] = sseed == hmac ? 'pass' : 'fail';\n }\n var hash2 = CryptoJS.SHA256(CryptoJS.enc.Latin1.parse(sseed));\n hash2 = hash2.toString(CryptoJS.enc.Latin1);\n checks['shash = sha256(sseed)'] = shash == hash2 ? 'pass' : 'fail';\n var hmac2 = CryptoJS.HmacSHA256(CryptoJS.enc.Latin1.parse(cseed), CryptoJS.enc.Latin1.parse(sseed));\n hmac2 = hmac2.toString(CryptoJS.enc.Latin1);\n console.log(\"####\" + checks['sseed = hmac_sha256(user:betctr,dseed)'])\n checks['fseed = hmac_sha256(cseed, sseed)'] = fseed == hmac2 ? 'pass' : 'fail';\n\n switch (game) {\n\n\n case 'spin':\n checks['correct result'] == 'fail';\n var resultsspin = ['1.25', '0.25', '1.25', '0',\n '2', '0.35', '2', '0.4',\n '1.25', '0.25', '1.25', '0',\n '3', '0', '1.5', '0.25'];\n var seg = unpack('C*', fseed);\n seg = seg[1] >> 4 & 0x0F;\n var res1 = (resultsspin[seg]) * 100;\n var res2 = tocheckres * 100;\n if (parseInt(res1) == parseInt(res2)) {\n checks['correct result'] = 'pass';\n } else {\n checks['correct result'] = 'fail';\n }\n break;\n\n case 'drop':\n var dropresult;\n if (betid > 3393416) {\n var results = ['1', '0.3', '1.5', '0', '3', '0', '1.5', '0.3', '1'];\n } else {\n var results = ['1', '0.4', '1.5', '0', '3', '0', '1.5', '0.4', '1'];\n }\n var slot = param.split(\"=\");\n var mystring = CryptoJS.HmacSHA256(CryptoJS.enc.Latin1.parse(slot[1]), CryptoJS.enc.Latin1.parse(fseed));\n var mystring = mystring.toString(CryptoJS.enc.Latin1);\n var segs2 = unpack('C*', mystring);\n var seg;\n checks['correct result'] == 'fail';\n for (i = 1; i < 64; i++) {\n seg2 = segs2[i];\n var seg = (seg2 >> 4) & 0x0F;\n if (seg < 9) {\n if (parseInt(tocheckres) == parseInt(results[seg])) {\n checks['correct result'] = 'pass';\n dropresult = results[seg];\n }\n break;\n }\n seg = seg2 & 0x0F;\n if (seg < 9) {\n if (parseInt(tocheckres) == parseInt(results[seg])) {\n checks['correct result'] = 'pass';\n dropresult = results[seg];\n }\n break;\n }\n seg = 4;\n if (parseInt(tocheckres) == parseInt(results[seg])) {\n checks['correct result'] = 'pass';\n dropresult = results[seg];\n }\n }\n break;\n\n case 'dice':\n var edge = \"0.01\";\n var hi = param.substring(0, 1) == '>' ? true : false;\n var target = param.substring(1) * 10000;\n var target = parseInt(target);\n var res = hi ? 1000000 : 0;\n var resarr = str_split(bin2hex(fseed), 5);\n for (var x = 0; x < resarr.length; x++) {\n var s = resarr[x];\n\n if (s.length == 5) {\n var d = hexdec(s);\n if (d < 1000000) {\n var res = d;\n break;\n }\n }\n }\n\n if (betid > 192992 && betid < 4544134) {\n edge = \"0.015\";\n console.log(\"Old edge\");\n }\n\n if ((hi && res > target) || (!hi && res < target)) {\n var t_target = hi ? 1000000 - target : target;\n\t\tvar part1 = ((1000000 * 10e12) / (t_target * 10e12))/1e12;\n var part2 = 1 - edge;\n var win = ((part1 * 1e12) * (part2 * 1e12))/1e12;\n var win = Math.round(win * 100000000) / 100000000;\n } else {\n var win = \"0.00000000\";\n // var win = \"0\";\n }\n console.log(win + \"==\" + result);\n if (win == result) {\n checks['correct result'] = 'pass';\n } else {\n checks['correct result'] = 'fail';\n }\n break;\n }\n return checks;\n}", "checkValidity() {\n this.validState = this.currentDataState.name && \n +this.currentDataState.amount && +this.currentDataState.maximumRides;\n }", "isChainValid(){\n //nao comecamos com o bloco 0, pois o bloco 0 é referente ao genesis\n for(let i = 1; i < this.chain.length; i++){\n const currentBlock = this.chain[i];\n const previousBlock = this.chain[i - 1];\n\n //caso o hash do bloco atual seja diferente que o hash gerado\n //ele nao sera valido\n if(currentBlock.hash !== currentBlock.calculateHash()){\n return false;\n }\n //caso o previousHash do nosso bloco atual não seja igual ao anterior\n //ira retornar falso, ou seja, ele pode ser qualquer coisa\n //menos um bloco pertencente a nossa blockchain\n if(currentBlock.previousHash !== previousBlock.hash){\n return false;\n }\n }\n //retorna true, ja que nossa moeda tem o valor perfeito\n return true;\n }", "checkExpiry(count, expiry, curExpiries) {\r\n if (count <= 0 || count == null) {\r\n alert(\"Please enter a valid count\"); \r\n this.setState({ errors: \"Please enter a valid count\" });\r\n return false;\r\n }\r\n // make sure that there are no duplicates\r\n if (curExpiries.indexOf(expiry) > - 1) {\r\n alert(\"Duplicate dates detected\"); \r\n this.setState({ errors: \"Duplicate dates detected\" });\r\n return false;\r\n }\r\n\r\n //create a new date object based on the expiry date entered. \r\n var today = new Date(new Date().toJSON().slice(0, 10));\r\n var date = new Date(expiry);\r\n\r\n curExpiries.push(expiry);\r\n // check that the expiry is valid.\r\n if (expiry == null || date < today) {\r\n alert(\"Please enter a valid expiry date\");\r\n this.setState({ errors: \"Please enter a valid expiry date\" });\r\n return false;\r\n }\r\n return true;\r\n }", "isChainValid(){\n for (let i = 1; i < this.chain.length; i++){\n const currentBlock = this.chain[i];\n const previousBlock = this.chain[i - 1];\n \n if(currentBlock.hash !== currentBlock.calculateHash()){\n return false;\n }\n\n if(currentBlock.previoushash !== previousBlock.hash){\n return false;\n }\n }\n\n return true;\n }", "checkValidity() {\n return this.state.name && +this.state.amount && +this.state.maximumRides;\n }", "isValidIndex(index) {\n return index >= 0 && index < this.options.length;\n }", "validProof(lastProof, proof) {\n const guessHash = crypto\n .createHmac(\"sha256\", \"420\")\n .update(`${lastProof}${proof}`)\n .digest(\"hex\");\n return guessHash.substr(0, 1) === \"a\";\n }", "isChainValid(){\r\n\r\n for(let i = 1;i < this.chain.length; i++){\r\n const currentBlock = this.chain[i];\r\n const previousBlock = this.chain[i - 1];\r\n\r\n //check if the current hash of the block is still valid\r\n if(currentBlock.hash !== currentBlock.calculateHash()){\r\n return false;\r\n }\r\n //check if the current block points to previous block\r\n if(currentBlock.previousHash !== previousBlock.hash){\r\n return false;\r\n }\r\n }\r\n return true;\r\n\r\n }", "isChainValid() {\n for (let i = 1; i < this.chain.length; i++) {\n const currentBlock = this.chain[i];\n const previousBlock = this.chain[i - 1];\n\n if (currentBlock.hash !== currentBlock.calculateHash()) {\n return false;\n }\n \n if (currentBlock.previousHash !== previousBlock.hash) {\n return false;\n }\n }\n return true;\n }", "async action(crypto, dataPeriods, currentBitcoinPrice) {\n // let stopped = this.stopLoss(0.1);\n // if (stopped) return;\n\n // stopped = this.takeProfit(this.takeProfitRatio);\n // if (stopped) return;\n\n let ema = await this.getEMA(dataPeriods);\n let currEMA = ema[ema.length - 1];\n\n var diff = (currentBitcoinPrice / currEMA * 100) - 100;\n\n if (!this.isInTrade()) {\n let bigDown = diff < -this.adaptativeDownTrigger();\n if (bigDown) {\n // BUY condition\n this.timeInTrade = 0;\n return this.buy();\n } else {\n return this.hold();\n }\n } else {\n this.timeInTrade++;\n let objectivePrice = this.getObjective();\n let bigUp = diff > this.adaptativeUpTrigger();\n if (currentBitcoinPrice > objectivePrice || bigUp) {\n return this.sell();\n } else {\n return this.hold();\n }\n }\n }", "async futuresCalc(curr, d1, d2){\n d1 = d1 || 7.5;\n d2 = d2 || 15;\n // console.log(this.pair);\n let res = await this.client.futuresBook({ symbol: this.pair });\n \n let sellMass = 0;\n let sellMass2 = 0;\n let sellStops = [];\n\n let buyMass = 0;\n let buyMass2 = 0;\n let buyStops = [];\n \n for (let i = 0; i < res.asks.length; i++) {\n // if(Number(res.asks[i].quantity) >= Number(valByID('threshold'))){\n // sellStops.push({price: Number(res.asks[i].price), quantity: Number(res.asks[i].quantity)});\n // }\n sellMass += res.asks[i].price - curr < d1 ? Number(res.asks[i].quantity) : 0;\n sellMass2 += res.asks[i].price - curr < d2 ? Number(res.asks[i].quantity) : 0;\n }\n for (let i = 0; i < res.bids.length; i++) {\n // if(Number(res.bids[i].quantity) >= Number(valByID('threshold'))){\n // buyStops.push({price: Number(res.bids[i].price), quantity: Number(res.bids[i].quantity)});\n // }\n buyMass += curr - res.bids[i].price < d1 ? Number(res.bids[i].quantity) : 0;\n buyMass2 += curr - res.bids[i].price < d2 ? Number(res.bids[i].quantity) : 0;\n }\n\n return {sellMass, sellMass2, buyMass, buyMass2};\n }", "function checkDayAvailability(arrayOfHash, startTime, endTime, numberOfCourts) {\n console.log(\"arrayOFHash\", arrayOfHash);\n var arr = [...Array(numberOfCourts+1).keys()];\n arr.shift();\n var availabilityBoolean = false;\n var intervalTimes = new Set(getIntervals(startTime, endTime));\n var hashSetTime;\n var startTimeEdited;\n var endTimeEdited;\n var hashSet;\n var bookingOverlapCounter = 0; // keep track of number of bookings in a day matching a court and also overlapping time. If none, then the court is free\n var prevCourtCounter = 0;\n var courtFreeId = null;\n var intersection;\n for (var court_no = 1; court_no <= arr.length; court_no++) { // 1..6\n //console.log(court_no);\n for (var hashBooking in arrayOfHash) {\n hashSet = arrayOfHash[hashBooking];\n // if none of the bookings in the hash (each representing a day) match, then no bookings for the current court on that day.\n // bookingOverlapCounter remains zero or no difference\n if ((hashSet.court_no == court_no) || ((hashSet.court_no == (court_no - 1)) && (hashSet.courtType == \"fullCourt\"))) { // if the previous skipped booking was in fact a full court booking\n startTimeEdited = hashSet.startTime.split(\"T\")[1].substr(0,5);\n endTimeEdited = hashSet.endTime.split(\"T\")[1].substr(0,5);\n //console.log(hashSet, startTimeEdited, endTimeEdited);\n hashSetTime = new Set(getIntervals(startTimeEdited, endTimeEdited));\n intersection = new Set([...intervalTimes].filter(x => hashSetTime.has(x)));\n // if intersection.size == 0, then bookingOverlapCounter remains 0 or no difference\n if (intersection.size != 0) { // meaning the court is free during the time in question\n bookingOverlapCounter++; // note that a booking in the current court overlaps with the desired booking\n }\n }\n }\n if (bookingOverlapCounter == prevCourtCounter) { // after iteration if no bookings match with a court\n courtFreeId = court_no;\n break;\n } else {\n prevCourtCounter = bookingOverlapCounter; // if not zero, i.e. assign the prevCourtCounter the new value to monitor difference.\n }\n }\n //console.log(\"Free court id\", courtFreeId);\n return courtFreeId; // null means no court available\n}", "isChainValid(){\n for(let i=1;i<this.chain.length;i++){\n const currentBlock = this.chain[i];\n const previousBlock = this.chain[i-1];\n //Verifies that the transaction in the current block are valid\n if(!currentBlock.hashValidTransactions()){\n //Blockchain in invalid state\n return false;\n }\n\n //Chain is false if current and recalculated Hash donot match\n if(currentBlock.hash!==currentBlock.calculateHash()){\n //Blockchain in invalid state\n return false;\n }\n //Chain is false if previousHash of current block does not match with hash of previousBlock\n if(currentBlock.previousHash!==previousBlock.hash){\n //Blockchain in invalid state \n return false;\n }\n } \n return true;\n }", "static NrgBalanceTransfer (script: string) {\n const parts = script.split(' ')\n\n if (parts.length !== 2 && parts.length !== 5 && parts.length !== 7) {\n debug(`0 - l: ${parts.length}`)\n return false\n }\n\n if (parts.length === 2) { // input lock script\n const [pubKey, signature] = parts\n\n // secp256k1.publicKeyCreate with compressed = true produces 33B pub key\n if (pubKey.length !== 66 || !isHexString(pubKey)) {\n debug(`inS 1 - pk: ${pubKey.length}`)\n return false\n }\n\n // signData produces 65B signature\n if (signature.length !== 130 || !isHexString(signature)) {\n debug(`inS 2 - sig: ${signature.length}`)\n return false\n }\n\n // do not validate input script further\n return true\n }\n\n if (parts.length === 7) { // script with OP_CHECKLOCKTIMEVERIFY\n const [height, op] = parts\n if (height.length > MAX_HEIGHT_HEX_LENGTH || !isHexString(height)) {\n debug(`1 - h: ${height}`)\n return false\n }\n\n if (op !== 'OP_CHECKLOCKTIMEVERIFY') {\n debug(`2 - op: ${op}`)\n return false\n }\n }\n\n // last 5 tokens are the same\n let [opDup, opBlake, hash, opEq, opChecksig] = parts.slice(-5)\n if (opDup !== 'OP_DUP') {\n debug(`3 - op: ${opDup}`)\n return false\n }\n\n if (opBlake !== 'OP_BLAKE2BLC' && opBlake !== 'OP_BLAKE2BL' && opBlake !== 'OP_BLAKE2BLS') {\n debug(`4 - op: ${opBlake} unsupported hashing function`)\n return false\n }\n\n if (hash.length !== 64 || !isHexString(hash)) {\n debug(`5 - hash: ${hash}`)\n return false\n }\n\n if (opEq !== 'OP_EQUALVERIFY') {\n debug(`6 - op: ${opEq}`)\n return false\n }\n\n if (opChecksig !== 'OP_CHECKSIG') {\n debug(`7 - op: ${opChecksig}`)\n return false\n }\n }", "vendItem(productIndex) {\n //check if valid\n let product = vm.products[productIndex]\n // IF Exists we have some you have enough money\n if (product && product.quantity > 0 && vm.currentTransaction >= product.price) {\n this.processTransaction(product)\n return JSON.parse(JSON.stringify(product))\n }\n return false\n }", "function esPleno(slots) {\r\n\tvar igual = true;\r\n\tvar slotPrimero = slots[0];\r\n\tfor(var i = 0; i < slots.length && igual; i++){\r\n\t\tigual &= slots[i] == slotPrimero;\r\n\t}\r\n\t\r\n\treturn igual;\r\n}", "isValid(\n DIFFICULTY // Utile à l'étape 2\n ) {\n return this.id === this.getHash();\n }", "isChainValid() {\n for (let index = 1; index < this.chain.length; index++) {\n const currentBlock = this.chain[index];\n const previousBlock = this.chain[index - 1];\n\n if (currentBlock.hash !== currentBlock.calculateHash()) {\n return false;\n }\n if (currentBlock.previousHash !== previousBlock.hash) {\n return false;\n }\n\n return true;\n }\n }", "isSolvable() {\n let inv_count = this.getInvCount();\n //console.log(inv_count);\n if (inv_count > 0)\n return (this.getInvCount() % 2 == 0);\n else\n return false;\n }", "static async checkConflicts(slot, prevHalfHour) {\n const tablesTaken = await this.findAll({\n where: { slot: slot }\n });\n const previousHalfHour = await this.findAll({\n where: { slot: prevHalfHour }\n });\n\n let tablesTakenTotal = tablesTaken.length + previousHalfHour.length;\n //no conflict return false, reservation can be made.\n if (tablesTakenTotal < 10) return false;\n //conflict return true\n else return true;\n }", "verifyFromPrevious(prevTransaction) {\n\n // Check the public keys match the recpient of the previous transaction\n const prevRecipient = prevTransaction.data.recipients[previousIdx];\n const address = prevRecipient.address;\n if (address !== this.data.publicKey) {\n return false;\n }\n\n // Check that the money sent matches the money from the previous transaction\n const prevAmount = prevRecipient.amount;\n let sentAmount = this.data.fee;\n for (recipient in this.data.recipients) {\n sentAmount += recipient.amount;\n }\n if (sentAmount > prevAmount) {\n return false\n }\n return true;\n }", "function isCountedInAW(a, b) {\n var min = moment(a[0].time, timeFormat); // First one's checkin time\n var max = a.length < 2\n ? moment(min).add(whatIsCountedAsAfterWork) // First one + maxTime\n : moment(a[a.length - 1].time, timeFormat).add(whatIsCountedAfterPrevious); // Previous added + maxTimeAfterPrevious\n var current = moment(b.time, timeFormat);\n if (current.isBetween(min, max)\n && (a.find((checkin) => { return checkin.uid === b.uid }) === undefined)) {\n return true;\n }\n return false;\n}", "verifyProof() {\n let h = utils.hash(this.serialize());\n let n = new BigInteger(h, 16);\n return n.compareTo(this.target) < 0;\n }", "function checkPair() {\n\n}", "chngSwithCheck (index) {\n\t\t\tvar counter = 0;\n\t\t\tthis.aStep3Data.map(el => {\n\t\t\t\tif (el.cross_authr == 1) {\n\t\t\t\t\tcounter += 1;\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (counter > 1) {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.aStep3Data[index].cross_authr = 0;\n\t\t\t\t\tthis.swalfire('error','One corresponding author is choosed already.');\n\t\t\t\t},600);\n\t\t\t}\n\t\t}", "isValid() {\n return this.hash === this.createHash();\n }", "function checkTotals() {\n\t/* See if a new breeder can be unlocked.\n\t As prices are in acending order, we know we cannot buy any after */\n\twhile (state.nextBreederUnlock < state.breeders.length\n\t\t\t&& state.larvae >= state.breeders[state.nextBreederUnlock].unlock) {\n\t\taddBreeder(state.nextBreederUnlock);\n\t\tstate.nextBreederUnlock++;\n\t}\n\t/* Check which breeders can be bought */\n\tfor (var i = 0; i < state.nextBreederUnlock; i++) {\n\t\tsetBreederLock(i, state.breeders[i].cost <= state.larvae);\n\t}\n\t/* Check if a new upgrade can be unlocked */\n\tfor (var i = state.nextUpgradeUnlock; i < state.upgrades.length; i++) {\n\t\t/* As prices are in acending order, we know we cannot buy any after */\n\t\tif (state.upgrades[i].canUnlock(state)) {\n\t\t\taddPurchaseUpgrade(i);\n\t\t\tstate.nextUpgradeUnlock++;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\t/* Check if the currently selected upgrade can be bought */\n\tif (screen1.currentUpgrade >= 0) {\n\t\tsetUpgradeLock(state.upgrades[screen1.currentUpgrade].cost <= state.larvae);\n\t}\n}", "checkPair() {\r\n const item1 = this.state.items[this.state.clicked1]\r\n const item2 = this.state.items[this.state.clicked2]\r\n\r\n // If clicked1 and clicked2 have the same pair property, they're a pair.\r\n const match = item1.pair === item2.pair\r\n let newState = Object.assign({}, this.state)\r\n\r\n if (match) {\r\n newState.clicked1 = -1\r\n newState.clicked2 = -1\r\n newState.known.push(item1.pair)\r\n this.setState(newState)\r\n } else {\r\n newState.clicked1 = -1\r\n newState.clicked2 = -1\r\n newState.wrong += 1\r\n // Delay so users can see what the wrong one was.\r\n setTimeout(() => this.setState(newState), 1500)\r\n }\r\n }", "checkCorectnessPoints(index) {\n const thisObject = this.state.pointsErrors;\n thisObject[index] = false;\n const pattern = /^\\d+$/;\n const toTest = this.state.submitedQuestions.quiz.questions_attributes[index].points;\n if (\n pattern.test(toTest.toString()) === false) {\n thisObject[index] = true;\n }\n this.setState({ pointsErrors: thisObject });\n }", "function findProfit( shareValues ) {\n\tvar array_len = shareValues.length;\n\tvar buy_day = 0;\n\tvar sale_day = 0;\n\tvar profit = 0;\n\n\tfor ( i = 1; i < array_len; i++ ) {\n\t\tif ( shareValues[ i ] > shareValues[ sale_day ] ) {\n\t\t\tsale_day = i;\n\t\t} else if ( shareValues[ i ] < shareValues[ buy_day ] && sale_day > i ) {\n\t\t\tbuy_day = i;\n\t\t}\n\t}\n\n\tif ( buy_day == sale_day ) {\n\t\tconsole.log( \"Not a good time to do business !!\" );\n\t} else {\n\t\tconsole.log( \"Buy share on day \" + ( buy_day + 1 ) + \" and sale it on day \" + ( sale_day + 1 ) )\n\t}\n}", "_addToIndex (index0, key0, key1, key2) {\n // Create layers as necessary\n const index1 = index0[key0] || (index0[key0] = {})\n const index2 = index1[key1] || (index1[key1] = {})\n // Setting the key to _any_ value signals the presence of the quad\n const existed = key2 in index2\n\n if (!existed) {\n index2[key2] = null\n }\n\n return !existed\n }", "function verifyPaintIndex() {\n\tif(typeof CandidateManager.candidates[paintIndex] === 'undefined') {\n\t\tpaintIndex = 'Tossup';\n\t}\n}", "updateKeysIfInvalid ({ commit, state, dispatch }) {\r\n const isOwnerKeyValid = isWifValid({\r\n wif: state.contractValues.ownerPrivateKeyWIF,\r\n networkChoice: state.contractValues.networkChoice\r\n });\r\n const isHeirKeyValid = isWifValid({\r\n wif: state.contractValues.heirPrivateKeyWIF,\r\n networkChoice: state.contractValues.networkChoice\r\n });\r\n if (!isOwnerKeyValid) {\r\n const ownerPrivateKeyWIF = newWIF(state.contractValues.networkChoice);\r\n commit('setContractValues', { ownerPrivateKeyWIF });\r\n }\r\n if (!isHeirKeyValid) {\r\n const heirPrivateKeyWIF = newWIF(state.contractValues.networkChoice);\r\n commit('setContractValues', { heirPrivateKeyWIF });\r\n }\r\n dispatch('updatePageStatusIC');\r\n }", "function _check_slot( offset, result ) {\n if ( now - that.lastUpdate > SPINTIME ) {\n var c = parseInt(Math.abs( offset / SLOT_HEIGHT)) % ITEM_COUNT;\n if ( c == result ) {\n if ( result == 0 ) {\n if ( Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n return true; // done\n }\n } else if ( Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) {\n return true; // done\n }\n }\n }\n return false;\n }", "buyUpgradeSale(element, index) {\n if (this.props.score.totalValue >= this.props.upgradesSale[index].price) {\n let newScore = this.props.score;\n newScore.totalValue = newScore.totalValue - this.props.upgradesSale[index].price;\n newScore.tpsSale += this.props.upgradesSale[index].perSecondBonus;\n\n let newUpgradesSale = this.props.upgradesSale[index];\n newUpgradesSale.amount++;\n newUpgradesSale.price = newUpgradesSale.initialPrice * newUpgradesSale.amount;\n newUpgradesSale.price += newUpgradesSale.price * (newUpgradesSale.amount / 10);\n newUpgradesSale.price = Math.floor(newUpgradesSale.price);\n\n this.props.updateScore(newScore);\n this.props.buyUpgradeSale(newUpgradesSale, index);\n\n //update total score and upgrade price before setting class\n if (\n this.props.score.totalValue >= this.props.upgradesSale[index].price &&\n element.disabled.substring(0, 8) === \"disabled\"\n ) {\n this.props.setUpgradeSaleClass(index, \"enabled\");\n setTimeout(() => {\n this.props.setUpgradeSaleClass(index, \"\");\n }, 1000);\n } else if (\n this.props.score.totalValue < this.props.upgradesSale[index].price &&\n element.disabled.substring(0, 8) !== \"disabled\"\n ) {\n this.props.setUpgradeSaleClass(index, \"disabled\");\n }\n }\n }", "static validProof(lastProof, proof) {\n const guess = `${ lastProof }${ proof }`;\n const guessHash = crypto\n .createHash('sha256')\n .update(guess)\n .digest('hex');\n\n return guessHash.indexOf('0000') === 0;\n }", "static validChain(chain) {\n let lastBlock = chain[0];\n let currentIndex = 1;\n\n while (currentIndex < chain.length) {\n const block = chain[currentIndex];\n console.log(lastBlock);\n console.log(block);\n console.log('\\n-------------\\n');\n\n // Check that the hash of the block is correct\n if (block.previousHash !== Blockchain.hash(lastBlock)) {\n return false;\n }\n\n if (!Blockchain.validProof(lastBlock.proof, block.proof)) {\n return false;\n }\n\n lastBlock = block;\n currentIndex += 1;\n\n return true;\n }\n }", "checkClosing() {\n let ret = false;\n if (\n (this.type === PositionType.LONG &&\n (/* this.pair.currentPrice >= this.takeProfitPrice || */\n this.pair.currentPrice <= this.stopLossPrice)) ||\n (this.type === PositionType.SHORT &&\n (/* this.pair.currentPrice <= this.takeProfitPrice || */\n this.pair.currentPrice >= this.stopLossPrice))\n ) {\n ret = true;\n }\n return ret;\n }", "function checkCashRegister(price, cash, cid) {\n let cost = price;\n let givinCash = cash;\n let allCash = 0;\n for(let i = 0; i < cid.length; i++){\n allCash += cid[i][1];\n }\n allCash = allCash.toFixed(2);\n console.log(allCash);\n let fund = givinCash - cost;\n // First Condition: \n if(fund > allCash){\n return {\n status: \"INSUFFICIENT_FUNDS\",\n change: []\n }\n }\n let standard = [[\"PENNY\", 0.01], [\"NICKEL\", 0.05], [\"DIME\", 0.1], [\"QUARTER\", 0.25], [\"ONE\", 1], [\"FIVE\", 5], [\"TEN\", 10], [\"TWENTY\", 20], [\"ONE HUNDRED\", 100]];\n\n fund = fund.toFixed(2);\n console.log(fund);\n if(fund === allCash){\n return {\n status: \"CLOSED\",\n change: cid\n }\n }\nlet change = [];\n for(let x = 8; x >= 0; x--){\n if(fund > standard[x][1]){\n if(fund >= cid[x][1]){\n change.push([cid[x][0],cid[x][1]]);\n fund = (fund - cid[x][1]).toFixed(2);\n }else if(fund < cid[x][1]){\n let available = (fund - (fund % standard[x][1])).toFixed(2);\n fund = (fund % standard[x][1]).toFixed(2)\n console.log(fund);\n change.push([cid[x][0], parseFloat(available)]);\n }\n }\n }\n\n let finalCheck = 0;\n for(let j = 0; j < change.length; j++){\n finalCheck += change[j][1];\n }\n finalCheck = finalCheck.toFixed(2);\n fund = givinCash - cost;\n if(finalCheck != fund){\n return {\n status: \"INSUFFICIENT_FUNDS\",\n change: []\n }\n }\n return {\n status: \"OPEN\",\n change: change\n }\n\n}", "function checkCashRegister(price, cash, cid) {\n\n console.log(\"price:\", price);\n console.log(\"cash:\", cash);\n // console.log(\"cid:\\n \", cid);\n \n let cashInDrawer = 0;\n \n for (let i=0; i<cid.length; i++) {\n for (let j=1;j<cid[i].length; j++) {\n // console.log(\"cid[i][1]:\", cid[i][1]);\n cashInDrawer += cid[i][1];\n }\n }\n console.log(\"cashInDrawer:\", cashInDrawer);\n \n let hash = {};\n let changeDue = cash - price;\n console.log(\"changeDue:\", changeDue);\n \n if (cashInDrawer < changeDue) {\n hash.status = \"INSUFFICIENT_FUNDS\";\n hash.change = []; \n } \n console.log(\"hash:\", hash) \n return hash;\n \n }", "hashValidTransactions(){\n for(const tx of this.transactions){\n if(!tx.isValid()){\n return false;\n }\n }\n return true;\n }", "validateTaxPayer() {\n let result = false;\n let taxPayerId = this.taxesView.accountID;\n let state = this.taxesView.accountState;\n let taxPayerExist = this.bank.players.some(p => p.id === taxPayerId);\n\n if (taxPayerExist) {\n state.reset();\n result = true;\n } else {\n state.hasError = true;\n }\n\n return result;\n }", "rangeCheck(index) {\n if (index >= this.sizeNum || index < 0) {\n throw new Error(\"is no index--->\" + index);\n }\n }", "isValidIndex(index) {\n return index >= 0 && index < this.renderedOptions.length;\n }", "async validar(){\n var exist=false;\n await this.state.casa.forEach((c)=>{\n if(c.numero===this.numero && c.index===this.index){\n exist=true;\n }\n });\n await this.state.pichon.forEach((c)=>{\n if(c.numero===this.numero && c.index===this.index){\n exist=true;\n }\n });\n return exist;\n }", "function isRelevant(index, someIndex) {\n return self.isInRange(index) && (\n index === someIndex ||\n index === self.previous(someIndex) ||\n index === self.next(someIndex)\n );\n }", "isChainValid(){\r\n for(let i=1; i < this.chain.length; i++){ //i starting from 1 and not 0 because 0 is genesis block\r\n const currentBlock = this.chain[i];\r\n const previousBlock = this.chain[i-1];\r\n \r\n if(currentBlock.hash != currentBlock.calculateHash()){\r\n return 'invalid block' ;\r\n }\r\n\r\n if(currentBlock.previousHash != previousBlock.hash){\r\n return 'invalid block';\r\n }\r\n }\r\n\r\n return 'Valid Block';\r\n }", "CheckMidAds(secondes) {\n let i = 0;\n let item = null;\n let show = 0;\n if (this.settled !== true) {\n return;\n }\n for (i = 0; i < this.midAds.length; i += 1) {\n item = this.midAds[i];\n show = parseInt(item[Const.FJCONFIG_SHOW_AT], 10);\n if (secondes === show) {\n this.logger.info(i, ' starting Ads Now .. ');\n if (this.midAds[i].started === false) {\n this.logger.info(i, ' starting a new Mid Ads .. ');\n this.midAds[i].started = true;\n this.StartAds(i, Const.AdsEnum.ADS_MID_ROLL);\n } else {\n this.logger.info(i, ' already started ', item[Const.FJCONFIG_URL],\n ' @@ ', item[Const.FJCONFIG_SHOW_AT]);\n }\n }\n }\n }", "isValidInvite(invite) {\n return !Object.keys(invite).find(v => !invite[v]);\n }", "static isValidChain(chain) {\n const len = chain.length;\n let lastBlock = Block.genesis();\n for (var i = 0; i < len; i++) {\n if (i == 0) {\n // genesis block\n if (JSON.stringify(chain[0]) !== JSON.stringify(Block.genesis())) {\n return false;\n }\n } else {\n // check for fields for each block\n const { timestamp, lastHash, hash, data } = chain[i];\n const validHash = cryptoHash(timestamp, lastHash, data);\n if (lastHash !== lastBlock.hash || validHash !== hash) {\n return false;\n }\n }\n lastBlock = chain[i];\n }\n return true;\n }", "_addToIndex(index0, key0, key1, key2) {\n // Create layers as necessary\n const index1 = index0[key0] || (index0[key0] = {});\n const index2 = index1[key1] || (index1[key1] = {});\n // Setting the key to _any_ value signals the presence of the quad\n const existed = (key2 in index2);\n if (!existed) index2[key2] = null;\n return !existed;\n }", "isValid (callback) {\n // TODO Needs better checking\n if (this.privKey &&\n this.privKey.public &&\n this.privKey.public.bytes &&\n Buffer.isBuffer(this.pubKey.bytes) &&\n this.privKey.public.bytes.equals(this.pubKey.bytes)) {\n callback()\n } else {\n callback(new Error('Keys not match'))\n }\n }", "isValid (callback) {\n // TODO Needs better checking\n if (this.privKey &&\n this.privKey.public &&\n this.privKey.public.bytes &&\n Buffer.isBuffer(this.pubKey.bytes) &&\n this.privKey.public.bytes.equals(this.pubKey.bytes)) {\n callback()\n } else {\n callback(new Error('Keys not match'))\n }\n }", "isValid (callback) {\n // TODO Needs better checking\n if (this.privKey &&\n this.privKey.public &&\n this.privKey.public.bytes &&\n Buffer.isBuffer(this.pubKey.bytes) &&\n this.privKey.public.bytes.equals(this.pubKey.bytes)) {\n callback()\n } else {\n callback(new Error('Keys not match'))\n }\n }", "isValid (callback) {\n // TODO Needs better checking\n if (this.privKey &&\n this.privKey.public &&\n this.privKey.public.bytes &&\n Buffer.isBuffer(this.pubKey.bytes) &&\n this.privKey.public.bytes.equals(this.pubKey.bytes)) {\n callback()\n } else {\n callback(new Error('Keys not match'))\n }\n }", "function checkCashRegister(price, cash, cid) {\n\n console.log(\"price:\", price);\n console.log(\"cash:\", cash);\n // console.log(\"cid:\\n \", cid);\n \n let cashInDrawer = 0; \n \n for (let i=0; i<cid.length; i++) {\n for (let j=1;j<cid[i].length; j++) {\n // console.log(\"cid[i][1]:\", cid[i][1]);\n cashInDrawer += cid[i][1];\n }\n }\n console.log(\"cashInDrawer:\", cashInDrawer);\n \n let hash = {};\n let changeDue = cash - price;\n console.log(\"changeDue:\", changeDue);\n \n if (cashInDrawer < changeDue) {\n hash.status = \"INSUFFICIENT_FUNDS\";\n hash.change = []; \n } else if (cashInDrawer === changeDue) {\n hash.status = \"CLOSED\";\n hash.change = cid;\n }\n console.log(\"hash:\", hash) \n return hash;\n \n }", "isValid(callback) {\n // TODO Needs better checking\n if (this.privKey && this.privKey.public && this.privKey.public.bytes && Buffer.isBuffer(this.pubKey.bytes) && this.privKey.public.bytes.equals(this.pubKey.bytes)) {\n callback();\n } else {\n callback(new Error('Keys not match'));\n }\n }", "function conflicts(slot1, slot2) {\n const sl2iter = slot2.values();\n let sl2 = sl2iter.next();\n for (let sl1 of slot1) {\n sl2 = advance(sl2, sl2iter, (initial) => (((initial.value.start + initial.value.length) < sl1.start)),\n (initial) => (initial.done));\n if (sl2.done) {\n return false;\n }\n \n if (compare(sl1, sl2.value) !== 0) {\n return true;\n }\n }\n return false;\n}", "isPaymentSufficient() {\n if (this.cashTendered >= this.amountDue) {\n console.log(\"Payment complete\")\n\n } else {\n this.insertCoin(type);\n }\n }", "analyzeMerchantLoyalty(safetyTally){\n\n if(this.props.route.params.product.firstTranDateRange >= 365){\n safetyTally += 2;\n } \n if(this.props.route.params.product.firstTranDateRange >= 1095){\n safetyTally += 2;\n } \n\n return safetyTally;\n }", "addStarData() {\n this.app.post(\"/block\", (req, res) => {\n // Add your code here\n let self = this;\n let validateAddrState = false;\n console.log(\"addStarData req.body: \", req.body)\n const starDataAddr = req.body.address;\n const starDataDEC = req.body.star.dec;\n const starDataRA = req.body.star.ra;\n const starDataStory = req.body.star.story;\n console.log(\"addStarData: starDataAddr: \", starDataAddr);\n // console.log(\"addStarData: starDataDEC: \", starDataDEC);\n // console.log(\"addStarData: starDataRA: \", starDataRA);\n // console.log(\"addStarData: starDataStory: \", starDataStory);\n\n /*****************************************\n * Check for only ONE STAR per request\n * to add a block to the chain...\n * \n *****************************************/\n // console.log(\"addStarData: self.mempoolValid[starDataAddr].status.address: \", self.mempoolValid[starDataAddr].status.address);\n if ( self.mempoolValid[starDataAddr] ) {\n console.log(\"addStarData: starDataAddr: \", starDataAddr)\n console.log(\"addStarData: self.mempoolValid[starDataAddr]: \", self.mempoolValid[starDataAddr]);\n console.log(\"addStarData: self.mempoolValid[starDataAddr].registerStar: \", self.mempoolValid[starDataAddr].registerStar);\n console.log(\"addStarData: self.mempoolValid[starDataAddr].status.messageSignature: \", self.mempoolValid[starDataAddr].status.messageSignature);\n if ( self.mempoolValid[starDataAddr].registerStar &&\n self.mempoolValid[starDataAddr].status.messageSignature ) {\n validateAddrState = true;\n console.log(\"addStarData: validateAddrState S/B true: \", validateAddrState);\n } else {\n console.log(\"addStarData: validateAddrState S/B false: \", validateAddrState);\n }\n } else {\n console.log(\"addStarData: self.mempoolValid[starDataAddr] NOT FOUND!!!\");\n console.log(\"addStarData: validateAddrState S/B false: \", validateAddrState);\n }\n let chkForOneBodyOnlyArray = [];\n chkForOneBodyOnlyArray.push(req.body);\n console.log(\"chkForOneBodyOnlyArray.length : \", chkForOneBodyOnlyArray.length);\n chkForOneBodyOnlyArray.map( (item, idx ) => {\n console.log(\"chkForOneBodyOnlyArray : idx: \", idx, \"item: \", item);\n console.log(\"chkForOneBodyOnlyArray : item.address: \", item.address);\n console.log(\"chkForOneBodyOnlyArray : item.star: \", item.star);\n let chkForOneStarOnlyArray = [];\n chkForOneStarOnlyArray.push(item.star);\n console.log(\"chkForOneStarOnlyArray.length : \", chkForOneStarOnlyArray.length);\n console.log(\"chkForOneBODYOnlyINSIDEoneStarArray.length : \", chkForOneBodyOnlyArray.length);\n if( ( chkForOneStarOnlyArray.length !== 1 ) &&\n chkForOneBodyOnlyArray.length !== 1 ) {\n console.log(\"Will return here, more than one body or more than one star in a body!!!\")\n res.send(\"Extra Data in Body or Star... ABORTING!!!\");\n return\n } else {\n chkForOneStarOnlyArray.map( (starItem, starIdx) => {\n console.log( \"chkForOneStarOnlyArray: starIndex\", starIdx, \"(BODY ITEM).address: \", item.address);\n console.log(\"chkForOneStarOnlyArray: starItem.dec: \", starItem.dec, \"starItem.ra: \", starItem.ra);\n console.log(\"chkForOneStarOnlyArray: starItem.story: \", starItem.story);\n })\n }\n })\n let blockBody = {\n address: starDataAddr,\n star: {\n dec: starDataDEC,\n ra: starDataRA,\n storyENCODED: Buffer(starDataStory).toString('hex')\n }\n }\n try {\n myBlockChain.getBlockHeight().then ((totalHeight) => {\n console.log(`BlockController: height = ${totalHeight}`);\n let blockNew = new BlockClass.Block(blockBody);\n blockNew.height = totalHeight;\n blockNew.hash = SHA256(JSON.stringify(blockNew)).toString();\n console.log(`blockNew: `, blockNew);\n if ( validateAddrState ) {\n myBlockChain.addBlock(blockNew).then( (addedBlock) => {\n // Add valid state to block being sent to frontend\n addedBlock.blockIsValid = true;\n // Add DECODED story as property to object returned...\n addedBlock.body.star.storyDECODED = hex2ascii(addedBlock.body.star.storyENCODED);\n console.log(\"then #1: addStarData: addedBlock: \", addedBlock);\n res.send(addedBlock);\n // NOW prevent a second star from being registered without ne validation request!\n self.mempoolValid[starDataAddr] = null;\n validateAddrState = false;\n })\n .catch((error) => {\n console.log(\"addStarData saw error\", error);\n });\n } else {\n // Add valid state to block being sent to frontend\n blockNew.blockIsValid = false;\n blockNew.body.star.storyDECODED = \"ERROR: Address has not been validated!\";\n blockNew.hash = \"ERROR: Address has not been validated!\";\n res.send( blockNew) ;\n }\n })\n }\n catch (err) {\n console.log(`addStarData addBlock: Saw error ${err}`)\n }\n })\n }", "isCorrect(index, answers) {\n if (answers.indexOf(index) != -1) {\n return 100;\n }\n return 0;\n }", "function pfPosBisa(x, y) {\n //check cell\n if (cellCheckDouble(x, y)) {\n return false;\n }\n //check block peta\n if (!petaPosValid(x, y)) {\n return false;\n }\n return true;\n}", "function checkHori(curArray, posArray) {\n for (var iter = 0; iter < curArray.length; iter++) {\n for (var i = 0; i < posArray.length; i++) {\n if (posArray[i][0] === curArray[iter][0] &&\n (posArray[i][1] === curArray[iter][1] + 1 ||\n posArray[i][1] === curArray[iter][1] - 1 ||\n posArray[i][1] === curArray[iter][1])) {\n\n return true;\n }\n }\n }\n\n return false;\n\n}", "function IsForwardComplete(x, y, sh, sp) {\n return x === settings.endX && y === settings.endY && sh === settings.endBlur && sp === settings.endSpread;\n }", "async function validateTaskIndex(index) {\n const data = await getData()\n \n // Validate index number by type and existence in database -->\n if (!isNaN(Number(index)) || Number.isInteger(index)) { // Is index of type Number and integer\n if (data[index]) return true;\n } \n return false;\n}", "function IsBackwardComplete(x, y, sh, sp) {\n return x === settings.defaultX && y === settings.defaultY && sh === settings.defaultBlur && sp === settings.defaultSpread;\n }", "hasSubParams(idx) {\n return ((this._subParamsIdx[idx] & 0xFF) - (this._subParamsIdx[idx] >> 8) > 0);\n }", "function getFeebonachi(index, number) {\n if(typeof index===\"undefined\" || number !==\"undefined\"){\nlet sum = 0;\nlet feebo = getClouserFeebo(1, number);\n\n\n };\n if(typeof number===\"undefined\" || index!==\"undefined\"){\nreturn getFeeboByIndex(index);\n };\n if(index===\"undefined\" || number ===\"undefined\"){\n return false;\n }\n\n\n}", "transfomationIsValid(trans, currentStep, r, begin) {\n if (trans.length === 0)\n return true;\n if (r.id <= 7)\n return true;\n /// LIST RESULT\n // console.log(\"\\n=====LIST RESULT:\");\n // console.log(\"CURRENT:\"+ExpressionToString(currentStep));\n if (r.id <= 6)\n return true;\n for (let i = begin; i < trans.length; i++) {\n let exp = trans[i].oldEXP;\n if (exp.id === currentStep.id || exp.id.includes(currentStep.id))\n return false;\n }\n // for (let i = 0; i < this.result.length; i++) {\n // if(this.result[i].detail[this.result[i].detail.length-1].exp.id === currentStep.id)return false;\n // }\n // console.log('====>END CHECK VALID TRANSFOMATION');\n return true;\n }" ]
[ "0.54913366", "0.5272588", "0.52386254", "0.5236217", "0.5190257", "0.5138925", "0.5124688", "0.5091307", "0.50820833", "0.5066742", "0.5047388", "0.50276417", "0.49885303", "0.49706858", "0.49332136", "0.49299714", "0.4924575", "0.49241933", "0.49210322", "0.49210256", "0.4915915", "0.48978058", "0.48918492", "0.48797524", "0.48732674", "0.48732674", "0.48680118", "0.48613295", "0.4857134", "0.48448193", "0.4839634", "0.483619", "0.48353076", "0.48240155", "0.48195106", "0.48117745", "0.4800863", "0.47800794", "0.47632542", "0.47456053", "0.47430563", "0.47399426", "0.47349596", "0.47327235", "0.47252405", "0.47210237", "0.4711693", "0.46946487", "0.46818832", "0.46747848", "0.46625233", "0.46601248", "0.46530086", "0.4652992", "0.465281", "0.4652504", "0.4648724", "0.46470863", "0.46355063", "0.46332338", "0.46239147", "0.46126524", "0.461081", "0.4610406", "0.4609745", "0.46095562", "0.46092728", "0.46082804", "0.4604446", "0.45896673", "0.45789513", "0.45678", "0.45668265", "0.45638463", "0.45603067", "0.45585513", "0.45558894", "0.45500943", "0.45491102", "0.45412418", "0.45409918", "0.4537354", "0.4537354", "0.4537354", "0.4537354", "0.45370448", "0.4526098", "0.4520289", "0.4520121", "0.45186913", "0.4518392", "0.45142332", "0.4506083", "0.4491835", "0.4491127", "0.4488807", "0.4480139", "0.44714203", "0.4471124", "0.44710362" ]
0.5947727
0
TODO: save chords to display circle of fifths heatmap data visualization
function detectChord(notes) { notes = notes.map(n => Tonal.Note.pc(Tonal.Note.fromMidi(n.note))).sort(); return Tonal.PcSet.modes(notes) .map((mode, i) => { const tonic = Tonal.Note.name(notes[i]); const names = Tonal.Dictionary.chord.names(mode); return names.length ? tonic + names[0] : null; }) .filter(x => x); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function drawChords (matrix, mmap) {\n var w = 980, h = 750, r1 = h / 2, r0 = r1 - 110, duration=5000;\n\n var fill = d3.scale.ordinal()\n // .range(['#c7b570','#c6cdc7','#335c64','#768935','#507282','#5c4a56','#aa7455','#574109','#837722','#73342d','#0a5564','#9c8f57','#7895a4','#4a5456','#b0a690','#0a3542',]);\n //.range(['#E54E45', \"#DBC390\", \"#13A3A5\", \"#403833\", \"#334D5C\", \"#C0748D\", \"#EFC94C\", \"#E27A3F\", \"#DF4949\", \"#7B3722\", \"#8F831F\", \"#F0900D\", \"#10325C\"]);\n .range(['#A9A18C', '#855723', '#4E6172', '#DBCA69', '#A3ADB8', '#668D3C', '#493829']);\n\n var chord = d3.layout.chord()\n .padding(.02)\n .sortSubgroups(d3.descending)\n .sortChords(d3.descending);\n\n var arc = d3.svg.arc()\n .innerRadius(r0)\n .outerRadius(r0 + 20);\n\n var svg = d3.select(\"#ext-chart\").append(\"svg:svg\")\n .attr(\"width\", w)\n .attr(\"height\", h)\n .append(\"svg:g\")\n .attr(\"id\", \"circle\")\n .attr(\"transform\", \"translate(\" + w / 2 + \",\" + h / 2 + \")\");\n\n svg.append(\"circle\")\n .attr(\"r\", r0 + 20);\n\n var rdr = chordRdr(matrix, mmap);\n chord.matrix(matrix);\n\n var g = svg.selectAll(\"g.group\")\n .data(chord.groups())\n .enter().append(\"svg:g\")\n .attr(\"class\", \"group\")\n .on(\"mouseover\", mouseover)\n .on(\"mouseout\", function (d) { d3.select(\"#tooltip\").style(\"visibility\", \"hidden\") });\n\n g.append(\"svg:path\")\n .style(\"stroke\", \"black\")\n .style(\"fill\", function(d) { return fill(rdr(d).gname); })\n .attr(\"d\", arc);\n\n g.append(\"svg:text\")\n .each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; })\n .attr(\"dy\", \".35em\")\n .style(\"font-family\", \"helvetica, arial, sans-serif\")\n .style(\"font-size\", \"12px\")\n .attr(\"text-anchor\", function(d) { return d.angle > Math.PI ? \"end\" : null; })\n .attr(\"transform\", function(d) {\n return \"rotate(\" + (d.angle * 180 / Math.PI - 90) + \")\"\n + \"translate(\" + (r0 + 26) + \")\"\n + (d.angle > Math.PI ? \"rotate(180)\" : \"\");\n })\n .text(function(d) { return rdr(d).gname; });\n\n var chordPaths = svg.selectAll(\"path.chord\")\n .data(chord.chords())\n .enter().append(\"svg:path\")\n .attr(\"class\", \"chord\")\n .style(\"stroke\", function(d) { return d3.rgb(fill(rdr(d).sname)).darker(); })\n .style(\"fill\", function(d) { return fill(rdr(d).sname); })\n .attr(\"d\", d3.svg.chord().radius(r0))\n .on(\"mouseover\", function (d) {\n d3.select(\"#tooltip\")\n .style(\"visibility\", \"visible\")\n .html(chordTip(rdr(d)))\n .style(\"font\", \"12px sans-serif\")\n .style(\"top\", function () { return (d3.event.pageY - 170)+\"px\"})\n .style(\"left\", function () { return (d3.event.pageX - 100)+\"px\";})\n })\n .on(\"mouseout\", function (d) { d3.select(\"#tooltip\").style(\"visibility\", \"hidden\") });\n\n function chordTip (d) {\n var q = d3.format(\",.1f\")\n return \"Flow Info:<br/><br>\"\n + d.sname + \" flow from \" + d.tname\n + \": \" + q(d.svalue) + \"T<br/>\"\n + \"<br/>\"\n + d.tname + \" flow from \" + d.sname\n + \": \" + q(d.tvalue) + \"T<br/>\";\n }\n\n function groupTip (d) {\n var p = d3.format(\".1%\"), q = d3.format(\",.2f\")\n return \"Influx Info:<br/><br/>\"\n + d.gname + \" : \" + q(d.gvalue) + \"T\"\n }\n\n function mouseover(d, i) {\n d3.select(\"#tooltip\")\n .style(\"visibility\", \"visible\")\n .html(groupTip(rdr(d)))\n .style(\"top\", function () { return (d3.event.pageY - 80)+\"px\"})\n .style(\"left\", function () { return (d3.event.pageX - 130)+\"px\";})\n\n chordPaths.classed(\"fade\", function(p) {\n return p.source.index != i\n && p.target.index != i;\n });\n }\n\n /* for brush slider */\n var margin = {top: 0, right: 50, bottom: 10, left: 50},\n width = w - margin.left - margin.right,\n height = 50 - margin.bottom - margin.top;\n\n var x = d3.scale.linear()\n .domain([10, 22])\n .range([0, width])\n .clamp(true);\n\n var brush = d3.svg.brush()\n .x(x)\n .extent([0, 0])\n .on(\"brush\", brushed);\n\n var svg = d3.select(\"#brush-slider\").append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n svg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + height / 2 + \")\")\n .call(d3.svg.axis()\n .scale(x)\n .orient(\"bottom\")\n .tickFormat(function(d) { return d + \":00\"; })\n .tickSize(0)\n .tickPadding(12))\n .select(\".domain\")\n .select(function() { return this.parentNode.appendChild(this.cloneNode(true)); })\n .attr(\"class\", \"halo\");\n\n var slider = svg.append(\"g\")\n .attr(\"class\", \"slider\")\n .call(brush);\n\n slider.selectAll(\".extent,.resize\")\n .remove();\n\n slider.select(\".background\")\n .attr(\"height\", height);\n\n var handle = slider.append(\"circle\")\n .attr(\"class\", \"handle\")\n .attr(\"transform\", \"translate(0,\" + height / 2 + \")\")\n .attr(\"r\", 9);\n\n slider\n .call(brush.event)\n .transition() // gratuitous intro!\n .duration(750)\n .call(brush.extent([16, 16]))\n .call(brush.event);\n\n function brushed() {\n var value = brush.extent()[0];\n\n if (d3.event.sourceEvent) { // not a programmatic event\n value = x.invert(d3.mouse(this)[0]);\n brush.extent([value, value]);\n }\n\n handle.attr(\"cx\", x(value));\n } \n }", "function HeatMap() {\n\n this.defaultOptions = {\n padding: 0.1,\n textPosition: \"c\",\n sorting: \"target\",\n sortingType: \"front\",\n orientation: \"top-left-h\",\n animationType: \"corner\",\n mouseOverOpacity: 1,\n animationTime: 1600,\n svgRectSize: 450,\n textPaddingInc: 700,\n rx: 15,\n ry: 15,\n margin: {\n left: 1,\n right: 1,\n top: 1,\n bottom: 1\n },\n };\n\n this.currentOptions = undefined,\n\n this.defaultColorScheme = {\n scheme: new Map ([\n [0, \"blue\"],\n [1, \"green\"],\n [2, \"yellow\"],\n [3, \"red\"],\n [4, \"crimson\"],\n [5, \"gray\"],\n [6, \"burlywood\"], //TODO Change color\n [7, \"white\"],\n [8, \"black\"]\n ])\n },\n\n // Init current options like default\n this.currentOptions = this.defaultOptions;\n\n this.createPositionArray = function(data, length, squareSize,\n scaleSquareX, scaleSquareY) {\n let dataArr = new Array(length);\n for (let i = 0; i < length; i++){\n let y;\n let x;\n\n switch(this.currentOptions.orientation){\n case \"bottom-left-v\":\n x = Math.floor(i / squareSize);\n y = i % squareSize;\n break;\n case \"bottom-left-h\":\n x = i % squareSize;\n y = Math.floor(i / squareSize);\n break;\n case \"top-left-h\":\n y = Math.floor(i / squareSize);\n y = squareSize - y - 1;\n x = i % squareSize;\n break;\n case \"bottom-right-h\":\n x = i % squareSize;\n x = squareSize - x - 1;\n y = Math.floor(i / squareSize);\n break;\n\n }\n dataArr[i] = {\n x: x,\n y: y,\n id : +data[i][\"id\"],\n value : +data[i][\"value\"],\n state : +data[i][\"state\"],\n link : data[i][\"linkto\"],\n target : data[i][\"target-path\"]\n }\n }\n return dataArr;\n }\n\n this.updateStyles = function() {\n let rects = this.svg.selectAll(\"#rectGroup\");\n\n rects\n .select('a')\n .select('rect')\n .attr('class', this.rectStyles);\n\n rects\n .select('a')\n .select('text')\n .attr('class', this.textStyles);\n }\n\n this.filterPrevArray = function (posArray, data){\n let dataArr = Array.from(data, e => e.id);\n let keys = [...this.prevPositionsByID.keys()];\n keys.forEach(element => {\n let findElement = dataArr.find(function(d) { return d.id == element });\n if (findElement === undefined) {\n console.log(\"deleted\");\n posArray.delete(element);\n }\n });\n return posArray;\n }\n\n this.setPositionsMap = function(data, squareSize) {\n this.prevPositionsByID.clear();\n for (let i = 0; i < data.length; i++){\n this.prevPositionsByID.set(data[i].id, data[i].x * squareSize + data[i].y);\n }\n }.bind(this);\n\n this.targetParse = function(targets) {\n\n let splitedTargets = new Array();\n for (let i = 0; i < targets.length; i++) {\n let tmp = targets[i].split('/');\n tmp.splice(0, 1);\n splitedTargets.push(tmp);\n };\n\n let depthMultiplier = 1;\n let maxDepth = Math.max.apply(Math, $.map(splitedTargets, function (el) { return el.length }));\n\n let resultSort = new Array(splitedTargets.length).fill(0);\n for (let i = 0; i < maxDepth; i++) {\n let targetsWeight = new Map();\n let currentWeight = 0;\n for (let j = 0; j < splitedTargets.length; j++){\n if (splitedTargets[i].length > i) {\n if (targetsWeight.has(splitedTargets[j][i])) {\n resultSort[j] += targetsWeight.get(splitedTargets[j][i]) * depthMultiplier;\n } else {\n targetsWeight.set(splitedTargets[j][i], currentWeight);\n resultSort[j] += currentWeight * depthMultiplier;\n currentWeight++;\n }\n }\n }\n depthMultiplier *= 0.1;\n }\n return resultSort;\n }\n\n this.simpleSort = function(a, b, type) {\n if (type == \"back\"){\n if (a < b) return 1;\n if (b < a) return -1;\n } else {\n if (a > b) return 1;\n if (b > a) return -1;\n }\n return 0;\n };\n\n this.sortingMap = function (data) {\n let type = this.currentOptions.sortingType;\n let simpleSort = this.simpleSort;\n let targetParse = this.targetParse;\n switch (this.currentOptions.sorting) {\n case \"none\":\n return data;\n break;\n case \"state\":\n data.sort(function (a, b) {\n if (a.state == 5) a.state = -1;\n if (b.state == 5) b.state = -1;\n let res;\n\n res = simpleSort(a.state, b.state, type);\n\n if (a.state == -1) a.state = 5;\n if (b.state == -1) b.state = 5;\n return res;\n });\n return data;\n break;\n case \"value\":\n data.sort(function (a, b) {\n let res;\n res = simpleSort(a.value, b.value, type);\n return res;\n });\n return data;\n break;\n case \"target\":\n let targets = data.map(a => a[\"target-path\"]);\n let sortWeight = targetParse(targets);\n for (let i = 0; i < data.length; i++){\n data[i].weight = sortWeight[i];\n }\n data.sort(function (a, b) {\n let res;\n res = simpleSort(a.weight, b.weight, type);\n return res;\n });\n return data;\n break;\n default:\n return data;\n break;\n }\n\n }\n\n this.calculateTextPos = function(xRect, yRect, textSize) {\n let x, y;\n switch (this.currentOptions.textPosition) {\n case \"c\":\n x = xRect / 2;\n y = yRect / 2;\n break;\n case \"r-c\":\n x = xRect - textSize.width / 2;\n y = yRect / 2;\n break;\n case \"l-c\":\n x = textSize.width / 2;\n y = yRect / 2;\n break;\n case \"t-c\":\n x = xRect / 2;\n y = textSize.height / 2;\n break;\n case \"b-c\":\n x = xRect / 2;\n y = yRect - textSize.height / 2;\n break;\n default:\n x = xRect / 2;\n y = yRect / 2;\n break;\n };\n return {x, y};\n }.bind(this);\n\n this.animateObjects = function(x, y, color, textSize) {\n let textCalculate = this.calculateTextPos;\n let animationTime = this.currentOptions.animationTime;\n let dataTmp = new Array();\n switch (this.currentOptions.animationType){\n case \"none\": {\n d3.select('#dataviz').selectAll('#rectGroup').select('rect')\n .attr(\"width\", x.bandwidth() )\n .attr(\"height\", y.bandwidth() )\n .style(\"fill\", function(d) { dataTmp.push({x: d.x, y: d.y}); return color(d.state)} )\n .attr(\"x\", function(d) { return x(d.x) })\n .attr(\"y\", function(d) { return y(d.y) });\n\n let lables = d3.select('#dataviz').selectAll('#textData')\n .data(dataTmp);\n // TODO try back animation\n lables\n .style(\"font-size\", function(d) { return textSize + \"px\" });\n lables\n .attr(\"x\", function(d) { return x(d.x) + textCalculate(x.bandwidth(), y.bandwidth(),\n d3.select(this).node().getBBox()).x; })\n .attr(\"y\", function(d) { return y(d.y) + textCalculate(x.bandwidth(), y.bandwidth(),\n d3.select(this).node().getBBox()).y; })\n .attr(\"opacity\", 1);\n break;\n }\n case \"center\": {\n d3.select('#dataviz').selectAll('#rectGroup').select('rect')\n .transition()\n .duration(animationTime)\n .attr(\"width\", x.bandwidth() )\n .attr(\"height\", y.bandwidth() )\n .style(\"fill\", function(d) { dataTmp.push({x: d.x, y: d.y}); return color(d.state)} )\n .attr(\"x\", function(d) { return x(d.x) })\n .attr(\"y\", function(d) { return y(d.y) });\n\n\n let lables = d3.select('#dataviz').selectAll('#textData')\n .data(dataTmp);\n // TODO try back animation\n lables\n .style(\"font-size\", function(d) { return textSize + \"px\" });\n lables\n .transition()\n .duration(animationTime)\n .attr(\"x\", function(d) { return x(d.x) + textCalculate(x.bandwidth(), y.bandwidth(),\n d3.select(this).node().getBBox()).x; })\n .attr(\"y\", function(d) { return y(d.y) + textCalculate(x.bandwidth(), y.bandwidth(),\n d3.select(this).node().getBBox()).y; })\n .attr(\"opacity\", 1);\n break;\n }\n default: {\n d3.select('#dataviz').selectAll('#rectGroup').select('rect')\n .transition()\n .duration(animationTime)\n .attr(\"width\", x.bandwidth() )\n .attr(\"height\", y.bandwidth() )\n .style(\"fill\", function(d) { dataTmp.push({x: d.x, y: d.y}); return color(d.state)} )\n .attr(\"x\", function(d) { return x(d.x) })\n .attr(\"y\", function(d) { return y(d.y) });\n\n\n let lables = d3.select('#dataviz').selectAll('#textData')\n .data(dataTmp);\n // TODO try back animation\n lables\n .style(\"font-size\", function(d) { return textSize + \"px\" });\n lables\n .transition()\n .duration(animationTime)\n .attr(\"x\", function(d) { return x(d.x) + textCalculate(x.bandwidth(), y.bandwidth(),\n d3.select(this).node().getBBox()).x; })\n .attr(\"y\", function(d) { return y(d.y) + textCalculate(x.bandwidth(), y.bandwidth(),\n d3.select(this).node().getBBox()).y; })\n .attr(\"opacity\", 1);\n break;\n }\n }\n }.bind(this);\n }", "function drawChords (matrix, mmap) {\n var w = 700, h = 600, r1 = w / 2, r0 = r1 - 100;\n\n var fill = d3.scale.ordinal()\n .range(['#c7b570','#c6cdc7','#335c64','#768935','#507282','#5c4a56','#aa7455','#574109','#837722','#73342d','#0a5564','#9c8f57','#7895a4','#4a5456','#b0a690','#0a3542',]);\n//console.log(d3.ascending);\n var chord = d3.layout.chord()\n .padding(.01)\n //.sortGroups()\n //.sortSubgroups(d3.ascending)\n\n .sortGroups(\n /*\n democrats = 26754682\n repubs = 58424112\n\n function d3_ascending(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n }\n\n */\n //console.log(d3.ascending);/\n //d3.ascending\n function(a,b){ \n //console.log(\"A: \", a, \"B: \", b);\n //if(a==1558488)return 2;\n //else \n \n //console.log(d3.ascending);\n //console.log(\"B: \", b);\n // A hack so that democrats and republicans\n // are right next to each other because\n // as it turns out, fossil fuel energy industry\n // gives more money than democrats recieve.\n var fossVal = 26928999;\n var demoVal = 26754682;\n var repubVal = 58424112;\n\n //console.log(a,b);\n if((a == fossVal)&&(b == demoVal)) return -1;\n if((b == demoVal)&&(a == repubVal)) return 1;\n\n // if((a == republicans)&&(b == demoVal)) return -1;\n // if((b == democrats)&&(a == repubVal)) return -1;\n \n if(a<b) {\n return -1;\n }else if (a>b) {\n return 1;\n }else if(a>=0) {\n return 0;\n }else {\n return NaN;\n }\n \n }\n )\n \n chord.sortSubgroups(\n d3.ascending\n \n );\n \n var arc = d3.svg.arc()\n .innerRadius(r0)\n .outerRadius(r0 + 20);\n\n var svg = d3.select(\"#chartBox\").append(\"svg:svg\")\n .attr(\"width\", w+400)\n .attr(\"height\", h+50)\n .attr(\"id\",\"chordDiagram\")\n .append(\"svg:g\")\n .attr(\"id\", \"circle\")\n .attr(\"transform\", function(){\n var trans= \"translate(\" + w / 2 + \",\" + h / 2 + \")\";\n var trans2 = \"scale(-1,-1)\";\n var trans3= trans + trans2;\n return trans3;\n })\n \n svg.append(\"circle\")\n .attr(\"r\", r0 + 20);\n\n var rdr = chordRdr(matrix, mmap);\n chord.matrix(matrix);\n //console.log(chord.matrix(matrix).groups);\n \n\n var g = svg.selectAll(\"g.group\")\n .data(chord.groups())\n .enter().append(\"svg:g\")\n .attr(\"class\", \"group\")\n .on(\"mouseover\", mouseover)\n .on(\"mouseout\", mouseout);\n\n g.append(\"svg:path\")\n .style(\"stroke\", \"white\")\n .style(\"fill\", function(d) { \n //console.log(rdr(d));\n var fillColor; \n //console.log(rdr(d).gname);\n if(rdr(d).gname==\"Republican\") return repubColor;\n else if (rdr(d).gname==\"Democrat\") return demoColor;\n\n return rdr(d).gdata == \"conMem\" ? \"purple\": groupColor; \n //return \"purple\";\n })\n .attr(\"d\", arc);\n\n g.append(\"svg:text\")\n .each(function(d) { \n d.angle = (d.startAngle + d.endAngle) / 2; \n //d.party = \"joe\";\n })\n .attr(\"dy\", \".35em\")\n .style(\"font-family\", \"helvetica, arial, sans-serif\")\n .style(\"font-size\", \"12px\")\n .attr(\"id\", function(d){\n return \"text\"+d.index;\n })\n .attr(\"text-anchor\", function(d) { \n return d.angle < Math.PI ? \"end\" : null;\n })\n // Space out all the text\n .attr(\"transform\", function(d) {\n var trans = \"rotate(\" + (d.angle * 180 / Math.PI - 90) + \")\"\n + \"translate(\" + (r0 + 26) + \")\" // pushes it out to a certain radius\n + (d.angle > Math.PI ? \"rotate(180)\" : \"\");\n \n var yUp = 280;\n \n //if(d.angle<.12) yUp = 280 + (d.value/89000 )*3;\n /*\n 89000\n 435900\n 595292\n 1518891\n */\n var xTrans = Math.sin(d.angle)*280;\n \n if(d.value<89052) yUp += 20;\n else if(d.value<435905) yUp += 20;\n else if(d.value<595293) yUp += 20;\n else if(d.value<1518892) yUp += 20;\n else if(d.value<1558488) {\n yUp += 20;\n xTrans += -20;\n }\n var yTrans = -Math.cos(d.angle)*yUp;\n //console\n\n var trans2 = \"translate(\"+xTrans+\",\"+ yTrans+\")\"\n \n var trans3 = \" scale(-1, -1)\";\n\n var allTrans = trans2 + trans3;\n return allTrans;\n // return \"rotate(\" + (d.angle * 180 / Math.PI - 90) + \")\"\n // + \"translate(\" + (r0 + 26) + \")\"\n // + (d.angle > Math.PI ? \"rotate(180)\" : \"\");\n })\n .style(\"visibility\",function(d){\n if(d.value<1558488) return \"hidden\";\n else return \"\"\n })\n \n .text(function(d) { \n if(rdr(d).gname.indexOf(\"&\") > -1) {\n return \"Materials\"\n\n }\n \n return rdr(d).gname; \n });\n\n var legend = d3.select(\"#chordDiagram\").append(\"g\")\n .attr(\"class\", \"legend\")\n .attr(\"x\", w - 65)\n .attr(\"y\", 50)\n .attr(\"height\", 100)\n .attr(\"width\", 100)\n\n //.attr('transform', 'translate(-20,50)') \n \n \n legend.selectAll('rect')\n .data(chordFill.domain().slice().reverse())\n .enter()\n .append(\"rect\")\n .attr(\"x\", 670)\n .attr(\"transform\", \"translate(10,90)\")\n .attr(\"y\", function(d, i){ \n return (i * 40);\n })\n .attr(\"width\", 20)\n .attr(\"height\", 20)\n .style(\"fill\", function(d) { \n //var color = color_hash[dataset.indexOf(d)][1];\n //return color;\n return chordFill(d);\n })\n \n legend.selectAll('text')\n .data(chordFill.domain().slice().reverse())\n .enter()\n .append(\"text\")\n .attr(\"transform\", \"translate(15,105)\")\n .attr(\"x\", 690)\n //.attr(\"y\", 50)\n //.attr(\"dy\", \".35em\")\n .attr(\"y\", function(d, i){ \n return i * 40;\n })\n .style(\"font-size\", \"12px\")\n .text(function(d) {\n switch(d){\n case 4: return \">80% D\";\n case 3: return \">60% D \";\n case 2: return \"~50% D/R\";\n case 1: return \">60% R\";\n case 0: return \">80% R\";\n }\n\n return d;\n })\n legend.append(\"text\")\n .attr(\"x\", 700)\n //.attr(\"y\", \"30\")\n .attr(\"dy\", \"6em\")\n .style(\"text-anchor\", \"middle\")\n .style(\"font-size\", \"10pt\")\n .text(\"Contribution Breakdown:\");\n \n legend.append(\"text\")\n .attr(\"x\", 750)\n .attr(\"dy\", \"30em\")\n .style(\"text-anchor\", \"middle\")\n .style(\"font-size\", \"12pt\")\n .style(\"fill\", \"rgb(33, 102, 172\") \n .text(\"Democrats: 188(43%)\");\n \n legend.append(\"text\")\n .attr(\"x\", 755)\n .attr(\"dy\", \"31em\")\n .style(\"text-anchor\", \"middle\")\n .style(\"font-size\", \"12pt\")\n .style(\"fill\", \"rgb(200, 15, 15)\")\n .text(\"Republicans: 245(56%)\");\n \n legend.append(\"text\")\n .attr(\"x\", 750)\n .attr(\"dy\", \"35em\")\n .style(\"text-anchor\", \"middle\")\n .style(\"font-size\", \"50pt\")\n .style(\"font-color\", \"steelblue\")\n .text(\"Data: Campaign Contributions from Oct 1, 2012 to Sept 30, 2014.\");\n \n legend.append(\"text\")\n .attr(\"x\", 755)\n .attr(\"dy\", \"51em\")\n .style(\"text-anchor\", \"middle\")\n .style(\"font-size\", \"12pt\")\n .text(\"Republicans: 245(56%)\");\n \n\n \n // chord.sortSubGroups(d3.descending)\n var chordPaths = svg.selectAll(\"path.chord\")\n .data(chord.chords())\n .enter().append(\"svg:path\")\n .attr(\"class\", \"chord\")\n .style(\"stroke\", \"black\")\n .style(\"fill\", function(d) { \n var dd =rdr(d);\n //var q = d3.round(num);\n // Make a number between 0 and 4\n if(dd.sname == \"Democrat\") {\n var num = dd.tvalue/dd.ttotal;\n var num2 = 4*num;\n var num3 = d3.round(num2);\n // console.log(dd.tname, num, num3);\n //console.log()\n \n return chordFill(num3);\n }\n\n else if(dd.sname == \"Republican\") {\n var num = dd.tvalue/dd.ttotal;\n var num2 = 4*num;\n var num3 = d3.round(num2);\n //console.log(dd.tname, num, num3);\n \n // Reverse the number\n return chordFill(4-num3);\n }\n else return \"Green\";\n // return dd.tname == \"Independent oil & gas producers\" ? \"#00592d\": \"#ff6200\"; \n })\n .attr(\"d\", d3.svg.chord().radius(r0))\n .on(\"mouseover\", function (d) {\n d3.select(\"#tooltip\")\n .style(\"visibility\", \"visible\")\n .html(chordTip(rdr(d)))\n .style(\"top\", function () { return (d3.event.pageY - 170)+\"px\"})\n .style(\"left\", function () { return (d3.event.pageX - 100)+\"px\";})\n })\n \n .on(\"mouseout\", function (d) { d3.select(\"#tooltip\").style(\"visibility\", \"hidden\") }); \n function chordTip (d) {\n var p = d3.format(\".1%\"), q = d3.format(\"$3,.2s\")\n //console.log(d);\n //console.log(d.tname);\n var msg= \"<strong></strong>\"\n \n\n \n + d.tname + \" to \" + d.sname +\"s\"\n + \": \" + q(d.tvalue) + \"<br/>\";\n // + p(d.tvalue/d.ttotal) + \" of \" + d.tname + \"'s Total (\" + q(d.ttotal) + \")<br/>\"\n // + p(d.tvalue/(d.mtotal/2)) + \" of Total Donated($\" + q(d.mtotal/2) + \")\";\n return msg;\n }\n\n\n function groupTip (d) {\n // console.log( d);\n var p = d3.format(\".1%\"), q = d3.format(\"$3,.2s\")\n // return \"Group Info:<br/>\"\n // d.gdata\n // + \"<br/>\"\n // + d.gname + \" : \" + q(d.gvalue) + \"<br/>\"\n // + p(d.gvalue/(d.mtotal/2)) + \" of Matrix Total (\" + q(d.mtotal/2) + \")\"\n return d.gname + \": \" + q(d.gvalue) + \"<br/>\"\n + p(d.gvalue/(d.mtotal/2)) + \" of Total (\" + q(d.mtotal/2) + \")\"\n \n }\n\n function fillInfoBox (d) {\n var generalCongressInfo =\"<h3>House of Representatives Make Up</h3>\"\n // console.log( d);\n \n\n var p = d3.format(\".1%\"), q = d3.format(\"$3,.2s\")\n \n // Fill in all the sub groups and how much they donated here\n // Maybe fill in special text for each one too.. idk. \n var subGroups = { \n \n \"Fossil Fuels\": { \"Coal mining\": { \"Republicans\":\"$1,797,895\", \"Democrats\":\"$31,000\"}, \"Electric Power Utilities\": { \"Republicans\":\"$2,769,115\",\"Democrats\":\"$1,106,153\"},\"Energy Production & Distribution\":{ \"Republicans\":\"$944,911\",\"Democrats\":\"$168,568\"}, \"Gas & Electric Utilities\":{\"Republicans\":\"$2,497,348\",\"Democrats\":\"$1,458,983\"}, \"Fuel Oil Dealers\":{\"Republicans\":\"$9,950\",\"Democrats\":\"$8,700\"}, \"Independent Oil & Gas Producers\":{\"Republicans\":\"$3,075,761\",\"Democrats\":\"$221,420\"},\"LPG/Liquid Propane Dealers & Producers\":{\"Republicans\":\"$113,100\",\"Democrats\":\"$13,000\"}, \"Natural Gas transmission & distribution\":{\"Republicans\":\"$1,618,810\", \"Democrats\":\"$353,880\"}, \"Oilfield service, equipment & exploration\":{\"Republicans\":\"$1,720,694\", \"Democrats\":\"$122,000\"}, \"Major (multinational) oil & gas producers\":{\"Republicans\":\"$2,401,775.00\", \"Democrats\":\"$327,400\"} ,\"Oil and Gas\":{\"Republicans\":\"$2,032,513\",\"Democrats\":\"$165,125\"}, \"Power plant construction & equipment\":{\"Republicans\":\"$595,488\",\"Democrats\":\"$179,200\"} , \"Petroleum refining & marketing\":{\"Republicans\":\"$2,940,985\", \"Democrats\":\"$255,225\"} },\n \n \"Materials & Manufacturing\" : { \"Industrial/Commercial Equipment & Materials\" : { \"Republicans\" : \"$3,221,728\" , \"Democrats\" : \"$1,356,742\"}, \"Metal mining & processing\": { \"Republicans\" : \"$304,700\" , \"Democrats\" : \"$76,500\"}, \"Steel\":{ \"Republicans\": \"$891,324\", \"Democrats\": \"$177,600\"}, \"Stone, Clay, Glass & Concrete Products\":{ \"Republicans\": \"$1,986,475\", \"Democrats\": \"$483,400\"}, \"Chemicals\" : {\"Republicans\" : \"$2,013,952\", \"Democrats\": \"$463,508\"}, \"Agricultural Chemicals (fertilizers & pesticides)\" : {\"Republicans\" : \"$447,200\", \"Democrats\" : \"$151,012\"}, \"Plumbing & Pipe Products\" : {\"Republicans\" : \"$129,940\", \"Democrats\": \"$22,700\"}, \"Manufacturing\" : {\"Republicans\" : \"$152,330\", \"Democrats\": \"$15,086\"}, \"Food and Kindred Products Manufacturing\" : {\"Republicans\" : \"$1,071,196\", \"Democrats\": \"$334,475\"}, \"Department, variety & convenience stores\" : {\"Republicans\" : \"$1,414,585\", \"Democrats\": \"$732,950\"}, \"Forestry & Forest Products\" : {\"Republicans\" : \"$1,438,038\", \"Democrats\": \"$416,933\"} }, \n \n\n \n \"Transportation\" : {\"Airlines\":{ \"Republicans\": \"$886,100\", \"Democrats\": \"$533,285\"}, \"Bus Services\" : {\"Republicans\" : \"$128,450\", \"Democrats\": \"$32,350\"}, \"Sea freight & passenger services\" : {\"Republicans\" : \"$702,164\", \"Democrats\" : \"$457,106\"}, \"Sea transport\" : {\"Republicans\" : \"$114,308\", \"Democrats\": \"$68,435\"}, \"Transportation\" : {\"Republicans\" : \"$248,600\", \"Democrats\": \"$43,700\"}, \"Trucking Companies & Services\" : {\"Republicans\" : \"$1,551,425\", \"Democrats\": \"$262,000\"}}, \n\n\n\n \"Construction\" : { \"Public works, industrial & commercial construction\" : { \"Republicans\" : \"$2,258,172\" , \"Democrats\" : \"$700,079\"}, \"Construction equipment\": { \"Republicans\" : \"$747,800\" , \"Democrats\" : \"$114,567\"}, \"Equipment rental & leasing\":{ \"Republicans\": \"$270,971\", \"Democrats\": \"$134,700\"}, \"Electrical contractors\":{ \"Republicans\": \"$817,885\", \"Democrats\": \"$307,750\"}, \"Engineering, architecture & construction mgmt svcs\" : {\"Republicans\" : \"$2,196,119\", \"Democrats\": \"$1,426,592\"}, \"Residential construction\" : {\"Republicans\" : \"$1,949,133\", \"Democrats\" : \"$592,051\"}, \"Special trade contractors\" : {\"Republicans\" : \"$744,627\", \"Democrats\": \"$231,535\"}, \"Plumbing, Heating & Air conditioning\": {\"Republicans\" : \"$423,407\", \"Democrats\" : \"$187,790\"} },\n \"Unions\" : {\"Building Trades Unions\":{ \"Republicans\": \"$1,484,550\", \"Democrats\": \"$7,531,333\"}, \"IBEW (Intl Brotherhood of Electrical Workers)\" : {\"Republicans\" : \"$52,590\", \"Democrats\": \"$1,568,775\"}, \"Teamsters union\" : {\"Republicans\" : \"$81,500\", \"Democrats\" : \"$1,093,850\"} },\n \n \"Business Associations\" : {\"General business associations\":{ \"Republicans\": \"$540,310\", \"Democrats\": \"$177,250\"}, \"Chambers of commerce\" : {\"Republicans\" : \"$173,819\", \"Democrats\": \"$34,025\"}, \"Small business associations\" : {\"Republicans\" : \"$22,550\", \"Democrats\" : \"$529,238\"}, \"Fiscal & tax policy\" : {\"Republicans\" : \"$40,450\", \"Democrats\" : \"$1,250\"} },\n \"Ideological Groups\" : {\"Republican/Conservative\":{ \"Republicans\": \"$5,754,017\", \"Democrats\": \"$23,100\"}, \"Minority/Ethnic Groups\" : {\"Republicans\" : \"$263,906\", \"Democrats\": \"$762,577\"}, \"Pro-resource development groups\" : {\"Republicans\" : \"$2,500\", \"Democrats\" : \"None\"} },\n \n \"Alternate energy production & services\" : {\"Alternate energy production & services\":{\"Republicans\": \"$337,300\", \"Democrats\": \"$257,992\"}},\n\n \"Environmental Policy\" : {\"Environmental Policy\":{ \"Republicans\": \"$224,458\", \"Democrats\": \"$1,334,030\"}},\n\n \"Homeland Security contractors\" : {\"Homeland Security contractors\":{ \"Republicans\": \"$54,050\", \"Democrats\": \"$35,000\"}},\n\n \"Nuclear energy\" : {\"Nuclear energy\":{ \"Republicans\": \"$256,450\", \"Democrats\": \"$179,450\"}}, \n\n };\n //_each\n var rows = \"\"; \n \n var aGroup= subGroups[d.gname];\n _.forEach(aGroup, function(n, key) {\n var demStr = n.Democrats;\n demStr = demStr.replace(/,/g, \"\");\n demStr = parseInt(demStr.replace(\"$\", \"\"));\n demStr = q(demStr);\n //console.log(n.Democrats)\n //console.log(q(parseInt(n.Democrats)))\n var repStr = n.Republicans;\n repStr = repStr.replace(/,/g, \"\");\n repStr = parseInt(repStr.replace(\"$\", \"\"));\n repStr = q(repStr);\n rows += '<tr><td><br>'+ key +'</br></td><td style=\"color: steelblue\"><br>' + demStr + '</br></td><td style=\"color: rgb(247, 25, 25)\"><br>' + repStr+ '</br></td></tr>';\n });\n var header = \"<strong>\" +d.gname + \":</strong> <br>\";\n var strGroups = '<table style=\"font-size: 12px\">' + rows + \"</table>\";\n\n var strTotalDonate = \"Contributed: \" + q(d.gvalue) + \" (\" + p(d.gvalue/(d.mtotal/2)) +\" of total donations) <br>\";\n var msg = header + strGroups;\n return msg;\n \n }\n\n function mouseover(d, i) {\n d3.select(\"#tooltip\")\n .style(\"visibility\", \"visible\")\n .style(\"background-color\", \"lightgray\")\n .style(\"color\", \"black\")\n .html(groupTip(rdr(d)))\n .style(\"top\", function () { return (d3.event.pageY - 80)+\"px\"})\n .style(\"left\", function () { return (d3.event.pageX - 130)+\"px\";})\n\n \n \n d3.select(\"#infoBox\")\n .style(\"font-size\", \"10pt\")\n .style(\"visibility\", \"visible\")\n .html(groupTip(rdr(d)))\n\n d3.select(\"#infoBox\")\n .style(\"font-size\", \"10pt\")\n //.style(\"visibility\", \"visible\")\n .html(fillInfoBox(rdr(d)))\n\n\n var textStringID = \"#text\"+i; \n d3.select(textStringID)\n .style(\"visibility\", \"visible\")\n\n chordPaths.classed(\"fade\", function(p) {\n return p.source.index != i\n && p.target.index != i;\n });\n }\n function mouseout(d, i) {\n d3.select(\"#infoBox\")\n .style(\"font-size\", \"10pt\")\n //.style(\"visibility\", \"visible\")\n .html(\"\")\n\n\n d3.select(\"#tooltip\").style(\"visibility\", \"hidden\") \n //Only remove text labels for small tight groups\n if(d.value<1558488) {\n var textStringID = \"#text\"+i; \n d3.select(textStringID)\n .style(\"visibility\", \"hidden\")\n }\n }\n\n\n \n }", "function heatMap(string) {\n\n var lower = string.toLowerCase()\n var index = alphabet.indexOf(lower)\n var sum = total(index)\n\n updateDomain(matrix[index], sum, index)\n \n svg.selectAll(\"rect.key\").remove()\n svg.selectAll(\"text.key\").remove()\n \n svg.selectAll(\"rect.key\")\n .data(keyboard)\n .enter()\n .append(\"g\")\n .each(function(d, i) {\n d3.select(this)\n .selectAll(\"rect\")\n .data(d)\n .enter()\n .append(\"rect\")\n .attr(\"class\", \"key\")\n .attr(\"width\", function(d){\n if (d == string){\n return width - 3\n }\n else {\n return width\n }\n })\n .attr(\"height\", function(d){\n if (d == string){\n return height - 3\n }\n else {\n return height\n }\n })\n .attr(\"x\", function(d, j) {\n if (d == string) {\n return xKey + 2 + i*20 + j*(width + 3)\n }\n else {\n return xKey + i*20 + j*(width + 3)\n }\n })\n .attr(\"y\", function(d, j) {\n if (d == string) {\n return yKey + 1 + i*(height + 3)\n }\n else {\n return yKey + i*(height + 3)\n } \n })\n .attr(\"stroke-width\", function(d){\n if (d == string) {\n return 1.2\n }\n else {\n return 1\n }\n })\n .attr(\"fill\", function(d) {\n var lettre = d.toLowerCase()\n var indice = alphabet.indexOf(lettre)\n if (indice != -1) {\n var value = matrix[index][indice]\n var shade = value/sum\n return color(shade);\n }\n else {\n return \"white\";\n }\n })\n .attr(\"stroke\", function(d) {\n if (alphabet.indexOf(d.toLowerCase()) != -1) {\n return \"black\";\n }\n else {\n return \"#C0C0C0\";\n }\n })\n .on(\"click\", function(d) {\n heatMap(d)\n barChart(d)\n })\n .on(\"mouseover\", function(d){\n var lettre = d.toLowerCase()\n var indice = alphabet.indexOf(lettre)\n if (indice != -1) {\n d3.select(this)\n .style(\"cursor\", \"pointer\")\n }\n })\n\n })\n \n svg.selectAll(\"text.key\")\n .data(keyboard)\n .enter()\n .append(\"g\")\n .each(function(d, i){\n d3.select(this)\n .selectAll(\"text\")\n .data(d)\n .enter()\n .append(\"text\")\n .attr(\"x\", function(d, j) {\n if (d == string){\n return xKey + 2 + 3 + i*20 + j*(width + 3)\n }\n else {\n return xKey + 3 + i*20 + j*(width + 3)\n } \n })\n .attr(\"y\", function(d, j) {\n if (d == string){\n return yKey + 2 + 15 + i*(height + 3)\n }\n else {\n return yKey + 15 + i*(height + 3)\n }\n \n })\n .text(function(d) {\n return d;\n })\n .attr(\"fill\", function(d) {\n if (alphabet.indexOf(d.toLowerCase()) != -1) {\n return \"black\";\n }\n else {\n return \"#C0C0C0\";\n } \n })\n })\n }", "function draw_heatmap()\n\n // Draw tweets on heatmap canvas\n{\n var canvas; \t\t\t// Canvas element on page\n var col;\t\t\t\t// Cell colour\n var cell_h;\t\t\t\t// Cell height\n var cell_w;\t\t\t\t// Cell width\n var ctx;\t\t\t\t// Canvas 2d context\n var h; // Canvas height\n var i, j;\t\t\t\t// Loop counters\n var scale;\t\t\t\t// d3 logarithmic colour scale\n var w; // Canvas width\n var x, y;\t\t\t\t// Top-left corner of cell\n\n\n if ( !( canvas = get_canvas( \"heatmap-canvas\" ) ) ) {\n return;\n }\n\n w = canvas.width;\t\t\t// Get width, height of canvas\n h = canvas.height;\n\n clear_canvas( \"heatmap-canvas\" );\t// Clear canvas contents\n\n ctx = canvas.getContext( \"2d\" ); // Get context, set fill colour\n ctx.strokeStyle = \"rgb( 192, 192, 192 )\";\n\n draw_heatmap_axis();\t\t\t// Draw scatterplot axis/labels\n draw_heatmap_legend();\t\t// Draw legend and limits\n draw_query_term( \"heatmap-canvas\" );\t// Draw query term and tweet count\n\n // Setup log scale to map sentiment frequency to colour\n\n scale = d3.scale.linear();\n scale.domain( [ 0, fq_hist_avg, fq_hist_max ] );\n\n if ( fq_hist_max == 0 ) {\t\t// No terms, all cells white\n scale.range( [ [ 255, 255, 255 ], [ 255, 255, 255 ], [ 255, 255, 255 ] ] );\n } else {\n scale.range( [ [ 19, 54, 231 ], [ 193, 196, 214 ], [ 223, 14, 14 ] ] );\n }\n\n // There's a 25-pixel pad to the right and left of the graph, and\n // another 20-pixel pad for each quadrant of the heatmap to offset\n // it within the axes\n\n cell_w = ( w - 130.0 ) / 8.0;\n cell_h = ( h - 130.0 ) / 8.0;\n\n y = 45;\t\t\t\t// Top of first quadrant\n for( i = 0; i < 8; i++ ) {\t\t// For all rows\n x = 45;\t\t\t\t// Left of first quadrant\n for( j = 0; j < 8; j++ ) {\t\t// For all columns\n ctx.beginPath();\t\t\t// Draw heatmap cell\n ctx.rect( x, y, cell_w, cell_h );\n ctx.stroke();\n\n // Colour above average cells red, below average cells blue, and\n // cells with no tweets white\n\n if ( fq_hist[ 7 - i ][ j ] > 0 ) {\n col = scale( fq_hist[ 7 - i ][ j ] );\n ctx.fillStyle = d3.rgb( col[ 0 ], col[ 1 ], col[ 2 ] ).toString();\n } else {\n ctx.fillStyle = \"#ffffff\";\n }\n ctx.fill();\n \n if ( j == 3 ) {\t\t\t// Add offset around Y-axis\n x += 40;\n }\n x += cell_w;\t\t\t// Move right to next cell\n }\n\n if ( i == 3 ) {\t\t\t// Add offset around X-axis\n y += 40;\n }\n y += cell_h;\t\t\t// Move down to next row of cells\n }\n}\t\t\t\t\t// End function draw_heatmap", "function updateHeatmap(index) {\n context.clearRect(0, 0, 800, 600);\n imageData.data.set(hmCol[index]);\n context.putImageData(imageData, 0, 0);\n}", "function displayHeat() {\n\n var gradient = [\n 'rgba(2, 15, 117, 0)',\n 'rgba(12, 29, 184, 1)',\n 'rgba(112, 70, 170, 1)',\n 'rgba(200, 105, 158, 1)',\n 'rgba(223, 81, 61, 1)',\n 'rgba(242, 109, 82, 1)',\n 'rgba(244, 129, 83, 1)',\n 'rgba(255, 120, 130, 1)',\n 'rgba(253, 163, 75, 1)',\n 'rgba(252, 197, 228, 1)'\n ]\n\n // (Kyle) - new single-layer heatmap with uniform radii.\n heatmap = new google.maps.visualization.HeatmapLayer({\n data: dataPointArray,\n map: map,\n dissipating: true,\n gradient: gradient,\n radius: 10\n })\n\n // (Kyle) - I have disabled the for-loop heatmap layer renderer - \n // the site was having trouble keeping up and the number of reviews \n // had too great a range.\n\n // for (i = 0; i < 10; i++) {\n // // this loop creates a heatmap layer for each datapoint so that\n // // each point can have its radius set individually\n // new google.maps.visualization.HeatmapLayer({\n // data: [dataPointArray[i]],\n // map: map,\n // dissipating: true\n // }).set(\"radius\", reviewArray[i] / 20);\n // }\n\n // after its been used the dataPointArray is emptied to allow for the next search\n dataPointArray = [];\n}", "function putChargers(map){\n // First charger icons\n var icon = new H.map.Icon('/static/img/preview_30.png');\n var coords = window.first_chargers_array;\n // Put first chargers in the map\n for(var i=0; i<coords.length; i++){\n var incidentMarker = new H.map.Marker({\n lat: coords[i][\"coords\"][0],\n lng: coords[i][\"coords\"][1]\n },{icon:icon});\n map.addObjects([incidentMarker]);\n }\n\n // Charger icons\n icon = new H.map.Icon('/static/img/last_30.png');\n var coords = window.chargers_array;\n // Put chargers in the map\n for(var i=0; i<coords.length; i++){\n var incidentMarker = new H.map.Marker({\n lat: coords[i][\"coords\"][0],\n lng: coords[i][\"coords\"][1]\n },{icon:icon});\n map.addObjects([incidentMarker]);\n }\n}", "function initialHeatmaps(){\r\n setupHeatmap(jsonData.length);\r\n setupGlbHeatmap();\r\n}", "function drawChords(matrix) {\n var width = 980,\n height = 900,\n innerRadius = height / 2 - 120,\n outerRadius = innerRadius - 25;\n\n\n /* SETUP */\n\n // color management \n var colorize = d3.scale.ordinal()\n .domain(d3.range(matrix.length))\n .range(generateColorArray(matrix.length));\n\n // creates the chord layout with basic paramenters\n // and passes the matrix data to the layout\n var chordDiagram = d3.layout.chord()\n .padding(.03)\n .sortSubgroups(d3.descending)\n .sortChords(d3.descending)\n .matrix(matrix);\n\n // arc path to create player arcs\n var arc = d3.svg.arc()\n .innerRadius(innerRadius)\n .outerRadius(outerRadius);\n\n // creates the svg element and appends it to the DOM tree\n // translates the coordinate system to the center of the element instead of top left\n var svg = d3.select(\"#diagram\").append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height)\n .append(\"g\")\n .attr(\"id\", \"circle\")\n .attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\");\n\n\n /* ARC STYLING */\n\n // ever player is a svg group with the arc, text, label and a click handler\n // playerGroups is the array containing all player groups\n var playerGroups = svg.selectAll(\"g.player\")\n .data(chordDiagram.groups())\n .enter().append(\"g\")\n .attr(\"class\", \"player\")\n .on(\"click\", highlight);\n\n // each player has their own color\n playerGroups.append(\"path\")\n .style(\"fill\", function(d) { return colorize(d.index); })\n .attr(\"d\", arc);\n\n // adds the player name, positioned in the middle of the arc\n playerGroups.append(\"text\")\n .each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; })\n .attr(\"dy\", \".3em\")\n .style(\"font-family\", \"'Helvetica Neue', Arial, sans-serif\")\n .style(\"font-size\", \"16px\")\n .style(\"fill\", \"#3b3939\")\n .attr(\"text-anchor\", function(d) { return d.angle > Math.PI ? \"end\" : null; })\n .attr(\"transform\", function(d) {\n return \"rotate(\" + (d.angle * 180 / Math.PI - 90) + \")\"\n + \"translate(\" + (innerRadius + 15) + \")\"\n + (d.angle > Math.PI ? \"rotate(180)\" : \"\");\n })\n .text(function(d) { return dataMapper.getPlayerName(d); });\n\n // creates tooltip for player\n playerGroups.append(\"title\").text(function(d) {\n return dataMapper.setPlayerInfo(d);\n });\n\n\n /* CHORD STYLING */\n\n // create chords between arcs\n var chordPaths = svg.selectAll(\"path.chord\")\n .data(chordDiagram.chords())\n .enter().append(\"path\")\n .attr(\"class\", \"chord\")\n .style(\"fill\", function (d) { return colorize(d.target.index); })\n .attr(\"d\", d3.svg.chord().radius(outerRadius - 3));\n\n\n // create chord tooltip\n chordPaths.append(\"title\").text(function(d) {\n return dataMapper.setChordInfo(d);\n });\n\n\n\n /* PLAYER GROUP CLICK HANDLER */\n\n function highlight(d, i) {\n if (highlightedPlayerIndex === i) {\n // if stored index is the same as clicked player\n chordPaths.classed({\"fade\": false });\n highlightedPlayerIndex = null;\n } else {\n // if no index is stored or the index isn't the stored one\n chordPaths.classed(\"fade\", function(p) {\n return p.source.index != i && p.target.index != i; \n });\n highlightedPlayerIndex = i;\n }\n }\n }", "function salesHeatmap() {}", "function attachDataToCells(array) {\n let categoryIndex = 0;\n let clueIndex = 0;\n for (let i = 0; i <= 29; i++) {\n $(`#${i}`).data(array[categoryIndex].clues[clueIndex]);\n categoryIndex++;\n if (categoryIndex >= 6) {\n categoryIndex = 0;\n clueIndex++;\n }\n // if (clueIndex >= 10) {\n // clueIndex = 9;\n // }\n }\n}", "function plot_freq_map(data, svg_info) {\n var fmap = data.board;\n var samples = data.samples;\n var svg = svg_info.svg;\n var xScale = svg_info.xScale;\n var yScale = svg_info.yScale;\n var textHeight = svg_info.textHeight;\n\n var max_val = d3.max(fmap, function(d) {\n return Math.abs(d);\n });\n\n var stones = svg.selectAll(\"circle\").data(fmap);\n\n //Transition stones that changed values\n stones.enter().append(\"circle\");\n\n stones\n .transition().duration(350)\n .attr(\"cx\", function(d, i) {\n return xScale(i % 19);\n })\n .attr(\"cy\", function(d, i) {\n return yScale(Math.floor(i / 19));\n })\n .attr(\"r\", function(d) {\n return xScale(compute_radius(d, max_val));\n }).filter(function(d) {\n return d != 0;\n })\n .attr(\"fill\", function(d) {\n if (d < 0) {\n return \"black\";\n } else if (d > 0) {\n return \"white\";\n } else {\n return null;\n }\n });\n stones.exit().transition().duration(800).attr(\"r\", 0).remove(); // Add metadata\n // svg.append(\"text\")\n // .attr(\"x\", 0)\n // .attr(\"y\", textHeight)\n // .attr(\"font-family\", \"sans-serif\")\n // .attr(\"font-size\", \"10px\")\n // .attr(\"fill\", \"black\")\n // .style(\"font-size\", \"10px\")\n // .text(\"Number of samples: \" + samples);\n}", "function showData() {\n //count the rows in our table\n background(255);\n strokeWeight(.1);\n // ellipse(x1,y1,x2,y2);\n\n var count = table.getRowCount();\n var rowHeight = 20;\n var j = 2 * PI / count;\n for (var r = 0; r < count; r++) {\n\n // loop through all the columns\n\n var valf = table.getString(r, 3);\n var valm = table.getString(r, 4);\n // display the text on the canvas\n valf = parseFloat(valf);\n valm = parseFloat(valm);\n\n var femaleRadius = map(valf, rangeLow, rangeHigh, 0, windowHeight / 1.01);\n var maleRadius = map(valm, rangeLow, rangeHigh, 0, windowHeight / 1.01);\n arc(windowWidth / 2, windowHeight / 2, femaleRadius, femaleRadius, r * j, r * j + j, PIE);\n arc(windowWidth / 2, windowHeight / 2, maleRadius, maleRadius, r * j, r * j + j, PIE);\n\n }\n}", "function numbers(){\n for(let i=1;i<tileColCount;i++)\n {\n let tmpx= i*(tileW+3);\n let tmpy=0;\n ctx.fillStyle=\"black\";\n ctx.font = \"15px Georgia\";\n ctx.fillText(i,tmpx+3,tmpy+12,20); \n }\n for(let j=1;j<tileRowCount;j++)\n {\n let tmpy= j*(tileW+3);\n let tmpx=0;\n ctx.fillStyle=\"black\";\n ctx.font = \"15px Georgia\";\n ctx.fillText(j,tmpx,tmpy+14,20); \n }\n}", "function drawCircleGrid() {\n\t\tfor (var i = 180; i <= 1100; i+=100) {\n\t\t\tfor (var j = 50; j <= 1100; j+=100) {\n\t\t\t\tvar myCircle = new Path.Circle(new Point(i, j), 10);\n\t\t\t\tmyCircle.fillColor = hue();\n\t\t\t}\n\t\t}\n\t}", "function doHeatMap(rows){\n let latCol = 0;\n let lngCol = 1;\n let heatMapData = [];\n\n if (rows!=null){\n for (let i = 0; i < rows.length; i++) {\n let f = rows[i].f;\n console.log(f)\n let coords = { lat: parseFloat(f[latCol].v), lng: parseFloat(f[lngCol].v) };\n console.log('Initializing the point with coords:')\n console.log(coords)\n heatMapData.push(new google.maps.LatLng(coords));\n }\n // Initialize with heatMapData\n heatmap = new google.maps.visualization.HeatmapLayer({\n data: heatMapData,\n maxIntensity: 20\n });\n console.log('Looking at heatmap data:')\n console.log(heatmap)\n toggleHeatmap();\n }\n else{\n console.log('No object heatMapData available')\n }\n }", "function graph5() {\n\nvar matrix = [\n [11975, 5871, 8916, 2868],\n [ 1951, 10048, 2060, 6171],\n [ 8010, 16145, 8090, 8045],\n [ 1013, 990, 940, 6907]\n];\n\nvar chord = d3.layout.chord()\n .padding(.05)\n .sortSubgroups(d3.descending)\n .matrix(matrix);\n\nvar width = 1000;\nvar height = width / 2,\n innerRadius = Math.min(width, height) * .41,\n outerRadius = innerRadius * 1.1;\n\nvar fill = d3.scale.ordinal()\n .domain(d3.range(4))\n .range([\"#000000\", \"#FFDD89\", \"#957244\", \"#F26223\"]);\n\nvar svg = d3.select(\"#chart-5\").append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\");\n\nsvg.append(\"g\").selectAll(\"path\")\n .data(chord.groups)\n .enter().append(\"path\")\n .style(\"fill\", function(d) { return fill(d.index); })\n .style(\"stroke\", function(d) { return fill(d.index); })\n .attr(\"d\", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius))\n .on(\"mouseover\", fade(.1))\n .on(\"mouseout\", fade(1));\n\nvar ticks = svg.append(\"g\").selectAll(\"g\")\n .data(chord.groups)\n .enter().append(\"g\").selectAll(\"g\")\n .data(groupTicks)\n .enter().append(\"g\")\n .attr(\"transform\", function(d) {\n return \"rotate(\" + (d.angle * 180 / Math.PI - 90) + \")\" + \"translate(\" + outerRadius + \",0)\";\n });\n\nticks.append(\"line\")\n .attr(\"x1\", 1)\n .attr(\"y1\", 0)\n .attr(\"x2\", 5)\n .attr(\"y2\", 0)\n .style(\"stroke\", \"#000\");\n\nticks.append(\"text\")\n .attr(\"x\", 8)\n .attr(\"dy\", \".35em\")\n .attr(\"transform\", function(d) { return d.angle > Math.PI ? \"rotate(180)translate(-16)\" : null; })\n .style(\"text-anchor\", function(d) { return d.angle > Math.PI ? \"end\" : null; })\n .text(function(d) { return d.label; });\n\nsvg.append(\"g\")\n .attr(\"class\", \"chord\")\n .selectAll(\"path\")\n .data(chord.chords)\n .enter().append(\"path\")\n .attr(\"d\", d3.svg.chord().radius(innerRadius))\n .style(\"fill\", function(d) { return fill(d.target.index); })\n .style(\"opacity\", 1);\n\n// Returns an array of tick angles and labels, given a group.\nfunction groupTicks(d) {\n var k = (d.endAngle - d.startAngle) / d.value;\n return d3.range(0, d.value, 1000).map(function(v, i) {\n return {\n angle: v * k + d.startAngle,\n label: i % 5 ? null : v / 1000 + \"k\"\n };\n });\n}\n\n// Returns an event handler for fading a given chord group.\nfunction fade(opacity) {\n return function(g, i) {\n svg.selectAll(\".chord path\")\n .filter(function(d) { return d.source.index !== i && d.target.index !== i; })\n .transition()\n .style(\"opacity\", opacity);\n };\n}\n\n}", "function nonogramify() {\n\t$('#nonogramify').remove();\n\t$('#color-picker').remove();\n\tnonogram = true;\n\ttilesToEliminate = countPixels(gridArr);\n\tvar tile = $('.pixel');\n\tvar colVal = 0;\n\tvar rowVal = 0;\n\ttile.addClass('tile');\n\tfor (var y = 0; y < gridArr.length; y++) {\n\t\tfor (var x = 0; x < gridArr[0].length; x++){\n\t\t\tif(gridArr[y][x] === 0) {\n\t\t\t\trowVal++;\n\t\t\t}\n\t\t\tif (gridArr[y][x] !== 0 || x === (gridArr[0].length - 1)) {\n\t\t\t\tif (rowVal !== 0){\n\t\t\t\t\t$('#row-'+y).children('ul').append('<li>'+rowVal+'</li>');\n\t\t\t\t}\n\t\t\t\trowVal = 0;\n\t\t\t}\n\t\t}\n\t}\n\tfor (var y = 0; y < gridArr[0].length; y++) {\n\t\tfor (var x = 0; x < gridArr.length; x++){\n\t\t\tif(gridArr[x][y] === 0) {\n\t\t\t\tcolVal++;\n\t\t\t}\n\t\t\tif (gridArr[x][y] !== 0 || x === (gridArr.length - 1)) {\n\t\t\t\tif (colVal !== 0){\n\t\t\t\t\t$('#column-'+y).children('ul').append('<li>'+colVal+'</li>');\n\t\t\t\t}\n\t\t\t\tcolVal = 0;\n\t\t\t}\n\t\t}\n\t}\n}", "function start()\n{\n _map = {}, _tiles = [];\n for (var i = 0; i < 10; i++) {\n for (var j = 0; j < 10; j++) {\n\n\n\n var x =_map[0 + ':' + 0];\n console.log(_tiles[j]);\n // console.log(_map);\n new Tile((Math.floor(Math.random() * colors.length))).insert(i, j);\n\n\n }\n }\n }", "function plot_error_heatmap_in_div(canvas_id, esb_type, esb_size) {\n if (inputObject.sort_by !== 'param' && inputObject.sort_by !== 'width' && inputObject.sort_by !== 'depth') {\n alert('Sort by incorrect:', inputObject.sort_by);\n return;\n }\n var tt = document.getElementById(canvas_id);\n if (tt.innerHTML !== '') {\n alert('Canvas not cleared!');\n return;\n }\n\n var net_arch = inputObject.network_archeticture;\n var dataset = inputObject.dataset;\n var h_sizes = inputObject.horizontal;\n var v_sizes = inputObject.vertical;\n\n // Get the index of columns we are going to display\n var indexes = get_indexes();\n\n var t = [net_arch, dataset, esb_type, esb_size];\n json_filename = 'data/error_heatmap/' + t.join('_') + '.json';\n var ret = readTextFile(json_filename);\n var json = JSON.parse(ret);\n var x_values = json.x_values;\n var z_values = json.data;\n\n // Get the data we need according to the indexes\n var x_values_t = [];\n for (let i of indexes) {\n x_values_t.push(x_values[i]);\n }\n var z_values_t = [];\n var new_line;\n for (let line of z_values) {\n new_line = [];\n for (let i of indexes) {\n new_line.push(line[i]);\n }\n z_values_t.push(new_line);\n }\n var y = [];\n for (let i = 1; i <= 250; i++) {\n y.push(i);\n }\n\n var data = [\n {\n z: z_values_t,\n x: x_values_t,\n y: y,\n type: 'heatmap',\n hoverongaps: false,\n colorscale: [[0.0, '#fbb4ae'],\n [0.33, '#fbb4ae'],\n [0.33, '#b3cde3'],\n [0.66, '#b3cde3'],\n [0.66, '#ccebc5'],\n [1.0, '#ccebc5']],\n colorbar: {\n tickmode: 'array',\n tickvals: [-0.7, 0, 0.7],\n ticktext: ['Single<br>better', 'Equal', 'Ensemble<br>better']\n }\n }\n ];\n var layout = {\n title: 'Comparing Validation Error',\n xaxis: {\n title: 'Width factor|Depth|Parameters (M)',\n type: 'category',\n tickangle: 45,\n automargin: true,\n },\n yaxis: {\n title: 'Number of epochs',\n tickmode: 'array',\n\n //tickvals:[1, 20, 40, 60, 80, 100, 120, 140, 160, 200, 250],\n //ticktext:[1, 20, 40, 60, 80, 100, 120, 140, 160, 200, 250],\n tickvals:[1, 30, 60, 90, 120, 160, 200, 240, 300, 400, 500, 600],\n ticktext:[1, 30, 60, 90, 120, 160, 200, 240, 300, 400, 500, 600],\n },\n\n };\n\n Plotly.newPlot(canvas_id, data, layout);\n}", "function setHeatmap() {\n // Get the array from localStorage\n let keysArr = JSON.parse(localStorage.getItem(\"localKeys\"));\n\n // This removes the leftClick and rightClick keys from keysArr\n keysArr = removeByAttr(keysArr, \"keyCode\", 134761167);\n keysArr = removeByAttr(keysArr, \"keyCode\", 4164761167);\n\n // This sorts keysArr in descending order of timeClicked and sets it to sortedArr\n let sortedArr = keysArr.sort((a, b) => b.timesClicked - a.timesClicked);\n\n // This gets the first item from sortedArr i.e. key with most presses\n let topKey = sortedArr[0].timesClicked;\n\n // Loop over all keys from keysArr\n for (let i in keysArr) {\n // This is the current or 'i'th object in the array\n let thisKey = keysArr[i];\n\n // Check if thisKey exits on the keyboard\n if (document.getElementById(thisKey.keyName)) {\n // This is to give colors to keys based on how many relative clicks to the topKey they have\n // The topKey is always the most intense color\n if (thisKey.timesClicked > 0.9 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[0];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0.8 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[1];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0.7 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[2];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0.6 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[3];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0.5 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[4];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0.4 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[5];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0.3 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[6];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0.2 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[7];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0.1 * topKey) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[8];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked > 0) {\n document.getElementById(thisKey.keyName).style.backgroundColor =\n heatmapColors[9];\n document.getElementById(thisKey.keyName).style.textShadow =\n \"0px 1px 0px #4b4848\";\n document.getElementById(thisKey.keyName).style.color = \"#fff\";\n } else if (thisKey.timesClicked == 0) {\n // console.log(\"thisKey never clicked\")\n } else {\n // console.log(\"KEYERR\");\n }\n } else {\n // console.log(\"This key not found:\");\n // console.log(thisKey.keyName);\n }\n }\n}", "function drawHeatMapViz(data, min, max, top_5) {\n\n hMapSvg = d3.select(\".heatmap_svg\");\n\n // Creating groups\n const g = hMapSvg.append(\"g\")\n .attr(\"transform\", `translate(${heatMapMargin.left}, ${heatMapMargin.top} )`);\n\n const hrArr = [\"00\", \"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\", \"21\", \"22\", \"23\"];\n\n\n // Ref (Heatmap) : https://www.d3-graph-gallery.com/graph/heatmap_style.html\n const myColor = d3.scaleSequential()\n .interpolator(d3.interpolateReds)\n .domain([min,max*1.2])\n\n const defs = g.append(\"defs\");\n\n let linearGradient = defs.append(\"linearGradient\")\n .attr(\"id\", \"linear-gradient\")\n .attr(\"x1\", \"0%\")\n .attr(\"x2\", \"100%\")\n .attr(\"y1\", \"0%\")\n .attr(\"y2\", \"100%\");\n\n linearGradient.append(\"stop\")\n .attr(\"offset\", \"0%\")\n .attr(\"stop-color\", myColor(min));\n\n linearGradient.append(\"stop\")\n .attr(\"offset\", \"25%\")\n .attr(\"stop-color\", myColor((max - min) * 0.25));\n\n linearGradient.append(\"stop\")\n .attr(\"offset\", \"50%\")\n .attr(\"stop-color\", myColor((max - min) * 0.5));\n\n linearGradient.append(\"stop\")\n .attr(\"offset\", \"75%\")\n .attr(\"stop-color\", myColor((max - min) * 0.75));\n\n linearGradient.append(\"stop\")\n .attr(\"offset\", \"100%\")\n .attr(\"stop-color\", myColor(max));\n\n g.append(\"rect\")\n .attr(\"x\", 80)\n .attr(\"y\", - 70)\n .attr(\"width\", heatMapWidth - 370)\n .attr(\"height\", 10)\n // .style(\"stroke\", \"black\")\n // .style(\"stroke-width\", 2)\n .style(\"fill\", \"url(#linear-gradient)\")\n\n g.append(\"text\")\n .attr(\"class\", \"min-value\")\n .attr(\"x\", 0)\n .attr(\"y\", -60)\n .text(Math.round(min) +\" (min)\")\n\n g.append(\"text\")\n .attr(\"class\", \"max-value\")\n .attr(\"x\", heatMapWidth - 270)\n .attr(\"y\", -60)\n .text(numberFormat(Math.round(max)) +\" (max)\")\n\n // X axis label\n // Ref: text label for the x axis (https://bl.ocks.org/d3noob/23e42c8f67210ac6c678db2cd07a747e)\n g.append(\"text\")\n .attr(\"class\", \"x axis-label\")\n .attr(\"x\", heatMapWidth / 3 + 50)\n .attr(\"y\", heatMapHeight - 5)\n .attr(\"font-size\", \"15px\")\n .attr(\"text-anchor\", \"middle\")\n .text(\"Hour\")\n\n // scaleBand is used to position many visual elements in a particular order with even spacing\n // ref: http://daydreamingnumbers.com/learn-d3/bar-charts-in-d3/\n // https://github.com/d3/d3-scale/blob/master/README.md#scaleBand\n // https://github.com/d3/d3-scale/blob/master/README.md#band_paddingInner\n const xAxisRange = d3.scaleBand()\n .domain(hrArr)\n .range([0, heatMapWidth - heatMapMargin.right - heatMapMargin.left])\n .padding(0.05);\n\n const xAxisCall = d3.axisBottom(xAxisRange)\n .tickSize(0)\n\n g.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", `translate(0, ${3*heatMapHeight/4})`)\n .call(xAxisCall) // https://stackoverflow.com/questions/12805309/javascript-library-d3-call-function\n .selectAll(\"text\") // https://stackoverflow.com/questions/12805309/javascript-library-d3-call-function\n .attr(\"y\", \"10\") // https://stackoverflow.com/questions/41193617/group-each-rect-and-text-in-d3#answer-41193711\n .attr(\"x\", \"-5\")\n .attr(\"text-anchor\", \"middle\")\n .select(\".domain\").remove();\n\n // Scaling y-axis data\n const yAxisRange = d3.scaleBand()\n .domain(top_5)\n .range([3*heatMapHeight/4, 0])\n .padding(0.05);\n\n // Creating y-axis\n // https://www.tutorialsteacher.com/d3js/axes-in-d3\n // https://observablehq.com/@d3/axis-ticks\n // tickFormat => https://github.com/d3/d3-axis#axis_tickFormat\n const yAxisCall = d3.axisLeft(yAxisRange)\n .ticks(6)\n .tickFormat(d => d)\n\n g.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(yAxisCall)\n\n // Y label\n g.append(\"text\")\n .attr(\"class\", \"y axis-label\")\n .attr(\"x\", - ( heatMapHeight / 3))\n .attr(\"y\", -120)\n .attr(\"font-size\", \"15px\")\n .attr(\"text-anchor\", \"middle\")\n .attr(\"transform\", \"rotate(-90)\")\n .text(\"Crime Type\")\n\n\n g.selectAll()\n .data(data, function(d) {return d.group+':'+d.variable;})\n .enter()\n .append(\"rect\")\n .attr(\"x\", function(d) {\n return xAxisRange(d.group) })\n .attr(\"y\", function(d) {\n return yAxisRange(d.variable) })\n .attr(\"rx\", 4)\n .attr(\"ry\", 4)\n .attr(\"width\", xAxisRange.bandwidth() )\n .attr(\"height\", yAxisRange.bandwidth() )\n .style(\"fill\", function(d) {\n return myColor(d.value)} )\n .style(\"stroke-width\", 4)\n .style(\"stroke\", \"none\")\n .style(\"opacity\", 0.8)\n .on(\"mousemove\", function(event, d){\n hMapTooltip\n .style(\"left\", event.pageX - 100 + \"px\")\n .style(\"top\", event.pageY - 90 + \"px\")\n .style(\"display\", \"inline-block\")\n .html(\"Crime Type: \" + (d.variable) + \"<br>Total Cases: \"+ numberFormat(d.value));\n })\n .on(\"mouseout\", function(d){ hMapTooltip.style(\"display\", \"none\");});\n\n}", "function sequence (csvData) {\n\tconsole.log(\"call sequence\");\n\t//recolor the map \n\td3.selectAll(\".hexbins\") //select every hexagon \n\t\t.style(\"fill\", function(d) { //color enumeration units \n\t\t\treturn choropleth(d, colorScale(csvData)); \n\t\t})\n\t\t\n}", "function visualise_heatmap(object) {\r\n\r\n\t//For heapmap drawing (AI recommendation) using plotly.js\r\n\tvar chartHeatMap = document.getElementById('chart_recommendation');\r\n\r\n\t//set the axis labels\r\n\tvar trends = object.trends;\r\n\tvar variances = object.variances;\r\n\r\n\t//set the frequencies for each bracket\r\n\tvar frequencies = [];\r\n\tfor (i = 0; i < variances.length; i++) {\r\n\t\tfrequencies.push(object.data[i]);\r\n }\r\n\r\n //declare the text showing when a mouse hover over a grid cell\r\n var textNew = [];\r\n\r\n //for each trend value\r\n for (i = 0; i < variances.length; i++) {\r\n\r\n //temporary array representing a list of values to be inserted\r\n var hover_text_info = [];\r\n\r\n //for each frequency value\r\n for (j = 0; j < object.data[i].length; j++) {\r\n\r\n //push in all information for showing for hover_text on heatmap\r\n hover_text_info.push('variance: '\r\n + String(variances[i])\r\n + '<br>trend: '\r\n + String(trends[j])\r\n + '<br>frequency: '\r\n + String(object.data[i][j]) );\r\n }\r\n\r\n //push the horizontal labelling in the hover_text on heatmap\r\n textNew.push(hover_text_info);\r\n }\r\n\r\n\t//find the bracket with maximum frequency\r\n\tvar maxFreq = 0;\r\n\tfor (i = 0; i < variances.length; i++) {\r\n\t\tif (maxFreq < Math.max(...frequencies[i])) {\r\n\t\t\tmaxFreq = Math.max(...frequencies[i]);\r\n\t\t}\r\n\t}\r\n\r\n\t//assign the ratio for logarithm function (we want the maximum value to be 100 in our heatmap)\r\n\tratioConversion = Math.pow(maxFreq, (1 / 100));\r\n\r\n\t//conversion using self-defined logarithm function\r\n\tfor ( i = 0; i < variances.length; i++ ) {\r\n\t\tfor ( j = 0; j < trends.length; j++ ) {\r\n\t\t\t//cannot apply logarithm function to a \"0\" as we cannot divide anything by 0\r\n if (frequencies[i][j] != 0)\r\n\r\n //modified to show colour (only)\r\n frequencies[i][j] = 100 + Math.log(frequencies[i][j]) / Math.log(ratioConversion);\r\n else\r\n //default frequencies (tho just for colour showing)\r\n frequencies[i][j] = 50\r\n }\r\n }\r\n\r\n\t// values on axis\r\n\tvar xValues = trends;\r\n\tvar yValues = variances;\r\n var zValues = frequencies;\r\n\r\n //set the colours to heatmap showing, intermediate colours will be filled automatically\r\n //simply reverse the order if we prefer the other way around\r\n\tvar colorscaleValue = [\r\n [0, '#ffffff'], // min\r\n\t\t[1, '#244749'] // max\r\n\t];\r\n\r\n //specify data for drawing heatmap\r\n\tvar data = [{\r\n\t\tx: xValues,\r\n\t\ty: yValues,\r\n\t\tz: zValues,\r\n type: 'heatmap',\r\n text: textNew,\r\n hoverinfo: 'text',\r\n\t\tcolorscale: colorscaleValue,\r\n showscale: false,\r\n\r\n //showing legend also requires a little plugin if needed\r\n\t\tshowlegend: true\r\n\t}];\r\n\r\n //set the layout for the heatmap\r\n\tvar layout = {\r\n\t\tannotations: [],\r\n\t\txaxis: {\r\n\t\t\tticks: '',\r\n\t\t\tside: 'bottom',\r\n title: 'Price Trend (%)',\r\n fixedrange: true,\r\n\r\n // set the font attributes\r\n titlefont: {\r\n family: 'Arial, serif',\r\n size: 14,\r\n color: 'black'\r\n },\r\n\r\n // change axis labels attributes\r\n showticklabels: true,\r\n tickangle: -45,\r\n tickfont: {\r\n family: 'Arial, serif',\r\n size: 12,\r\n color: '#808080',\r\n },\r\n\r\n // size: 11,\r\n // color: '#000000',\r\n // family: 'Arial, monospace',\r\n // autosize: false\r\n\t\t},\r\n\t\tyaxis: {\r\n\t\t\tticks: '',\r\n\t\t\tticksuffix: ' ',\r\n title: 'Variance (%)',\r\n fixedrange: true,\r\n\r\n // set the title font attributes\r\n titlefont: {\r\n family: 'Arial, serif',\r\n size: 14,\r\n color: 'black'\r\n },\r\n\r\n // change axis labels attributes\r\n showticklabels: true,\r\n // tickangle: 45,\r\n\r\n tickfont: {\r\n family: 'Arial, serif',\r\n size: 12,\r\n color: '#808080',\r\n },\r\n\r\n\t\t\t//please change the width and height for the div allocated\r\n width: 300,\r\n height: 250,\r\n\t\t\tautosize: false\r\n },\r\n\r\n //please also change the margin for appropriate presentation (frontend)\r\n margin:{\r\n l: 60,\r\n r: 20,\r\n b: 65,\r\n t: 0,\r\n pad: 4\r\n }\r\n\t};\r\n\r\n // Set init val to selected\r\n var prevIndex = [2,8]\r\n var prevVal = data[0].z[prevIndex[0]][prevIndex[1]];\r\n data[0].z[prevIndex[0]][prevIndex[1]] = 0\r\n\r\n\t//plot the heatmap and add onclick\r\n\tPlotly.newPlot('chart_recommendation', data, layout, { displayModeBar: false });\r\n chartHeatMap.on('plotly_click', onClick);\r\n\r\n // On-click function\r\n function onClick(clicked){\r\n\r\n //the values we needed to show stocks selected\r\n var clicked_x = clicked.points[0].x;\r\n var clicked_y = clicked.points[0].y;\r\n var clicked_z = clicked.points[0].z;\r\n\r\n // Reset old val and set new\r\n data[0].z[prevIndex[0]][prevIndex[1]] = prevVal;\r\n index = clicked.points[0].pointIndex;\r\n prevVal = data[0].z[index[0]][index[1]];\r\n data[0].z[index[0]][index[1]] = 0\r\n prevIndex = index;\r\n\r\n // Draw new plot\r\n Plotly.newPlot('chart_recommendation', data, layout, { displayModeBar: false })\r\n chartHeatMap.on('plotly_click', onClick);\r\n\r\n //update information on SVE\r\n graph_endpoint(clicked_y, clicked_x);\r\n };\r\n\r\n}", "function buildArtwork(columnCount, rowCount, chosenPalette, paddingOffset, density) {\n\n // Create Mask\n document.getElementById('svg').innerHTML += mask(columnCount, rowCount, paddingOffset)\n \n // Set grid stroke\n var gridColor = sample(chosenPalette.colors);\n\n // Set frequency based on artwork size and density\n var frequency = (rowCount * columnCount)*density;\n\n // Building full circles, generating arrays first to reduce duplicate coordinates.\n var fullCircleFrequency = frequency/10\n var fullCircleXList = [];\n for (var i = 0; i <= (columnCount-1); i++) {\n fullCircleXList.push(i)\n }\n var fullCircleYList = [];\n for (var i = 0; i <= (rowCount-1); i++) {\n fullCircleYList.push(i)\n }\n for (let i = 1; i < fullCircleFrequency; i++) {\n var x = sample(fullCircleXList);\n fullCircleXList.splice(x,1);\n var y = sample(fullCircleYList);\n fullCircleYList.splice(y,1);\n document.getElementById('svg').innerHTML += fullCircle(x, y, chosenPalette, paddingOffset);\n };\n\n // Building squares with multiply color mode\n var squareFrequency = frequency/6\n var squareXList = [];\n for (var i = 0; i <= (columnCount-1); i++) {\n squareXList.push(i)\n }\n var squareYList = [];\n for (var i = 0; i <= (rowCount-1); i++) {\n squareYList.push(i)\n }\n for (let i = 1; i < squareFrequency; i++) {\n var x = sample(squareXList);\n squareXList.splice(x,1);\n var y = sample(squareYList);\n squareYList.splice(y,1);\n document.getElementById('svg').innerHTML += square(x, y, chosenPalette, paddingOffset);\n };\n\n // Building quarter circles with multiply color mode\n var quarCirFrequency = frequency/6\n var quarCirXList = [];\n for (var i = 0; i <= (columnCount); i++) {\n quarCirXList.push(i)\n }\n var quarCirYList = [];\n for (var i = 0; i <= (rowCount); i++) {\n quarCirYList.push(i)\n }\n for (let i = 1; i < quarCirFrequency; i++) {\n var x = sample(quarCirXList);\n quarCirXList.splice(x,1);\n var y = sample(quarCirYList);\n quarCirYList.splice(y,1);\n document.getElementById('svg').innerHTML += quarCir(x, y, chosenPalette, paddingOffset);\n };\n\n // For each column\n for (let x = 0; x < columnCount; x++) {\n // For each row\n for (let y = 0; y < rowCount; y++) {\n // Build grid stroke\n document.getElementById('svg').innerHTML += grid(x, y, gridColor, paddingOffset); \n }\n }\n }", "function updateHeatmap() {\n let heatData = getHeatmapData();\n heatmapLayer.setData(heatData);\n heatmapLayer.setMap(incidentHeatmap);\n}", "_createCell(div, nodes, tooltipId) {\n const cell = div.selectAll('g')\n .data(nodes)\n .enter()\n .append('svg:g')\n .attr('class', 'heatmap-chart__cell')\n .attr('transform', d => `translate(${d.x},${d.y})`);\n\n // tooltip\n cell.on('mousemove', (d) => {\n if (d && d.role !== 'value') {\n return;\n }\n\n const tooltipWidth = 200;\n const xPosition = d3.event.pageX - (tooltipWidth + 20);\n const yPosition = d3.event.pageY + 5;\n\n d3.select(`${tooltipId}`)\n .style('left', xPosition + 'px')\n .style('top', yPosition + 'px');\n\n Object.keys(d).forEach(key => {\n d3.select(`${tooltipId} #${key}`).text(d[key]);\n });\n\n d3.select(`${tooltipId}`).classed('hidden', false);\n }).on('mouseout', function () {\n d3.select(`${tooltipId}`).classed('hidden', true);\n }).on('mousedown', function () {\n d3.select(`${tooltipId}`).classed('hidden', true);\n });\n\n // colored background\n cell.append('svg:rect')\n .attr('width', d => Math.max(d.dx - 1, 0))\n .attr('height', d => Math.max(d.dy - 1, 0))\n .style('fill', d => getBackgroundColor(d.actualValue, d.inverse));\n\n // colored text\n cell.append('svg:text')\n .attr('x', d => (d.dx / 2))\n .attr('y', d => (d.dy / 2))\n .attr('dy', '.35em')\n .attr('text-anchor', 'middle')\n .text((d) => {\n const text = d.label || '';\n\n //each character takes up 7 pixels on an average\n const estimatedTextLength = text.length * 7;\n if (estimatedTextLength > d.dx) {\n return text.substring(0, d.dx / 7) + '..';\n } else {\n return text;\n }\n })\n .style('fill', (d) => {\n // return default color for icons\n if (d.role !== 'value') {\n return 'rgba(0,0,0,0.45)';\n }\n return getTextColor(d.actualValue, d.inverse);\n });\n\n cell.on('click', get(this, 'includeHandler').bind(this));\n cell.on(\"contextmenu\", get(this, 'excludeHandler').bind(this));\n }", "static emptyHeatmapJson() {\n let max_time = 14*6; //14 hours in 10 minute increments\n let incrementLabels = []//new Array(max_time).fill(' ');\n let noon = 24; // 4*2*3 = 4 hours in 30 minute chunks\n let mins = ':00'\n for (let i = 0, hours = 8; i < max_time; i += 6) {\n let ampm = i < noon ? 'a': 'p';\n if (i && i % 6 == 0)\n hours = (hours % 12) + 1;\n\n //mins = i % 2 == 0 ? ':00' : ':30';\n incrementLabels.push(hours + mins + ampm);\n }\n \n let empty_heatmap = [...Array(max_time)].map(() => Array(5).fill(0));\n console.log(JSON.stringify(empty_heatmap));\n\n let heatmap_data = {\n init: \"init\",\n weekdayNames: [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\"],\n timeIncrements: incrementLabels,\n heatmap: empty_heatmap\n };\n return heatmap_data;\n }", "function _drawHeatmap(storm) {\n var renderLine = d3.svg.line()\n .x(function (d) { \n // console.log(\"d = \", d)\n return getPixels(d.location).x; \n })\n .y(function (d) { \n return getPixels(d.location).y;\n })\n .interpolate(\"cardinal\")\n\n // wrap each storm in a 'g' tag with the name set\n var g = svg.append(\"g\").attr(\"name\", storm.name).attr(\"class\", \"storm\")\n\n g.selectAll(\"path\")\n .data(chunk(storm.data))\n .enter()\n .append(\"path\")\n .attr(\"d\", function (d) {\n // console.log(\"drawing a line for datum d = \", d)\n return renderLine(d);\n })\n .attr(\"stroke\", function (d) {\n return interp(d[0].maxWind / MAX_WIND);\n })\n .attr(\"stroke-width\", function (d) {\n return d[0].maxWind / MAX_WIND * 5\n }).on(\"mouseover\", function(d) {\n renderTooltip(storm);\n g.selectAll(\"path\")\n .attr(\"stroke\", function(d) {\n return interpOther(d[0].maxWind / MAX_WIND);\n })\n }).on(\"mouseout\", function(d) {\n clearTooltip();\n g.selectAll(\"path\")\n .attr(\"stroke\", function(d) {\n return interp(d[0].maxWind / MAX_WIND);\n })\n });\n }", "function displayImg(){\n\t\t\t\t\n\t\tvar notes = ['A', 'Bb', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'];\n\n\t\t//Letters denotes the notes on each string. number denotes the the height in pixels a green dot should be in order to be placed on its string.\n\t\t//* '0' means an 'open string', in this case the green dot doesn't show.\n\t\t//** The height slightly changes along strings1+string4 because they have a small angel. \n\t\tvar string1 = [['A', 0], ['Bb', 170], ['B', 170], ['C', 170], ['C#', 170], ['D', 172], ['D#', 172], ['E', 174], ['F', 174], ['F#', 175], ['G', 175], ['G#', 176]];\n\t\tvar string2 = [['E', 0], ['F', 167], ['F#', 167], ['G', 167], ['G#', 167],['A', 167], ['Bb', 167], ['B', 167], ['C', 167], ['C#', 167], ['D', 167], ['D#', 167]];\n\t\tvar string3 = [['C', 0], ['C#', 165], ['D', 165], ['D#', 165], ['E', 165], ['F', 165], ['F#', 165], ['G', 165], ['G#', 165], ['A', 165], ['Bb', 165], ['B', 165]];\n\t\tvar string4 = [['G', 0], ['G#', 161], ['A', 161], ['Bb', 161], ['B', 161], ['C', 159], ['C#', 159], ['D', 157], ['D#', 157], ['E', 156], ['F', 156], ['F#', 155]];\n\n\t\tvar chord1 = document.getElementById('chordSelect1').value;\n\t\tvar chord2 = document.getElementById('chordSelect2').value;\n\n\n\t\tvar dot1 = document.getElementById('greenDot1');\n\t\tvar dot2 = document.getElementById('greenDot2');\n\t\tvar dot3 = document.getElementById('greenDot3');\n\t\tvar dot4 = document.getElementById('greenDot4');\n\n\t\t//When a chord is chosen the function findChord return an array with the notes of the chord\n\t\t//The function placeDot use the findChord array to place the dots\n\t\tif (chord1 != \"-\" && chord2 != \"-\"){\n\t\t\tvar chordparts = findChord(notes, chord1, chord2);\n\n\t\t\tvar p = Number(document.getElementById('position').value);\n\n\t\t\tplaceDot (string1, chordparts, dot1, p);\n\t\t\tplaceDot (string2, chordparts, dot2, p);\n\t\t\tplaceDot (string3, chordparts, dot3, p);\n\t\t\tplaceDot (string4, chordparts, dot4, p);\n\t\t}\n\n\t}", "function displayChord () {\n const { notes, frets } = getNoteFretPairs();\n const { minFret, chordLength } = getFretRange(frets);\n\n // Initializes the diagram\n const c = document.getElementById('fretboard');\n c.height = chordLength * 60 + 160;\n c.width = 300;\n const brush = c.getContext('2d');\n\n // Sets the fill color to be brown\n brush.fillStyle = '#670A0A';\n brush.clearRect(0, 0, c.width, c.height);\n brush.fillRect(51, 51, 199, c.height - 101);\n\n drawFretboardMarkers(brush, minFret, chordLength);\n drawFrets(brush, c.height);\n drawStrings(brush, c.height);\n drawNut(brush);\n drawNotes(brush, frets, notes, minFret);\n labelMinFret(brush, minFret);\n }", "function setUpHeatMap(rasterSize, container){\n const size = 100 / rasterSize + \"%\";\n\n container.empty();\n for(let y = 0; y < rasterSize; y++){\n for(let x = 0; x < rasterSize; x++){\n container.append(' <div id=\"containerX' + x + 'Y' + y + '\" class=\"heatMapContainer waves-effect waves-teal\" data-x=\"' + x + '\" data-y=\"' + y + '\" data-temperature=\"\" style=\"height:' + size + ' ;width: ' + size + ';\"></div>')\n }\n container.append('<div class=\"clearfix\"></div>');\n }\n}", "function legendDraw(){\n\n let legWidth = Math.min($(\"#heat-legend\").width(),300);\n let gridSize = legWidth/10;\n\n\n //// Heatmap legend\n var x = [0,20,40,60,80,100];\n\n // set colormap (color varies from white to steelblue)\n let color_heat = d3v5.scaleSequential(\n d3v5.interpolateBlues//function(t) { return d3v5.interpolate(\"white\", \"steelblue\")(t); }\n )\n .domain([0, 1]);\n\n // Collect legend characteristics\n heat_legend = new Array();\n for(ii=0 ; ii<x.length; ii++){\n heat_legend.push({\n x: (gridSize+5)*(ii+1) ,\n y: 0,\n width: gridSize,\n height: gridSize,\n fill:color_heat(x[ii]/100),\n label: x[ii]+\"%\"\n })\n }\n\n // Draw legend svg\n let legend = d3v4.select(\"#heat-legend\").append(\"svg\")\n .attr(\"width\",legWidth )\n .attr(\"height\", legWidth/5)\n .append(\"g\");\n\n // Colors\n legend.selectAll('rect')\n .data(heat_legend)\n .enter().append('rect')\n .attr(\"x\", function(d) { return d.x; })\n .attr(\"y\", function(d) { return d.y; })\n .attr(\"width\", function(d) { return d.width; })\n .attr(\"height\", function(d) { return d.height; })\n .attr('fill',function(d){return d.fill});\n\n // Values\n legend.selectAll('text')\n .data(heat_legend)\n .enter().append('text')\n .attr(\"x\", function(d) { return (d.x+gridSize/2); })\n .attr(\"y\", function(d) { return (d.y+gridSize*3/2); })\n .attr(\"text-anchor\",\"middle\")\n .attr(\"alignment-baseline\",\"middle\")\n .attr(\"font-size\",\"10\")\n .text(function(d) {return d.label;});\n\n //// Cluster Number Legend\n //// Cluster legend\n let radWidth = Math.min($(\"#cluster-legend\").width(),50);\n let circleEx = d3v4.select(\"#cluster-legend\").append(\"svg\")\n .attr(\"width\",legWidth )\n .attr(\"height\", radWidth);\n\n circleEx.append(\"circle\")\n .attr(\"cx\", gridSize*1.5)\n .attr(\"cy\", radWidth/2)\n .attr(\"r\", radWidth/3)\n .attr('fill',\"#343a40\");\n\n circleEx.append(\"text\")\n .attr(\"x\", gridSize*1.5)\n .attr(\"y\", radWidth/2)\n .attr(\"fill\",\"#F0F8FF\")\n .attr(\"alignment-baseline\",\"middle\")\n .attr(\"text-anchor\",\"middle\")\n .attr(\"font-size\",\"12\")\n .text(\"38\");\n}", "function load(e) {\n //console.log(e);\n //var tile = e.tile, g = tile.element;\n // var bigness = Math.pow(2, e.tile.zoom);\n // var smallness = 1.0 / bigness;\n // for (let x = 0; x < 255; x++) {\n // for (let y = 0; y < 255; y++) {\n //\n // //var q = doNoise(x * smallness, y * smallness, tile.row, tile.column, 1000000 * smallness, 1);\n // //if(x==0)\n // // console.log(q);\n // //console.log(q);\n // if ( Math.random() > 0.9999) {\n // var point = g.appendChild(po.svg(\"image\"));\n // point.setAttribute(\"width\", 0.0125 * bigness);\n // point.setAttribute(\"x\", Math.random() * 255);\n // point.setAttribute(\"y\", Math.random() * 255);\n // point.setAttribute(\"height\", 0.012g5 *bigness);\n // //var url = \"https://images.vexels.com/media/users/3/127601/isolated/lists/4874bc2389e71df4c479ad933b12226a-elliptical-tree-icon.png\";\n // //var url = \"https://cdn0.iconfinder.com/data/icons/simple-flat-colored-trees/100/Tree_green_circle_branches-512.png\";\n // var url = \"https://cdn0.iconfinder.com/data/icons/pixelo/32/tree.png\";\n // //var url = \"https://image.flaticon.com/icons/png/128/72/72223.png\";\n // point.setAttribute(\"href\", url);\n // }\n // }\n // }\n\n //point.setAttribute(\"fill\", \"url(\\\"https://d1nhio0ox7pgb.cloudfront.net/_img/g_collection_png/standard/64x64/tree.png\\\")\");\n //point.setAttribute(\"fill\", \"red\");\n\n}", "renderSeeds() {\n for (let j = 0; j < 6; j++) {\n let element = document.querySelector('#h' + j);\n let integer = parseInt(element.innerText);\n for(let i = 0; i < integer; i++) {\n const div = document.createElement('div');\n div.style.cssText = 'height: 10px; width: 10px; background-color: #F6F5FD; margin: 5px; border-radius: 50%; display; inline; float: left;';\n element.append(div);\n }\n }\n for (let h = 0; h < 6; h++) {\n let element = document.querySelector('#h' + h);\n element.removeChild(element.childNodes[0]);\n }\n for (let jj = 7; jj < 13; jj++) {\n let element = document.querySelector('#h' + jj);\n let integer = parseInt(element.innerText);\n for(let ii = 0; ii < integer; ii++) {\n const div = document.createElement('div');\n div.style.cssText = 'height: 10px; width: 10px; background-color: #F6F5FD; margin: 5px; border-radius: 50%; display; inline; float: left;';\n element.append(div);\n }\n }\n for (let hh = 7; hh < 13; hh++) {\n let element = document.querySelector('#h' + hh);\n element.removeChild(element.childNodes[0]);\n }\n\n }", "function displayCells (cells, settings) {\n var size = settings.cellSize;\n var cells = settings.worldSVG\n .selectAll('circle')\n .data(cells, function (d) { return d; })\n\n cells.enter()\n .append('circle')\n .attr('class', 'cell')\n .attr('r', size / 2 + 'px')\n .attr('cx', function (d) { return settings.scale(d[0]) + 'px'; })\n .attr('cy', function (d) { return settings.scale(d[1]) + 'px'; })\n .style('fill', '#45e')\n\n cells.exit()\n .remove();\n}", "function spiralHeatmap () {\n // constants\n const radians = 0.0174532925\n\n // All options that are accessible to caller\n // Default values\n var radius = 250\n var holeRadiusProportion = 0.3 // proportion of radius\n var arcsPerCoil = 12 // assuming months per year\n var coilPadding = 0 // no padding\n var arcLabel = '' // no labels\n var coilLabel = '' // no labels\n var startAngle = 0 //starts at 12 o'clock\n\n function chart (selection) {\n selection.each(function (data) {\n const arcAngle = 360 / arcsPerCoil\n const labelRadius = radius + 20\n\n var arcLabelsArray = []\n\n for (var i = 0; i < arcsPerCoil; i++) {\n arcLabelsArray.push(i)\n }\n\n\n\n // Create/update the x/y coordinates for the vertices and control points for the paths\n // Stores the x/y coordinates on the data\n updatePathData(data)\n\n let thisSelection = d3\n .select(this)\n .append('g')\n .attr('class', 'spiral-heatmap')\n\n var arcLabelsG = thisSelection\n .selectAll('.arc-label')\n .data(arcLabelsArray)\n .enter()\n .append('g')\n .attr('class', 'arc-label')\n\n arcLabelsG\n .append('text')\n .text(function (d) {\n return data[d][arcLabel]\n })\n .attr('x', function (d, i) {\n let labelAngle = i * arcAngle + arcAngle / 2\n return x(labelAngle, labelRadius)\n })\n .attr('y', function (d, i) {\n let labelAngle = i * arcAngle + arcAngle / 2\n return y(labelAngle, labelRadius)\n })\n .style('text-anchor', function (d, i) {\n return i < arcLabelsArray.length / 2 ? 'start' : 'end'\n })\n\n arcLabelsG\n .append('line')\n .attr('x2', function (d, i) {\n let lineAngle = i * arcAngle\n let lineRadius = radius + 10\n return x(lineAngle, lineRadius)\n })\n .attr('y2', function (d, i) {\n let lineAngle = i * arcAngle\n let lineRadius = radius + 10\n return y(lineAngle, lineRadius)\n })\n\n var arcs = thisSelection\n .selectAll('.arc')\n .data(data)\n .enter()\n .append('g')\n .attr('class', 'arc')\n\n arcs.append('path').attr('d', function (d) {\n // start at vertice 1\n let start = 'M ' + d.x1 + ' ' + d.y1\n // inner curve to vertice 2\n let side1 =\n ' Q ' +\n d.controlPoint1x +\n ' ' +\n d.controlPoint1y +\n ' ' +\n d.x2 +\n ' ' +\n d.y2\n // straight line to vertice 3\n let side2 = 'L ' + d.x3 + ' ' + d.y3\n // outer curve vertice 4\n let side3 =\n ' Q ' +\n d.controlPoint2x +\n ' ' +\n d.controlPoint2y +\n ' ' +\n d.x4 +\n ' ' +\n d.y4\n // combine into string, with closure (Z) to vertice 1\n return start + ' ' + side1 + ' ' + side2 + ' ' + side3 + ' Z'\n })\n\n // create coil labels on the first arc of each coil\n if (coilLabel != '') {\n coilLabels = arcs\n .filter(function (d) {\n return d.arcNumber == 0\n })\n .raise()\n\n coilLabels\n .append('path')\n .attr('id', function (d) {\n return 'path-' + d[coilLabel]\n })\n .attr('d', function (d) {\n // start at vertice 1\n let start = 'M ' + d.x1 + ' ' + d.y1\n // inner curve to vertice 2\n let side1 =\n ' Q ' +\n d.controlPoint1x +\n ' ' +\n d.controlPoint1y +\n ' ' +\n d.x2 +\n ' ' +\n d.y2\n return start + side1\n })\n .style('opacity', 0)\n\n coilLabels\n .append('text')\n .attr('class', 'coil-label')\n .attr('x', 3)\n .attr('dy', -4)\n .append('textPath')\n .attr('xlink:href', function (d) {\n return '#path-' + d[coilLabel]\n })\n .text(function (d) {\n return d[coilLabel]\n })\n }\n })\n\n function updatePathData (data) {\n let holeRadius = radius * holeRadiusProportion\n let arcAngle = 360 / arcsPerCoil\n let dataLength = data.length\n let coils = Math.ceil(dataLength / arcsPerCoil) // number of coils, based on data.length / arcsPerCoil\n let coilWidth = radius * (1 - holeRadiusProportion) / (coils + 1) // remaining radius (after holeRadius removed), divided by coils + 1. I add 1 as the end of the coil moves out by 1 each time\n\n data.forEach(function (d, i) {\n let coil = Math.floor(i / arcsPerCoil)\n let position = i - coil * arcsPerCoil\n let startAngle = position * arcAngle\n let endAngle = (position + 1) * arcAngle\n let startInnerRadius = holeRadius + i / arcsPerCoil * coilWidth\n let startOuterRadius =\n holeRadius +\n i / arcsPerCoil * coilWidth +\n coilWidth * (1 - coilPadding)\n let endInnerRadius = holeRadius + (i + 1) / arcsPerCoil * coilWidth\n let endOuterRadius =\n holeRadius +\n (i + 1) / arcsPerCoil * coilWidth +\n coilWidth * (1 - coilPadding)\n\n // vertices of each arc\n d.x1 = x(startAngle, startInnerRadius)\n d.y1 = y(startAngle, startInnerRadius)\n d.x2 = x(endAngle, endInnerRadius)\n d.y2 = y(endAngle, endInnerRadius)\n d.x3 = x(endAngle, endOuterRadius)\n d.y3 = y(endAngle, endOuterRadius)\n d.x4 = x(startAngle, startOuterRadius)\n d.y4 = y(startAngle, startOuterRadius)\n\n // CURVE CONTROL POINTS\n let midAngle = startAngle + arcAngle / 2\n let midInnerRadius =\n holeRadius + (i + 0.5) / arcsPerCoil * coilWidth\n let midOuterRadius =\n holeRadius +\n (i + 0.5) / arcsPerCoil * coilWidth +\n coilWidth * (1 - coilPadding)\n\n // MID POINTS, WHERE THE CURVE WILL PASS THRU\n d.mid1x = x(midAngle, midInnerRadius)\n d.mid1y = y(midAngle, midInnerRadius)\n d.mid2x = x(midAngle, midOuterRadius)\n d.mid2y = y(midAngle, midOuterRadius)\n\n d.controlPoint1x = (d.mid1x - 0.25 * d.x1 - 0.25 * d.x2) / 0.5\n d.controlPoint1y = (d.mid1y - 0.25 * d.y1 - 0.25 * d.y2) / 0.5\n d.controlPoint2x = (d.mid2x - 0.25 * d.x3 - 0.25 * d.x4) / 0.5\n d.controlPoint2y = (d.mid2y - 0.25 * d.y3 - 0.25 * d.y4) / 0.5\n\n d.arcNumber = position\n d.coilNumber = coil\n })\n\n return data\n }\n\n function x (angle, radius) {\n // change to clockwise\n let a = 360 - angle\n // start from 12 o'clock\n a = a + 180 - startAngle;\n return radius * Math.sin(a * radians)\n }\n\n function y (angle, radius) {\n // change to clockwise\n let a = 360 - angle\n // start from 12 o'clock\n a = a + 180 - startAngle;\n return radius * Math.cos(a * radians)\n }\n\n function chartWH (r) {\n return r * 2\n }\n }\n\n chart.radius = function (value) {\n if (!arguments.length) return radius\n radius = value\n return chart\n }\n\n chart.holeRadiusProportion = function (value) {\n if (!arguments.length) return holeRadiusProportion\n holeRadiusProportion = value\n return chart\n }\n\n chart.arcsPerCoil = function (value) {\n if (!arguments.length) return arcsPerCoil\n arcsPerCoil = value\n return chart\n }\n\n chart.coilPadding = function (value) {\n if (!arguments.length) return coilPadding\n coilPadding = value\n return chart\n }\n\n chart.arcLabel = function (value) {\n if (!arguments.length) return arcLabel\n arcLabel = value\n return chart\n }\n\n chart.coilLabel = function (value) {\n if (!arguments.length) return coilLabel\n coilLabel = value\n return chart\n }\n \n chart.startAngle = function (value) {\n if (!arguments.length) return startAngle\n startAngle = value\n return chart\n }\n\n return chart\n}", "function drawChromosomes(gffData) {\n\tcorrectGff(gffData);\n\tvar length = gffData.length;\n\tvar chr=1;\n\tvar chromosome = gffData[0][0];\n\tfor (var i=0; i< length; i++) {\n\t\tvar current = gffData[i][0]; \n\t\tif (chromosome !== current) {\n\t\t\tchromosome = current;\n\t\t\tchr++;\n\t\t} else {\n\t\t\tchromosome = current;\n\t\t}\n\t}\n\tconsole.log(\"the number is : \", chr);\n\t//Create SVG element\n\tvar y1= 0;\n\tvar lmjfCurrent;\n\tvar lmjfBefore = gffData[0][0][gffData[0][0].length-2] + gffData[0][0][gffData[0][0].length-1];\n\tvar svg = d3.select(\"div#svgGff\")\n .append(\"svg\")\n .attr(\"width\", 3000)\n .attr(\"height\", 3500);\n\n //Drawing the lines :\n var ch = [];\n ch.length = chr;\n svg.selectAll(\"line\")\n \t.data(ch)\n \t.enter()\n \t.append(\"line\")\n \t.attr(\"x1\",60)\n \t.attr(\"y1\" , function (d, i) {\n \t\treturn i * (3000/chr) + 10;\n \t})\n \t.attr(\"x2\", function (d, i) {\n \t\treturn 60 + l_major_chr_length[i]/500;\n \t})\n \t.attr(\"y2\", function (d, i) {\n \t\treturn i * (3000/chr) + 10;\n \t})\n \t.attr(\"stroke\",\"black\")\n \t.attr(\"strokeWidth\",\"10px\");\n\n //Writing some labels :\n svg.selectAll(\"text\")\n \t.data(ch)\n \t.enter()\n \t.append(\"text\")\n \t.text( function (d, i) {\n \t\treturn \"\" + (i+1); \n \t})\n \t.attr(\"x\",10) \n \t.attr(\"y\", function (d, i){\n \t\treturn i * (3000/chr) + 10;\n \t})\n \t.attr(\"font-family\", \"century\")\n \t\t.attr(\"font-size\", \"15px\")\n \t\t.classed(\"text\", true)\n\n //Drawing the CDS position in a shape of circles\n svg.selectAll(\"circle\")\n \t.data(gffData)\n \t.enter()\n \t.append(\"circle\")\n \t.classed('circle',true)\n \t.attr(\"id\", function (d,i) {\n \t\treturn i;\n \t})\n \t.attr(\"cx\", function (data) {\n \t\tlmjfCurrent = data[0][data[0].length -2] + data[0][data[0].length -1];\n \t\treturn (60 + data[2]/500);\n \t})\n \t.attr('cy', function (data) {\n \t\tlmjfCurrent = data[0][data[0].length -2] + data[0][data[0].length -1];\n \t\tif (lmjfCurrent === lmjfBefore) {\n \t\t\t// console.log(\"y1 =\", y1);\n \t\t\tlmjfBefore = lmjfCurrent;\n \t\t\treturn y1 * (3000/chr) + 10\n \t\t} else {\n \t\t\tlmjfBefore = lmjfCurrent;\n \t\t\t// console.log(\"they are not equal anymore !!\")\n \t\t\ty1++;\n \t\t\treturn y1 * (3000/chr) + 10;\n \t\t}\n \t})\n \t.attr('r', function (data) {\n \t\treturn (((data[3]- data[2])/2)/500);\n\t\t})\n\t\t.attr(\"fill\", function(data) {\n\t\t\tr= ((data[3]- data[2])/2)/500\n\t\t\tif ((r> 0) && (r<=15)) {\n\t\t\t\treturn \"yellow\"\n\t\t\t} else if ((r>15)&& (r<=25)) {\n\t\t\t\treturn \"orange\"\n\t\t\t}else if (r>25) {\n\t\t\t\treturn \"red\"\n\t\t\t}\n\t\t})\n \n //Description of the circles : \n y1=0;\n lmjfBefore = gffData[0][0][gffData[0][0].length-2] + gffData[0][0][gffData[0][0].length-1];\n \n \t $('svg circle').tipsy({ \n\t gravity: 'w', \n\t html: true, \n\t title: function() {\n\t var d = this.__data__;\n \t\t var newArray = d[4].split(';')\n\t // console.log(\"the data is d = :\", d);\n\t debugger;\n\t return newArray[0] + '<br>' + newArray[1] + '<br>' + newArray[2] + '<br>' + newArray[3] + '<br>' + newArray[4]\n\t + '</span>'; \n\t }\n });\n}", "function generateHeatmap(data) {\n const svMin = 30;\n const svMax = 100;\n const hue = 204;\n\n if (!data.length) return [rgb2hex(...hsv2rgb(hue, svMin / 100, svMax / 100))];\n\n const sortedData = data.toSorted((a, b) => a - b);\n const dataMin = sortedData[0];\n const dataMax = sortedData[sortedData.length - 1];\n return sortedData.map((datum) => {\n const fractionalPos =\n datum === 0 ? 0 : (datum - dataMin) / (dataMax - dataMin);\n const offset = (svMax - svMin) * fractionalPos;\n const sat = (svMin + offset) / 100;\n const val = (svMax - offset) / 100;\n return rgb2hex(...hsv2rgb(hue, sat, val));\n });\n}", "function drawMap(dataColumn) {\r\n var valueById = d3.map();\r\n \r\n data.forEach(function(d) {\r\n var id = name_id_map[d[config.state]];\r\n valueById.set(id, +d[dataColumn]); \r\n });\r\n // Get the domain from the data set for setting up the color scale\r\n quantize.domain([d3.min(data, function(d){ return +d[dataColumn] }),\r\n d3.max(data, function(d){ return +d[dataColumn] })]);\r\n \r\n // Draw the states\r\n g.selectAll(\"path\")\r\n .data(topojson.feature(us, us.objects.states).features)\r\n .enter().append(\"path\")\r\n .attr(\"class\", \"feature\")\r\n // .attr(\"transform\", \"scale(\" + SCALE + \")\")\r\n // .on(\"click\", clicked)\r\n .style(\"fill\", function(d) {\r\n return quantize(valueById.get(d.id)); // fill color based on number of petitions filed\r\n }\r\n )\r\n .attr(\"d\", path)\r\n .on(\"mousemove\", function(d) { // tooltip\r\n var html = \"\";\r\n \r\n html += \"<div class=\\\"tooltip_kv\\\">\";\r\n html += \"<span class=\\\"tooltip_key\\\">\";\r\n html += id_name_map[d.id];\r\n html += \"</span>\";\r\n html += \"</div>\";\r\n \r\n for (var i = 0; i < Object.keys(data[0]).length -1 ; i++) {\r\n html += \"<div class=\\\"tooltip_kv\\\">\";\r\n html += \"<span class='tooltip_key'>\";\r\n html += Object.keys(data[0])[i];\r\n html += \"</span>\";\r\n html += \"<span class=\\\"tooltip_value\\\">\";\r\n html += (dataMap[id_name_map[d.id]][Object.keys(data[0])[i]]);\r\n html += \"\";\r\n html += \"</span>\";\r\n html += \"</div>\";\r\n }\r\n \r\n $(\"#tooltip-container\").html(html);\r\n $(this).attr(\"fill-opacity\", \"0.7\");\r\n $(\"#tooltip-container\").show();\r\n \r\n var coordinates = d3.mouse(this);\r\n \r\n var map_width = $('.feature')[0].getBoundingClientRect().width;\r\n \r\n if (d3.event.layerX < map_width / 2) {\r\n d3.select(\"#tooltip-container\")\r\n .style(\"top\", (d3.event.layerY + 15) + \"px\")\r\n .style(\"left\", (d3.event.layerX + 15) + \"px\");\r\n } else {\r\n var tooltip_width = $(\"#tooltip-container\").width();\r\n d3.select(\"#tooltip-container\")\r\n .style(\"top\", (d3.event.layerY + 15) + \"px\")\r\n .style(\"left\", (d3.event.layerX - tooltip_width - 30) + \"px\");\r\n }\r\n })\r\n .on(\"mouseout\", function() {\r\n $(this).attr(\"fill-opacity\", \"1.0\");\r\n $(\"#tooltip-container\").hide();\r\n });\r\n // draw the states mesh\r\n g.append(\"path\")\r\n .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))\r\n .attr(\"class\", \"mesh\")\r\n // .attr(\"transform\", \"scale(\" + SCALE + \")\")\r\n .attr(\"d\", path);\r\n }", "function initTTCHeatMap() \n{\n ttcMap = new google.maps.Map(document.getElementById('ttcMap'), {\n zoom: 11,\n center: {lat: 43.744385, lng: -79.406937},// center: {lat: 37.775, lng: -122.434},\n mapTypeId: 'satellite'\n });\n\n //Setup ttc heatmap. Shows ttc vehicles as each indivitual point\n ttcHeatmap = new google.maps.visualization.HeatmapLayer({\n data: ttcVehicleLocations,\n map: ttcMap\n });\n\n\n // Settings for each zoom level\n ttcMap.addListener('zoom_changed', function() \n {\n var zoomLevel = ttcMap.getZoom();\n console.log(\"ttc radius is: \", ttcHeatmap.get('radius'));\n if(zoomLevel == 10)\n {\n console.log(\"Change concentration settings. Zoom level is: \", ttcMap.getZoom());\n ttcHeatmap.setOptions({\n dissipating: true,\n maxIntensity: 7,\n radius: 6,\n opacity: 0.7\n //dissipating: false\n });\n }\n\n else if(zoomLevel == 9)\n {\n console.log(\"Change concentration settings. Zoom level is: \", ttcMap.getZoom());\n ttcHeatmap.setOptions({\n dissipating: true,\n maxIntensity: 7,\n radius: 4,\n opacity: 0.7\n //dissipating: false\n });\n }\n else if(zoomLevel == 8)\n {\n console.log(\"Change concentration settings. Zoom level is: \", ttcMap.getZoom());\n ttcHeatmap.setOptions({\n dissipating: true,\n maxIntensity: 8,\n radius: 2,\n opacity: 0.9\n //dissipating: false\n });\n }\n\n else if(zoomLevel == 7)\n {\n console.log(\"Change settings. Zoom level is: \", ttcMap.getZoom());\n ttcHeatmap.setOptions({\n dissipating: true,\n maxIntensity: 10,\n radius: 1,\n opacity: 0.9\n //dissipating: false\n });\n }\n else if(zoomLevel < 7)\n {\n console.log(\"Change concentration settings. Zoom level is: \", ttcMap.getZoom());\n ttcHeatmap.setOptions({\n dissipating: true,\n maxIntensity: 10,\n radius: 0.5\n //dissipating: false\n });\n }\n else//This is default view. Todo: Find the best one here\n {\n console.log(\"Change settings. Zoom level is: \", ttcMap.getZoom());\n ttcHeatmap.setOptions({\n dissipating: true,\n maxIntensity: 4,\n radius: null,\n opacity: null\n //dissipating: false\n });\n }\n });\n}", "function generateRandomHexMap(numColumns, numRows) {\n var cells = [];\n for (var x = 0; x < numColumns; x++) {\n for (var y = 0; y < numRows; y++) {\n var color = randomTile();\n var cell = { \"x\": x, \"y\": y, \"data\": { \"color\": color } };\n cells.push(cell);\n }\n }\n return cells;\n}", "function buildArtwork(columnCount, rowCount, chosenPalette, paddingOffset, density) {\n\n // Create Mask\n document.getElementById('svg').innerHTML += mask(columnCount, rowCount, paddingOffset)\n\n // For each column\n for (let x = 0; x < columnCount; x++) {\n // For each row\n for (let y = 0; y < rowCount; y++) {\n\n // Randomly select artwork type\n var shapeSelection = getRandomInt(0, 7);\n\n // IF 0 draw a chip set0\n if (shapeSelection === 0) {\n document.getElementById('svg').innerHTML += chipSet0(x, y, chosenPalette, paddingOffset);\n }\n\n // IF 1 draw a chip set1\n if (shapeSelection === 1) {\n document.getElementById('svg').innerHTML += chipSet1(x, y, chosenPalette, paddingOffset);\n }\n\n // IF 2 draw a chip set2\n if (shapeSelection === 2) {\n document.getElementById('svg').innerHTML += chipSet2(x, y, chosenPalette, paddingOffset);\n }\n\n // IF 3 draw a chip set3\n if (shapeSelection === 3) {\n document.getElementById('svg').innerHTML += chipSet3(x, y, chosenPalette, paddingOffset);\n }\n\n // IF 4 draw a chip set4\n if (shapeSelection === 4) {\n document.getElementById('svg').innerHTML += chipSet4(x, y, chosenPalette, paddingOffset);\n }\n\n // IF 5 draw a chip set5\n if (shapeSelection === 5) {\n document.getElementById('svg').innerHTML += chipSet5(x, y, chosenPalette, paddingOffset);\n }\n\n // IF 6 draw a chip set6\n if (shapeSelection === 6) {\n document.getElementById('svg').innerHTML += chipSet6(x, y, chosenPalette, paddingOffset);\n }\n\n // IF 7 draw a chip set7\n if (shapeSelection === 7) {\n document.getElementById('svg').innerHTML += chipSet7(x, y, chosenPalette, paddingOffset);\n }\n\n }\n }\n\n // Remove streamers based on density\n var numOfPaths = document.getElementById('svg').querySelectorAll('path').length;\n var numOfPathsToRemove = Math.round(numOfPaths - (numOfPaths * density));\n if (density === 0) {\n Array.prototype.forEach.call( document.getElementById('svg').querySelectorAll('path'), function( node ) {\n node.parentNode.removeChild( node );\n });\n }\n else {\n for (let i = 0; i < numOfPathsToRemove; i++) {\n var randomPath = getRandomInt(1, numOfPaths - 1)\n document.getElementById('svg').querySelectorAll('path')[randomPath].remove();\n var numOfPaths = numOfPaths - 1;\n }\n }\n }", "function updateDistanceHeatmapContainer(dataAll) {\n\n\td3.select(\"#container\").selectAll('svg').remove();\n\td3.select(\"#container\").selectAll('div').remove();\n\n\tvar createScatterPlotFlag = true;\n\t// temp trend type used to store the previous trend type\n\tvar tempTrendType = \"\";\n\n\tfor (var key in dataAll){\n\t\tdata = dataAll[key];\n\t\theatmapMatrix = jsonto2darray(data.heatmap);\n\n\t\tgroupInfo = {'groupby': data.splitby, 'value': data.subgroup}\n\n\t\tif (data.detail_view_type == 'scatter') {\t\n\t\t\t\n\t\t\trowLabels = [];\n\t\t\tcolLabels = [];\n\n\t\t\t// get rows' labels\n\t\t\tfor (var rowkey in data.heatmap) {\n\t\t\t\trowLabels.push(rowkey);\n\t\t\t}\n\n\t\t\t// get columns' lables\n\t\t\tvar first_row = data.heatmap[Object.keys(data.heatmap)[0]];\n\t\t\tfor (var colkey in first_row) {\n\t\t\t\tcolLabels.push(colkey);\n\t\t\t}\n\n\t\t\tmatrix_data = UpdateLinearRegressionMatrixFormat(heatmapMatrix, rowLabels, \n\t\t\t\t\t\t\t\t\t\t\t\t\tcolLabels, groupInfo, data.trend_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata.detail_view_type);\n\n\t\t\tif (createScatterPlotFlag) {\n\t\t\t\t// Scatter plot\n\t\t\t\tcatAttrs = data.splitby;\n\t\t\t\tconAttrs = [];\n\t\t\t\tconAttrs.push(rowLabels[0]);\n\t\t\t\tconAttrs.push(colLabels[0]);\t\t\t\t\n\t\t\t\tcreateScatterplot(csvData);\n\t\t\t\tcreateScatterPlotFlag = false;\n\t\t\t}\n\n\t\t} else if (data.detail_view_type == 'rank') {\n\t\t\tvar pushFlag = true;\n\t\t\trowLabels = [];\n\t\t\tcolLabels = [];\n\t\t\t\n\t\t\tfor (var rowkey in data.heatmap) {\n\t\t\t\trow = data.heatmap[rowkey];\n\n\t\t\t\t// Using the first row to set the columns' labels\n\t\t\t\tif (pushFlag) {\n\t\t\t\t\tfor (var colKey in row) {\n\t\t\t\t\t\tcolLabels.push(colKey);\n\t\t\t\t\t}\n\t\t\t\t\tpushFlag = false;\n\t\t\t\t}\n\t\t\n\t\t\t\trowLabels.push(rowkey);\n\t\t\t}\n\n\t\t\tmatrix_data = UpdateRankTrendMatrixFormat(\n\t\t\t\t\t\t\t\theatmapMatrix, rowLabels, colLabels, \n\t\t\t\t\t\t\t\tgroupInfo, data.trend_type, data.detail_view_type);\n\t\t}\n\n\t\t// if a new trend type, draw the title for new trend type \n\t\tif (data.trend_type != tempTrendType) {\n\t\t\tdrawTrendDisplayName(data.trend_display_name);\n\t\t\ttempTrendType = data.trend_type;\n\t\t}\n\n\t\tdistanceMatrixHeatmap({\n\t\t\tcontainer : '#container',\n\t\t\tdata\t : matrix_data,\n\t\t\trowLabels : rowLabels,\n\t\t\tcolLabels : colLabels,\t\t\t\n\t\t\tsubLabel : data.splitby + ' : ' + data.subgroup,\n\t\t\toverviewLegendType: data.overview_legend_type\n\t\t});\n\t}\n\n\t// Cell Click Event\n\td3.select(container).selectAll(\".cell\")\n\t\t.on(\"click\", clickHeatmapMatrixCell);\t\n}", "function drawInterestHexagons(){\n\t\tvar group = hexGroup.selectAll(\".interestHexagons\")\n\t\t.data(hexagonCenters)\n\t\t.enter()\n\t\t.append(\"g\")\n\t\t.attr(\"id\", function(d){\n\t\t\treturn d.interest.replace(/ /g,''); \n\t\t})\n\t\t.classed(\"hexagonGroup\", true);\n\n\t\t//Add hexagons\n\t\tgroup.append(\"polygon\")\n\t\t.attr(\"points\", function(d){\n\t\t\treturn d.pointList.map(function(d){\n\t\t\t\treturn [d.xPos, d.yPos].join(\",\");\n\t\t\t}).join(\" \");\n\t\t})\n\t\t.classed(\"interestHexagons\", true)\n\t\t.attr(\"id\", function(d){ return d.interest.replace(/ /g,'')+\"Poly\";})\n\t\t.attr(\"stroke\", \"#1c1c1c\")\n\t\t.attr(\"stroke-width\", \"5px\");\n\t\t\n\t\t//Add Icons\n\t\tvar dimensions = size * .75;\n\t\tgroup.append(\"svg:image\")\n\t\t.attr(\"xlink:href\", function(d){\n\t\t\treturn \"hexagon_icons/\" + d.icon;\n\t\t})\n\t\t.attr(\"width\", dimensions)\n\t\t.attr(\"height\", dimensions)\n\t\t.attr(\"x\", function(d){ return d.x - dimensions/2;})\n\t\t.attr(\"y\", function(d){ return d.y - dimensions * .6;});\n\t\t\n\t\t//Add Labels\n\t\tvar fontSize = toInt(size / 5) + \"px\";\n\t\tgroup.append(\"text\")\n\t\t.attr(\"x\", function(d){\n\t\t\treturn d.x;\n\t\t})\n\t\t.attr(\"y\", function(d){\n\t\t\treturn d.y + size * .5;\n\t\t})\n\t\t.text(function(d) {return d.interest})\n\t\t.attr(\"id\", function(d) { return d.interest.replace(/ /g,'')+\"Text\";})\n\t\t.attr(\"font-size\", fontSize)\n\t\t.attr(\"fill\", \"black\")\n\t\t.attr(\"text-anchor\", \"middle\")\n\t\t.classed(\"hexagonText\", true);\n\n\t}", "function showChord() {\r\n\r\n for (var i in positions) {\r\n var p = positions[i];\r\n if (!p.value.match(/^(1|2)?\\d|x$/i)) {\r\n alert('Fret position must be a number from 0-24 or X!');\r\n p.focus();\r\n return;\r\n }\r\n }\r\n\r\n for (var i in fingers) {\r\n var f = fingers[i];\r\n if (!f.value.match(/^1|2|3|4|T|-$/i)) {\r\n alert('Fingerings must be one of 1,2,3,4,T or -.');\r\n f.focus();\r\n return;\r\n }\r\n }\r\n\r\n var name = $('chordname').value;\r\n var chord = pE.value + '-' + pA.value + '-' + pD.value + '-' + pG.value + '-' + pB.value + '-' + pe.value;\r\n var size = $('size').value;\r\n if (chord.length == 11) {\r\n chord = chord.replace(/-/g, '');\r\n }\r\n name = escapeName(name);\r\n var fingers = fE.value + fA.value + fD.value + fG.value + fB.value + fe.value;\r\n var chordUrl = name + '.png?p=' + chord + '&f=' + fingers + '&s=' + size;\r\n var url = 'http://' + document.location.host + document.location.pathname.replace('index.html', '');\r\n url += chordUrl;\r\n\r\n if (window.analyticsId) {\r\n ga('send', 'pageview', {\r\n 'page': '/' + chordUrl,\r\n 'title': name + ': ' + chord\r\n });\r\n }\r\n\r\n document.location = '#' + chordUrl;\r\n\r\n $('chord-link').setAttribute('href', url);\r\n $('chord-link').innerHTML = url;\r\n $('chord-image-link').setAttribute('href', url);\r\n\r\n var image = $('chord-image');\r\n image.setAttribute('src', url);\r\n image.setAttribute('alt', unescapeName(name) + ' chord');\r\n image.setAttribute('title', unescapeName(name) + ' chord');\r\n}", "function Grid(){\r\n var hueGrid;\r\n \r\n var hueDev = 5;\r\n var maxHue = 360;\r\n var cellSize = 10;\r\n \r\n //Based on size of window\r\n var nRows = Math.floor(300 / cellSize + 1);\r\n var nCols = Math.floor(400 / cellSize + 1);\r\n \r\n //Initialize array\r\n hueGrid = Array(nRows);\r\n \r\n //Fill array\r\n for(let i = 0; i < nRows; i++){\r\n hueGrid[i] = Array(nCols);\r\n for (let j = 0; j < nCols; j++){\r\n hueGrid[i][j] = random(maxHue);\r\n //console.log(\"filled the grid\");\r\n }\r\n }\r\n \r\n //Show it\r\n this.display = function(){\r\n //drawing cells of the grid\r\n //Columns\r\n for (let i = 0; i < hueGrid.length; i++){\r\n //Rows\r\n for(let j = 0; j < hueGrid[i].length; j++){\r\n //wrap around hue value\r\n hueGrid[i][j] = hueGrid[i][j] + random(-hueDev, hueDev);\r\n \r\n if(hueGrid[i][j] < 0){\r\n hueGrid[i][j] = hueGrid[i][j] - maxHue;\r\n }\r\n else if(hueGrid[i][j] < 0){\r\n hueGrid[i][j] += maxHue;\r\n }\r\n \r\n\r\n fill(hueGrid[i][j],100,100);\r\n rect( j * cellSize, i * cellSize, cellSize, cellSize);\r\n }\r\n }\r\n }\r\n}", "function updateHeatmap() {\n // Build new x scale based on myGroups (in case re-sorted)\n x = x.domain(myGroups);\n\n // Re/build the heatmap (selecting by custom key 'tcga_id:gene'):\n svg_heatmap.selectAll()\n .data(dataInput, d => (d.tcga_participant_barcode + ':' + d.gene))\n .enter()\n .append(\"rect\")\n .attr(\"x\", d => x(d.tcga_participant_barcode))\n .attr(\"y\", d => y(d.gene))\n .attr(\"width\", x.bandwidth())\n .attr(\"height\", y.bandwidth())\n .style(\"fill\", d => colorScale_exp(d[\"z-score\"]))\n .on(\"mouseover\", mouseover)\n .on(\"mousemove\", mousemove)\n .on(\"mouseleave\", mouseleave);\n\n // Re/build sample tracks (currently only handles categorical data)\n // Get sample track selected vars (only in observable)\n //let sampTrackVars = getClinvarSelection();\n let sampTrackVars = Object.keys(clinicalData[0]).filter(el => (el.match(/^(?!cohort|date|tcga_participant_barcode$)/)));\n\n // Build color scales for all selected variables\n let colorScale_all = sampTrackVars.reduce((acc, v) => {\n let var_domain = d3.map(clinicalData, d => d[v]).keys().sort().filter(el => el !== \"NA\");\n acc[v] = d3.scaleOrdinal()\n .domain(var_domain)\n .range(d3.schemeCategory10)\n .unknown(\"lightgray\"); return acc\n }, {})\n\n // Recompute total sample tracks height and update svg_sampletrack height\n let sampTrackHeight_total = (sampTrackHeight + margin.space) * sampTrackVars.length;\n svg_frame.select('.sampletrack').attr('height', sampTrackHeight_total)\n\n // Build new scale for sample track labels:\n let y_samp = d3.scaleBand()\n .range([0, sampTrackHeight_total])\n .domain(sampTrackVars);\n\n // Build sample track for each variable\n svg_sampletrack.html(\"\"); // have to clear to keep some spaces as white\n sampTrackVars.forEach(v => {\n svg_sampletrack.selectAll()\n .data(clinicalData, d => (d.tcga_participant_barcode + \":\" + v))\n .enter()\n .append(\"rect\")\n .attr(\"var\", v)\n .attr(\"x\", d => x(d.tcga_participant_barcode))\n .attr(\"y\", y_samp(v))\n .attr(\"width\", x.bandwidth())\n .attr(\"height\", sampTrackHeight)\n .style(\"fill\", d => colorScale_all[v](d[v]))\n .attr(\"fill0\", d => colorScale_all[v](d[v]))\n .on(\"mouseover\", mouseover)\n .on(\"mousemove\", mousemove_samp)\n .on(\"mouseleave\", mouseleave_samp);\n })\n // Append labels axis to the sample track:\n svg_sampletrack.select('#sampLabels').remove(); // first remove previous labels\n svg_sampletrack.append(\"g\")\n .attr('id', 'sampLabels')\n .style('font-size', 9.5)\n .call(d3.axisLeft(y_samp).tickSize(0))\n .select(\".domain\").remove();\n\n // Sample Track Legend:\n // function to get width of bounding text box for a given string, font-size\n let svg_temp = divObject.append(\"svg\")\n function getTextWidth(str, fs) {\n let text_temp = svg_temp\n .append('text')\n .style('font-size', fs + \"px\")\n .text(str);\n var dim = text_temp.node().getBBox();\n return dim.width\n }\n\n // get max sizes of variable name and all unique variable labels (for column width), and number of variables (for legend height)\n let var_summary = sampTrackVars.map(v => {\n let myLabs = d3.map(clinicalData, d => d[v]).keys().sort().filter(el => el !== \"NA\").map(el => ({ val: el }));\n let var_width = getTextWidth(v + \":\\xa0\", 15); // text width of variable name\n let lab_width = Math.max(...myLabs.map(el => getTextWidth(\"\\xa0\" + el.val, 10))); // max text width of each unique label\n return { var: v, labs: myLabs, nlab: myLabs.length, max_width: Math.ceil(Math.max(lab_width + sampTrackHeight, var_width)) }\n })\n svg_temp.html(\"\")\n\n // calculate cumulative sum of column widths with spacing for x-positioning each variable\n const cumulativeSum = (sum => value => sum += value)(0);\n let x_spacing = var_summary.map(el => el.max_width + margin.space).map(cumulativeSum);\n var_summary = var_summary.map(o => { o.x = x_spacing[var_summary.indexOf(o)] - o.max_width; return o });\n\n // fill sample track legend\n svg_sampLegend.html(\"\");\n var_summary.forEach(v => {\n svg_sampLegend\n .append(\"text\")\n .attr(\"x\", v.x)\n .attr(\"alignment-baseline\", \"hanging\")\n .style(\"font-size\", \"15px\")\n .attr(\"text-decoration\", \"underline\")\n .text(v.var + \":\");\n svg_sampLegend.selectAll()\n .data(v.labs, d => v.var + \":\" + d.val + \"_box\")\n .enter()\n .append(\"rect\")\n .attr(\"x\", v.x)\n .attr(\"y\", (d, i) => 20 + i * (sampTrackHeight + margin.space))\n .attr(\"width\", sampTrackHeight)\n .attr(\"height\", sampTrackHeight)\n .style(\"fill\", d => colorScale_all[v.var](d.val))\n .style(\"stroke\", \"black\");\n svg_sampLegend.selectAll()\n .data(v.labs, d => v.var + \":\" + d.val + \"_text\")\n .enter()\n .append(\"text\")\n .attr(\"x\", v.x + sampTrackHeight)\n .attr(\"y\", (d, i) => 20 + i * (sampTrackHeight + margin.space) + sampTrackHeight / 2)\n .attr(\"alignment-baseline\", \"central\")\n .style(\"font-size\", \"10px\")\n .text(d => \"\\xa0\" + d.val);\n });\n // adjust sampLegend size\n // height is max number of labels times entry height, plus space for title\n // width is cumulative sum of max label width for each column plus the colored rectangle and spacing\n let sampLegendHeight = 20 + (sampTrackHeight + margin.space) * Math.max(...var_summary.map(el => el.nlab));\n div_sampLegend.select(\".sampLegend\")\n .attr(\"height\", sampLegendHeight + margin.space)\n .attr(\"width\", var_summary.reduce((a, b) => a + b.max_width + sampTrackHeight + margin.space, 0))\n if (sampLegendHeight < 200) {\n div_sampLegend.select('#legend')\n .attr('height', sampLegendHeight + 'px')\n } else {\n div_sampLegend.select('#legend')\n .style('height', '200px')\n }\n\n if (sampTrackVars.length == 0) {\n svg_sampLegend\n .append(\"text\")\n .attr(\"alignment-baseline\", \"hanging\")\n .style(\"font-size\", \"18px\")\n .text(\"No clinical features selected\");\n div_sampLegend.select(\".sampLegend\")\n .attr(\"height\", 20)\n .attr(\"width\", 250)\n div_sampLegend.select('#legend')\n .style('height', '20px')\n };\n\n // Generate dendrogram IF clustering selected and ready\n if (doCluster && clusterReady) { // only show dendrogram if these flags indicate to show\n // Build dendrogram as links between nodes:\n cluster = d3.cluster().size([heatWidth - legendWidth, dendHeight]); // match dendrogram width to heatmap x axis range\n // Give the data to this cluster layout:\n data = clust_results.clusters;\n root = d3.hierarchy(data);\n cluster(root);\n\n // Build dendrogram as links between nodes:\n svg_dendrogram.selectAll('path')\n .data(root.descendants().slice(1))\n .enter()\n .append('path')\n .attr(\"d\", elbow)\n .style(\"fill\", 'none')\n .style(\"stroke-width\", \"0.5px\")\n .attr(\"stroke\", 'black')\n\n // Give dendrogram svg height and shift down heatmap + sampletracks\n svg_dendrogram.attr(\"height\", dendHeight);\n svg_frame.select(\".sampletrack\")\n .attr(\"y\", margin.top + dendHeight)\n svg_frame.select(\".heatmap\")\n .attr(\"y\", margin.top + dendHeight + sampTrackHeight_total);\n frameHeight = margin.top + dendHeight + margin.space + heatHeight + sampTrackHeight_total + margin.bottom;\n \n } else { // otherwise remove the dendrogam and shift the heatmap up\n svg_dendrogram.attr(\"height\", 0);\n svg_frame.select(\".sampletrack\")\n .attr(\"y\", margin.top)\n svg_frame.select(\".heatmap\")\n .attr(\"y\", margin.top + sampTrackHeight_total);\n frameHeight = margin.top + heatHeight + sampTrackHeight_total + margin.bottom;\n }\n // apply new frameHeight (adjusting for dendrogram and # sample tracks)\n svg_frame.attr('height', frameHeight)\n }", "function createMap() {\n //declare needed variables\n let tooltipContent = '',\n labelFormat = '',\n labelValue = '',\n codeValue = '';\n\n //fill topology\n d3.json(folderPath + mapName + '.json', function (error, data) {\n\n //get grid size\n let dimensions = data.size;\n\n if (map.series[0].tileIcon === 'hexagonal') {\n //set tile size\n tileSize = Math.min(Math.floor(map.plot.width / (dimensions.x - 1)), Math.floor(map.plot.height / (dimensions.y % 2 === 0 ? 0.5 + dimensions.y * 0.75 : dimensions.y * 0.75)));\n\n //calculate margins\n margins.x = (map.plot.width - (tileSize * dimensions.x)) / 2;\n margins.y = (map.plot.height - (tileSize * (dimensions.y * 0.75))) / 2;\n }\n else {\n //set tile size\n tileSize = Math.min(Math.floor(map.plot.width / dimensions.x), Math.floor(map.plot.height / dimensions.y));\n\n //calculate margins\n margins.x = (map.plot.width - (tileSize * dimensions.x)) / 2;\n margins.y = (map.plot.height - (tileSize * dimensions.y)) / 2;\n }\n\n //set radius\n r = tileSize / 2 - 1;\n\n //center g\n mapG.attr('transform', 'translate(' + map.plot.left + ',' + map.plot.top + ')');\n\n //set tile map data\n tileData = data.objects;\n\n //create tile shapes based on icon type\n if (map.series[0].tileIcon === 'circle')\n createCircleTiles();\n else if (map.series[0].tileIcon === 'square')\n createSquareTiles();\n else if (map.series[0].tileIcon === 'hexagonal')\n createHexTiles();\n\n tiles\n .on('mousemove', function (d, i) {\n //check whether tooltip enabled\n if (map.tooltip.format !== '') {\n //set default tooltip content\n tooltipContent = \"no data available\";\n //check whether current data exists\n if (d.currentData) {\n //get values from shape\n codeValue = d.code;\n labelValue = d.name;\n\n //set tooltip content\n tooltipContent = map.tooltip.format.replaceAll('{code}', codeValue).replaceAll('{label}', labelValue);\n tooltipContent = map.getContent(d.currentData, map.series[0], tooltipContent);\n }\n //show tooltip\n map.showTooltip(tooltipContent);\n }\n })\n .on('mouseout', function (d) {\n //hide tooltip\n map.hideTooltip();\n });\n\n //check if labels are enabled\n //if (map.series[0].labelsEnabled && map.series[0].labelFormat !== '') {\n if (map.series[0].labelFormat !== '') {\n //create labels\n labels = mapG.append('g').selectAll('text')\n .data(tileData)\n .enter().append('text')\n .style(\"text-anchor\", \"middle\")\n .style('font-family', map.series[0].labelFontFamily)\n .style('font-style', map.series[0].labelFontStyle === 'bold' ? 'normal' : map.series[0].labelFontStyle)\n .style('font-weight', map.series[0].labelFontStyle === 'bold' ? 'bold' : 'normal')\n .attr(\"dy\", \".35em\")\n .on('mousemove', function (d, i) {\n //check whether tooltip enabled\n if (map.tooltip.format !== '') {\n //set default tooltip content\n tooltipContent = \"no data available\";\n //check whether current data exists\n if (d.currentData) {\n //get values from shape\n codeValue = d.code;\n labelValue = d.name;\n\n //set tooltip content\n tooltipContent = map.tooltip.format.replaceAll('{code}', codeValue).replaceAll('{label}', labelValue);\n tooltipContent = map.getContent(d.currentData, map.series[0], tooltipContent);\n }\n //show tooltip\n map.showTooltip(tooltipContent);\n }\n })\n .on('mouseout', function (d) {\n //hide tooltip\n map.hideTooltip();\n });\n }\n\n //raise on loaded\n if (map.onLoaded) map.onLoaded();\n\n //animate tiles\n animateTiles();\n });\n\n //attach clear content method to map\n map.clear = function () {\n //clear current data from all paths\n tiles.each(function (d) {\n d.currentData = null;\n });\n };\n\n //set update method to chart\n map.update = function (data, keepAxis) {\n //set chart data\n map.data = data;\n\n //update xy domain\n map.calculateDomain();\n map.updateLegend();\n\n //animate tiles\n animateTiles();\n };\n\n //handles legend click\n map.legendClick = function (d, i) {\n if (map.legend.type === 'ranged') {\n if (d.clicked) {\n tiles.attr('fill-opacity', function (d) {\n if (d.legendClass === 'ranged-' + i)\n return 0.1;\n else\n return d.fillOpacity;\n });\n } else {\n tiles.attr('fill-opacity', function (d) {\n if (d.legendClass === 'ranged-' + i)\n return 1;\n else\n return d.fillOpacity;\n });\n }\n }\n };\n\n //handles legend hover\n map.onLegendHover = function (d, i, status) {\n if (map.legend.type === 'ranged') {\n if (status) {\n tiles\n .attr('fill-opacity', function (d) {\n if (d.legendClass !== 'ranged-' + i)\n return 0.1;\n else\n return d.fillOpacity;\n })\n .style('stroke-opacity', function (d) {\n if (d.legendClass !== 'ranged-' + i)\n return 0.1;\n else\n return d.fillOpacity;\n });\n } else {\n tiles\n .attr('fill-opacity', function (d) { return d.fillOpacity; })\n .style('stroke-opacity', function (d) { return d.fillOpacity; });\n }\n }\n };\n }", "_createHexagonMap () {\n var map = {};\n\n let radius = MAP_RADIUS;\n for (let q = -radius; q <= radius; q++) {\n map[q] = {};\n let r1 = Math.max(-radius, -q - radius);\n let r2 = Math.min(radius, -q + radius);\n for (let r = r1; r <= r2; r++) {\n map[q][r] = { q, r, color: Math.random() * 0xffffff };\n }\n }\n\n return map;\n }", "function initCells() {\n\tfor (var i=0; i<NY; i++) {\n\t\tfor (var j=0; j<NX; j++) {\n\t\t\tcells[i][j].innerHTML = '<img src=\"images/i0.png\" />';\n\t\t\ttemplate.children[i].children[j].innerHTML = levels[currentLevel][i][j]==0?' ':levels[currentLevel][i][j].toString();\n\t\t}\n\t}\n}", "function update_heat(selectedVar) {\n if (selectedVar == 'morning') {\n\n d3.csv(\"data/assignment_3/morning_heat.csv\", function (data) {\n console.log(data)\n\n // Clear existing Heap Map\n mem_start_heat.setLatLngs([]);\n mem_end_heat.setLatLngs([]);\n casual_start_heat.setLatLngs([]);\n casual_end_heat.setLatLngs([]);\n\n data.forEach(function (row) {\n // Add Member Heat Map Points\n if (row.member_casual == 'member') {\n // start location\n row.start_lat = +row.start_lat;\n row.start_lng = +row.start_lng;\n mem_start_heat.addLatLng([row.start_lat, row.start_lng]);\n // end location\n row.end_lat = +row.end_lat;\n row.end_lng = +row.end_lng;\n mem_end_heat.addLatLng([row.end_lat, row.end_lng]);\n }\n\n // Add Casual Heat Map Points\n if (row.member_casual == 'casual') {\n // start location\n row.start_lat = +row.start_lat;\n row.start_lng = +row.start_lng;\n casual_start_heat.addLatLng([row.start_lat, row.start_lng]);\n // end location\n row.end_lat = +row.end_lat;\n row.end_lng = +row.end_lng;\n casual_end_heat.addLatLng([row.end_lat, row.end_lng]);\n }\n\n });\n });\n }\n\n else if (selectedVar == 'evening') {\n\n d3.csv(\"data/assignment_3/evening_heat.csv\", function (data) {\n console.log(data)\n\n // Clear existing Heap Map\n mem_start_heat.setLatLngs([]);\n mem_end_heat.setLatLngs([]);\n casual_start_heat.setLatLngs([]);\n casual_end_heat.setLatLngs([]);\n\n data.forEach(function (row) {\n // Add Member Heat Map Points\n if (row.member_casual == 'member') {\n // start location\n row.start_lat = +row.start_lat;\n row.start_lng = +row.start_lng;\n mem_start_heat.addLatLng([row.start_lat, row.start_lng]);\n // end location\n row.end_lat = +row.end_lat;\n row.end_lng = +row.end_lng;\n mem_end_heat.addLatLng([row.end_lat, row.end_lng]);\n }\n\n // Add Casual Heat Map Points\n if (row.member_casual == 'casual') {\n // start location\n row.start_lat = +row.start_lat;\n row.start_lng = +row.start_lng;\n casual_start_heat.addLatLng([row.start_lat, row.start_lng]);\n // end location\n row.end_lat = +row.end_lat;\n row.end_lng = +row.end_lng;\n casual_end_heat.addLatLng([row.end_lat, row.end_lng]);\n }\n\n });\n });\n }\n}", "function drawLeds() {\r\n noFill();\r\n stroke(\"black\");\r\n const numRows = 16\r\n for (let i = 21; i < 108; i++) {\r\n for (let j = 0; j <= 15; j++) {\r\n const espace = separation//separation*15\r\n\r\n let x = (espace * j / 15) * b// convertimos los numeros del 0 al 15 a una escala de 0 a 0.2*15=3\r\n rect(i * noteSeparation + offsetHorizontal,\r\n - x * a + offsetVertical,\r\n noteWidth,\r\n -10);\r\n }\r\n }\r\n}", "function HeatMapSetter(data)\n{\n // Initialize the map\n var map = new L.Map(\"heatMap\", \n {\n center: new L.LatLng(38.230462, 21.753150),\n zoom: 14\n });\n\n // Initialize the map layer\n var mapLayer = L.tileLayer(\"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\",{\n attribution: 'Map data &copy; <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors'\n });\n\n // Add the map layer to the map\n map.addLayer(mapLayer);\n\n // Initialize the heat map layer\n var heatmapLayer = L.heatLayer(data);\n\n // Add the heat map layer to the map\n map.addLayer(heatmapLayer);\n}", "getHeatMap() {\n\n if(this.activePollutant == null || this.stateDataArray == null || this.stateDataArray.length == 0) return null;\n\n switch(this.activePollutant.toUpperCase()) {\n\n case 'CARBON MONOXIDE' :\n return d3.scaleLinear()\n .domain([0,d3.max(this.stateDataArray, function(d) { if(d) return d['CO'] })])\n .interpolate(d3.interpolateRgb)\n .range([\"#f9fbe7\",\"#c0ca33\"]);\n break;\n\n case 'SULPHUR DIOXIDE' :\n return d3.scaleLinear()\n .domain([0,d3.max(this.stateDataArray, function(d) { if(d) return d['SO2'] })])\n .interpolate(d3.interpolateRgb)\n .range([\"#ffeda0\",\"#f03b20\"]);\n break;\n\n case 'NITROUS OXIDE' :\n return d3.scaleLinear()\n .domain([0,d3.max(this.stateDataArray, function(d) { if(d) return d['NO2'] })])\n .interpolate(d3.interpolateRgb)\n .range([\"#fde0dd\",\"#c51b8a\"]);\n break;\n\n case 'OZONE' :\n return d3.scaleLinear()\n .domain([0,d3.max(this.stateDataArray, function(d) { if(d) return d['O3'] })])\n .interpolate(d3.interpolateRgb)\n .range([\"#ece2f0\",\"#1c9099\"]);\n\n default: return null;\n }\n \n }", "function finalChord() {\n\t\n\t/*Remove button*/\n\td3.select(\"#clicker\")\n\t\t.style(\"visibility\", \"hidden\");\n\td3.select(\"#skip\")\n\t\t.style(\"visibility\", \"hidden\");\n\td3.select(\"#progress\")\n\t\t.style(\"visibility\", \"hidden\");\n\t\n\t/*Remove texts*/\n\tchangeTopText(newText = \"\",\n\t\tloc = 0, delayDisappear = 0, delayAppear = 1);\n\tchangeBottomText(newText = \"\",\n\t\tloc = 0, delayDisappear = 0, delayAppear = 1);\t\t\t\n\n\t/*Create arcs or show them, depending on the point in the visual*/\n\tif (counter <= 4 ) {\n\t\tg.append(\"svg:path\")\n\t\t .style(\"stroke\", function(d) { return fill(d.index); })\n\t\t .style(\"fill\", function(d) { return fill(d.index); })\n\t\t .attr(\"d\", arc)\n\t\t .style(\"opacity\", 0)\n\t\t .transition().duration(1000)\n\t\t .style(\"opacity\", 1);\n\t\t \n\t} else {\n\t\t /*Make all arc visible*/\n\t\tsvg.selectAll(\"g.group\").select(\"path\")\n\t\t\t.transition().duration(1000)\n\t\t\t.style(\"opacity\", 1);\n\t};\n\t\n\t/*Make mouse over and out possible*/\n\td3.selectAll(\".group\")\n\t\t.on(\"mouseover\", fade(.02))\n\n\t\t.on(\"mousemove\", function () {\n\n\t\t\t//Change titles\n\t\t\td3.select(\"#chart-tooltip .tooltip-title\").html(this.className.baseVal.slice(6, this.className.baseVal.length))\n\n\t\t\t//Place & show the tooltip\n\t\t\td3.select(\"#chart-tooltip\")\n\t\t\t\t.style(\"top\", (event.clientY - 5 + \"px\"))\n\t\t\t\t.style(\"left\", (event.clientX + 5 + \"px\"))\n\t\t\t\t.style(\"opacity\", 1)\n\n\n\t\t})\n\t\t.on(\"mouseout\",function(){\n\t\t\td3.select(\"#chart-tooltip\")\n\t\t\t\t.style(\"top\", (event.clientY - 5 + \"px\"))\n\t\t\t\t.style(\"left\", (event.clientX + 5 + \"px\"))\n\t\t\t\t.style(\"opacity\", 0);\n\n\t\t\tsvg.selectAll(\"path.chord\")\n\t\t\t\t.transition()\n\t\t\t\t.style(\"stroke-opacity\", 0.8)\n\t\t\t\t.style(\"fill-opacity\", 0.8);\n\t\t} );\n\t\t\n\t/*Show all chords*/\n\tchords.transition().duration(1000)\n\t\t.style(\"opacity\", opacityValueBase);\n\n\t/*Show all the text*/\n\td3.selectAll(\"g.group\").selectAll(\"line\")\n\t\t.transition().duration(100)\n\t\t.style(\"stroke\",\"#000\");\n\t/*Same for the %'s*/\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(100)\n\t\t.selectAll(\".tickLabels\").style(\"opacity\",1);\n\t/*And the Names of each Arc*/\t\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(100)\n\t\t.selectAll(\".titles\").style(\"opacity\",1);\t\t\n\n}", "function changeRadius() \n{\n ttcHeatmap.set('radius', ttcHeatmap.get('radius') ? null : 20);\n}", "function drawHeatMap(svg, data) {\n\t\tvar length = months.length; // 12 month\n\t\tvar colorScale;\n\n\t\tvar cards = svg.selectAll('.hour')\n\t\t .data(data);\n\n\t\tcards.enter().append('rect')\n\t\t .attr('x', function(d, i) { \n\t\t return (i % length) * boxWidth;\n\t\t })\n\t\t .attr('y', function(d, i){\n\t\t return Math.floor(i / length) * boxWidth; // 0 ~ 11 -> 0, 12 ~ 23, ....\n\t\t })\n\t\t .attr(\"rx\", 4)\n\t\t .attr(\"ry\", 4)\n\t\t .attr(\"class\", \"hour bordered\")\n\t\t .attr(\"width\", boxWidth)\n\t\t .attr(\"height\", boxWidth)\n\t .style(\"fill\", function(d, i) {\n\t \n\t if (i % length === 0) {\n\t // create new scale for every year\n\t var yearData = data.slice(i, i + length);\n\t colorScale = d3.scaleQuantile()\n\t .domain([d3.min(yearData), d3.max (yearData)])\n\t .range(colors);\n\t }\n\t return colorScale(d); \n\t });\n\n\t\tcards.select(\"title\").text(function(d) { return d.value; });\n\n\t\tcards.exit().remove();\n\t}", "function chartHeatMapRadial () {\n\n /* Default Properties */\n var svg = void 0;\n var chart = void 0;\n var classed = \"heatMapRadial\";\n var width = 400;\n var height = 300;\n var margin = { top: 20, right: 20, bottom: 20, left: 20 };\n var transition = { ease: d3.easeBounce, duration: 500 };\n var colors = [\"#D34152\", \"#f4bc71\", \"#FBF6C4\", \"#9bcf95\", \"#398abb\"];\n var dispatch = d3.dispatch(\"customValueMouseOver\", \"customValueMouseOut\", \"customValueClick\", \"customSeriesMouseOver\", \"customSeriesMouseOut\", \"customSeriesClick\");\n\n /* Chart Dimensions */\n var chartW = void 0;\n var chartH = void 0;\n var radius = void 0;\n var innerRadius = void 0;\n\n /* Scales */\n var xScale = void 0;\n var yScale = void 0;\n var colorScale = void 0;\n\n /* Other Customisation Options */\n var startAngle = 0;\n var endAngle = 270;\n var thresholds = void 0;\n\n /**\n * Initialise Data and Scales\n *\n * @private\n * @param {Array} data - Chart data.\n */\n function init(data) {\n chartW = width - (margin.left + margin.right);\n chartH = height - (margin.top + margin.bottom);\n\n var _dataTransform$summar = dataTransform(data).summary(),\n rowKeys = _dataTransform$summar.rowKeys,\n columnKeys = _dataTransform$summar.columnKeys,\n tmpThresholds = _dataTransform$summar.thresholds;\n\n if (typeof thresholds === \"undefined\") {\n thresholds = tmpThresholds;\n }\n\n if (typeof radius === \"undefined\") {\n radius = Math.min(chartW, chartH) / 2;\n }\n\n if (typeof innerRadius === \"undefined\") {\n innerRadius = radius / 4;\n }\n\n if (typeof colorScale === \"undefined\") {\n colorScale = d3.scaleThreshold().domain(thresholds).range(colors);\n }\n\n xScale = d3.scaleBand().domain(columnKeys).rangeRound([startAngle, endAngle]).padding(0.1);\n\n yScale = d3.scaleBand().domain(rowKeys).rangeRound([radius, innerRadius]).padding(0.1);\n }\n\n /**\n * Constructor\n *\n * @constructor\n * @alias heatMapRadial\n * @param {d3.selection} selection - The chart holder D3 selection.\n */\n function my(selection) {\n // Create SVG element (if it does not exist already)\n if (!svg) {\n svg = function (selection) {\n var el = selection._groups[0][0];\n if (!!el.ownerSVGElement || el.tagName === \"svg\") {\n return selection;\n } else {\n return selection.append(\"svg\");\n }\n }(selection);\n\n svg.classed(\"d3ez\", true).attr(\"width\", width).attr(\"height\", height);\n\n chart = svg.append(\"g\").classed(\"chart\", true);\n } else {\n chart = selection.select(\".chart\");\n }\n\n // Update the chart dimensions and add layer groups\n var layers = [\"heatRingsGroups\", \"circularSectorLabels\", \"circularRingLabels\"];\n chart.classed(classed, true).attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\").attr(\"width\", chartW).attr(\"height\", chartH).selectAll(\"g\").data(layers).enter().append(\"g\").attr(\"class\", function (d) {\n return d;\n });\n\n selection.each(function (data) {\n // Initialise Data\n init(data);\n\n // Heat Map Rings\n var heatMapRing = component.heatMapRing().radius(function (d) {\n return yScale(d.key);\n }).innerRadius(function (d) {\n return yScale(d.key) + yScale.bandwidth();\n }).startAngle(startAngle).endAngle(endAngle).colorScale(colorScale).xScale(xScale).yScale(yScale).dispatch(dispatch).thresholds(thresholds);\n\n // Create Series Group\n var seriesGroup = chart.select(\".heatRingsGroups\").selectAll(\".seriesGroup\").data(data);\n\n seriesGroup.enter().append(\"g\").attr(\"class\", \"seriesGroup\").merge(seriesGroup).call(heatMapRing);\n\n seriesGroup.exit().remove();\n\n // Circular Labels\n var circularSectorLabels = component.circularSectorLabels().radius(radius * 1.04).radialScale(xScale).textAnchor(\"start\");\n\n chart.select(\".circularSectorLabels\").call(circularSectorLabels);\n\n // Ring Labels\n var circularRingLabels = component.circularRingLabels().radialScale(yScale).textAnchor(\"middle\");\n\n chart.select(\".circularRingLabels\").call(circularRingLabels);\n });\n }\n\n /**\n * Width Getter / Setter\n *\n * @param {number} _v - Width in px.\n * @returns {*}\n */\n my.width = function (_v) {\n if (!arguments.length) return width;\n width = _v;\n return this;\n };\n\n /**\n * Height Getter / Setter\n *\n * @param {number} _v - Height in px.\n * @returns {*}\n */\n my.height = function (_v) {\n if (!arguments.length) return height;\n height = _v;\n return this;\n };\n\n /**\n * Margin Getter / Setter\n *\n * @param {number} _v - Margin in px.\n * @returns {*}\n */\n my.margin = function (_v) {\n if (!arguments.length) return margin;\n margin = _v;\n return this;\n };\n\n /**\n * Radius Getter / Setter\n *\n * @param {number} _v - Radius in px.\n * @returns {*}\n */\n my.radius = function (_v) {\n if (!arguments.length) return radius;\n radius = _v;\n return this;\n };\n\n /**\n * Inner Radius Getter / Setter\n *\n * @param {number} _v - Inner radius in px.\n * @returns {*}\n */\n my.innerRadius = function (_v) {\n if (!arguments.length) return innerRadius;\n innerRadius = _v;\n return this;\n };\n\n /**\n * Colors Getter / Setter\n *\n * @param {Array} _v - Array of colours used by color scale.\n * @returns {*}\n */\n my.colors = function (_v) {\n if (!arguments.length) return colors;\n colors = _v;\n return this;\n };\n\n /**\n * Color Scale Getter / Setter\n *\n * @param {d3.scale} _v - D3 color scale.\n * @returns {*}\n */\n my.colorScale = function (_v) {\n if (!arguments.length) return colorScale;\n colorScale = _v;\n return this;\n };\n\n /**\n * Thresholds Getter / Setter\n *\n * @param {Array} _v - Array of thresholds.\n * @returns {*}\n */\n my.thresholds = function (_v) {\n if (!arguments.length) return thresholds;\n thresholds = _v;\n return my;\n };\n\n /**\n * Transition Getter / Setter\n *\n * @param {d3.transition} _v - D3 transition style.\n * @returns {*}\n */\n my.transition = function (_v) {\n if (!arguments.length) return transition;\n transition = _v;\n return this;\n };\n\n /**\n * Dispatch Getter / Setter\n *\n * @param {d3.dispatch} _v - Dispatch event handler.\n * @returns {*}\n */\n my.dispatch = function (_v) {\n if (!arguments.length) return dispatch();\n dispatch = _v;\n return this;\n };\n\n /**\n * Dispatch On Getter\n *\n * @returns {*}\n */\n my.on = function () {\n var value = dispatch.on.apply(dispatch, arguments);\n return value === dispatch ? my : value;\n };\n\n return my;\n }", "function updateNeighbors(i, j) {\n\tif (i>0) {\n\t\tif (values[i-1][j] > 0) {\n\t\t\tvalues[i-1][j] += values[i-1][j]==4?-3:1;\n\t\t\tvar imRoute = 'images/i' + values[i-1][j].toString() + '.png';\n\t\t\tcells[i-1][j].innerHTML = '<img src=\"' + imRoute + '\" />';\n\t\t}\n\t}\n\tif (j>0) {\n\t\tif (values[i][j-1] > 0) {\n\t\t\tvalues[i][j-1] += values[i][j-1]==4?-3:1;\n\t\t\tvar imRoute = 'images/i' + values[i][j-1].toString() + '.png';\n\t\t\tcells[i][j-1].innerHTML = '<img src=\"' + imRoute + '\" />';\n\t\t}\n\t}\n\tif (i<NY-1) {\n\t\tif (values[i+1][j] > 0) {\n\t\t\tvalues[i+1][j] += values[i+1][j]==4?-3:1;\n\t\t\tvar imRoute = 'images/i' + values[i+1][j].toString() + '.png';\n\t\t\tcells[i+1][j].innerHTML = '<img src=\"' + imRoute + '\" />';\n\t\t}\n\t}\n\tif (j<NX-1) {\n\t\tif (values[i][j+1] > 0) {\n\t\t\tvalues[i][j+1] += values[i][j+1]==4?-3:1;\n\t\t\tvar imRoute = 'images/i' + values[i][j+1].toString() + '.png';\n\t\t\tcells[i][j+1].innerHTML = '<img src=\"' + imRoute + '\" />';\n\t\t}\n\t}\n}", "setDefaults () {\n this.appearance.heatmap = {}\n this.appearance.heatmap.cellSize = 50\n this.appearance.heatmap.columns = this.data.matrix[0].length\n this.appearance.heatmap.rows = this.data.matrix.length\n this.appearance.heatmap.width = this.appearance.heatmap.cellSize * this.appearance.heatmap.columns\n this.appearance.heatmap.height = this.appearance.heatmap.cellSize * this.appearance.heatmap.rows\n\n // Main Title\n if (this.settings.title !== '') {\n this.appearance.title = {\n font: {\n size: 16\n },\n padding: {\n bottom: 20\n }\n }\n } else {\n this.appearance.title = {\n font: {\n size: 0\n },\n padding: {\n bottom: 0\n }\n }\n }\n // Row Axis Title\n this.appearance.rowAxis = {}\n if (this.settings.rowAxis !== '') {\n this.appearance.rowAxis.title = {\n font: {\n size: 12\n },\n padding: {\n left: 30\n }\n }\n } else {\n this.appearance.rowAxis.title = {\n font: {\n size: 0\n },\n padding: {\n left: 0\n }\n }\n }\n // Col Axis Title\n this.appearance.colAxis = {}\n if (this.settings.colAxis !== '') {\n this.appearance.colAxis.title = {\n font: {\n size: 12\n },\n padding: {\n top: 30\n }\n }\n } else {\n this.appearance.colAxis.title = {\n font: {\n size: 0\n },\n padding: {\n top: 0\n }\n }\n }\n // Row Labels\n this.appearance.rowAxis.labels = {\n font: {\n size: 14\n },\n padding: {\n left: 15\n },\n width: this.data.rowLabels.width\n }\n // Col Labels\n this.appearance.colAxis.labels = {\n font: {\n size: 14\n },\n padding: {\n top: 15\n },\n height: this.data.colLabels.height\n }\n // Clustering\n var size = [] // Row Size, Col Size\n var padding = [] // Row R, Col T (only between dendrogram and heatmap)\n if (this.data.rowTree != null) var rowHeight = 50 + this.data.rowTree.height * 0.2\n if (this.data.colTree != null) var colHeight = 50 + this.data.colTree.height * 0.2\n // console.log('row height' + rowHeight)\n // console.log('col height' + rowHeight)\n switch (this.settings.clustering.type) {\n case 'n':\n size = [0, 0]\n padding = [0, 0]\n break\n case 'r':\n size = [rowHeight, 0]\n padding = [10, 0]\n break\n case 'c':\n size = [0, colHeight]\n padding = [0, 10]\n break\n case 'b':\n size = [rowHeight, colHeight]\n padding = [10, 10]\n break\n default:\n size = [0, 0]\n padding = [0, 0]\n break\n }\n this.appearance.clustering = {\n row: {\n size: size[0],\n padding: {\n right: padding[0]\n }\n },\n col: {\n size: size[1],\n padding: {\n bottom: padding[1]\n }\n }\n }\n\n // Canvas\n this.appearance.margin = {\n left: 50,\n right: 50,\n top: 50,\n bottom: 50\n }\n this.configureComponents()\n }", "function loadHeatMap(gridCellIdx) {\n var extra_bottom_margin = 50;\n var excess_top_margin = 30;\n\n var svg = svg_list[gridCellIdx];\n var height = svg_height_list[gridCellIdx];\n var width = svg_width_list[gridCellIdx];\n\n var onlyUnique = (value, index, self) => {\n return self.indexOf(value) === index;\n }\n\n var type1 = base_data.map(a => a[\"Type 1\"]);\n var type2 = base_data.map(a => a[\"Type 2\"]);\n\n var allTypes = type1.concat(type2);\n allTypes = allTypes.filter(onlyUnique);\n allTypes = allTypes.sort((a, b) => {\n if (a < b)\n return -1;\n\n if (b > a)\n return 1;\n\n return 0;\n });\n\n // Build X scales and axis:\n var x = d3.scaleBand()\n .range([ left_margin, width * 0.95 ])\n .domain(allTypes)\n .padding(0.01);\n svg.append(\"g\")\n .attr(\"transform\", \"translate(0,\" + (height - (bottom_margin + extra_bottom_margin)) + \")\")\n .call(d3.axisBottom(x))\n .selectAll(\"text\")\n .attr(\"y\", 12)\n .attr(\"x\", 5)\n .attr(\"dy\", \".35em\")\n .attr(\"transform\", \"rotate(-30)\")\n .style(\"text-anchor\", \"end\")\n .text(function(d, i) {\n if (d === \"\")\n return \"None\";\n else\n return d;\n });\n\n // Build Y scales and axis:\n var y = d3.scaleBand()\n .range([ height - (bottom_margin + extra_bottom_margin), top_margin - excess_top_margin ])\n .domain(allTypes)\n .padding(0.01);\n svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + left_margin + \", 0)\")\n .call(d3.axisLeft(y))\n .selectAll(\"text\")\n .text(function(d, i) {\n if (d === \"\")\n return \"None\";\n else\n return d;\n });\n\n var data = setupHeatMapData(allTypes, base_data);\n\n var avgList = data.map(a => +a[\"Special Stats Avg\"]);\n var maxAvg = Math.max.apply(null, avgList);\n maxAvg = Math.ceil(maxAvg);\n\n // Build color scale\n var myColor = d3.scaleLinear()\n .range([\"black\", \"orange\"])\n .domain([0, maxAvg])\n\n // Add the squares\n svg.selectAll()\n .data(data, function(d) {return d[\"Type 1\"]+':'+d[\"Type 2\"];})\n .enter()\n .append(\"rect\")\n .attr(\"x\", function(d) { return x(d[\"Type 1\"]) })\n .attr(\"y\", function(d) { return y(d[\"Type 2\"]) })\n .attr(\"width\", x.bandwidth() )\n .attr(\"height\", y.bandwidth() )\n .style(\"fill\", function(d) { return myColor(d[\"Special Stats Avg\"])} )\n\n // Append a defs (for definition) element to the SVG\n var defs = svg.append(\"defs\");\n\n // Append a linearGradient element to the defs\n var linearGradient = defs.append(\"linearGradient\")\n .attr(\"id\", \"linear-gradient\")\n .attr(\"x1\", \"0%\")\n .attr(\"y1\", \"0%\")\n .attr(\"x2\", \"100%\")\n .attr(\"y2\", \"0%\");\n\n // Set the color for the start (0%)\n linearGradient.append(\"stop\")\n .attr(\"offset\", \"0%\")\n .attr(\"stop-color\", \"black\");\n\n // Set the color for the end (100%)\n linearGradient.append(\"stop\")\n .attr(\"offset\", \"100%\")\n .attr(\"stop-color\", \"orange\");\n\n var center_point = (width/2);\n\n // Draw the rectangle and fill with gradient\n svg.append(\"rect\")\n .attr(\"width\", 300)\n .attr(\"height\", 20)\n .style(\"fill\", \"url(#linear-gradient)\")\n .attr(\"transform\", \"translate(\" + (center_point-150) + \",\" + (height - bottom_margin - 10) + \")\");\n\n // Gradient legend minimum value label\n svg.append(\"text\")\n .attr(\"transform\", \"translate(\" + ((center_point-150)-10) + \" ,\" + (height - bottom_margin + 5) + \")\")\n .attr(\"font-weight\", \"bold\")\n .style(\"text-anchor\", \"end\")\n .text(\"0\");\n\n // Gradient legend maximum value label\n svg.append(\"text\")\n .attr(\"transform\", \"translate(\" + ((center_point+150)+10) + \" ,\" + (height - bottom_margin + 5) + \")\")\n .attr(\"font-weight\", \"bold\")\n .style(\"text-anchor\", \"start\")\n .text(maxAvg);\n}", "function loadStarPlot(gridCellIdx) {\n var svg = svg_list[gridCellIdx];\n var height = svg_height_list[gridCellIdx];\n var width = svg_width_list[gridCellIdx];\n\n var x_center_start = width * 0.6;\n var y_center_start = height * 0.45;\n\n let features = [\"HP\", \"Attack\", \"Defense\", \"Sp. Atk\", \"Sp. Def\", \"Speed\"];\n\n var data = avgDataByColumn(base_data, features, \"Evolution\");\n data.sort((a, b) => (a[\"Evolution\"] > b[\"Evolution\"]) ? 1 : -1)\n\n let radialScale = d3.scaleLinear().domain([0, 100])\n .range([0, height * 0.35]);\n\n let ticks = [20, 40, 60, 80, 100];\n // Draw grid lines (circles)\n ticks.forEach(t =>\n svg.append(\"circle\")\n .attr(\"cx\", x_center_start)\n .attr(\"cy\", y_center_start)\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"gray\")\n .attr(\"r\", radialScale(t))\n );\n // Draw tick labels\n ticks.forEach(t =>\n svg.append(\"text\")\n .attr(\"x\", x_center_start + 5)\n .attr(\"y\", y_center_start - radialScale(t))\n .text(t.toString())\n );\n // Draw axis for each feature\n var angleToCoordinate = (angle, value) => {\n let x = Math.cos(angle) * radialScale(value);\n let y = Math.sin(angle) * radialScale(value);\n return {\"x\": x_center_start + x, \"y\": y_center_start - y};\n }\n\n for (var i = 0; i < features.length; i++) {\n let ft_name = features[i];\n let angle = (Math.PI / 2) + (2 * Math.PI * i / features.length);\n let line_coordinate = angleToCoordinate(angle, 100);\n let label_coordinate = angleToCoordinate(angle, 120);\n svg.append(\"line\")\n .attr(\"x1\", x_center_start)\n .attr(\"y1\", y_center_start)\n .attr(\"x2\", line_coordinate.x)\n .attr(\"y2\", line_coordinate.y)\n .attr(\"stroke\",\"black\")\n svg.append(\"text\")\n .attr(\"x\", label_coordinate.x)\n .attr(\"y\", label_coordinate.y + 5)\n .style(\"text-anchor\", \"middle\")\n .text(ft_name);\n }\n // Drawing the line for the spider chart\n let line = d3.line().x(d => d.x).y(d => d.y);\n let colors = [\"darkgreen\", \"deeppink\", \"darkorange\", \"navy\"];\n\n // Get coordinates for a data point\n var getPathCoordinates = (d) => {\n let coordinates = [];\n for (var i = 0; i < features.length; i++){\n let ft_name = features[i];\n let angle = (Math.PI / 2) + (2 * Math.PI * i / features.length);\n coordinates.push(angleToCoordinate(angle, d[ft_name]));\n }\n return coordinates;\n }\n\n for (var i = 0; i < data.length; i ++){\n let d = data[i];\n let color = colors[i];\n d[\"Color\"] = color;\n let coordinates = getPathCoordinates(d);\n\n // Draw the path element\n svg.append(\"path\")\n .datum(coordinates)\n .attr(\"d\",line)\n .attr(\"stroke-width\", 3)\n .attr(\"stroke\", color)\n .attr(\"fill\", color)\n .attr(\"stroke-opacity\", 1)\n .attr(\"opacity\", 0.35);\n }\n\n // Initialize the element containers for the legend items\n var legend = svg.selectAll(\"g.sp_legend\")\n .data(data)\n .enter().append(\"g\")\n .attr(\"class\", \"sp_legend\")\n .attr(\"transform\", function(d, i) { return \"translate(50,\" + i * 25 + \")\"; });\n\n // Initialize the color box of the legend items\n legend.append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", top_margin)\n .attr(\"width\", 18)\n .attr(\"height\", 18)\n .style(\"fill\", function(d, i) {return d[\"Color\"];});\n\n // Initialize the text label of the legend items\n legend.append(\"text\")\n .attr(\"x\", 22)\n .attr(\"y\", top_margin + 9)\n .attr(\"dy\", \".35em\")\n .style(\"text-anchor\", \"start\")\n .text(function(d, i) {\n let evol = d[\"Evolution\"];\n let evolCategories = [\"Does Not Evolve\", \"1st Evolution\", \"2nd Evolution\", \"3rd Evolution\"];\n return evolCategories[evol];\n });\n}", "createHeatmapLayers() {\n const properties = [\"deaths\", \"kills\"];\n let heatmapConfig = assign({}, this.state.heatmapConfig);\n let heatmapLayers = {};\n\n heatmapConfig.gradient = { \".3\": \"yellow\", \".4\": \"orange\", \"1\": \"red\" };\n heatmapLayers = h337.create(heatmapConfig);\n\n this.setState({ heatmapLayers });\n }", "function showConjugates () {\n\n pointsTable = lens.pointsTable.getData(); \n pointsList = Optics.calculatePointToPoint(renderableLens.total, pointsTable);\n totalLens = renderableLens.total;\n\n if (pointsList.length > 0) {\n pointsList.forEach( elem => {\n console.log(\"showing .... conjugate pair id = \" + elem.id);\n drawConjugates(elem, displayOptions);\n } );\n }\n }", "function finalChord() {\n\t\n\t/*Remove button*/\n\td3.select(\"#clicker\")\n\t\t.style(\"visibility\", \"hidden\");\n\td3.select(\"#skip\")\n\t\t.style(\"visibility\", \"hidden\");\n\td3.select(\"#progress\")\n\t\t.style(\"visibility\", \"hidden\");\n\t\n\t/*Remove texts*/\n\tchangeTopText(newText = \"\",\n\t\tloc = 0, delayDisappear = 0, delayAppear = 1);\n\tchangeBottomText(newText = \"\",\n\t\tloc = 0, delayDisappear = 0, delayAppear = 1);\t\t\t\n\n\t/*Create arcs or show them, depending on the point in the visual*/\n\tif (counter <= 4 ) {\n\t\tg.append(\"svg:path\")\n\t\t .style(\"stroke\", function(d) { return fill(d.index); })\n\t\t .style(\"fill\", function(d) { return fill(d.index); })\n\t\t .attr(\"d\", arc)\n\t\t .style(\"opacity\", 0)\n\t\t .transition().duration(1000)\n\t\t .style(\"opacity\", 1);\n\t\t \n\t} else {\n\t\t /*Make all arc visible*/\n\t\tsvg.selectAll(\"g.group\").select(\"path\")\n\t\t\t.transition().duration(1000)\n\t\t\t.style(\"opacity\", 1);\n\t};\n\t\n\t/*Make mouse over and out possible*/\n\td3.selectAll(\".group\")\n\t\t.on(\"mouseover\", fade(.02))\n\t\t.on(\"mouseout\", fade(.80));\n\t\t\n\t/*Show all chords*/\n\tchords.transition().duration(1000)\n\t\t.style(\"opacity\", opacityValueBase);\n\n\t/*Show all the text*/\n\td3.selectAll(\"g.group\").selectAll(\"line\")\n\t\t.transition().duration(100)\n\t\t.style(\"stroke\",\"#000\");\n\t/*Same for the %'s*/\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(100)\n\t\t.selectAll(\".tickLabels\").style(\"opacity\",1);\n\t/*And the Names of each Arc*/\t\n\tsvg.selectAll(\"g.group\")\n\t\t.transition().duration(100)\n\t\t.selectAll(\".titles\").style(\"opacity\",1);\t\t\n\n}", "function drawUserSelectedTimeTTCDataOnMap(data)\n{\n //console.log(\"drawUserSelectedTimeTTCDataOnMap: data received is: \", data);\n var numberOfVehicles = data.length;\n //console.log(\"numberOfVehicles is: \", numberOfVehicles);\n\n // Remove old vehicles from ttcVehicleLocations\n ttcVehicleLocations.splice(0,ttcVehicleLocations.length);\n\n // Formatting the data to send to ttcHeatmap\n var i;\n for(i = 0; i < numberOfVehicles; i++)\n {\n var latitude = data[i][\"coordinates\"][1];\n var longitude = data[i][\"coordinates\"][0];\n var entry = new google.maps.LatLng(latitude, longitude);\n ttcVehicleLocations.push(entry);\n }\n\n console.log(\"new ttcVehicleLocations.length after push is: \", ttcVehicleLocations.length);\n\n //Remove old ttcHeatmap data\n ttcHeatmap.setMap(null);\n\n //Add in new one\n //heatmap.setdata(ttcVehicleLocations)\n //heatmap.setMap(ttcMap)\n\n ttcHeatmap = new google.maps.visualization.HeatmapLayer({\n data: ttcVehicleLocations,\n map: ttcMap\n });\n\n //Dont show the please wait modal as new ttcHeatmap generated\n $('#myPleaseWait').modal('hide');\n return;\n}", "function drawBoard()\n{\n\tfor(let i = 0; i < 7; i++)\n\t{\n\t\tfor(let j = 0; j < 6; j++)\n\t\t{\n\t\t\tif(allChips[i][j] == 0)\n\t\t\t{\n\t\t\t\tctx.beginPath();\n\t\t\t\tctx.fillStyle = 'white';\n\t\t\t\tctx.arc((40+50*i), (40+50*j), 20, 0, 2 * Math.PI);\n\t\t\t\tctx.fill();\n\t\t\t\tctx.stroke();\n\t\t\t}\n\t\t\telse if(allChips[i][j] == 1)\n\t\t\t{\n\t\t\t\tctx.beginPath();\n\t\t\t\tctx.fillStyle = 'red';\n\t\t\t\tctx.arc((40+50*i), (40+50*j), 20, 0, 2 * Math.PI);\n\t\t\t\tctx.fill();\t\t\t}\n\t\t\telse //allChips[i][j] == 2\n\t\t\t{\n\t\t\t\tctx.beginPath();\n\t\t\t\tctx.fillStyle = 'yellow';\n\t\t\t\tctx.arc((40+50*i), (40+50*j), 20, 0, 2 * Math.PI);\n\t\t\t\tctx.fill();\n\t\t\t}\n\t\t}\n\t}\n}", "function setup (){\n \n pjCol = 0; //pixeles\n pjFill = 0; // pixeles\n xPos = (pjCol * 40)+ 20;\n xPos = (pjFill * 40)+ 20;\n\n\n// Crear arreglo de arreglos\nfor (let index = 0; index < 20; index ++){\n\n mapa.push (new Array(20));\n}\n\n//Asignar valores iniciales\nfor (let fill = 0; fill < 20; fill++){\n for (let col = 0; col < 6; col++){\n mapa [fill][col] = 0;\n }\n}\n\n//seleccionamos algunos [fill][col] --> y, x\nmapa [0][0] = 1;\nmapa [0][1] = 1;\nmapa [0][4] = 1;\nmapa [0][5] = 1;\nmapa [1][0] = 1;\nmapa [1][1] = 1;\nmapa [1][4] = 1;\nmapa [1][5] = 1;\nmapa [2][0] = 1;\nmapa [2][1] = 1;\nmapa [2][4] = 1;\nmapa [2][5] = 1;\nmapa [3][4] = 1;\nmapa [4][4] = 1;\nmapa [3][5] = 1;\n \n}", "function extractionCallback(data) {\n var heatmapData = [];\n for (var key in data) {\n if (data.hasOwnProperty(key) && data[key].avgDelay > 0) { // && (Date.now() - data[key].timestamp) < 900000 ){ //15min\n heatmapData.push({\n location: new google.maps.LatLng(data[key].center.lat, data[key].center.lng),\n weight: (data[key].avgDelay)\n });\n }\n }\n map.drawHeatmap(heatmapData);\n }", "function renderMap() {\n\n //Clear old map data\n deleteMarkers();\n initMap();\n\n var infoWindow = new google.maps.InfoWindow();\n for (var key in streamValues){\n var position = new google.maps.LatLng(streamValues[key].latitude, streamValues[key].longitude);\n bounds.extend(position);\n addMarker(position);\n map.fitBounds(bounds);\n path.push(position);\n\n let infoContent = \"<b>ts</b>: \"+ moment(streamValues[key].ts).format('MMMM Do YYYY, H:mm:ss') + \"</br>\" +\n \"<b>lat</b>: \" + streamValues[key].latitude + \"</br>\" +\n \"<b>long</b>: \" + streamValues[key].longitude + \"</br>\";\n google.maps.event.addListener(markers[key], 'click', (function(marker, key) {\n return function() {\n infoWindow.setContent(infoContent);\n infoWindow.open(map, marker);\n }\n })(markers[key], key));\n }\n\n heatmap = new google.maps.visualization.HeatmapLayer({\n data: path\n });\n\n polyline.setPath(path);\n}", "function heatmapLayer(values) {\n var data = new ol.source.Vector();\n\n for (var i = 0; i< values.length; i++) {\n var v = values[i];\n var coord = ol.proj.transform([v[0], v[1]],'EPSG:4326', 'EPSG:3857');\n var lonLat = new ol.geom.Point(coord);\n var pointFeature = new ol.Feature({\n geometry: lonLat,\n weight:v[2]\n });\n\n data.addFeature(pointFeature);\n }\n \n //building the heatmap layer\n var heatmapLayer = new ol.layer.Heatmap({\n source:data,\n radius:50,\n opacity:0.9\n });\n\n return heatmapLayer;\n}", "drawBoard(){\n for(var i = 0; i<this.numColumns; i++){\n this.boardData.push([]);\n\n for(var j = 0; j<this.numRows; j++){\n\n this.boardData[i].push(new Hex(this, this.initOffset.x + i*this.hexWidth,this.initOffset.y +j*this.vertOffset, ((j%2) * this.hexWidth/2), {row: j, col: i}, this.hexScale, this.game));\n this.boardData[i][j].draw();\n\n }\n }\n console.log(this.identifierDict);\n\n }", "function calcHeatMapBG(){\n $(\".heat-map-cell\").each(function (i, cell) {\n calcHeatMapCellBackground(cell);\n })\n }", "function chartHeatMapTable () {\n\n /* Default Properties */\n var svg = void 0;\n var chart = void 0;\n var classed = \"heatMapTable\";\n var width = 400;\n var height = 300;\n var margin = { top: 50, right: 20, bottom: 20, left: 50 };\n var transition = { ease: d3.easeBounce, duration: 500 };\n var colors = [\"#D34152\", \"#f4bc71\", \"#FBF6C4\", \"#9bcf95\", \"#398abb\"];\n var dispatch = d3.dispatch(\"customValueMouseOver\", \"customValueMouseOut\", \"customValueClick\", \"customSeriesMouseOver\", \"customSeriesMouseOut\", \"customSeriesClick\");\n\n /* Chart Dimensions */\n var chartW = void 0;\n var chartH = void 0;\n\n /* Scales */\n var xScale = void 0;\n var yScale = void 0;\n var colorScale = void 0;\n\n /* Other Customisation Options */\n var thresholds = void 0;\n\n /**\n * Initialise Data and Scales\n *\n * @private\n * @param {Array} data - Chart data.\n */\n function init(data) {\n chartW = width - margin.left - margin.right;\n chartH = height - margin.top - margin.bottom;\n\n var _dataTransform$summar = dataTransform(data).summary(),\n rowKeys = _dataTransform$summar.rowKeys,\n columnKeys = _dataTransform$summar.columnKeys,\n tmpThresholds = _dataTransform$summar.thresholds;\n\n if (typeof thresholds === \"undefined\") {\n thresholds = tmpThresholds;\n }\n\n if (typeof colorScale === \"undefined\") {\n colorScale = d3.scaleThreshold().domain(thresholds).range(colors);\n }\n\n xScale = d3.scaleBand().domain(columnKeys).range([0, chartW]).padding(0.1);\n\n yScale = d3.scaleBand().domain(rowKeys).range([0, chartH]).padding(0.1);\n }\n\n /**\n * Constructor\n *\n * @constructor\n * @alias heatMapTable\n * @param {d3.selection} selection - The chart holder D3 selection.\n */\n function my(selection) {\n // Create SVG element (if it does not exist already)\n if (!svg) {\n svg = function (selection) {\n var el = selection._groups[0][0];\n if (!!el.ownerSVGElement || el.tagName === \"svg\") {\n return selection;\n } else {\n return selection.append(\"svg\");\n }\n }(selection);\n\n svg.classed(\"d3ez\", true).attr(\"width\", width).attr(\"height\", height);\n\n chart = svg.append(\"g\").classed(\"chart\", true);\n } else {\n chart = selection.select(\".chart\");\n }\n\n // Update the chart dimensions and add layer groups\n var layers = [\"heatRowGroups\", \"xAxis axis\", \"yAxis axis\"];\n chart.classed(classed, true).attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\").attr(\"width\", chartW).attr(\"height\", chartH).selectAll(\"g\").data(layers).enter().append(\"g\").attr(\"class\", function (d) {\n return d;\n });\n\n selection.each(function (data) {\n // Initialise Data\n init(data);\n\n // Heat Map Rows\n var heatMapRow = component.heatMapRow().width(chartW).height(chartH).colorScale(colorScale).xScale(xScale).yScale(yScale).dispatch(dispatch).thresholds(thresholds);\n\n // Create Series Group\n var seriesGroup = chart.select(\".heatRowGroups\").selectAll(\".seriesGroup\").data(data);\n\n seriesGroup.enter().append(\"g\").attr(\"class\", \"seriesGroup\").attr(\"transform\", function (d) {\n return \"translate(0, \" + yScale(d.key) + \")\";\n }).merge(seriesGroup).call(heatMapRow);\n\n seriesGroup.exit().remove();\n\n // X Axis\n var xAxis = d3.axisTop(xScale);\n\n chart.select(\".xAxis\").call(xAxis).selectAll(\"text\").attr(\"y\", 0).attr(\"x\", -8).attr(\"transform\", \"rotate(60)\").style(\"text-anchor\", \"end\");\n\n // Y Axis\n var yAxis = d3.axisLeft(yScale);\n\n chart.select(\".yAxis\").call(yAxis);\n });\n }\n\n /**\n * Width Getter / Setter\n *\n * @param {number} _v - Width in px.\n * @returns {*}\n */\n my.width = function (_v) {\n if (!arguments.length) return width;\n width = _v;\n return this;\n };\n\n /**\n * Height Getter / Setter\n *\n * @param {number} _v - Height in px.\n * @returns {*}\n */\n my.height = function (_v) {\n if (!arguments.length) return height;\n height = _v;\n return this;\n };\n\n /**\n * Margin Getter / Setter\n *\n * @param {number} _v - Margin in px.\n * @returns {*}\n */\n my.margin = function (_v) {\n if (!arguments.length) return margin;\n margin = _v;\n return this;\n };\n\n /**\n * Colors Getter / Setter\n *\n * @param {Array} _v - Array of colours used by color scale.\n * @returns {*}\n */\n my.colors = function (_v) {\n if (!arguments.length) return colors;\n colors = _v;\n return this;\n };\n\n /**\n * Color Scale Getter / Setter\n *\n * @param {d3.scale} _v - D3 color scale.\n * @returns {*}\n */\n my.colorScale = function (_v) {\n if (!arguments.length) return colorScale;\n colorScale = _v;\n return this;\n };\n\n /**\n * Thresholds Getter / Setter\n *\n * @param {Array} _v - Array of thresholds.\n * @returns {*}\n */\n my.thresholds = function (_v) {\n if (!arguments.length) return thresholds;\n thresholds = _v;\n return this;\n };\n\n /**\n * Transition Getter / Setter\n *\n * @param {d3.transition} _v - D3 transition style.\n * @returns {*}\n */\n my.transition = function (_v) {\n if (!arguments.length) return transition;\n transition = _v;\n return this;\n };\n\n /**\n * Dispatch Getter / Setter\n *\n * @param {d3.dispatch} _v - Dispatch event handler.\n * @returns {*}\n */\n my.dispatch = function (_v) {\n if (!arguments.length) return dispatch();\n dispatch = _v;\n return this;\n };\n\n /**\n * Dispatch On Getter\n *\n * @returns {*}\n */\n my.on = function () {\n var value = dispatch.on.apply(dispatch, arguments);\n return value === dispatch ? my : value;\n };\n\n return my;\n }", "function draftRndHeatmap() {\n var element = document.getElementById(\"draft-round\");\n //element.innerHTML = \"\";\n\n var route = \"/draft/rnd/\";\n\n Plotly.d3.json(route, function(error, response) {\n if (error) return console.warn(error);\n\n var data = response;\n\n var layout = {\n title: '# College players drafted in each round of NFL Draft',\n titlefont: {size: 24},\n\n }\n \n var RND = document.getElementById(\"draft-round\");\n Plotly.newPlot(RND, data, layout);\n });\n}", "function getHexMap(numColumns, numRows) {\n var columns = [];\n for (var c = 0; c < numColumns; c++) {\n var row = [];\n for (var r = 0; r < numRows; r++) {\n row.push(randomTile());\n }\n columns.push(row);\n }\n return columns;\n}", "function drawHeatMap(element, data, options) {\n\n if (!options.selectedObjects || !options.selectedObjects.length) {\n return;\n }\n if (!options.selectedStatistics || !options.selectedStatistics.length) {\n return;\n }\n\n /*console.log('data: '); \n console.log (data);\n console.log('options: '); \n console.log (options);*/\n\n // Show the selected objects by the Pulse user with this widget\n var displayObjects = data.objects\n .filter((object) => options.selectedObjects.includes(object.id));\n \n // Show the selected statistics by the Pulse user with this widget\n var displayStats = data.statistics\n .filter((stat) => options.selectedStatistics.includes(stat.id));\n \n // Generate the data structure to be displayed in highcharts\n //[[0, 0, 10], [0, 1, 19], [0, 2, 8], [0, 3, 24], [0, 4, 67], [1, 0, 92], [1, 1, 58], [1, 2, 78], [1, 3, 117], [1, 4, 48], [2, 0, 35], [2, 1, 15], [2, 2, 123], [2, 3, 64], [2, 4, 52], [3, 0, 72], [3, 1, 132], [3, 2, 114], [3, 3, 19], [3, 4, 16], [4, 0, 38], [4, 1, 5], [4, 2, 8], [4, 3, 117], [4, 4, 115], [5, 0, 88], [5, 1, 32], [5, 2, 12], [5, 3, 6], [5, 4, 120], [6, 0, 13], [6, 1, 44], [6, 2, 88], [6, 3, 98], [6, 4, 96], [7, 0, 31], [7, 1, 1], [7, 2, 82], [7, 3, 32], [7, 4, 30], [8, 0, 85], [8, 1, 97], [8, 2, 123], [8, 3, 64], [8, 4, 84], [9, 0, 47], [9, 1, 114], [9, 2, 31], [9, 3, 48], [9, 4, 91]],\n\n var displayData = [];\n\n for (var i = 0; i < displayObjects.length; i++) {\n for (var j = 0; j < displayStats.length; j++) {\n displayData.push([i,j,displayStats[j].values[i]]);\n } \n }\n \n\n var xObjectScale = displayObjects.map((object) => object.label);\n var yStatScale = displayStats.map((stat) => stat.label);\n\n //console.log(xObjectScale);\n //console.log(yStatScale);\n\n //Show generated data to be displayed in the chart based on snapshot data\n //console.log('displayed data');\n //console.log(displayData);\n\n \tHighcharts.chart(element, {\n\n\t\t chart: {\n\t\t type: 'heatmap',\n\t\t height: options.height,\n marginTop: 10,\n\t\t marginBottom: 100,\n\t\t plotBorderWidth: 1\n\t\t },\n\n\t\t title: {\n text: '',\n },\n\n\t\t xAxis: {\n\t\t categories: xObjectScale\n\t\t },\n\n\t\t yAxis: {\n\t\t categories: yStatScale,\n\t\t title: null\n\t\t },\n\n\t\t colorAxis: {\n\t\t min: 0,\n\t\t minColor: '#FFFFFF',\n\t\t maxColor: Highcharts.getOptions().colors[0]\n\t\t },\n\n\t\t legend: {\n\t\t align: 'right',\n\t\t layout: 'vertical',\n\t\t margin: 0,\n\t\t verticalAlign: 'top',\n\t\t y: 25,\n\t\t symbolHeight: 280\n\t\t },\n\n tooltip: {\n formatter: function () {\n return '<b>' + this.series.xAxis.categories[this.point.x] + '</b> has <br><b>' +\n this.point.value + '</b> agents in the <br><b>' + this.series.yAxis.categories[this.point.y] + ' status </b>';\n }\n },\n\n\t\t series: [{\n\t\t name: 'Sales per employee',\n\t\t borderWidth: 1,\n\t\t data: displayData,\n\t\t dataLabels: {\n\t\t enabled: true,\n\t\t color: '#000000'\n\t\t }\n\t\t }]\n\n });\n\n return true;\n\n }", "function _selectionHandler(t, c) {\n \n\tvar $this = $(t).closest('.hm-container').parent();\n\tvar $cfg = $this.data('heatmap').config;\n\n\tif ($cfg.onReady.state != loadStates.READY) return true;\n\n\tvar $ctx = $($this).data('ctx');\n\n\tvar start_x = Math.min(c.x1, c.x2) - $ctx.heatmap_bbox[0];\n\tvar end_x = Math.max(c.x1, c.x2) - $ctx.heatmap_bbox[0];\n\t\n\tvar start_y = Math.min(c.y1, c.y2) - $ctx.heatmap_bbox[1];\n\tvar end_y = Math.max(c.y1, c.y2) - $ctx.heatmap_bbox[1];\n\t\n\tvar startCol = parseInt(start_x / $ctx.pix_per_col);\n\tvar endCol = parseInt(end_x / $ctx.pix_per_col + 1);\n\t\n\tvar startRow = parseInt(start_y / $ctx.pix_per_row);\n\tvar endRow = parseInt(end_y / $ctx.pix_per_row + 1);\n\t\n\t;;; var id = $($this).attr(\"id\");\n\t//;;; _debug(id + ': ' + c.x1 + ' ' + c.x2 + ' ' + c.y1 + ' ' + c.y2 + ' ' + c.width + ' ' + c.height);\n\t//;;; _debug(\"startRow: \" + startRow + \" endRow: \" + endRow + \" startCol: \" + startCol + \" endCol: \" + endCol);\n\t\n\t//;;; _debug('onSelect: ' + typeof $cfg.onSelect.val);\n\tif (typeof $cfg.onSelect.val == 'function') {\n\t var startProfile, endProfile, startSample, endSample;\n\n\t if ($ctx.orient == 'ver') {\n\t\tstartSample = Math.max(0, startCol);\n\t\tendSample = Math.max(0, endCol);\n\t\tstartProfile = Math.max(0, startRow);\n\t\tendProfile = Math.max(0, endRow);\n\t }\n\t else {\n\t\tstartSample = Math.max(0, startRow);\n\t\tendSample = Math.max(0, endRow);\n\t\tstartProfile = Math.max(0, startCol);\n\t\tendProfile = Math.max(0, endCol);\n\t }\n\t\n\t var profiles = Array.prototype.slice.call($ctx.profile_metadata, startProfile, endProfile);\n\t var samples = Array.prototype.slice.call($ctx.sample_metadata, startSample, endSample);\n\n\t return $cfg.onSelect.val (profiles, samples, \n\t\t\t\t { start_profile: startProfile, end_profile: endProfile, \n\t\t\t\t\tstart_sample: startSample, end_sample: endSample }, $ctx);\n\t}\n\treturn true;\n }", "function plot(rows = 36, cols = 64) {\n\n /* 'c' will contain the whole generated html rect tags string to change innerhtml of enclosing div */\n /* 'y' will denote the 'y' coordinate where the next grid must be placed */\n let c = \"\", y = 0;\n\n /* Looping for each row */\n for (let i = 0; i < rows; i++) {\n\n /* 'x' is a coordinate denoting where the next grid must be placed */\n var x = 0;\n\n /* For each row we will loop for each column present in the Grid */\n for (let j = 0; j < cols; j++) {\n\n /* 'colr' will store the rest grid color which is dark gray currently */\n let colr = grid_color;\n\n /* If the Rectange present in the grid is on the border side then change the color in order to highlight borders */\n if(i === 0 || j === 0 || i === rows - 1 || j === cols - 1){\n colr = border_color;\n }\n\n /* Creating a rect tag that is appending in 'c' for now and will be updated to innerhtml of enclosing div */\n /* I know you will be wondering about the id given to each rect :-\n * Each rect must be provided with id in order to do anything with the corresponding rect.\n * Operations like coloring the grid as well saving saving any number in corresponding matrix needs an id of the rect.\n * Hence id is important to allot to each rect to make further changes in matrix on which whole algo is based.\n * In order to assing every rect id i decided to allot their corresponding row_number + : + col_number to be as id\n * As with this scenario it is easy to remember and will be unique for every rect tag. \n */\n c += `<rect id=${i + \":\" + j} x=\"${x}\" y=\"${y}\" width=\"30\" height=\"30\" fill=\"${colr}\" r=\"0\" rx=\"0\" ry=\"0\" stroke=\"#000\" style=\"-webkit-tap-highlight-color: rgba(0, 0, 0, 0); stroke-opacity: 0.2;\" stroke-opacity=\"0.2\"></rect>`;\n\n /* Incrementing the 'x' coordinate as we have width of 30px and hence 'x' coordinate for next rect will be +30 from current pos. */\n x += 30;\n }\n\n /* Incrementing the 'y' coordinate as we have placed sufficient rect in 1 row now need to advance 'y' as height of each rect \n is 30px hence for every rect in next column the y coordinate will be +30*/\n y += 30;\n }\n\n /* At last after creating rect tags using loops, now update innerHtml of enclosing div with id='container'[grid.html] */\n document.getElementById(\"container\").innerHTML = c;\n\n /* I wanted to preplace the Source - coordinate so at rect with id='src_crd' will be coloured green */\n document.getElementById(src_crd).style.fill = \"rgb(0, 255, 0)\";\n matrix[split(src_crd, 0)][split(src_crd, 1)] = 1; /* Update the pos as '1' to denote source location */\n\n /* I wanted to preplace the Destination - coordinate so at rect with id='dst_crd' will be coloured Red */\n document.getElementById(dst_crd).style.fill = \"rgb(255, 0, 0)\";\n matrix[split(dst_crd, 0)][split(dst_crd, 1)] = 2; /* Update the pos as '2' to denote Destination location */\n\n }", "function DrawMapHexExtras(Center:Vector2, type:int) {\n\tif (type==5 || type==6 || type==35 || type==37) {\n\t\tvar MapTexture : Texture2D = gameObject.GetComponent(MeshRenderer).material.mainTexture;\n\t\tvar OriginX = Center.x * MapTexture.width-35;\n\t\tvar OriginY = Center.y * MapTexture.height-48;\n\t\tfor (var iconY=0; iconY<SnowPattern.height; iconY++) {\n\t\t\tfor (var iconX=0; iconX<SnowPattern.width; iconX++) {\n\t\t\t\tfor (var i=0; i<10; i++) {\n\t\t\t\t\tvar testColor : Color = SnowPattern.GetPixel(iconX, iconY);\n\t\t\t\t\tif (UnityEngine.Random.Range(0.0, 1.0) < testColor.r) {\n\t\t\t\t\t\tvar TempColor = MapTexture.GetPixel(OriginX+iconX, OriginY+iconY);\n\t\t\t\t\t\tvar NewColor = (TempColor * 0.9) + (new Color(0.6, 0.6, 0.65) * 0.1);\n\t\t\t\t\t\tMapTexture.SetPixel(OriginX+iconX, OriginY+iconY, NewColor);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\t\t\t\n}", "display() {\r\n for (let i = 0; i < DIMENSIONS; i++) {\r\n for (let j = 0; j < DIMENSIONS; j++) {\r\n fill(TILE_COLOUR);\r\n rect(SCALE*i, SCALE*j, SCALE, SCALE);\r\n if (this.grid[i][j] > 0) {\r\n fill(TEXT_COLOUR);\r\n text(this.grid[i][j], SCALE*(i + 1/2), SCALE*(j + 1/2));\r\n }\r\n }\r\n }\r\n }", "function plotData(value, type) {\n\n d3.select(\"#matches_map\").selectAll(\"svg\").attr(\"pointer-events\", \"all\");\n \n d3.csv(\"data/matched_viz_v3.csv\", function(data) {\n \n if (type == \"ED\"){\n data = data.filter(function(d){return d.CENSUS_ENUMDIST == value;});\n } else if (type == \"graph\") {\n data = data.filter(function(d){ return parseInt(d.graph_ID) == value;});\n }\n\n var i = Math.floor(data.length / 2);\n\n map.flyTo( [data[i].LAT, data[i].LONG], zoom=18 );\n\n var svg = d3.select(\"#matches_map\")\n .select(\"svg\")\n .attr(\"id\", \"mapSVG\")\n .selectAll(\"cd_circles\")\n .data(data)\n .enter();\n \n // cd\n svg.append(\"circle\")\n .attr(\"id\", function(d) { return d.CD_ID })\n .attr(\"class\", \"cd\")\n .attr(\"cx\", function(d){ return map.latLngToLayerPoint([d.LAT, d.LONG]).x })\n .attr(\"cy\", function(d){ return map.latLngToLayerPoint([d.LAT, d.LONG]).y })\n .attr(\"r\", 20)\n .attr(\"visibility\", \"false\")\n .attr(\"pointer-events\", \"visible\")\n .style(\"fill\", \"#fd8b8b\")\n .attr(\"stroke\", false)\n .attr(\"fill-opacity\", .4)\n .on(\"mouseover\", function(d) {\n var className = \".\" + d.CD_ID;\n d3.selectAll(className)\n .style(\"font-weight\", \"bold\");\n\n table.row(className).scrollTo();\n\n })\n .on(\"mouseout\", function(d) {\n var className = \".\" + d.CD_ID;\n d3.selectAll(className)\n .style(\"font-weight\", \"normal\");\n })\n .on(\"click\", function(d) {\n var className = \".\" + d.CD_ID;\n d3.selectAll(className)\n .style(\"background\", \"#f2f2f2\");\n });\n\n // census\n svg.append(\"circle\")\n .attr(\"id\", function(d) { return d.CENSUS_ID; })\n .attr(\"class\", \"census\")\n .attr(\"cx\", function(d){ return map.latLngToLayerPoint([d.CENSUS_Y, d.CENSUS_X]).x })\n .attr(\"cy\", function(d){ return map.latLngToLayerPoint([d.CENSUS_Y, d.CENSUS_X]).y })\n .attr(\"r\", 20)\n .attr(\"visibility\", \"false\")\n .attr(\"pointer-events\", \"visible\")\n .style(\"fill\", \"#8ba4fd\")\n .attr(\"stroke\", false)\n .attr(\"fill-opacity\", .4)\n .on(\"mouseover\", function(d) {\n var className = \".\" + d.CENSUS_ID;\n d3.selectAll(className)\n .style(\"font-weight\", \"bold\");\n\n table.row(className).scrollTo();\n\n })\n .on(\"mouseout\", function(d) {\n var className = \".\" + d.CENSUS_ID;\n d3.selectAll(className)\n .style(\"font-weight\", \"normal\");\n })\n .on(\"click\", function(d) {\n var className = \".\" + d.CENSUS_ID;\n d3.selectAll(className)\n .style(\"background\", \"#f2f2f2\");\n });\n\n // matches\n svg.append(\"line\")\n .attr(\"id\", function(d) { return d.CD_ID + d.CENSUS_ID; })\n .attr(\"class\", \"match\")\n .attr(\"x1\", function(d) { return map.latLngToLayerPoint([d.LAT, d.LONG]).x; })\n .attr(\"y1\", function(d) { return map.latLngToLayerPoint([d.LAT, d.LONG]).y; })\n .attr(\"x2\", function(d) { return map.latLngToLayerPoint([d.CENSUS_Y, d.CENSUS_X]).x; })\n .attr(\"y2\", function(d) { return map.latLngToLayerPoint([d.CENSUS_Y, d.CENSUS_X]).y; }) \n .attr(\"visibility\", \"false\")\n .attr(\"pointer-events\", \"visible\")\n .attr(\"stroke\", function(d) {\n if (d.selected_algo == 1) {\n return \"black\";\n } else {\n return \"grey\";\n }\n })\n .attr(\"stroke-dasharray\", function(d) {\n if (d.selected_dist == 1) {\n return \"none\";\n } else {\n return \"20\";\n }\n })\n .attr(\"stroke-width\", 3)\n .style(\"opacity\", 0.5)\n .on(\"mouseover\", function(d) {\n var className = \".\" + d.CD_ID + \".\" + d.CENSUS_ID;\n d3.selectAll(className)\n .style(\"font-weight\", \"bold\");\n\n table.row(className).scrollTo();\n\n })\n .on(\"mouseout\", function(d) {\n var className = \".\" + d.CD_ID + \".\" + d.CENSUS_ID;\n d3.selectAll(className)\n .style(\"font-weight\", \"normal\");\n })\n .on(\"click\", function(d) {\n var className = \".\" + d.CD_ID + \".\" + d.CENSUS_ID;\n d3.selectAll(className)\n .style(\"background\", \"#fafafa\");\n });\n \n var tableWidth = document.getElementById(\"results\").offsetWidth;\n var tableHeight = document.getElementById(\"results\").offsetHeight;\n\n var table = $('#recordTable').DataTable({\n destroy: true,\n data: data,\n columns: [\n { \"data\" : \"graph_ID\", \"title\" : \"Graph\" },\n { \"data\" : \"group_ID\", \"title\" : \"Group\" },\n { \"data\" : \"CENSUS_ENUMDIST\", \"title\" : \"ED\" },\n { \"data\" : \"CD_ID\", \"title\" : \"CD\" },\n { \"data\" : \"CENSUS_ID\", \"title\" : \"CENSUS\" },\n { \"data\" : \"CD_FIRST_NAME\", \"title\" : \"CD First Name\" },\n { \"data\" : \"CD_LAST_NAME\", \"title\" : \"CD Last Name\" },\n { \"data\" : \"MATCH_ADDR\", \"title\" : \"CD Addr\" },\n { \"data\" : \"CD_OCCUPATION\", \"title\" : \"CD Occupation\" },\n { \"data\" : \"CENSUS_NAMEFRSCLEAN\", \"title\" : \"Cen First Name\" },\n { \"data\" : \"CENSUS_NAMELASTB\", \"title\" : \"Cen Last Name\" },\n { \"data\" : \"CENSUS_MATCH_ADDR\", \"title\" : \"Cen Addr\" },\n { \"data\" : \"CENSUS_AGE\", \"title\" : \"Age\" },\n { \"data\" : \"CENSUS_OCCLABELB\", \"title\" : \"Cen Occupation\" },\n { \"data\" : \"confidence_score\", \"title\" : \"Confidence Score\" },\n { \"data\" : \"in_cluster\", \"title\" : \"Cluster\" },\n { \"data\" : \"spatial_weight\", \"title\" : \"Spatial Weight\" },\n { \"data\" : \"selected_algo\", \"title\" : \"Selected\" },\n { \"data\" : \"selected_dist\", \"title\" : \"True\" },\n { \"data\" : \"dist\", \"title\" : \"Distance\" }\n ],\n initComplete: function () {\n this.api().columns().every( function () {\n var column = this;\n var select = $('<input type=\"text\" placeholder=\"Search\" size=\"3\"/>')\n .appendTo( $(column.header()) )\n .on( 'keyup', function () {\n var val = $.fn.dataTable.util.escapeRegex(\n $(this).val()\n );\n \n column\n .search( val )\n .draw();\n } );\n\n } );\n },\n \"ordering\" : false,\n scrollY: tableHeight * 0.7,\n scrollX: tableWidth * 0.9,\n scroller: true,\n \"createdRow\": function(row, data, dataIndex) {\n $(row).addClass(data.CD_ID);\n $(row).addClass(data.CENSUS_ID);\n },\n dom: 'Bfrtip',\n buttons: [ 'colvis' ]\n });\n\n // update location on zoom\n map.on(\"moveend\", function() {\n d3.selectAll(\".cd\")\n .attr(\"cx\", function(d){ return map.latLngToLayerPoint([d.LAT, d.LONG]).x })\n .attr(\"cy\", function(d){ return map.latLngToLayerPoint([d.LAT, d.LONG]).y });\n\n d3.selectAll(\".census\")\n .attr(\"cx\", function(d){ return map.latLngToLayerPoint([d.CENSUS_Y, d.CENSUS_X]).x })\n .attr(\"cy\", function(d){ return map.latLngToLayerPoint([d.CENSUS_Y, d.CENSUS_X]).y });\n\n d3.selectAll(\".match\")\n .attr(\"x1\", function(d) { return map.latLngToLayerPoint([d.LAT, d.LONG]).x; })\n .attr(\"y1\", function(d) { return map.latLngToLayerPoint([d.LAT, d.LONG]).y; })\n .attr(\"x2\", function(d) { return map.latLngToLayerPoint([d.CENSUS_Y, d.CENSUS_X]).x; })\n .attr(\"y2\", function(d) { return map.latLngToLayerPoint([d.CENSUS_Y, d.CENSUS_X]).y; }) \n \n });\n });\n}", "function colorSquare(){\n let s = new Array;\n let v = new Array;\n for (let k = 0; k <= numberofTree; k++) {\n ctx.fillRect(parseFloat($('#mortal-tree'+k).css('left'))-780,parseFloat($('#mortal-tree'+k).css('top')) - 360,29,29);\n ctx.fillStyle = \"rgb(214,236,239)\";\n }\n for (let k = 1; k <= numberofTree; k++) {\n s[k] = (parseFloat($('#mortal-tree'+k).css('left'))-780)/30;\n v[k] = (parseFloat($('#mortal-tree'+k).css('top')) - 360)/30;\n tab[i+v[k]][j+s[k]] = 4;\n } \n }", "function drawTTCDataonMap(data)\n{\n //console.log(\"drawTTCDataonMap recived data as: \", data);\n var numberOfVehicles = data.length;\n console.log(\"numberOfVehicles is: \", numberOfVehicles);\n\n // Formatting the data to send to ttcHeatmap\n var i;\n for(i = 0; i < numberOfVehicles; i++)\n {\n var latitude = data[i][\"coordinates\"][1];\n var longitude = data[i][\"coordinates\"][0];\n var entry = new google.maps.LatLng(latitude, longitude);\n ttcVehicleLocations.push(entry);\n }\n //console.log(\"ttcVehicleLocations is: \", ttcVehicleLocations);\n initTTCHeatMap();\n}", "function draw_map(map) {\n for (let i = 0; i < map.length; i++) {\n let x1 = parseInt(i % 100);\n let x2 = parseInt(i / 100);\n drawcell(x1, x2, map[i]);\n }\n}", "function block_lemo4moodle_drawHeatmap() {\n var xValues = [heatmapAll + '<br>00:00-06:00', heatmapOwn + '<br>00:00-06:00', heatmapAll +\n '<br>06:00-12:00', heatmapOwn + '<br>06:00-12:00', heatmapAll + '<br>12:00-18:00', heatmapOwn +\n '<br>12:00-18:00', heatmapAll + '<br>18:00-24:00', heatmapOwn + '<br>18:00-24:00', heatmapAll +\n '<br>' + heatmapOverall, heatmapOwn + '<br>' + heatmapOverall, heatmapAll + '<br>' +\n heatmapAverage, heatmapOwn + '<br>' + heatmapAverage];\n\n var yValues = [heatmapMonday, heatmapTuesday, heatmapWednesday, heatmapThursday, heatmapFriday,\n heatmapSaturday, heatmapSunday];\n\n var zValues = heatmapData;\n\n var colorscaleValue = [\n [0, '#ffffff'],\n [1, '#4a9dd4']\n ];\n\n var data = [{\n x: xValues,\n y: yValues,\n z: zValues,\n type: 'heatmap',\n colorscale: colorscaleValue,\n showscale: false\n }];\n\n var layout = {\n title: heatmapTitle,\n annotations: [],\n xaxis: {\n ticks: '',\n side: 'top'\n },\n yaxis: {\n ticks: '',\n ticksuffix: ' ',\n width: 700,\n height: 700,\n autosize: false\n }\n };\n\n for (var i = 0; i < yValues.length; i++) {\n for (var j = 0; j < xValues.length; j++) {\n var currentValue = zValues[i][j];\n if (currentValue != 0.0) {\n var textColor = 'black';\n } else {\n var textColor = 'black';\n }\n var result = {\n xref: 'x1',\n yref: 'y1',\n x: xValues[j],\n y: yValues[i],\n text: zValues[i][j],\n font: {\n family: 'Arial',\n size: 12,\n color: textColor\n },\n showarrow: false,\n };\n layout.annotations.push(result);\n }\n }\n\n Plotly.newPlot('heatmap', data, layout);\n}", "function setup ( ){\n createCanvas( 400, 400 ) ;\n background( 0 ) ;\n \n currWindow = new DataSeries( 50 ) ;\n \n // In constrast to RBG, HSV allows us to adjust the \"hotness\" of colors to correspond\n // to altitudes. This allows 100 possible shades of color\n colorMode ( HSB, 100, 100, 100 ) ;\n \n // Scale the centroid\n centroidY = map( centroidLat, minLat, maxLat, 0, height ) ;\n centroidX = map ( centroidLon, maxLon, minLon, 0, width ) ;\n\n // Use a window of 100 points for now\n currWindow = new DataSeries ( 500 ) ;\n \n // reference points\n var westLong = map ( minLon, minLon, maxLon, 5, width - 5) ;\n var eastLong = map ( maxLon, minLon, maxLon, 5, width - 20) ;\n var northLat = map( minLat, minLat, maxLat, 20, height ) ;\n var southLat = map( maxLat, minLat, maxLat, 5, height - 20 ) ;\n fill( 10, 100, 100 ) ;\n textSize ( 32 ) ;\n text ( \"W\", westLong, 200 ) ;\n text( \"E\", eastLong, 200 ) ;\n text ( \"N\", width / 2, northLat, 40 ) ;\n text ( \"S\", width / 2, southLat, 20 ) ;\n //rect ( eastLong, 200, 10, 10 ) ;\n}", "function showYear(all_data, year, n){\n \n \n // Local-global variables\n var rainCan, tempCan, rainCom, tempCom;\n \n //--------- filter data per year--------------------\n var data = all_data.filter(d => {\n return d.year === year;\n });\n \n //-------------- Temperature heatmap--------------------\n // Temperature\n var box = svg_temp.append('g').attr(\"class\", year)\n .attr('transform', `translate(${(boxwidth+5)*n})`)\n \n box.selectAll(\"rect\").data(data).enter()\n .append(\"rect\").attr('class', 'ok')\n .attr(\"x\", (d,i)=>{\n return boxwidth/12*i;\n })\n .attr('y', '0%')\n .attr('width',boxwidth/12-1)\n .attr('height','100%')\n .style('fill',(d,i)=>{\n if(d.year == '2014'&& d.month=='jan')return '#141623';\n else if (d.year == '2014'&& d.month=='feb')return '#141623';\n else if (d.year == '2014'&& d.month=='mar')return '#141623';\n else if (d.year == '2014'&& d.month=='apr')return '#141623';\n else if (d.year == '2014'&& d.month=='may')return '#141623';\n // else return 3;\n else return tempScale(d.avg_temp);\n \n // return tempScale(d.avg_temp);\n }).on('mouseover', (d)=>{\n //highlight\n // this.append(\"rect\").attr('x','100%').attr('y','100%').\n \n div_temp_heatmap.style('visibility','visible');\n \n console.log(this);\n \n \n div_temp_heatmap.html(d.avg_temp.toFixed(2) +'°C').style(\"left\", (d3.event.pageX +10) + \"px\")\n .style(\"top\", (d3.event.pageY +10) + \"px\");\n \n // Pie chart\n makePie(d);\n \n })\n .on('mouseout',(d)=>{\n div_temp_heatmap.style('visibility','hidden');\n });\n \n // -------------------- Rainfall Heatmap --------------------------\n var rainbox = svg_rain.append('g').attr(\"class\", year)\n .attr('transform', `translate(${(boxwidth+5)*n})`)\n \n rainbox.selectAll(\"rect_rain\").data(data).enter()\n .append(\"rect\")\n .attr(\"x\", (d,i)=>{\n return boxwidth/12*i;\n })\n .attr('y', '0%')\n .attr('width',boxwidth/12-1)\n .attr('height','100%')\n .style('fill',(d,i)=>{\n if(d.year == '2014'&& d.month=='jan')return '#141623';\n else if (d.year == '2014'&& d.month=='feb')return '#141623';\n else if (d.year == '2014'&& d.month=='mar')return '#141623';\n else if (d.year == '2014'&& d.month=='apr')return '#141623';\n else if (d.year == '2014'&& d.month=='may')return '#141623';\n // else return 3;\n else return rainScale(d.rainfall_actual);\n \n // return rainScale(d.rainfall_actual);\n }).on('mouseover', (d)=>{\n \n div_rain_heatmap.style('visibility','visible');\n \n div_rain_heatmap.html(d.rainfall_actual.toFixed(2) +'mm').style(\"left\", (d3.event.pageX +10) + \"px\")\n .style(\"top\", (d3.event.pageY +10) + \"px\");\n \n // Pie chart\n makePie(d);\n })\n .on('mouseout',(d)=>{\n div_rain_heatmap.style('visibility','hidden');\n });\n \n //--------------------------- Temp Can -----------------------------------\n \n createTempCan();\n \n setTimeout(function() {\n updateTempCan();\n },200);\n \n function createTempCan(){\n \n tempCan = box.selectAll(\"circle_tempCan\").data(data).enter()\n .append(\"circle\")\n .attr(\"cx\", (d,i)=>{\n return (boxwidth/12*i)+(boxwidth/24);\n })\n .attr('cy', (d,i)=>{\n return canScale(0);\n })\n // .attr('r','3px')\n .attr('r',(d)=>{\n if(d.year == '2014'&& d.month=='jan')return 0;\n else if (d.year == '2014'&& d.month=='feb')return 0;\n else if (d.year == '2014'&& d.month=='mar')return 0;\n else if (d.year == '2014'&& d.month=='apr')return 0;\n else if (d.year == '2014'&& d.month=='may')return 0;\n else return 3;\n })\n .style('fill', '#efefef')\n .on('mouseover', (d)=>{\n \n div_temp_can.style('visibility','visible');\n \n // div_temp.transition().duration(50).style(\"opacity\", 1).style(\"visibility\", 'visible');\n // div_temp.html('Temp: <br>'+ d.avg_temp +' °C <br><br> Can:<br> '+ d.overall_can_rate +\n // '%'+ '<br><br> Com:<br>'+d.com) \n \n // div_temp.html('<br> Can:<br> '+ d.overall_can_rate +'%'+ '<br><br> Com:<br>'+d.com) \n // .style('left','3%').style('top','40%').style('font-size', '14px').style('line-height','1.5')\n \n div_temp_can.html('Cancellations: '+ d.overall_can_rate +'%').style(\"left\", (d3.event.pageX +10) + \"px\")\n .style(\"top\", (d3.event.pageY +10) + \"px\");\n \n })\n .on('mouseout',(d)=>{\n div_temp_can.style('visibility','hidden');\n });\n }\n \n \n \n function updateTempCan(){\n tempCan.transition().ease(d3.easeElastic).duration(2000).attr('cy',(d,i)=>{\n return canScale(d.overall_can_rate);\n })\n }\n \n // -------------------------- Rain Can -----------------------------\n createRainCan();\n \n setTimeout(function() {\n updateRainCan();\n },200);\n \n \n function createRainCan(){\n // Rain_Cancellations\n rainCan = rainbox.selectAll(\"circle_rainCan\").data(data).enter()\n .append(\"circle\")\n .attr(\"cx\", (d,i)=>{\n return (boxwidth/12*i)+(boxwidth/24);\n })\n .attr('cy', (d)=>{\n return canScale(0);\n })\n .attr('r',(d)=>{\n if(d.year == '2014'&& d.month=='jan')return 0;\n else if (d.year == '2014'&& d.month=='feb')return 0;\n else if (d.year == '2014'&& d.month=='mar')return 0;\n else if (d.year == '2014'&& d.month=='apr')return 0;\n else if (d.year == '2014'&& d.month=='may')return 0;\n else return 3;\n })\n .style('fill', '#efefef')\n .on('mouseover', (d)=>{\n div_rain_can.style('visibility','visible');\n \n // div_rain.transition().duration(50).style(\"opacity\", 1).style(\"visibility\", 'visible');\n // // div_rain.html('Rain: <br>'+ d.rainfall_actual.toFixed(2) +' mm <br><br> Can:<br> '+ d.overall_can_rate +\n // // '%'+ '<br><br> Com:<br>'+d.com) \n\n // div_rain.html('<br> Can:<br> '+ d.overall_can_rate +'%'+ '<br><br> Com:<br>'+d.com) \n // .style('left','3%').style('bottom','18%').style('font-size', '14px').style('line-height','1.5')\n \n div_rain_can.html('Cancellations: '+ d.overall_can_rate +'%').style(\"left\", (d3.event.pageX +10) + \"px\")\n .style(\"top\", (d3.event.pageY +10) + \"px\");\n })\n .on('mouseout',(d)=>{\n div_rain_can.style('visibility','hidden');\n });\n }\n \n \n function updateRainCan(){\n rainCan.transition().ease(d3.easeElastic).duration(2000).attr('cy',(d,i)=>{\n return canScale(d.overall_can_rate);\n })\n }\n \n \n \n // ------------------------- Temp Com ---------------------------\n \n createTempCom();\n \n setTimeout(function() {\n updateTempCom();\n },800);\n \n function createTempCom(){\n tempCom = box.selectAll(\"circle_tempCom\").data(data).enter()\n .append(\"circle\")\n .attr(\"cx\", (d,i)=>{\n return (boxwidth/12*i)+(boxwidth/24);\n })\n .attr('cy', (d,i)=>{\n return comScale(0);\n })\n .attr('r',(d)=>{\n if(d.year == '2014'&& d.month=='jan')return 0;\n else if (d.year == '2014'&& d.month=='feb')return 0;\n else if (d.year == '2014'&& d.month=='mar')return 0;\n else if (d.year == '2014'&& d.month=='apr')return 0;\n else if (d.year == '2014'&& d.month=='may')return 0;\n else return 3;\n }).attr('fill','none')\n .attr('stroke', '#efefef').style('stroke-width', '0.5px')\n .on('mouseover', (d)=>{\n div_temp_com.style('visibility','visible');\n // div_temp.transition().duration(50).style(\"opacity\", 1).style(\"visibility\", 'visible');\n // div_temp.html('Temp: <br>'+ d.avg_temp +' °C <br><br> Can:<br> '+ d.overall_can_rate +\n // '%'+ '<br><br> Com:<br>'+d.com) \n // // .style(\"left\", (d3.event.pageX) + \"px\") \n // // .style(\"top\", (d3.event.pageY - 28) + \"px\");\n // .style('left','3%').style('bottom','46%').style('font-size', '14px').style('line-height','1.5')\n \n div_temp_com.html('Complaints: '+ d.com).style(\"left\", (d3.event.pageX +10) + \"px\")\n .style(\"top\", (d3.event.pageY +10) + \"px\");\n \n })\n .on('mouseout',(d)=>{\n div_temp_com.style('visibility','hidden');\n });\n }\n \n function updateTempCom(){\n tempCom.transition().ease(d3.easeElastic).duration(2000).attr('cy',(d,i)=>{\n return comScale(d.com);\n })\n }\n \n \n // ------------------------- Rain Com ---------------------------\n \n createRainCom();\n \n setTimeout(function() {\n updateRainCom();\n },800);\n \n function createRainCom(){\n rainCom = rainbox.selectAll(\"circle_rainCom\").data(data).enter()\n .append(\"circle\")\n .attr(\"cx\", (d,i)=>{\n return (boxwidth/12*i)+(boxwidth/24);\n })\n .attr('cy', (d,i)=>{\n return comScale(0);\n })\n .attr('r',(d)=>{\n if(d.year == '2014'&& d.month=='jan')return 0;\n else if (d.year == '2014'&& d.month=='feb')return 0;\n else if (d.year == '2014'&& d.month=='mar')return 0;\n else if (d.year == '2014'&& d.month=='apr')return 0;\n else if (d.year == '2014'&& d.month=='may')return 0;\n else return 3;\n }).attr('fill','none')\n .attr('stroke', '#efefef').attr('stroke-width', '0.5px')\n .on('mouseover', (d)=>{\n \n div_rain_com.style('visibility','visible');\n \n // div_rain.transition().duration(50).style(\"opacity\", 1).style(\"visibility\", 'visible');\n // div_rain.html('Rain: <br>'+ d.rainfall_actual.toFixed(2) +' mm <br><br> Can:<br> '+ d.overall_can_rate +\n // '%'+ '<br><br> Com:<br>'+d.com) \n // // .style(\"left\", (d3.event.pageX) + \"px\") \n // // .style(\"top\", (d3.event.pageY - 28) + \"px\");\n // .style('left','3%').style('bottom','18%').style('font-size', '14px').style('line-height','1.5')\n \n div_rain_com.html('Complaints: '+ d.overall_can_rate +'%').style(\"left\", (d3.event.pageX +10) + \"px\")\n .style(\"top\", (d3.event.pageY +10) + \"px\");\n \n })\n .on('mouseout',(d)=>{\n div_rain_com.style('visibility','hidden');\n });\n \n \n }\n \n function updateRainCom(){\n rainCom.transition().ease(d3.easeElastic).duration(2000).attr('cy',(d,i)=>{\n return comScale(d.com);\n })\n }\n \n }", "function heat_map(data) {\n //create time series JSON array from filtered data\n var filtered = JSON.stringify(data, ['year', 'month']);\n var timeseries = $.parseJSON(filtered);\n var timeseriesUNIX = [];\n var timeseriesJSON = {};\n\t\n //transform times to unix time stamps and parse into JSON format\n $.each(timeseries, function (a) {\n timeseriesUNIX[a] = (new Date(timeseries[a].year, timeseries[a].month - 1).getTime() / 1000);\n\n //adding to JSON array\n if (timeseriesJSON.hasOwnProperty(timeseriesUNIX[a])) {\n ++timeseriesJSON[timeseriesUNIX[a]];\n } else {\n timeseriesJSON[timeseriesUNIX[a]] = 1;\n }\n\n });\n\n timeseriesJSON = JSON.stringify(timeseriesJSON);\n timeseriesJSON = $.parseJSON(timeseriesJSON);\n\n\n //Create Time Series Plot\n $('#time_series').html(function () {\n\t\t//if no calendar exists, create a new one\n if (cal == undefined){\n //creating new heatmap\n cal = new CalHeatMap();\n cal.init({\n itemSelector: \"#time_series\",\n itemName: ['time'],\n verticalOrientation: true,\n domain: \"year\",\n subDomain: \"month\",\n cellRadius: 10,\n data: timeseriesJSON,\n animationDuration: 0,\n start: new Date(2010, 0),\n cellSize: 40,\n range: 5,\n subDomainTextFormat: \"%b\",\n legend: [1, 3, 5, 7],\n legendVerticalPosition: \"top\",\n legendHorizontalPosition: \"center\",\n legendCellSize: 25,\n legendMargin: [0, 0, 30, 0],\n legendCellPadding: 8,\n label: {\n height: 55\n }\n\n });\n\t\t\n\t\t}\n\t\t//update existing calendar w/ new data\n\t\telse{\n\t\tcal.update(timeseriesJSON);\n\n\t\t};\n\t\t\n\t\n });\n\t\treturn cal; \n\t\n}", "function displayChessboard() {\n var rows = [];\n for (var i = 0; i < 5; i++) {\n var row = [];\n for (var j = 0; j < 5; j++) {\n if ((j + i) % 2 == 0) row.push(new TextCell('##'));\n else row.push(new TextCell(' '));\n }\n rows.push(row);\n }\n console.log(drawTable(rows));\n}", "function render() {\n svg.data(props.data);//raw_data\n // Filter, shuffle, slice, and sort data\n // var data = filter(raw_data);\n // // Select subset of data according to calculated proportions, returns data of length <= 1200\n // selected = select(data);\n // data = selected[0];\n // var proportions = selected[1];\n\n // data = data.sort((d1, d2) => (d1.predicted_category > d2.predicted_category) ? 1 : -1);\n // const l = data.length;\n\n chart.selectAll('circle').remove();\n\n // Append new circles\n const squares = chart.selectAll('circle')\n .data(data, function (d) { return d.hmid; })\n\n squares.enter().append('circle')\n .attr('cx', (d, i) => {\n const n = i % numPerRow;\n return scale(n);\n })\n .attr('cy', (d, i) => {\n const n = Math.floor(i / numPerRow);\n return scale(n);\n })\n .attr('r', circleSize)\n .attr('fill','white')\n .transition().delay(function (d, i) { return .9 * i; })\n // .on(\"mouseover\", handleMouseOver)\n // .on(\"mouseout\", handleMouseOut)\n // .attr(\"data-toggle\", \"modal\")\n // .attr(\"data-target\", \"#myModal\")\n // .attr(\"class\", (d) => { return d.predicted_category; });\n // updateProportions(proportions); // update proportions under icons\n\n\n // function handleMouseOver(d) {\n // // highlight rect \n // d3.select(this).style(\"fill\", function (d) { return colorMap[d.predicted_category]; });\n // d3.select(this).style(\"stroke\", \"gray\");\n // d3.select(this).style(\"stroke-width\", \"1.5px\");\n // // tooltip\n // tooltip.transition()\n // .duration(30)\n // .style(\"opacity\", 1)\n // tooltip.html(\"&ldquo;\" + d.cleaned_hm + \"&rdquo;\" + \"<br> <br> <div class='tooltip-footer'> CLICK TO SEE MORE </div>\")\n // .style(\"left\", (d3.event.pageX + 20) + \"px\")\n // .style(\"top\", (d3.event.pageY - 20) + \"px\");\n // //data for modal\n // d3.select(this).attr(\"class\", \"info\").datum(d).style(\"cursor\", \"pointer\");\n // }\n\n // function handleMouseOut(d) {\n // // unhighlight color\n // d3.select(this).style(\"stroke\", \"white\");\n // d3.select(this).style(\"stroke-width\", \"0px\");\n // d3.select(this).style(\"fill\", function (d) { return colorMap[d.predicted_category]; });\n // // tooltip\n // tooltip.transition()\n // .duration(30)\n // .style(\"opacity\", 0);\n // d3.select(this).attr(\"class\", null)\n // }\n\n // function updateProportions(proportions) {\n // let categories = Object.keys(proportions);\n // for (c of categories) {\n // document.getElementById(\"icon-proportion-\" + c).innerHTML = proportions[c] + \"%\";\n // }\n // }\n\n }", "function addTiles(co,jk,jj,dp,dn,dq,dk,dj,dl,dh,dg,di){xc_eg(co,\"jn\",\"jn\",{\"width\":jk,\"height\":jj,\"jn\":[dp||\"\",dn||\"\",dq||\"\",dk||\"\",dj||\"\",dl||\"\",dh||\"\",dg||\"\",di||\"\"],\"ca\":0,\"bs\":0,\"id\":\"\"},0)}", "function addHeatmap(map) {\n\t/* Data points defined as an array of LatLng objects */\n\tvar heatmapData = genHeatMapData();\n\tvar heatmap = new google.maps.visualization.HeatmapLayer({\n\t\tdata : heatmapData,\n\t\tmaxIntensity : 100,\n\t\tradius : 15\n\t});\n\theatmap.setMap(map);\n}", "function drawFigure(coord, key) {\n if (key == 0) {\n $(coord).html('<img class=\"img img-responsive\" src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Red-circle.svg/1024px-Red-circle.svg.png\">')\n } else if (key == 1) {\n $(coord).html('<img class=\"img img-responsive\" src=\"http://www.clker.com/cliparts/0/7/e/a/12074327311562940906milker_X_icon.svg.hi.png\">');\n }\n}", "function populate(hexmap) {\n // Clear the old map, if any\n $('#hexmap').children().remove();\n \n for (index in hexmap) {\n var x = hexmap[index].x, y = hexmap[index].y;\n var data = hexmap[index].data;\n var color = data.color;\n\n // clone the tile and place it\n var tile = placeTile(color, x, y);\n\n // Add some event handling\n tile.bind(\"mouseover\", function(event) {\n //$(this).highlightHex();\n var row = $(this).data(\"row\");\n var column = $(this).data(\"column\");\n $.tooltip(\"Hex position (row \" + row + \", column \" + column + \")\");\n //highlightHex(row, column);\n });\n }\n}", "populateGridColorArrays() {\n //for every column..\n for (let i = 0; i < this.colNum; i++) {\n\n // //Generate colors based on a split complementry palette\n // if (i % 2 == 0) {\n // this.hVal = 19;\n // this.sVal = 91;\n // this.bVal = 95;\n // this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n // } else if (i % 3 == 0) {\n // this.hVal = 59;\n // this.sVal = 96;\n // this.bVal = 87;\n // this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n // }else{\n // this.hVal = 240;\n // this.sVal = 57;\n // this.bVal = 89;\n // this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n // }\n\n // //Generate colors based on a triad palette\n // if (i % 2 == 0) {\n // this.hVal = 19;\n // this.sVal = 91;\n // this.bVal = 100;\n // this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n // } else if (i % 3 == 0) {\n // this.hVal = 173;\n // this.sVal = 96;\n // this.bVal = 40;\n // this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n // }else{\n // this.hVal = 259;\n // this.sVal = 82;\n // this.bVal = 90;\n // this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n // }\n\n //Generate colors based on a analogus palette\n\n //based on the row number push one of three possible colors into the right hand side color array\n if (i % 3 === 0) {\n this.hVal = 261;\n this.sVal = 75;\n this.bVal = 91;\n this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n } else if (i % 2 === 0) {\n this.hVal = 231;\n this.sVal = 90;\n this.bVal = 89;\n this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n } else {\n this.hVal = 202;\n this.sVal = 90;\n this.bVal = 89;\n this.colorsRight[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n }\n\n //based on the row number push one of two possible colors (white or black) into the left hand side color array\n //two possible colors linearly interpolate to three possible colors creating and asnyschronus relation between the left and right hand sides\n if (i % 2 == 0) {\n this.hVal = 0;\n this.sVal = 0;\n this.bVal = 20;\n this.colorsLeft[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n } else {\n this.hVal = 0;\n this.sVal = 0;\n this.bVal = 85;\n this.colorsLeft[i] = color(this.hVal, this.sVal, this.bVal, this.mouduleAlpha);\n }\n }\n\n }", "render(props, state) {\n\t\treturn (\n\t\t\t<div class={style.this}>\n <h3>Heatmap layout</h3>\n Heatmaps contain information regarding price / volume evolution for multiple periods :\n <ul>\n <li>Price evolution on the left</li>\n <li>Volume evolution on the right</li>\n <li>The smallest evolution period (ex: 5 minutes is at the bottom)</li>\n <li>The largest evolution period (ex: 5 days is at the top)</li>\n </ul>\n <img class={style.heatmap} src=\"assets/img/heatmap_delta.svg\"/>\n <ul>\n <li><span class={style.hintNumber}>1 : </span>price / volume evolution over a 5 days period</li>\n <li><span class={style.hintNumber}>2 : </span>price / volume evolution over a 1 day period</li>\n <li><span class={style.hintNumber}>3 : </span>price / volume evolution over a 4 hours period</li>\n <li><span class={style.hintNumber}>4 : </span>price / volume evolution over a 1 hour period</li>\n <li><span class={style.hintNumber}>5 : </span>price / volume evolution over a 15 minutes period</li>\n <li><span class={style.hintNumber}>6 : </span>price / volume evolution over a 5 minutes period</li>\n <li><span class={style.hintNumber}>7 : </span>heatmap summary with current price & volume</li>\n </ul>\n <br/>\n <h3>Display values</h3>\n Clicking anywhere in the heatmap will switch between price/volume evolution & price/volume values, where for each period :\n <ul>\n <li>previous price / volume will be at the top</li>\n <li>new price / volume will be at the bottom</li>\n </ul>\n <img class={style.heatmap} src=\"assets/img/heatmap_values.svg\"/>\n <br/>\n <h3>Display details</h3>\n Clicking on the summary will open a detailed view of the heatmap\n </div>\n\t\t);\n\t}", "function redraw_clusters() {\n\n\t\tmap.spin(true);\n\t\tinitialize_clusters();\n\n\t} // end of function redraw_clusters", "function renderHeatmap(hmFile) {\n var hmFileURL = '';\n\n\n if(hmFile) {\n hmFileURL = backendURL + FRDO_HEATMAPS + '/' + hmFile;\n }\n else return;\n\n $.ajax({\n type: 'GET',\n url: hmFileURL,\n dataType : 'json',\n success: function(d){\n var counts = [];\n if(d) {\n console.debug(d);\n \n setCenter(d);\n map = new google.maps.Map($('#frdo-heatmap')[0], mapOptions);\n\n heatmapData = {\n min: 100, // empirical \n max: 1500, // empirical \n data: []\n };\n \n heatmap = new HeatmapOverlay(map, {\n 'radius': 15,\n 'visible': true, \n 'opacity': 40\n });\n \n heatmapData.data = d;\n console.log('Scaling heatmap with min:' + heatmapData.min + ' and max: ' + heatmapData.max);\n google.maps.event.addListenerOnce(map, 'idle', function(){\n heatmap.setDataSet(heatmapData);\n });\n }\n },\n error: function(msg){\n $('#frdo-heatmap').html('<p>There was a problem getting the heat-map data:</p><code>' + msg.responseText + '</code>');\n } \n });\n}" ]
[ "0.6713943", "0.6671842", "0.6503217", "0.63301", "0.61315715", "0.60597485", "0.6042422", "0.6019636", "0.60035074", "0.5991313", "0.5932931", "0.5911504", "0.58962834", "0.58921283", "0.5867655", "0.58638865", "0.5849583", "0.58356595", "0.5831848", "0.581714", "0.57955825", "0.57866687", "0.5777234", "0.57763493", "0.57760316", "0.5762805", "0.57550794", "0.5744088", "0.57238114", "0.5722406", "0.5677187", "0.5661668", "0.56565297", "0.56459904", "0.5639685", "0.5626275", "0.56210023", "0.5618125", "0.5615861", "0.5611834", "0.56079566", "0.56078315", "0.5606036", "0.55917954", "0.55895734", "0.55894023", "0.5586909", "0.5580051", "0.5563505", "0.5560669", "0.55588686", "0.5552172", "0.55516255", "0.55449295", "0.55436504", "0.5540621", "0.5528834", "0.55268747", "0.55234224", "0.5518604", "0.54984057", "0.5495217", "0.54944795", "0.5493948", "0.5492351", "0.5488836", "0.54867435", "0.5483422", "0.54802924", "0.54771405", "0.5475", "0.5473106", "0.5468676", "0.54679394", "0.54639614", "0.5459538", "0.5454871", "0.5450273", "0.54468036", "0.5442563", "0.54363215", "0.542949", "0.54234815", "0.5423329", "0.54190797", "0.5418703", "0.54170907", "0.5414948", "0.5404719", "0.54022545", "0.5399107", "0.5394503", "0.53924197", "0.53874177", "0.5380102", "0.53795296", "0.53783935", "0.53759634", "0.537563", "0.5373881", "0.5363488" ]
0.0
-1
For an additional challenge, add '' signs to scores in the bottom two percent of A, B, C, and D scores, and '+' signs to the top two percent of B, C and D scores (sorry, Mr.Cerise never gives an A+). Given 88, console.log "Score: 88. Grade: B+". Given 61 log "Score: 61. Grade: D".
function accLetterGrade(score) { var grade; if(score >= 0 && score <= 100) { if(score < 60) { grade = "F"; } else if(score < 70) { if(score <= 62) { grade = "D-"; } else if(score < 70) { grade = "D+"; } else { grade = "D"; } } else if(score < 80) { if(score <= 72) { grade = "C-"; } else if(score < 80) { grade = "C+"; } else { grade = "C"; } } else if(score < 90) { if(score <= 82) { grade = "B-"; } else if(score < 90) { grade = "B+"; } else { grade = "B"; } } else if(score < 100) { if(score <= 92) { grade = "A-"; } else { grade = "A"; } } console.log("Score: " + score + ". Grade: " + grade); } else if(score >= 100) { console.log("Woah, you got a score of " + score + "!? You're such an overachiever. Still no A+"); } else { console.log("Either you did so poorly in this class you managed to get a score less than 0, or I've accidentally logged your grade as something other than a number!"); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function moreAccurateGrades(grade)\n{\n if(grade >= 93)\n {\n console.log(\"A\");\n }\n else if(grade >= 90)\n {\n console.log(\"A-\");\n }\n else if(grade >= 88)\n {\n console.log(\"B+\");\n }\n else if(grade >= 83)\n {\n console.log(\"B\");\n }\n else if(grade >= 80)\n {\n console.log(\"B-\");\n }\n else if(grade >= 78)\n {\n console.log(\"C+\");\n }\n else if(grade >= 73)\n {\n console.log(\"C\");\n }\n else if(grade >= 70)\n {\n console.log(\"C-\");\n }\n else if(grade >= 68)\n {\n console.log(\"D+\");\n }\n else if(grade >= 63)\n {\n console.log(\"D\");\n }\n else if(grade >= 60)\n {\n console.log(\"D-\");\n }\n else\n {\n console.log(\"F\");\n }\n}", "function getGrade(score1, score2, score3) {\n let letterGrade = '';\n const mean = (score1 + score2 + score3) / 3;\n\n if (mean >= 90 && mean <= 100) {\n letterGrade = 'A';\n } else if (mean >= 80 && mean < 90) {\n letterGrade = 'B';\n } else if (mean >= 70 && mean < 80) {\n letterGrade = 'C';\n } else if (mean >= 60 && mean < 70) {\n letterGrade = 'D';\n } else {\n letterGrade = 'F';\n }\n\n console.log(letterGrade);\n}", "function grade(score) {\n if (score >= 90) {\n return \"A\";\n }\n else if(score >= 80) {\n return \"B\";\n }\n else if(score >= 70) {\n return \"C\";\n }\n else if(score >= 60) {\n return \"D\";\n }\n else {\n return \"F\";\n }\n }", "function getGrade(s1, s2, s3) {\n // Code here\n\n let score = (s1 + s2 + s3) / 3\n\n if (score >= 90 && score <= 100) {\n return 'A';\n } else if (score >= 80 && score <= 90) {\n return 'B';\n } else if (score >= 70 && score < 80) {\n return 'C';\n } else if (score >= 60 && score < 70) {\n return 'D';\n } else {\n return 'F';\n }\n}", "function Score(grade){\n\tlet letterGrade;\n\n\tif(grade < 60){\n\t\tletterGrade = \"F\"\n\t}else if(grade >= 60 && grade < 70){\n\t\tletterGrade = \"D\";\n\t}else if(grade >= 70 && grade < 80){\n\t\tletterGrade = \"C\";\n\t}else if(grade >= 80 && grade < 90){\n\t\tletterGrade = \"B\";\n\t}else if(grade >= 90 && grade < 100){\n\t\tletterGrade = \"A\";\n\t}else if(grade == 100){\n\t\tletterGrade = \"A+ Woo!\";\n\t}else if(grade > 100){\n\t\tletterGrade = \"A++!! I didn't think that was possible!\";\n\t}\n\treturn letterGrade;\n}", "function letterGrade (score) {\n if (score < 60) {\n return 'F'\n } else if (score < 70) {\n return 'D'\n } else if (score < 80) {\n return 'C'\n } else if (score < 90) {\n return 'B'\n } else {\n return 'A'\n }\n}", "function assignGrade(score) {\n if (score > 90) {\n return \" an A\";\n } else if (score > 80) {\n return \" a B\";\n } else if (score > 70) {\n return \" a C\";\n } else if (score > 65) {\n return \" a D\";\n } else {\n return \" an E\";\n }\n }", "function printGrade(midtermScore, finalScore) {\n let totalScore = midtermScore + finalScore;\n\n if (totalScore >= 90) {\n console.log('A');\n } else if (totalScore >= 80) {\n console.log('B');\n } else if (totalScore >= 70) {\n console.log('C');\n } else if (totalScore >= 60) {\n console.log('D');\n } else {\n console.log('F');\n }\n}", "function grade(score) {\n if (score < 60) {\n return 'F'\n } else if (score >= 60 && score < 70) {\n return 'D'\n } else if (score >= 70 && score < 80) {\n return 'C'\n } else if (score >= 80 && score < 90) {\n return 'B'\n } else if (score >= 90) {\n return 'A'\n }\n}", "function letterGrade(score) {\n var grade = \"\";\n\n if (score > 100 || score < 0) {\n grade = \"Invalid\";\n } else if (score >= 90) {\n grade = \"A\";\n } else if (score >= 80) {\n grade = \"B\";\n } else if (score >= 70) {\n grade = \"C\";\n } else if (score >= 60) {\n grade = \"D\";\n } else if (score < 60) {\n grade = \"F\";\n }\n return \"Score: \" + score + \". Grade: \" + grade;\n}", "function grade(score) {\n let g = 'not graded';\n if (score >= 90) {\n g = 'a';\n } else if (score >= 80) {\n g = 'b';\n } else if (score >= 70) {\n g = 'c';\n } else if (score >= 60) {\n g = 'd';\n } else {\n g = 'f';\n }\n return g;\n}", "function getGrade(gradeOne, gradeTwo, gradeThree) {\n let score = (gradeOne + gradeTwo + gradeThree) / 3;\n if (90 <= score) return 'A';\n if (80 <= score) return 'B';\n if (70 <= score) return 'C';\n if (60 <= score) return 'D';\n return 'F';\n}", "function letterGrade(score, total){\n var grade = ((score/total) * 100);\n //console.log(grade);\n if(grade > 100){\n console.log(\"Call Elon you're a genius!\")\n }else if(grade >= 90 && grade <= 100){\n console.log(\"A\")\n }else if(grade >= 80 && grade <= 89){\n console.log(\"B\")\n }else if(grade >= 70 && grade <= 79){\n console.log(\"C\")\n }else if(grade >= 60 && grade <= 69){\n console.log(\"D\")\n }else if(grade >= 0 && grade <=59){\n console.log(\"F\")\n }else{\n console.log(\"Study Up!\")\n }\n }", "function letterGrade(){\r\n if(total > 4.33){\r\n return letter = \"A+\";\r\n }else if(total > 4.00){\r\n return letter = \"A\";\r\n }else if(total > 3.67){\r\n return letter = \"A-\";\r\n }else if(total > 3.33){\r\n return letter = \"B+\";\r\n }else if(total > 3.00){\r\n return letter = \"B\";\r\n }else if(total > 2.67){\r\n return letter = \"B-\";\r\n }else if(total > 2.33){\r\n return letter = \"C+\";\r\n }else if(total > 2.00){\r\n return letter = \"C\";\r\n }else if(total > 1.67){\r\n return letter = \"C-\";\r\n }else if(total > 1.33){\r\n return letter = \"D+\";\r\n }else if(total > 1.00){\r\n return letter = \"D\";\r\n }else if(total < .67){\r\n return letter = \"D-\";\r\n }else{\r\n return letter = \"F\";\r\n } \r\n}", "function grade(grade){\n if (grade === 100){\n return \"A+\";\n }\n else if (grade >= 90){\n return \"A\";\n }\n else if (grade >= 80){\n return \"B\";\n }\n else if (grade >= 70){\n return \"C\";\n }\n else if (grade >= 65){\n return \"D\";\n }\n else{\n return \"F\";\n }\n}", "function grade(score, total) {\n var percentage = (score * 100) / total;\n if (percentage >= 90 && percentage <= 100) {\n console.log(\"A\");\n } else if (percentage >= 80 && percentage <= 89) {\n console.log(\"B\");\n } else if (percentage >= 70 && percentage <= 79) {\n console.log(\"C\");\n } else if (percentage >= 60 && percentage <= 69) {\n console.log(\"D\");\n } else {\n console.log(\"F\");\n }\n}", "function assignGrade(score) {\n if (score > 90) {\n return 'A';\n } else if (score > 80) {\n return 'B';\n } else if (score > 70) {\n return 'C';\n } else if (score > 65) {\n return 'D';\n } else {\n return 'F';\n };\n}", "function letterGrade(score){\n if(score < 60){\n console.log(\"Score: \" + score + \". Grade: F\")\n }\n else if(score < 70){\n console.log(\"Score: \" + score + \". Grade: D\")\n }\n else if(score < 80){\n console.log(\"Score: \" + score + \". Grade: C\")\n }\n else if(score < 90){\n console.log(\"Score: \" + score + \". Grade: B\")\n }\n else{\n console.log(\"Score: \" + score + \". Grade: A\")\n }\n}", "function convertScoreToGradeWithPlusAndMinus(score) {\n \n if ( score > 100 || score < 0 ) {\n return 'INVALID SCORE';\n }\n \n if ( score >= 90 ) {\n if ( score <= 92 ) {\n return 'A-';\n } else if ( score >= 98 ) {\n return 'A+';\n } else { \n return 'A';\n }\n } else if ( score >= 80 ) {\n if ( score <= 82 ) {\n return 'B-';\n } else if ( score >= 88 ) {\n return 'B+';\n } else { \n return 'B';\n }\n } else if ( score >= 70 ) {\n if ( score <= 72 ) {\n return 'C-';\n } else if ( score >= 78 ) {\n return 'C+';\n } else { \n return 'C';\n }\n } else if ( score >= 60 ) {\n if ( score <= 62 ) {\n return 'D-';\n } else if ( score >= 68 ) {\n return 'D+';\n } else { \n return 'D';\n }\n } else {\n return 'F';\n }\n\n}", "function finalGrade(n1, n2, n3) {\n avgGrade = (n1+n2+n3)/3;\n if(n1 < 0 || n1 > 100 || n2 < 0 || n2 > 100 || n3 < 0 || n3 > 100 ){\n return 'You have entered an invalid grade.';\n }else if(avgGrade <=59) {\n return 'F';\n }else if(avgGrade <= 69){\n return 'D';\n }else if(avgGrade <= 79){\n return 'C';\n }else if(avgGrade <= 89){\n return 'B';\n }else {\n return 'A';\n }\n }", "function getFinalScore(yourScore, possibleScore) { \n function getGrade(score, total) {\n const percentage = score / total;\n if (percentage < .6) {\n return \"a good try, but not passing yet, try again and improve your score\";\n } else if (percentage < .7) {\n return \"a D, almost passing\";\n } else if (percentage < .8) {\n return \"a C, you passed\";\n } else if (percentage < .9) {\n return \"a B, not bad\";\n } else if (percentage < 1.0) {\n return \"an A, you're pretty good at this\";\n } else {\n return \"an A, Perfect score!\";\n }\n }\n\n const gradeString = getGrade(yourScore, possibleScore);\n return `Your final score is ${yourScore} out of ${possibleScore}. That's ${gradeString}.`;\n}", "function assignGrade () {\r\nvar grade = document.projectThree.inputOne.value;\r\nif (grade >= 97) {\r\n return 'A+';\r\n}\r\nelse if (grade >= 93 && grade <= 96) {\r\n return 'A';\r\n}\r\nelse if (grade >= 90 && grade <= 92) {\r\n return 'A-';\r\n}\r\nelse if (grade >= 87 && grade <= 89) {\r\n return 'B+';\r\n}\r\nelse if (grade >= 83 && grade <= 86) {\r\n return 'B';\r\n}\r\nelse if (grade >= 80 && grade <= 82) {\r\n return 'B-';\r\n}\r\nelse if (grade >= 77 && grade <= 79) {\r\n return 'C+';\r\n}\r\nelse if (grade >= 73 && grade <= 76) {\r\n return 'C';\r\n}\r\nelse if (grade >= 70 && grade <= 72) {\r\n return 'C-';\r\n}\r\nelse if (grade >= 67 && grade <= 69) {\r\n return 'D+';\r\n}\r\nelse if (grade >= 63 && grade <= 66) {\r\n return 'D';\r\n}\r\nelse if (grade >= 60 && grade <= 62) {\r\n return 'D-';\r\n}\r\nelse if (grade >= 57 && grade <= 59) {\r\n return 'F+';\r\n}\r\nelse if (grade >= 53 && grade <= 56) {\r\n return 'F';\r\n}\r\nelse if (grade >= 0 && grade <= 52) {\r\n return 'F-';\r\n}\r\nelse {\r\n return 'Invalid input';\r\n}\r\n}", "function getGrade (num1, num2, num3) {\n let average = (num1 + num2 + num3) / 3;\n if (average >= 90 && average <= 100) {\n return 'A';\n } else if (average >= 80 && average < 90) {\n return 'B';\n } else if (average >= 70 && average < 80) {\n return 'C';\n } else if (average >= 60 && average < 70) {\n return 'D';\n }\n return 'F';\n}", "function yourScore() {\n return fname + ' scored ' + (mid + final);\n }", "function getGrade(s1, s2, s3) {\n /*\n let a = (s1+s2+s3) / 3;\n\n if (a >= 90 && a <= 100) {\n return 'A';\n } else if (a >= 80 && a < 90) {\n return 'B';\n } else if (a >= 70 && a < 80) {\n return 'C';\n } else if (a >= 60 && a < 70) {\n return 'D';\n } else {\n return 'F';\n }\n */\n\n let avg = (s1 + s2 + s3) / 3;\n\n if (avg >= 90 && avg <= 100) return 'A';\n else if (avg >= 80 && avg < 90) return 'B';\n else if (avg >= 70 && avg < 80) return 'C';\n else if (avg >= 60 && avg < 70) return 'D';\n else return 'F';\n}", "function getGrade(num1, num2, num3) {\n let mean = (num1 + num2 + num3) / 3;\n\n if (mean >= 90) {\n return 'A';\n } else if (mean >= 80) {\n return 'B';\n } else if (mean >= 70) {\n return 'C';\n } else if (mean >= 60) {\n return 'D';\n } else {\n return 'F';\n }\n}", "function calculateGrade(marks) {\n let score = 0;\n\n for (let mark of marks) {\n score += mark;\n }\n\n score = score / marks.length;\n\n if (score > 90)\n return 'A';\n else if (score > 80)\n return 'B'\n else if (score > 70)\n return 'C'\n else if (score > 60)\n return 'D'\n\n return 'F';\n}", "function gradeScale(score) {\n if (!score) {\n return \"\";\n }\n if (score >= 90) {\n return \"A\";\n } else if (score >= 80) {\n return \"B\";\n } else if (score >= 70) {\n return \"C\";\n } else if (score >= 60) {\n return \"D\";\n } else {\n return \"F\";\n }\n}", "function getGrade(score) {\n\tif (score >= 25) {\n\t\tgrade = 'A';\n\t} else if (score >= 20) {\n\t\tgrade = 'B';\n\t} else if (score >= 15) {\n\t\tgrade = 'C';\n\t} else if (score >= 10) {\n\t\tgrade = 'D';\n\t} else if (score >= 5) {\n\t\tgrade = 'E';\n\t} else if (score >= 0) {\n\t\tgrade = 'F';\n\t}\n\treturn grade;\n}", "function computeGrade(grades) {\r\n for (let grade of grades) {\r\n if (grade >= 90 && grade <= 100) {\r\n return \"A\";\r\n } else if (grade >= 80) {\r\n return \"B\";\r\n } else if (grade >= 70) {\r\n return \"C\";\r\n } else if (grade >= 60) {\r\n return \"D\";\r\n } else if (grade < 60 && grade >= 0) {\r\n return \"NC\";\r\n }\r\n }\r\n}", "function Gradefinder(a)\n{\n if(a>=90)\n {\n return 'S Grade';\n }\n else if(a>=80)\n {\n return 'A Grade';\n }\n else if(a>=70)\n {\n return 'B Grade';\n }\n else if(a>=60)\n {\n return 'C Grade';\n }\n else if(a>=50)\n {\n return 'D Grade';\n }\n else if(a>=40)\n {\n return 'E Grade';\n }\n}", "function gradeScale(score) {\n if (!score) {\n return \"\";\n }\n if (score >= 90) {\n return \"A\";\n } else if (score >= 80) {\n return \"B\";\n } else if (score >= 70) {\n return \"C\";\n } else if (score >= 60) {\n return \"D\";\n } else {\n return \"F\";\n }\n }", "function getGrade (s1, s2, s3) {\n // Code here\n var mean = (s1 + s2 + s3) / 3;\n var grade;\n if (mean >= 90) { grade = \"A\"; }\n else if (mean >= 80) { grade = \"B\"; }\n else if (mean >= 70) { grade = \"C\"; }\n else if (mean >= 60) { grade = \"D\"; }\n else { grade = \"F\"; }\n return grade;\n}", "function grade(num) {\n var score = num;\n\n if (score === 100) {\n console.log(\"You got a perfect score!\");\n } else if (score >= 90) {\n console.log(\"You got an A!\");\n } else if (score >= 80) {\n console.log(\"You got a B!\");\n } else if (score >= 70) {\n console.log(\"You got a C!\");\n } else if (score >= 60) {\n console.log(\"You got a D!\");\n } else {\n console.log(\"You failed.\");\n }\n}", "function calculateGrade(marks) {\n let count = 0;\n let total = 0;\n\n for (let score of marks) {\n total += score;\n count++;\n }\n\n let gradeScore = total / count;\n let gradeLetter;\n\n if (gradeScore < 60) gradeLetter = 'F';\n if (gradeScore >= 60 && gradeScore <= 69) gradeLetter = 'D';\n if (gradeScore >= 70 && gradeScore <= 79) gradeLetter = 'C';\n if (gradeScore >= 80 && gradeScore <= 89) gradeLetter = 'B';\n if (gradeScore >= 90) gradeLetter = 'A';\n\n return gradeLetter;\n}", "function check() {\n if ((correct+wrong) != 0) {\n score = \"\" + ((correct / (correct + wrong)) * 100);\n score = score.substring(0,4) + \"%\";\n alert(\"YOUR SCORE: \" + score + \"\\n\"\n + correct + \" correct\\n\"\n + wrong + \" incorrect\")\n }\n\n else alert(\"You haven't answered anything yet.\");\n}", "function grade() {\n\n//question 1 answer r1\nif (answer1 === \"r1\") {\n correct++;\n } else if ((answer1 === \"r2\") || (answer1 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n\n//question 2 answer r3\nif (answer2 === \"r3\") {\n correct++;\n } else if ((answer2 === \"r2\") || (answer2 === \"r1\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 3 answer r1\nif (answer3 === \"r1\") {\n correct++;\n } else if ((answer3 === \"r2\") || (answer3 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 4 answer r2\nif (answer4 === \"r2\") {\n correct++;\n } else if ((answer4 === \"r1\") || (answer4 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 5 answer r3\nif (answer5 === \"r3\") {\n correct++;\n } else if ((answer5 === \"r2\") || (answer5 === \"r1\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n}", "function letterGrade(grade){\n if(grade >= 90){\n return 'A';\n }else if(grade >= 80){\n return 'B';\n }else if(grade >= 70){\n return 'C';\n }else if(grade >= 60){\n return 'D';\n }else{\n return 'F';\n }\n}", "function getGrade (s1, s2, s3) {\n var s = (s1+s2+s3)/3;\n var l = ['A','B','C','D','F'],i;\n if((10-(~~(s/10)))-1<0){\n i = 0;\n }else if((10-(~~(s/10)))-1>4){\n i = 4;\n }else{\n i = 10-(~~(s/10))-1;\n }\n return l[i];\n}", "function grades(number){\n if(number >=90){\n return 'A';\n } else if(number >=80){\n return 'B';\n }else if(number >=70){\n return 'C';\n }else if(number >=60){\n return 'D';\n }else{\n return 'F';\n }\n }", "function grade_changer(letter_grade) {\n var grade\n if (letter_grade == \"A+\") {\n grade = 15;\n } else if (letter_grade == \"A\") {\n grade = 14;\n } else if (letter_grade == \"A-\") {\n grade = 13;\n } else if (letter_grade == \"B+\") {\n grade = 12;\n } else if (letter_grade == \"B\") {\n grade = 11;\n } else if (letter_grade == \"B-\") {\n grade = 10;\n } else if (letter_grade == \"C+\") {\n grade = 9;\n } else if (letter_grade == \"C\") {\n grade = 8;\n } else if (letter_grade == \"C-\") {\n grade = 7;\n } else if (letter_grade == \"D+\") {\n grade = 6;\n } else if (letter_grade == \"D\") {\n grade = 5;\n } else if (letter_grade == \"D-\") {\n grade = 4;\n } else if (letter_grade == \"F+\") {\n grade = 3;\n } else if (letter_grade == \"F\") {\n grade = 2;\n } else if (letter_grade == \"F-\") {\n grade = 1;\n } else {\n grade = 0;\n }\n return grade\n }", "grade(Student, subject){\n return `${Student.name} receives a perfect score on ${subject}`;\n }", "function assignGrade()\r\n{\r\n //capture a score from HTML\r\n var score = Number(document.project3.num1.value);\r\n if (score >= 90) //that's an A\r\n {\r\n return 'A';\r\n }\r\n else if (score >= 80)\r\n {\r\n return 'B';\r\n } //FINISH IT!!! MORTAL KOMBAT!\r\n}", "function calculateGrade2(marks) {\n let sum = 0;\n\n for (let mark of marks) {\n sum += mark;\n }\n\n let average = sum / marks.lenght;\n\n if (average < 59) return \"F\";\n if (average < 69) return \"D\";\n if (average < 79) return \"C\";\n if (average < 89) return \"B\";\n return \"A\";\n}", "function getGrade(score) {\n let grade;\n\n if (score > 25) {\n grade = \"A\";\n console.log(score + grade);\n } else if (score > 20) {\n grade = \"B\";\n console.log(score + grade);\n } else if (score > 15) {\n grade = \"C\";\n console.log(score + grade);\n } else if (score > 10) {\n grade = \"D\";\n console.log(score + grade);\n } else if (score > 5) {\n grade = \"E\";\n console.log(score + grade);\n } else {\n grade = \"F\";\n console.log(score + grade);\n }\n\n return grade;\n}", "function scoreCalc(a){ //this function will assign the score to its class\n if (a>=0 && a<=49){ \n gradeClass=\"F\";\n } else if (a>49 && a<60){\n gradeClass=\"E\";\n } else if (a>59 && a<70){\n gradeClass=\"D\";\n } else if (a>69 && a<80){\n gradeClass=\"C\";\n } else if (a>79 && a<90){\n gradeClass=\"B\";\n } else if (a>89 && a<=100){\n gradeClass=\"A\";\n } else {\n gradeClass=\"INVALID GRADE\";\n }\n return result= `You got a ${gradeClass} (${num}%)!`;\n }", "function getFinalScore (score, counter) {\n return ' Your final score is ' + score + ' out of ' + counter + '. '\n}", "function calculateGrade(marks) {\n const average = calculateAverage(marks);\n if (average < 60) return \"F\";\n if (average < 70) return \"D\";\n if (average < 80) return \"C\";\n if (average < 90) return \"B\";\n return \"A\";\n}", "function calculateGrade(marks) {\n const average = calculateAverage(marks);\n if (average < 60) return \"F\";\n if (average < 70) return \"D\";\n if (average < 80) return \"C\";\n if (average < 90) return \"B\";\n return \"A\";\n}", "function getGrade(score) {\n let grade;\n // Write your code here\n \n if (score > 25 && score <= 30) {\n grade = 'A';\n } else if (score > 20 && score <= 25) {\n grade = 'B';\n } else if (score > 15 && score <= 20) {\n grade = 'C'; \n } else if (score > 10 && score <= 15) {\n grade = 'D';\n } else if (score > 5 && score <= 10) {\n grade = 'E';\n } else if (score >= 0 && score <= 5) {\n grade = 'F';\n } else {\n grade = 'error'\n }\n return grade;\n}", "function finalGrade(g1, g2, g3){\n let avg = Math.floor((g1 + g2 + g3) / 30);\n let grade;\n\n if(valid(g1) && valid(g2) && valid(g3)){\n switch (avg) {\n case 10:\n grade = \"A\";\n break;\n case 9:\n grade = \"A\";\n break;\n case 8:\n grade = \"B\";\n break;\n case 7:\n grade = \"C\";\n break;\n case 6:\n grade = \"D\";\n break;\n default:\n grade = \"F\";\n break;\n }\n }\n\n return grade;\n}", "function myGrade(mark) {\n if (mark >= 90 && mark <= 100) {\n console.log('Your grade is: A*')\n } else if (mark >= 80 && mark <= 89) {\n console.log('Your grade is: A')\n } else if (mark >= 70 && mark <= 79) {\n console.log('Your grade is: B')\n } else if (mark >= 60 && mark <= 69) {\n console.log('Your grade is: C')\n } else if (mark >= 50 && mark <= 59) {\n console.log('Your grade is: D')\n } else if (mark <= 49) {\n console.log('Your grade is: E')\n } else {\n console.log('Hmm... may be your are a genius!')\n }\n}", "function result() {\n var input = document.getElementById(\"marks\");\n // console.log(\"your marks=\", input.value);\n if (input.value > 90) {\n console.log(\"The grade for\", input.value, \"is AA\");\n } else if (input.value > 80 && input.value <= 90) {\n console.log(\"The grade for\", input.value, \"is AB\");\n } else if (input.value > 70 && input.value <= 80) {\n console.log(\"The grade for\", input.value, \"is BB\");\n } else if (input.value > 60 && input.value <= 70) {\n console.log(\"The grade for\", input.value, \"is BC\");\n } else if (input.value > 50 && input.value <= 60) {\n console.log(\"The grade for\", input.value, \"is CC\");\n } else if (input.value > 40 && input.value <= 50) {\n console.log(\"The grade for\", input.value, \"is CD\");\n } else if (input.value > 30 && input.value <= 40) {\n console.log(\"The grade for\", input.value, \"is DD\");\n } else console.log(\"The grade for\", input.value, \"is FF\");\n}", "gradeAssignment(student) {\n let val1 = Math.floor(Math.random() * 100);\n let plusMin = \"\";\n let val2 = Math.floor(Math.random() * 100);\n val1 >= 50 ? (plusMin = \"plus\") : (plusMin = \"minus\");\n if (plusMin === \"plus\") {\n if (student.grade + val2 > 100) {\n student.grade = 100;\n } else {\n student.grade += val2;\n }\n } else if (plusMin === \"minus\") {\n if (student.grade - val2 < 0) {\n student.grade = 0;\n } else {\n student.grade -= val2;\n }\n }\n console.log(\n `${this.name} graded ${student.name}\\'s assignment. ${\n student.name\n } now has a grade of ${student.grade}!`\n );\n }", "function gradefinder(a)\n{\n if(a>=90)\n {\n console.log(`grade-A`);\n }\n else if(a>=80)\n {\n console.log(`grade-B`);\n }\n else if(a>=70)\n {\n console.log(`grade-C`);\n }\n else if(a>=60)\n {\n console.log(`grade-D`);\n }\n else if(a>=50)\n {\n console.log(`grade-E`);\n }\n else{\n console.log(`Fail`);\n }\n}", "function calculateGrade(marks) {\n const average = calculateAverage(marks);\n\n if (average < 60) return \"F\";\n if (average < 70) return \"D\";\n if (average < 80) return \"C\";\n if (average < 90) return \"B\";\n return \"A\";\n}", "function grade(marks) {\n if(marks > 90) {\n alert(\"AA\");\n }\n else {\n if (marks > 80) {\n alert(\"AB\");\n }\n else {\n if (marks > 70) {\n alert(\"BB\");\n }\n else {\n if (marks > 60) {\n alert(\"BC\");\n }\n else {\n if (marks > 50) {\n alert(\"CC\");\n }\n else {\n if (marks > 40) {\n alert(\"CD\");\n }\n else {\n if (marks > 30){\n alert(\"AA\");\n }\n else\n alert(\"FF\");\n }\n }\n }\n }\n }\n }\n}", "function LetterGrade(grade) {\n\tif (grade >= 90) {\n\t\tmessage 'A grade of ' + grade + ' is an A.';\n\t\treturn message;\n\t}\n\n\telse if (grade >= 80 & grade < 90) {\n\t\tmessage 'A grade of ' + grade + ' is a B.';\n\t\treturn message;\n\t}\n\n\telse if (grade >= 70 & grade < 80) {\n\t\tmessage 'A grade of ' + grade + ' is a C.';\n\t\treturn message;\n\t}\n\n\telse if (grade >= 60 & grade < 70) {\n\t\tmessage 'A grade of ' + grade + ' is a D.';\n\t\treturn message;\n\t}\n\n\telse if (grade < 60) {\n\t\tmessage 'A grade of ' + grade + ' is an F.';\n\t\treturn message;\n\t}\n}", "function reportCard() {\n\n ///////////////////////// DO NOT MODIFY\n let testTotal = 0; ////// DO NOT MODIFY\n let quizTotal = 0; ////// DO NOT MODIFY\n let homeworkTotal = 0; // DO NOT MODIFY\n ///////////////////////// DO NOT MODIFY\n /*\n * NOTE: The 'testTotal', 'quizTotal', and 'homeworkTotal' variables\n * should be representative of the sum of the test scores, quiz\n * scores, and homework scores the user enters, respectively.\n */\n\n ///////////////////// DO NOT MODIFY\n let tests = 0; ////// DO NOT MODIFY\n let quizzes = 0; //// DO NOT MODIFY\n let homeworks = 0; // DO NOT MODIFY\n ///////////////////// DO NOT MODIFY\n\n /*\n * NOTE: The 'tests', 'quizzes', and 'homeworks' variables should be\n * representative of the number of tests, quizzes, and homework\n * grades the user enters, respectively.\n */\n\twhile (true){\n\t\tlet testsInput=prompt(\"Enter your test score\");\n\t\tif(testsInput==-1){\n\t\t\tbreak;\n\t\t}\n\t\tif(Number(testsInput)>=0 && Number(testsInput<=100)){\n\t\t\ttestTotal=Number(testsInput)+testTotal;\n\t\t\ttests++;\n\t\t}\n\n\t}\n\twhile(true){\n\t\tlet quizInput=prompt(\"Enter your quiz score\");\n\t\tif (quizInput==-1){\n\t\t\tbreak;\n\t\t}\n\t\tif(Number(quizInput)>=0 && Number(quizInput)<=100){\n\t\t\tquizTotal=Number(quizInput)+quizTotal;\n\t\t\tquizzes++;\n\t\t}\n\t}\n\twhile(true){\n\t\tlet homeworkInput=prompt(\"Enter your homework score\");\n\t\tif (homeworkInput==-1){\n\t\t\tbreak;\n\t\t}\n\t\tif(Number(homeworkInput)>=0 && Number(homeworkInput)<=100){\n\t\t\thomeworkTotal=Number(homeworkInput)+homeworkTotal;\n\t\t\thomeworks++;\n\t\t}\n\t}\n\tlet testAverage=(testTotal/tests).toFixed(2);\n\tlet quizAverage=(quizTotal/quizzes).toFixed(2);\n\tlet homeworksAverage=(homeworkTotal/homeworks).toFixed(2);\n\tgrade=(.6*testAverage+.3*quizAverage+.1*homeworksAverage).toFixed(2);\n\tdocument.getElementById(\"report-card-output\").innerHTML=\"Tests: \"+testAverage+\"</br>Quizzes: \"+quizAverage+\"</br>Homework: \"+homeworksAverage+\"</br>Grade: \"+grade;\n /////////////////////// DO NOT MODIFY\n check('report-card', // DO NOT MODIFY\n testTotal, ////////// DO NOT MODIFY\n tests, ////////////// DO NOT MODIFY\n quizTotal, ////////// DO NOT MODIFY\n quizzes, //////////// DO NOT MODIFY\n homeworkTotal, ////// DO NOT MODIFY\n homeworks /////////// DO NOT MODIFY\n ); //////////////////// DO NOT MODIFY\n /////////////////////// DO NOT MODIFY\n}", "function gradeCal() {\n //setting up my variables\n var numberGrade;\n var letterGrade;\n var i = 0;\n\n //Are things different\n //I do not know if my code is changing!\n\n //Get the values entered into the HTML via jquery and then calculate the grade\n numberGrade = ($(\"#Assignments\").val() * 0.5)\n + ($(\"#GroupProjects\").val() * 0.1)\n + ($(\"#Quizzes\").val() * 0.1)\n + ($(\"#Exams\").val() * 0.2)\n + ($(\"#Intex\").val() * 0.1);\n numberGrade = numberGrade.toPrecision(3);\n\n //Lets find the letter grade\n if (numberGrade > 94) {\n letterGrade = \"A\";\n }\n else if (numberGrade > 90) {\n letterGrade = \"A-\";\n }\n else if (numberGrade >= 87) {\n letterGrade = \"B+\";\n }\n else if (numberGrade >= 84) {\n letterGrade = \"B\";\n }\n else if (numberGrade >= 80) {\n letterGrade = \"B-\";\n }\n else if (numberGrade >= 77) {\n letterGrade = \"C+\";\n }\n else if (numberGrade >= 74) {\n letterGrade = \"C\";\n }\n else if (numberGrade >= 70) {\n letterGrade = \"C-\";\n }\n else if (numberGrade >= 67) {\n letterGrade = \"D+\";\n }\n else if (numberGrade >= 64) {\n letterGrade = \"D\";\n }\n else if (numberGrade >= 60) {\n letterGrade = \"D-\";\n }\n else {\n letterGrade = \"E\";\n }\n\n //check if inputs are empty\n if ($(\"#Assignments\").val() === \"\" || $(\"#GroupProjects\").val() === \"\" || $(\"#Quizzes\").val() === \"\" || $(\"#Exams\").val() === \"\" || $(\"#Intex\").val() === \"\") {\n alert(\"Please, make sure that all feilds are entered\");\n ++i\n }\n\n //check if inputs are between 0 and 100\n if (($(\"#Assignments\").val() > 100 || $(\"#Assignments\").val() < 0) || ($(\"#GroupProjects\").val() > 100 || $(\"#GroupProjects\").val() < 0) || ($(\"#Quizzes\").val() > 100 || $(\"#Quizzes\").val() < 0) || ($(\"#Exams\").val() > 100 || $(\"#Exams\").val() < 0) || ($(\"#Intex\").val() > 100 || $(\"#Intex\").val() < 0)) {\n alert(\"Please, make sure that the numbers intputed are between 0 and 100\");\n ++i\n }\n\n //Give a message to the user\n if (i === 0) {\n alert(`With those numbers, the final grade would be ${numberGrade}% which is an ${letterGrade}`);\n }\n}", "function grades(grade){\n if(grade >= 2.00 && grade <= 2.99){\n // console.log(`Fail`);\n return `Fail`;\n } else if(grade > 2.99 && grade <= 3.49){\n // console.log(`Poor`);\n return `Poor`;\n } else if(grade > 3.49 && grade <= 4.49){\n //console.log(`Good`);\n return `Good`;\n } else if(grade > 4.49 && grade <= 5.49){\n // console.log(`Very Good`);\n return `Very Good`;\n } else if(grade > 5.49 && grade <= 6.00){\n // console.log('Excellent');\n return `Excellent`;\n }\n}", "function AssignLetterGrade(gradeScore) {\n // Grading Scale\n const gradingScale = {\n \"A+\": 96,\n A: 93,\n \"A-\": 90,\n \"B+\": 87,\n B: 83,\n \"B-\": 80,\n \"C+\": 77,\n C: 73,\n \"C-\": 70,\n D: 66,\n \"D-\": 60,\n F: 50,\n };\n\n // Assign Letter Grade\n if (gradeScore < 50 && gradeScore !== 0) {\n return \"F\";\n } else {\n for (let [key, value] of Object.entries(gradingScale)) {\n if (gradeScore >= value) {\n return key.toString();\n }\n }\n }\n}", "function test() {\n for (i = 0; i <= 10; i++) {\n if (i >= 1 && i <= 3) {\n var grade = 'E';\n console.log('Calificatul corespunzator punctajului ' + i + ' este ' + grade + \" .\");\n } else if (i >= 4 && i <= 6) {\n var grade = 'D';\n console.log('Calificatul corespunzator punctajului ' + i + ' este ' + grade + \" .\");\n } else if (i >= 7 && i <= 8) {\n var grade = 'B';\n console.log('Calificatul corespunzator punctajului ' + i + ' este ' + grade + \" .\");\n } else if (i <= 9) {\n var grade = 'A';\n console.log('Calificatul corespunzator punctajului ' + i + ' este ' + grade + \" .\");\n } else if (i >= 10) {\n var grade = 'A+';\n console.log('Calificatul corespunzator punctajului ' + i + ' este ' + grade + \" .\");\n }\n }\n }", "function getGrade(score1, score2, score3) {\n let average = (score1 + score2 + score3) / 3;\n switch (true) {\n case average < 60:\n console.log(\"F\");\n break;\n case average < 70:\n console.log(\"D\");\n break;\n case average < 80:\n console.log(\"C\");\n break;\n case average < 90:\n console.log(\"B\");\n break;\n default:\n console.log(\"A\");\n break;\n }\n}", "function grade(num){\n var grade\n switch (true) {\n case (num >= 90 && num <= 100):\n grade = \"A\"\n break;\n case (num >= 80 && num <= 89):\n grade = \"B\"\n break;\n case (num >= 70 && num <= 79):\n grade = \"C\"\n break;\n case (num >= 60 && num <= 69):\n grade = \"D\"\n break;\n default:\n grade = \"F\"\n break;\n\n }\n console.log(`Score: ${num}. Grade: ${grade}`);\n}", "function gradecalc(firstInSem, secondInSem, finalSem, assignment, attendance)\r\n {\r\n\tvar total = (firstInSem * 30) / 100 + (secondInSem * 30) / 100 + (finalSem * 50) / 100 + (assignment) + (attendance);\r\n\tvar grade = total.toFixed(2);\r\n\tdocument.getElementById('gradeObject').innerHTML = (\"Your Marks :-\", grade);\r\n\tconsole.log(grade);\r\n\tif (total >= 35)\r\n\t{\r\n\t\tif (finalSem >= 35) \r\n\t\t{\r\n\t\t\tvar marks = (total-35).toFixed(2)\r\n\t\t\tdocument.getElementById(\"p2\").innerHTML = (`<br>You are Safe and you crossed Danger Zone, Your extra marks is ${marks}!`);\r\n\t\t} \r\n\t\telse \r\n\t\t{\t\r\n\t\t\tvar marks = (35-finalSem).toFixed(2)\r\n\t\t\tdocument.getElementById(\"p2\").innerHTML = (\"You Have a Backlog in this paper and have to give this paper again :-(\");\r\n\t\t\tdocument.getElementById(\"p2\").innerHTML = \t` You are UnSafe and you have to gain ${marks} more marks from Teacher (Current Time). <br/> Means Next time in Final Back Paper you have to score Only 35 Marks. `;\r\n\r\n\t\t}\r\n\t} else \r\n\t{\r\n\t\tvar marks = ((35 - total) * 2).toFixed(2)\r\n\t\tif ((finalSem + (35 - total) * 2) < 35) {\r\n\t\t\tdocument.getElementById(\"p2\").innerHTML = `You are UnSafe and you have to gain ${marks} more marks from Teacher (Current Time).\\n <br/> Means Next time in Final Back Paper you have to score Only 35 Marks.`;\r\n\r\n\t\t} else {\r\n\t\t\tvar moreNeed = (finalSem + (35 - total) * 2).toFixed(2)\r\n\t\t\tdocument.getElementById(\"p2\").innerHTML = `You are UnSafe and you have to gain ${marks} more marks from Teacher (Current Time).\\n <br/> Means Next time in Final Back Paper you have to score Only ${moreNeed} Marks`;\r\n\r\n\t\t}\r\n\t}\r\n}", "function convertScoreToGrade(score) {\n if (score > 100 || score < 0) {\n return 'PUNTUACION INVALIDA';\n }\n\n if (score >= 90 && score <= 100) {\n return 'A';\n }\n\n if (score >= 80 && score <= 89) {\n return 'B';\n }\n\n if (score >= 70 && score <= 79) {\n return 'C';\n }\n\n if (score >= 60 && score <= 69) {\n return 'D';\n }\n\n if (score >= 0 && score <= 59) {\n return 'F';\n }\n}", "function getGrade(scr1, scr2, scr3) {\n let score = (scr1 + scr2 + scr3) / 3;\n switch (true) { //the switch does the evaluating, so put T or F here\n case (score < 60): //the case is WHAT the switch is evaluating\n console.log('F');\n break;\n case (score < 70):\n console.log('D');\n break;\n case (score < 80):\n console.log('C');\n break;\n case (score < 90):\n console.log('B');\n break;\n case (score >= 90):\n console.log('A');\n break;\n }\n}", "scoreToDisplay() {\n let score = '';\n\n if (this.P1point === this.P2point && this.P1point < 3) {\n if (this.P1point === 0)\n score = 'Love';\n if (this.P1point === 1)\n score = 'Fifteen';\n if (this.P1point === 2)\n score = 'Thirty';\n score += '-All';\n }\n if (this.P1point === this.P2point && this.P1point > 2)\n score = 'Deuce';\n\n if (this.P1point > 0 && this.P2point === 0) {\n if (this.P1point === 1)\n this.P1res = 'Fifteen';\n if (this.P1point === 2)\n this.P1res = 'Thirty';\n if (this.P1point === 3)\n this.P1res = 'Forty';\n\n this.P2res = 'Love';\n score = this.P1res + '-' + this.P2res;\n }\n if (this.P2point > 0 && this.P1point === 0) {\n if (this.P2point === 1)\n this.P2res = 'Fifteen';\n if (this.P2point === 2)\n this.P2res = 'Thirty';\n if (this.P2point === 3)\n this.P2res = 'Forty';\n\n this.P1res = 'Love';\n score = this.P1res + '-' + this.P2res;\n }\n\n if (this.P1point > this.P2point && this.P1point < 4) {\n if (this.P1point === 2)\n this.P1res = 'Thirty';\n if (this.P1point === 3)\n this.P1res = 'Forty';\n if (this.P2point === 1)\n this.P2res = 'Fifteen';\n if (this.P2point === 2)\n this.P2res = 'Thirty';\n score = this.P1res + '-' + this.P2res;\n }\n if (this.P2point > this.P1point && this.P2point < 4) {\n if (this.P2point === 2)\n this.P2res = 'Thirty';\n if (this.P2point === 3)\n this.P2res = 'Forty';\n if (this.P1point === 1)\n this.P1res = 'Fifteen';\n if (this.P1point === 2)\n this.P1res = 'Thirty';\n score = this.P1res + '-' + this.P2res;\n }\n\n if (this.P1point > this.P2point && this.P2point >= 3) {\n score = 'Advantage ' + this.player1Name;\n }\n\n if (this.P2point > this.P1point && this.P1point >= 3) {\n score = 'Advantage ' + this.player2Name;\n }\n\n if (this.P1point >= 4 && this.P2point >= 0 && (this.P1point - this.P2point) >= 2) {\n score = 'Win for ' + this.player1Name;\n }\n if (this.P2point >= 4 && this.P1point >= 0 && (this.P2point - this.P1point) >= 2) {\n score = 'Win for ' + this.player2Name;\n }\n return score;\n }", "function calcGP(grade) {\n\tswitch (grade) {\n \t\tcase \"A+\":GP += 4.3;\n \t\tbreak;\n \t\tcase \"A\":GP += 4;\n \t\tbreak;\n \t\tcase \"A-\":GP += 3.7;\n \t\tbreak;\n \t\tcase \"B+\":GP += 3.3;\n \t\tbreak;\n \t\tcase \"B\":GP += 3;\n \t\tbreak;\n \t\tcase \"B-\":GP += 2.7;\n \t\tbreak;\n \t\tcase \"C+\":GP += 2.3;\n \t\tbreak;\n \tcase \"C\":GP += 2;\n \t\tbreak;\n \tcase \"C-\":GP += 1.7;\n \t\tbreak;\n \tcase \"D+\":GP += 1.3;\n \t\tbreak;\n \tcase \"D\":GP += 1;\n \t\tbreak;\n \tcase \"D-\":GP += 0.7;\n \t\tbreak;\n \tdefault: break;\n \t\n\t}\n}", "function getGrade(score) {\n let grade;\n // Write your code here\n if (score>25 && score<=30){\n grade='A'\n }\n else if(score>20 &&score<=25){\n grade='B'\n }\n else if(score>15 &&score<=20){\n grade='C'\n }\n else if(score>10 &&score<=15){\n grade='D'\n }else if(score>5 &&score<=10){\n grade='E'\n }\n else if(score>0 &&score<=5){\n grade='F'\n }\n return grade;\n}", "function letterGrader(num) {\n if (num <= 59) {\n console.log(\"This is the Answer to Task 7 ----> \" + \"Your letter grade is an \\\"F\\\".\");\n } else if (num >= 60 && num <= 69) {\n console.log(\"This is the Answer to Task 7 ----> \" + \"Your letter grade is a \\\"D\\\".\");\n } else if (num >= 70 && num <= 79) {\n console.log(\"This is the Answer to Task 7 ----> \" + \"Your letter grade is a \\\"C\\\".\");\n } else if (num >= 80 && num <= 89) {\n console.log(\"This is the Answer to Task 7 ----> \" + \"Your letter grade is a \\\"B\\\".\");\n } else if (num >= 90 && num <= 100) {\n console.log(\"This is the Answer to Task 7 ----> \" + \"Your letter grade is an \\\"A\\\".\");\n }\n}", "function myGrade (grade) {\n if (grade >= 90) {\n console.log(\"Your grade is an A!\");\n } else if (grade < 90 && grade >= 80) {\n console.log(\"Your grade is a B!\");\n } else if (grade < 80 && grade >= 70) {\n console.log(\"Your grade is a C.\");\n } else if (grade < 70 && grade >= 60) {\n console.log(\"Your grade is a D.\");\n } else {\n console.log(\"Your grade is an F.\")\n }\n}", "function gradeAssignment(score){\n\n}", "function computeGrade(essay) {\n essay = essay.trim();\n let nnn = ['very', 'thing', 'always', 'never', 'like', 'lot', 'good', 'bad', 'stuff', 'nice', 'really', 'many', 'i', 'you'];\n let score = 100;\n //Checks length\n if (essay.length < 100)\n score -= 50;\n if (essay.length > 250)\n score -= (essay.length - 250) * 5;\n essayArray = essay.split(' ');\n // NNN & Checks if is a word\n for (let i = 0; i < essayArray.length; i++) {\n let element = essayArray[i];\n element = element.toLowerCase();\n if (element.includes(\",\") || element.includes(\".\"))\n element = element.substring(0, element.length - 1);\n if (words[element] != 1 || nnn.includes(element))\n score--;\n if (element.includes(\"'\"))\n score -= 2;\n };\n //N2SSWTSW\n let wordset = new Set();\n const sentences = essay.split('.');\n for(let i = 0;i<sentences.length;i++) \n {\n let element = sentences[i].trim().split(' ')[0];\n if(wordset.has(element))\n score-=3;\n console.log(sentences.length);\n console.log(element);\n wordset.add(element);\n }\n console.log(score);\n return score > -100 ? score : -100;\n}", "function grades()\n{\n\tvar hwavg, mtexam, finalexam, acravg, finalavg, grade;\n\t\n\tvar errorMessage = \"<span style='color: #000000; background-color: #FF8199;\" + \n\t\t\t\t\t\t\"width: 100px;font-weight: bold; font-size: 14px;'>\" +\n\t\t\t\t\t\t\"Input must be integers between 0 and 100</span>\";\n\n\thwavg = document.forms[\"myform\"].elements[\"hwavg\"].value;\n\tmtexam = document.forms[\"myform\"].elements[\"midterm\"].value;\n\tfinalexam = document.forms[\"myform\"].elements[\"finalexam\"].value;\n\tacravg = document.forms[\"myform\"].elements[\"acravg\"].value;\n\n\thwnum = parseInt(hwavg, 10);\n\tmtnum = parseInt(mtexam, 10);\n\tfinnum = parseInt(finalexam, 10);\n\tacrnum = parseInt(acravg, 10);\n\n\n\tif( isNaN(hwnum) || isNaN(mtnum) || isNaN(finnum) || isNaN(acrnum) || \n\t\thwnum < 0 || mtnum < 0 || finnum < 0 || acrnum < 0 || \n\t\thwnum > 100 || mtnum > 100 || finnum > 100 || acrnum > 100)\n {\n \tdocument.getElementById(\"errorMsg\").innerHTML = errorMessage; \n }\n \telse \n \t{\n\n\t\tfinalavg = (.5 * hwnum) + (.2 * mtnum) + (.2 * finnum) + (.1 * acrnum);\n\n\t\tif(finalavg >= 90) \n\t\t\t{grade = \"A\";}\n\t\telse if (finalavg >= 80 && finalavg < 90) \n\t\t\t{grade = \"B\";}\n\t\telse if (finalavg >= 70 && finalavg < 80) \n\t\t\t{grade = \"C\";}\n\t\telse if (finalavg >= 60 && finalavg < 70) \n\t\t\t{grade = \"D \\nStudent will need to retake the course\";}\n\t\telse if (finalavg < 60)\n\t\t\t{grade = \"F \\nStudent will need to retake the course\";}\n \n \tdocument.forms[\"myform\"].elements[\"result\"].value = ( \"Final Average: \" + finalavg.toFixed(0) +\n \t\t\"\\nFinal Grade: \" + grade);\n }\n\n \n\t\n}", "function assignGrade(num){\n if (num > 90){\n console.log(\"A\");\n } else if(num > 80){\n console.log(\"B\");\n }else if(num > 70){\n console.log(\"C\");\n }else if( num > 60){\n console.log(\"D\");\n }else if(num < 60){\n console.log(\"F\");\n }\n}", "function scrabbleScore() {\n console.log(`Currently using : ${scoringAlgorithms[2].name}`);\n\tconsole.log(`The score for your word, ${userWord}, is ${oldScrabbleScoreTotal(userWord)}!`);\n}", "function findLetterGrade(grade) {\n var letterGrade = \"N/A\"\n if (grade >= 90) {\n letterGrade = \"A\"\n } else if (grade >= 80) {\n letterGrade = \"B\"\n } else if (grade >= 70) {\n letterGrade = \"C\"\n } else if (grade >= 60) {\n letterGrade = \"D\"\n } else {\n letterGrade = \"F\"\n };\n document.getElementById(\"WHO2\").value = letterGrade;\n}", "function convertScoreToGrade(score) {\n switch (true) {\n case (score > 100 || score < 0): console.log(\"INVALID SCORE\");\n break;\n case (score > 89 && score < 100): console.log(\"A\");\n break;\n case (score > 79 && score < 90): console.log(\"B\");\n break;\n case (score > 70 && score < 80): console.log(\"C\");\n break;\n case (score > 60 && score < 71): console.log(\"D\");\n break;\n default: console.log(\"F\");\n }\n}", "function calculateGradeNeeded(){\n\n var finalExamWeight = document.getElementById(\"examWeight\").value;\n var preferredScore = document.getElementById(\"preferredScore\").value;\n var gradeNeeded = \"\";\n if(finalExamWeight == \"\" || preferredScore == \"\"){\n document.getElementById(\"output1\").innerHTML = \"Please enter your your final weight and desired grade\"\n }else{\n gradeNeeded = ((preferredScore - ((100-(finalExamWeight))/100)*CurrentGrade) / finalExamWeight) *100;\n if(CurrentGrade == \"\"){\n document.getElementById(\"output1\").innerHTML = \"Please Calculate your Current Grade first!\"\n }else{\n document.getElementById(\"output1\").innerHTML = \"You will need to score at least \" + gradeNeeded + \"% on your final to get a \" + preferredScore + \"% overall.\";\n }\n\n }\n\n\n}", "function grades(arrName, arrpoints) {\n var arrName;\n var arrpoints;\n var result = '';\n for (i = 0; i < arrName.length; i++) {\n if (arrpoints[i] < 51) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and failed to complete the exam.\\n\"\n } else if (arrpoints[i] <= 60) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 6.\\n\"\n } else if (arrpoints[i] <= 70) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 7.\\n\"\n } else if (arrpoints[i] <= 80) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 8.\\n\"\n } else if (arrpoints[i] <= 90) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 9.\\n\"\n } else if (arrpoints[i] <= 100) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 10.\\n\"\n }\n }\n return result;\n\n}", "function calcScore() {\n console.log(\"incorrect answers: \" + wrongCount);\n console.log(\"correct answers: \" + correctCount);\n let totalAttempts = wrongCount + correctCount;\n let score = (correctCount / totalAttempts) * 100;\n console.log(\"total score: \" + score);\n // textScore = toString(score);\n let printScore = $(\"<h2>\").text(score);\n $('.displayScore').append(printScore);\n\n }", "function gradesOfDoom(mark){\n //90s should be A \n if (mark>89){\n return 'A';\n }\n //80s should be B \n else if (mark>79){\n return 'B';\n }\n //70s should be Cs \n else if (mark>69){\n return 'C';\n }\n //60s should be D \n else if (mark>59){\n return 'D';\n }\n //and anything below 60 should be F\n else if (mark<60){\n return 'F';\n }\n }", "function score() {\n\treturn `Human: ${playerPoints} Computer: ${computerPoints}`;\n}", "function task14_16_8(){\n var names =[\"Michael\",\"John\",\"Tony\"];\n var score =[320,230,480];\n var total = 500;\n document.write(\"Score of \"+names[0]+ \" is \"+score[0]+ \" Percentage: \"+ score[0]/total * 100 + \"% <br>\");\n document.write(\"Score of \"+names[1]+ \" is \"+score[1]+ \" Percentage: \"+ score[1]/total * 100 + \"% <br>\");\n document.write(\"Score of \"+names[2]+ \" is \"+score[2]+ \" Percentage: \"+ score[2]/total * 100 + \"% <br>\");\n}", "function letter(num){\n var letterGrade = \"\";\n if ((num <= 110) && (num >= 90)){\n letterGrade = \"A\";\n }\n else if ((num <= 89.99) && (num >= 80)){\n letterGrade = \"B\";\n }\n else if ((num <= 79.99) && (num >= 70)){\n letterGrade = \"C\";\n }\n else if ((num <= 69.99) && (num >= 60)){\n letterGrade = \"D\";\n }\n else if((num <= 59.99) && (num >= 0)){\n letterGrade = \"F\";\n }\n return letterGrade;\n }", "function getVals() {\n\n //Get Current Grade\n var currentGrade = document.getElementById(\"currentGrade\").value;\n currentGrade /= 100;\n\n //Get Desired Grade\n var desiredGrade = document.getElementById(\"desiredGrade\").value;\n desiredGrade /= 100;\n\n //Get Weight\n var weight = document.getElementById(\"weight\").value;\n weight /= 100;\n\n //Calcuate Final Grade\n var finalGrade = (desiredGrade - (1-weight)*currentGrade) / weight;\n finalGrade = Math.round(finalGrade * 100)\n\n\n if(finalGrade > 90){\n document.getElementById(\"result\").innerHTML = \"You need a \" + finalGrade + \"% on your final exam to get a \" + desiredGrade * 100 + \" in the class. Better start studying.\";\n } else if (finalGrade <= 90 && finalGrade > 80) {\n document.getElementById(\"result\").innerHTML = \"You need a \" + finalGrade + \"% on your final exam to get a \" + desiredGrade * 100 + \" in the class. Could be worse.\";\n } else if (finalGrade <= 80 && finalGrade > 70) {\n document.getElementById(\"result\").innerHTML = \"You need a \" + finalGrade + \"% on your final exam to get a \" + desiredGrade * 100 + \" in the class. No sweat, you got this.\";\n } else if (finalGrade <= 70 && finalGrade > 60) {\n document.getElementById(\"result\").innerHTML = \"You need a \" + finalGrade + \"% on your final exam to get a \" + desiredGrade * 100 + \" in the class. This'll be easy.\";\n } else {\n document.getElementById(\"result\").innerHTML = \"You need a \" + finalGrade + \"% on your final exam to get a \" + desiredGrade * 100 + \" in the class. Enjoy not studying!\";\n }\n\n\n }", "function grades(arrName, arrpoints) {\n \n var arrName;\n var arrpoints;\n var result = '';\n \n for (i = 0; i < arrName.length; i++) {\n if (arrpoints[i] < 51) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and failed to complete the exam.\\n\"\n } else if (arrpoints[i] <= 60) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 6.\\n\"\n } else if (arrpoints[i] <= 70) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 7.\\n\"\n } else if (arrpoints[i] <= 80) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 8.\\n\"\n } else if (arrpoints[i] <= 90) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 9.\\n\"\n } else if (arrpoints[i] <= 100) {\n result += arrName[i] + \" acquired \" + arrpoints[i] + \" points and earned 10.\\n\"\n }\n }\n \n return result;\n\n}", "function mapping() {\r\n //precondition: \r\n //\tnum1 is a real number\r\n\r\n //Postcondition:\r\n //\tone of these letter grades is outputted (A+,A,B,B,C+,C,D+,D,E,F) \r\n\r\n\r\n /* in Ex1, change the following two lines such that \r\n num1 and num2 are parsed to integer before be \r\n assigned to w and h, respectively. */\r\n /* in Ex 2, rename w and h to a and b, respectively. */\r\n\r\n var grade = parseInt(document.getElementById(\"num1\").value);\r\n /* in Ex2, write a similar code to the above line\r\n to capture the value for c*/\r\n\r\n\r\n /* in Ex2 to Ex4, you need to replace the following line \r\n with some other formulas */\r\n\r\n\r\n\r\n /* in Ex5, you should delete from Line 15 to this line */\r\n\r\n //in Ex 5, uncomment this block\r\n var letter;\r\n switch (true){\r\n case (grade>89): \r\n letter=\"A+\";\r\n break;\r\n case (grade>79): \r\n letter=\"A\";\r\n break;\r\n case (grade>74): \r\n letter=\"B+\";\r\n break;\r\n case (grade>69): \r\n letter=\"B\";\r\n break;\r\n case (grade>64): \r\n letter=\"C+\";\r\n break;\r\n case (grade>59): \r\n letter=\"C\";\r\n break;\r\n case (grade>54): \r\n letter=\"D+\";\r\n break;\r\n case (grade>49): \r\n letter=\"D\";\r\n break;\r\n case (grade > 39):\r\n letter = \"E\";\r\n break;\r\n // in Ex5, you need to add more cases for other letter grades\r\n default:\r\n letter=\"F\";\r\n }\r\n\r\n\r\n /* in Ex2 to Ex5, you need to renmae \"sum\" to make it more relevant\r\n to those problems, you may also need to rename s to a better \r\n varibale that you have in your formulas above */\r\n document.getElementById(\"output\").innerHTML = letter;\r\n}", "function getGrade(marks){\n\n if(marks>90){\n console.log('Hey, you got A rank');\n }\n else if(marks > 80){\n console.log('Hey, you got just kidding B')\n }else if(marks >70){\n console.log('Hey, Happy man you got \"c\"')\n }\n else{\n console.log('this is not working');\n }\n \n}", "function getAlphaGrade(grade) {\n let alphaGrade;\n if (grade >= 90) {\n alphaGrade = \"A\";\n } else (grade >= 80) {\n alphaGrade = \"B\";\n } else if (grade >= 70) {\n alphaGrade = \"C\";\n } else if (grade >= 60) {\n alphaGrade = \"D\";\n } else {\n alphaGrade = \"F\";\n }\n return alphaGrade;\n}", "function scoreConverter(score) {\r\n score = score / 100;\r\n\r\n if (score >= 0 && score <= 0.49) {\r\n console.log(\"You got a F (%s%)!\", score * 100);\r\n } else if (score >= 0.5 && score <= 0.59) {\r\n console.log(\"You got a E (%s%)!\", score * 100);\r\n } else if (score >= 0.6 && score <= 0.69) {\r\n console.log(\"You got a D (%s%)!\", score * 100);\r\n } else if (score >= 0.7 && score <= 0.79) {\r\n console.log(\"You got a C (%s%)!\", score * 100);\r\n } else if (score >= 0.8 && score <= 0.89) {\r\n console.log(\"You got a B (%s%)!\", score * 100);\r\n } else if (score >= 0.9 && score <= 1) {\r\n console.log(\"You got a A (%s%)!\", score * 100);\r\n }\r\n}", "function gradeCalculator(grade) {\n //show needs return a string\n let show;\n //with if will find out the grade of the student\n if (grade >= 90) {\n show = \"You got an A \" + \"(\" + grade.toString() + \"%)!\"\n return show;\n }else if (grade >= 80) {\n show = \"You got a B \" + \"(\" + grade.toString() + \"%)!\"\n return show;\n }else if (grade >= 70) {\n show = \"You got a C \" + \"(\" + grade.toString() + \"%)!\"\n return show;\n }else if (grade >= 60) {\n show = \"You got a D \" + \"(\" + grade.toString() + \"%)!\"\n return show;\n }else if (grade >= 50) {\n show = \"You got an E \" + \"(\" + grade.toString() + \"%)!\"\n return show;\n }else if (grade >= 0) {\n show = \"You got a F \" + \"(\" + grade.toString() + \"%)!\"\n return show;\n }\n}", "function calculateGradePoint(letterGrade) {\n if (letterGrade === \"A\")\n return 4\n\n if (letterGrade === \"B\")\n return 3\n\n if (letterGrade === \"C\")\n return 2\n\n if (letterGrade === \"D\")\n return 1\n\n if (letterGrade === \"E\")\n return 0\n}", "function acquiredEarned (a, b) {\n var result = '';\n for (var i = 0; i < a.length; i++) {\n if (b[i] < 51) {\n result = a[i] + ' acquired ' + b[i] + ' points and failed to complete the exam.';\n } else if (b[i] < 61) {\n result = a[i] + ' acquired ' + b[i] + ' points and earned 6.';\n } else if (b[i] < 71) {\n result = a[i] + ' acquired ' + b[i] + ' points and earned 7.';\n } else if (b[i] < 81) {\n result = a[i] + ' acquired ' + b[i] + ' points and earned 8.';\n } else if (b[i] < 91) { \n result = a[i] + ' acquired ' + b[i] + ' points and earned 9.';\n } else if (b[i] < 100) {\n result = a[i] + ' acquired ' + b[i] + ' points and earned 10.';\n }\n console.log(result);\n }\n}", "function convertPercentToGPA(universityIndex, marks, creditWeights){\n var GPAtotal=0;\n var creditTotal=0;\n var pointTotal=0; //for calculating the 12-point grade\n var pointTotal9=0; //used for calculating the 9-point grade\n\n var referencePercentageIndex=universities[universityIndex][1]; //the index of which percentage ranges to use from the GPA list\n var referenceLetterGradeIndex=universities[universityIndex][2]; //the index of which letter grades to use from the GPA list\n\n for (var i=0; i<maxCourses; i++){ //checks every input for a valid entry\n\n //finds the range at which the mark fits in\n for (var j=0; j<sizeOfGPAList; j++){ \n\n var mark=parseFloat(marks[i]);\n\n //checks to make sure an input is valid\n if (mark>=0 && mark<=100 &&!isNaN(mark) && mark>=GPAlist[j][referencePercentageIndex]){\n\n var creditWeight=Number(creditWeights[i]);\n GPAtotal+=GPAlist[j][0]*creditWeight; //adds the GPA to the total\n creditTotal+=creditWeight;\n pointTotal+=GPAlist[j][8]*creditWeight;\n pointTotal9+=GPAlist[j][10]*creditWeight;\n break;\n }\n }\n }\n\n var GPA=GPAtotal/creditTotal;\n var points=pointTotal/creditTotal;\n var points9=pointTotal9/creditTotal;\n\n if (isNaN(GPA) || isNaN(points)){//Checks to make sure that the fields were filled in\n GPA=0;\n points=0;\n points9=0;\n }\n\n //calculates the letter grade based on final GPA\n var i;\n for (i = 0; i <sizeOfGPAList; i++) {\n if (Math.round(GPA*10)/10>=GPAlist[i][0]){ //rounds GPA to 1 decimal place before converting to letter grade. So a 3.95 is same as a 4.0\n break;\n }\n }\n\n var grades=new Array(GPA,GPAlist[i][referenceLetterGradeIndex],points,points9);\n\n return grades;\n}", "function getScore(correct, missed, noAnswer){\n let x = (correct / (correct + missed + noAnswer)) * 100;\n return x;\n }", "function graduation(credits, grades){\n if(credits >= 120 || grades >= 2.0){\n return 'Congratulations on a job well done.';\n }else{\n return 'See you in summer school.'\n }\n}", "function convertLetterToGPA(universityIndex, marks, creditWeights){\n var GPAtotal=0;\n var creditTotal=0;\n var pointTotal=0; //to calculate the 12-point grade\n var pointTotal9=0; //used for calculating the 9-point grade\n\n var referenceLetterGradeIndex=universities[universityIndex][2]; //index of where to obtain the letter grade from the GPAlist\n\n for (var i=0; i<maxCourses; i++){ //checks every input for a valid entry\n\n \n for (var j = 0; j <sizeOfGPAList; j++) {\n\n ///tries to match the entry with a mark in the GPAlist\n if (marks[i].toUpperCase()==GPAlist[j][referenceLetterGradeIndex]){\n\n var creditWeight=Number(creditWeights[i]);\n GPAtotal+=GPAlist[j][0]*creditWeight; //adds the GPA to the total\n creditTotal+=creditWeight;\n pointTotal+=GPAlist[j][8]*creditWeight;\n pointTotal9+=GPAlist[j][10]*creditWeight;\n break;\n }\n }\n }\n\n var GPA=GPAtotal/creditTotal;\n var points=pointTotal/creditTotal;\n var points9=pointTotal9/creditTotal;\n\n if (isNaN(GPA) || isNaN(points)){//Checks to make sure that the fields were filled in (since a creditTotal would be 0)\n GPA=0;\n points=0;\n points9=0;\n }\n\n //matches a letter grade to the GPA\n var i;\n for (i = 0; i <sizeOfGPAList; i++) {\n if (Math.round(GPA*10)/10>=GPAlist[i][0]){ //rounds GPA to 1 decimal place before converting to letter grade. So a 3.95 is same as a 4.0\n break;\n }\n }\n\n var grades=new Array(GPA,GPAlist[i][referenceLetterGradeIndex],points,points9);\n\n return grades;\n}" ]
[ "0.7395894", "0.7371303", "0.73184234", "0.730597", "0.7254876", "0.72222245", "0.7221039", "0.7205958", "0.71949196", "0.7190736", "0.7185203", "0.717798", "0.7093158", "0.7086015", "0.70766014", "0.7070722", "0.7048823", "0.6979189", "0.697838", "0.6972952", "0.6959466", "0.6948997", "0.6939765", "0.6915279", "0.68983495", "0.6895162", "0.68800604", "0.68760884", "0.6871301", "0.6785596", "0.67346805", "0.6715479", "0.6680657", "0.66744196", "0.6672785", "0.66590655", "0.6649472", "0.6643032", "0.66189927", "0.6617988", "0.661649", "0.65915525", "0.656996", "0.6531153", "0.65184414", "0.6518132", "0.65155953", "0.6505888", "0.6505888", "0.6504037", "0.64991343", "0.6489274", "0.64788127", "0.6460501", "0.645798", "0.64462256", "0.6420947", "0.6420503", "0.6414862", "0.64113355", "0.64012367", "0.6396799", "0.6392374", "0.63859004", "0.63825554", "0.63818866", "0.6377687", "0.63670075", "0.63657933", "0.63640106", "0.6357185", "0.63520324", "0.63462883", "0.63343096", "0.63076365", "0.6306008", "0.6295377", "0.627976", "0.6260538", "0.6237736", "0.62376755", "0.6235469", "0.6224464", "0.6218489", "0.62128866", "0.6212249", "0.62078625", "0.62051713", "0.61979413", "0.6192878", "0.6191324", "0.61874217", "0.6186576", "0.6174562", "0.6160106", "0.61596644", "0.615526", "0.6153458", "0.6131535", "0.6127527" ]
0.7341423
2
component did mount fxn
componentDidMount(){ firebase.auth().onAuthStateChanged((user) => { if (user) { this.setState({ user }) document.getElementById("title").classList.add("loginTitle"); document.getElementById("title").classList.remove("logoutTitle"); document.getElementById("headImg").classList.add("loginImg"); document.getElementById("headImg").classList.remove("logoutImg"); // User is signed in. } else { this.setState({user: {} }) document.getElementById("title").classList.remove("loginTitle"); document.getElementById("title").classList.add("logoutTitle"); document.getElementById("headImg").classList.remove("loginImg"); document.getElementById("headImg").classList.add("logoutImg"); // No user is signed in. } }); firebase.database().ref('/growls').on('value', snapshot => { let growls = snapshot.val(); this.setState({growls}) }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "componenetWillMount() { }", "componenetDidMount() { }", "componentDidMount(){ //Cuando un compoennte se monta y se muestra en pantalla se llama este método\n console.log(\"did Mount\");\n }", "componentDidMount() {\n let state = this.state;\n this.mounted = true;\n this.setState( state );\n }", "componentDidMount() {\n this.componentLoaded = true;\n }", "_mountComponent() {\n\t\t// wait next frame\n\t\tthis.mutate(() => {\n\t\t\t// sometimes, the component has been unmounted between the\n\t\t\t// fastdom execution, so we stop here if it's the case\n\t\t\tif ( ! this._componentAttached) return;\n\t\t\t// init\n\t\t\tthis.componentMount();\n\t\t\t// render\n\t\t\tthis.render();\n\t\t\t// component did mount\n\t\t\tthis.componentDidMount();\n\t\t});\n\n\t}", "componentDidMount(){\n console.log(\"component DID MOUNT!\")\n }", "mount() {\n this.willMount();\n this.render();\n this.didMount();\n }", "didMount() {\n }", "componentDidMount(){\n this.updateEventCards().then( () => {\n this.componentMounted = true;\n });\n }", "onComponentMount() {\n\n }", "componentDidMount() {\n console.log('Component Did Mount');\n console.log('-------------------');\n\n }", "function viewWillMount() {\n // stub\n }", "componentDidMount() {\n console.log('componentDidMoun');\n }", "componentDidMount() {\n console.log(\"component did mount\");\n }", "createdCallback() {\n\t // component will mount only if part of the active document\n\t this.componentWillMount();\n\t}", "componentDidMount(){\n console.log('Component Did Mount')\n }", "componentDidMount() {\r\n console.log(\"El componente se renderizó\");\r\n }", "componentDidMount(){\n console.log(\"El componente se ha montado\")\n }", "componentDidMount(){\n console.info(this.constructor.name+ 'Component mount process finished');\n }", "componentDidMount() {\n\t\tthis.init();\n\t}", "componentDidMount(){\n console.log(\"ComponentdidMount\"); \n }", "componentDidMount() {\n console.log('Component DID MOUNT!')\n }", "willMount() {\n }", "componentDidMount() {\n console.log(\"Component mounted\");\n }", "componentDidMount() {\n\n\t}", "componentDidMount()\n {\n\n }", "componentDidMount() {\n console.log('component did mount')\n }", "componentDidMount(){\n \n }", "function onMount(fn) {\n get_current_component().$$.on_mount.push(fn);\n}", "componentDidMount() {\n // alert(\"se acaba de cargar el componente\")\n }", "componentDidMount() {\n console.log(\"component mounted\");\n }", "componentDidMount(){\n console.log('component did mount...');\n }", "attachedCallback() {\n\t\t// update attached status\n\t\tthis._componentAttached = true;\n\n\t\t// wait until dependencies are ok\n\t\tthis._whenMountDependenciesAreOk().then(() => {\n\t\t\t// switch on the mountWhen prop\n\t\t\tswitch(this.props.mountWhen) {\n\t\t\t\tcase 'inViewport':\n\t\t\t\t__whenInViewport(this).then(() => {\n\t\t\t\t\tthis._mountComponent();\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t\tcase 'mouseover':\n\t\t\t\t\tthis.addEventListener('mouseover', this._onMouseoverComponentMount.bind(this));\n\t\t\t\tbreak;\n\t\t\t\tcase 'isVisible':\n\t\t\t\t\t__whenVisible(this).then(() => {\n\t\t\t\t\t\tthis._mountComponent();\n\t\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t// mount component directly\n\t\t\t\t\tthis._mountComponent();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}", "componentDidMount() {\n\t\tthis.startup();\n\t}", "componentDidMount() {\n\t\tthis.props.onLoad();\n\t}", "componentDidMount() {\n\t}", "componentDidMount() {\n\t}", "componentDidMount() {\n\t}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {}", "componentDidMount() {\n this.props.onMount();\n }", "componentDidMount () {\n\n\t}", "componentDidMount () {\n\n\t}", "componentDidMount(){\n this.componentDidUpdate();\n }", "componentDidMount() {\n this.onLoad();\n }", "function proxiedComponentDidMount(){mountedInstances.push(this);if(typeof current.componentDidMount==='function'){return current.componentDidMount.apply(this,arguments);}}", "function proxiedComponentDidMount(){mountedInstances.push(this);if(typeof current.componentDidMount==='function'){return current.componentDidMount.apply(this,arguments);}}", "componentDidMount() { \n \n }", "componentDidMount(){\n console.log(\">>>>in componentDidMount<<<<<\")\n }", "componentDidMount(){\n }", "componentDidMount() {\n this.setState({\n mount: true\n })\n }", "componentDidMount() {\n\t\tthis._loadInitialState().done();\n\t}", "componentWillMount(){\n console.log(\"I am in Component Will Mount\");\n console.log(\"------------------------------------------\");\n }", "componentDidMount() {\n console.log('--------------------------- componentDidMount -----------------------------');\n }", "componentDidMount() {\n\t\tconsole.log('in componentDidMount');\n\t}", "componentDidMount() {\n this.componentDidUpdate();\n }", "componentDidMount() {\n console.log('I am mounted')\n }", "componentDidMount() {\n \n }", "componentDidMount() {\n if(typeof componentHandler !== 'undefined')\n componentHandler.upgradeDom();\n }", "componentDidMount(){\n\n }", "componentDidMount(){\n\n }", "componentDidMount(){\n console.log(\"ComponentDidMount Execution\");\n\n }", "componentDidMount(){\n console.log('mounted to the page')\n }", "componentDidMount() {\n \n }", "componentDidMount() {\n \n }", "componentDidMount() {\n if (super.componentDidMount) super.componentDidMount();\n\n this.checkForStateChange(undefined, this.state);\n }", "componentDidMount() {\n console.log('Mount');\n }", "componentWillMount(){\n console.log(\"ComponentWillMount Execution\");\n }", "componentDidMount(){\n\n }", "componentDidMount(){\n\n }", "componentDidMount() {\n // console.log(\"=========================> componentDidMount\");\n }", "componentDidMount(){\n }", "componentDidMount() {\n this._isMounted = true;\n if (!this.manuallyBindClickAway) {\n this._bindClickAway();\n }\n }", "componentDidMount(){\n console.log('componentDidMount');\n }", "componentDidMount(){\n\n\n\n\n}", "componentDidMount() {\n this.forceUpdate();\n }", "componentDidMount () {\n\n }", "componentDidMount(){\n this.setupEffectController();\n this.initView();\n this.display();\n }", "componentDidMount() {\n this._isMounted = true;\n this.getLocation();\n this.getGame();\n }", "componentDidMount() {\n\t\tconsole.log('jalan');\n\t}", "componentDidMount(){\n \t\teventsStore.addListener(eventsConstants.EVENT_CREATED, this.handleEventCreatedSuccessfully.bind(this));\n \t}", "componentDidMount() {\n console.log('Child Did Mount');\n }", "componentWillMount(){\n console.log('nao ta montado');\n }", "componentDidMount() {\n\n }", "componentDidMount() {\n\n }", "componentDidMount() {\n\n }" ]
[ "0.81764495", "0.7803353", "0.7756498", "0.7564405", "0.75093657", "0.7385242", "0.73402876", "0.7327044", "0.7324841", "0.7324073", "0.72921973", "0.7288123", "0.72577995", "0.7251849", "0.7250091", "0.7241546", "0.7227328", "0.72191167", "0.719574", "0.7187165", "0.7180157", "0.71700203", "0.7149655", "0.71455413", "0.71412426", "0.7135111", "0.71322685", "0.7131937", "0.71255344", "0.7121899", "0.7115509", "0.71129817", "0.7109908", "0.7104585", "0.7087235", "0.70861185", "0.7083015", "0.7083015", "0.7083015", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7070884", "0.7068249", "0.70535135", "0.70535135", "0.7049286", "0.7046129", "0.70376956", "0.70376956", "0.7033288", "0.7027004", "0.70269674", "0.70153403", "0.70058346", "0.6998433", "0.69886136", "0.69819057", "0.69778347", "0.6976541", "0.6972425", "0.69675803", "0.6962453", "0.6962453", "0.6959069", "0.69524467", "0.69493353", "0.69493353", "0.6944688", "0.6941732", "0.6937877", "0.6923049", "0.6923049", "0.6922817", "0.6922568", "0.6921947", "0.6912967", "0.6908275", "0.6907932", "0.69035894", "0.69026434", "0.68873596", "0.6876767", "0.68738854", "0.687191", "0.68622375", "0.6860544", "0.6860544", "0.6860544" ]
0.0
-1
we pass data as well as callback functions
function framework(data,scb,fcb){ //scb and fcb are success and failure call back for(let i=2;i*i<data;i++){ if(data%i==0){ return fcb(); } } return scb(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function _callback(err, data) { _call(callback, err, data); }", "function callback(){}", "function callback() {}", "function callback() {}", "function callback() {}", "function callback() {}", "function callback() {}", "onData(data) {\n this.emit(\"data\", data);\n this.onSuccess();\n }", "function runCallback( callback, data ){\n if(typeof callback === 'function') callback();\n }", "onData(data) {\n this.emit(\"data\", data);\n this.onSuccess();\n }", "onData(data) {\n this.emit(\"data\", data);\n this.onSuccess();\n }", "onData(data) {\n this.emit(\"data\", data);\n this.onSuccess();\n }", "onData(data) {\n this.emit(\"data\", data);\n this.onSuccess();\n }", "makeData (callback) {\n\t\tthis.init(callback);\n\t}", "makeData (callback) {\n\t\tthis.init(callback);\n\t}", "makeData (callback) {\n\t\tthis.init(callback);\n\t}", "makeData (callback) {\n\t\tthis.init(callback);\n\t}", "runCallbacks(event, data, requestInfo, additionalData) {\n let callbacksToRun = this.callbacks[event];\n\n if (callbacksToRun) {\n for (let callback of callbacksToRun) {\n callback(data, requestInfo, additionalData);\n }\n }\n }", "function CallbackData(data,page, handler,method){\n\tvar methodTxt = 'POST';\n\tif(CallbackData.arguments[3]) methodTxt = CallbackData.arguments[3];\n\tvar request = createRequest();\n\tif(request)\n\t{\n\t\t// prepare request\n\t\trequest.open(methodTxt, page, true);\n\t\trequest.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\n\t\t// when the request is answered, relayResponse() will be called\n\t\trequest.onreadystatechange = function(){ relayResponse(request, handler); }\n\n\t\t// fire off the request\n\t\trequest.send(data);\n\t}\n\telse\n\t{\n\t\t// request object wasn't instantiated\n\t\thandler(false, 'Unable to create request object.');\n\t}\n}", "function callbacksGetData(data, callback) {\n setTimeout(() => {\n callback(data);\n }, 2);\n}", "function printDataCallback() {\nfunction printData(str, data) {\n console.log(data);\n}\ncallbackFunction(printData);\n}", "function callbackFuncWithData(data){\n\t\t\t\t\t\t// Get all longitutes, lattitudes and names of the matching addresses\n\t\t\t\t\t\t\tfor (var i=0; i<data.length; i++) {\n\t\t\t\t\t\t\t\tvar counter = data[i];\n\t\t\t\t\t\t\t\tvar taxiLat = counter.lat;\n\t\t\t\t\t\t\t\tvar taxiLon = counter.lon;\n\t\t\t\t\t\t\t\taddressName = counter.display_name;\n\t\t\t\t\t\t\t\talert(\"Showing matched taxi address at \" + addressName);\n\t\t\t\t\t\t\t\t// Use the longitudes and lattitudes of the addresses to update the map \n\t\t\t\t\t\t\t\tvar taxiLoc = new plugin.google.maps.LatLng(taxiLat, taxiLon);\n\t\t\t\t\t\t\t\t// add a marker on the map for the address of a matched taxi address on the map \n\t\t\t\t\t\t\t\tmap.addMarker({\n\t\t\t\t\t\t\t\t'position': {lat: taxiLat, lng: taxiLon},\n\t\t\t\t\t\t\t\t'title': \"Taxi\"\n\t\t\t\t\t\t\t\t}, function (marker) {\n\t\t\t\t\t\t\t\tmarker.showInfoWindow();\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t// set the map to show matched addresses\n\t\t\t\t\t\t\t\tmap.setCenter(taxiLoc);\n\t\t\t\t\t\t\t\tmap.setZoom(15);\n\t\t\t\t\t\t\t\tmap.refreshLayout();\n\t\t\t\t\t\t\t\tmap.setVisible(true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}", "makeData (callback) {\n\t\tBoundAsync.series(this, [\n\t\t\tthis.adjustMarkers,\t\t\t// adjust those markers for a different commit\n\t\t\tthis.setData\t\t\t\t// set the data to be used in the request that will result in a message sent\n\t\t], callback);\n\t}", "passData(callback) {\n this.getLocalStorageData();\n callback(this.formData);\n }", "detail(...args) {\n callback(...args);\n }", "function dataHandler(data) { console.log(data); }", "function ondata(data) {\n\tswitch (data.type) {\n\t\tcase 'publish':\n\t\t\tsaveMsg.call(this, data.channel, data.msg);\n\t\t\tonNewData.call(this, data.channel, data.msg);\n\t\t\tbreak;\n\t\tcase 'subscribe':\n\t\t\tchsSub.call(this, data.id, data.channels);\n\t\t\tonNewSubscr.call(this, data.id, data.channels);\n\t\t\tbreak;\n\t\tcase 'notify':\n\t\t\tonNewNotifications.call(this, data.notifications);\n\t\t\tbreak;\n\t}\n}", "function printDataCallback() {\n function callback(err, data) {\n console.log(data);\n }\n\n callbackFunction(callback);\n}", "data(data) {\n this.__processEvent('data', data);\n }", "onData(data) {\n let done = false;\n if (data.progress) {\n this.onProgress(this.progressBarElement, this.progressBarMessageElement, data.progress);\n }\n if (data.complete === true) {\n done = true;\n if (data.success === true) {\n this.onSuccess(this.progressBarElement, this.progressBarMessageElement, this.getMessageDetails(data.result));\n } else if (data.success === false) {\n this.onTaskError(this.progressBarElement, this.progressBarMessageElement, this.getMessageDetails(data.result));\n } else {\n done = undefined;\n this.onDataError(this.progressBarElement, this.progressBarMessageElement, \"Data Error\");\n }\n if (data.hasOwnProperty('result')) {\n this.onResult(this.resultElement, data.result);\n }\n } else if (data.complete === undefined) {\n done = undefined;\n this.onDataError(this.progressBarElement, this.progressBarMessageElement, \"Data Error\");\n }\n return done;\n }", "function dataLoaded(err,data,m){\n}", "loadData( event, callback ) {\n\n\t\treturn callback( null, {} );\n\n\t}", "makeData (callback) {\n\t\tObject.assign(this.postOptions, {\n\t\t\tcreatorIndex: 1,\n\t\t\twantCodeError: true\n\t\t});\n\t\tBoundAsync.series(this, [\n\t\t\tCodeStreamAPITest.prototype.before.bind(this),\n\t\t\tthis.replyToCodeError\n\t\t], callback);\n\t}", "function handleCallback(data) {\n console.log(data);\n }", "receive_oob_data(callback, obj) {\n // TODO: Track usage stats and warn about misuse\n callback(obj)\n }", "function generalCallback(data) {\n lastValue = data;\n }", "function gotData(data){\n console.log(data);\n}", "function callback(response, status, jqXHRobject){\n //tasks using the data go here\n var mydata = response;\n console.log(response);\n nextFunction(mydata);\n}", "_callback(err, data, res){\n if (err) this._errorHandling(res, err);\n res.send(data || 'Successfully completed');\n }", "function callback(){\n console.log(\"Charts Data Executed\");\n}", "onDataChange() {}", "_sendData() {\n\n }", "function onCallBack(message){\t\t\n\t\tif(message.body){\n\t\t\tconsole.log('receiving data',message.body);\t\n\t\t\tvar data = message.body\n\t\t\twhenMassegeResieved(JSON.parse(data));\t\n\t\t}else{\n\t\t\tconsole.log('message contain no data');\n\t\t}\t\t\n\t}", "function callbackParams(callback) {\n callback();\n}", "submitData(e, callbackData){\r\n\t\t\tlet data = {};\r\n\t\t\tlet resource = api_uri+'JSON/Privmsgs';\r\n\t\t\tlet dateNow = moment().format('YYYY-MM-DD hh:mm:ss');\r\n\t\t\tlet author = \"\";\r\n\t\t\tlet title = \"\";\r\n\t\t\tlet desc = \"\";\r\n\t\t\tlet penerima = \"\";\r\n\t\t\tlet loginInfo = false;\r\n\r\n\r\n\t\t\tif (e.data.status == \"newmessage\") {\r\n\t\t\t\tthis.getIkaJikMember(\r\n\t\t\t\t\te.penerima,\r\n\t\t\t\t\t(callback)=>{\r\n\t\t\t\t\t\tauthor = e.jikmember;\r\n\t\t\t\t\t\ttitle = e.title;\r\n\t\t\t\t\t\tdesc = e.desc;\r\n\t\t\t\t\t\tpenerima = callback.jikmember;\r\n\t\t\t\t\t\t// perivate message\r\n\t\t\t\t\t\tdata = {\r\n\t\t\t\t\t\t\t\"privmsg_author\": author,\r\n\t\t\t\t\t\t\t\"privmsg_date\": dateNow,\r\n\t\t\t\t\t\t\t\"privmsg_subject\": title,\r\n\t\t\t\t\t\t\t\"privmsg_body\": desc,\r\n\t\t\t\t\t\t\t\"privmsg_notify\": 1,\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tthis.sendData(\r\n\t\t\t\t\t\t\tresource,\r\n\t\t\t\t\t\t\tdata,\r\n\t\t\t\t\t\t\t(callback)=>{\r\n\t\t\t\t\t\t\t\tif (callback.status == 200) {\r\n\t\t\t\t\t\t\t\t\t// perivate message\r\n\t\t\t\t\t\t\t\t\tlet resourcesTo = api_uri+'JSON/PrivmsgsTo';\r\n\t\t\t\t\t\t\t\t\tlet dataTo = {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"pmto_message\": callback.data.privmsg_id,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"pmto_recipient\": penerima,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"pmto_allownotify\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tthis.sendData( resourcesTo, dataTo, (callbackTo)=>{\r\n\t\t\t\t\t\t\t\t\t\tcallbackData(callbackTo);\r\n\t\t\t\t\t\t\t\t\t} );\r\n\t\t\t\t\t\t\t\t}\r\n\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}else{\r\n\t\t\t\tauthor = e.data.data.author;\r\n\t\t\t\ttitle = e.title;\r\n\t\t\t\tdesc = e.desc;\r\n\t\t\t\tpenerima = e.data.data.user;\r\n\t\t\t\t// perivate message\r\n\t\t\t\tdata = {\r\n\t\t\t\t\t\"privmsg_author\": author,\r\n\t\t\t\t\t\"privmsg_date\": dateNow,\r\n\t\t\t\t\t\"privmsg_subject\": title,\r\n\t\t\t\t\t\"privmsg_body\": desc,\r\n\t\t\t\t\t\"privmsg_notify\": 1,\r\n\t\t\t\t}\r\n\t\t\t\tthis.sendData(\r\n\t\t\t\t\tresource,\r\n\t\t\t\t\tdata,\r\n\t\t\t\t\t(callback)=>{\r\n\t\t\t\t\t\tif (callback.status == 200) {\r\n\t\t\t\t\t\t\t// perivate message\r\n\t\t\t\t\t\t\tlet resourcesTo = api_uri+'JSON/PrivmsgsTo';\r\n\t\t\t\t\t\t\tlet dataTo = {\r\n\t\t\t\t\t\t\t\t\t\t\t\"pmto_message\": callback.data.privmsg_id,\r\n\t\t\t\t\t\t\t\t\t\t\t\"pmto_recipient\": penerima,\r\n\t\t\t\t\t\t\t\t\t\t\t\"pmto_allownotify\": \"1\"\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tthis.sendData( resourcesTo, dataTo, (callbackTo)=>{\r\n\t\t\t\t\t\t\t\tcallbackData(callbackTo);\r\n\r\n\t\t\t\t\t\t\t} );\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t}\r\n\r\n\t}", "function callback() {\n\n}", "function getData()\n\t\t{\n\t\t\tvar newData = { hello : \"world! it's \" + new Date().toLocaleTimeString() }; // Just putting some sample data in for fun.\n\n\t\t\t/* Get my data from somewhere and populate newData with it... Probably a JSON API or something. */\n\t\t\t/* ... */\n\t\t\tupdateCallback(newData);\n\t\t}", "function callTest(data){\n var call_array=data.tests[data.actual_name]; //array\n if (call_array)\n for (var n=0;n<call_array.length;n++){\n var params=call_array[n];\n console.log(\"- con params: \",JSON.stringify(params.slice(0,2)),\"callback: \",typeof params[2]);\n data.obj_to_test[data.actual_name](params[0],params[1],params[2]); //call fn con los params - params[3] es una callbackfn\n }\n}", "function doRequest(url, data, callback) {\n callback({ url, data });\n }", "function commonGateway(type,url,data,callback) {\n $.ajax({\n type: type,\n url: url,\n data: data,\n cache: false,\n datatype: \"json\",\n success: function(data){\n callback(data);\n }\n });\n}", "function callback(data) {\n\t\t\tconsole.log('DB Req callback');\n\t\t\tconsole.log(data);\n\t\t}", "function sendData(data, callback) {\n $.ajax({\n type: data.method,\n data: data.data,\n url: data.url,\n dataType: data.dataType\n }).done((response)=> {\n //DEBUG\n console.log(\"Data sent\");\n if(callback !== undefined) {\n callback(response);\n }\n })\n}", "makeData (callback) {\n\t\tif (this.streamType === 'direct') {\n\t\t\tthis.skipFollow = true;\n\t\t\tthis.expectedVersion = 2;\n\t\t}\n\t\tthis.init(callback);\n\t}", "publishPlatformEventHelper(data, eventType, playerType, playerBoardId, callback) {\n console.log(' in publishPlatformEventHelper ' + playerBoardId);\n let mainThis = this;\n console.log('before calling publish eevent '+ this.playerBoardId);\n //data must be in string\n let jsonData = !data ? '': data;\n publishPlatformEventMethod({'data': JSON.stringify(jsonData), 'eventType': eventType,\n 'playerType': playerType, 'ludoBoardId': playerBoardId})\n .then(result => {\n console.log('success publishPlatformEventHelper ');\n if(callback) {\n callback(result);\n }\n }).catch(error => {\n console.log('error is '+ error);\n });\n \n }", "function handleCb(key, payload) {\n if (key && callbacks[key])\n callbacks[key](payload);\n }", "function handleData(data){\n switch(state){\n case 0:\n functions.authenticate();\n break;\n case 1:\n functions.processRequest(data);\n break;\n case 2:\n functions.forward(data);\n break;\n case -1:\n default:\n console.log(data.toString());\n break;\n };\n }", "function responseApiCall(data, req, res) {\n console.log('responseApiCall'); \n\n var cb = req.query.callback;\n var jsonP = false;\n\n console.log('responseApiCall callback : ' + cb);\n\n if (cb != null) {\n jsonP = true;\n res.writeHead(200, {'Content-Type': 'text/javascript', 'connection' : 'close'});\n } else {res.writeHead(200, {'Content-Type': \"application/x-json\"});}\n\n if (jsonP) {res.end(cb + \"(\" + JSON.stringify(data) + \");\" );}\n else { res.end(JSON.stringify(data));}\n}", "processCallbackData() {\n\t\tconst {\n\t\t\tdata,\n\t\t\trequestDataToState,\n\t\t} = this.props;\n\n\t\tif ( data && ! data.error && 'function' === typeof requestDataToState ) {\n\t\t\tthis.setState( requestDataToState );\n\t\t}\n\t}", "function queryDataPost(url,dataSend,callback){\n \n $.ajax({\n type: 'POST',\n url: url,\n data: dataSend,\n async: true,\n dataType: 'text',\n success: callback\n });\n}", "function getData(callback) {\n console.log('AWS done triggered');\n doneCalled = true;\n trigger_upload();\n callback('NA');\n }", "function gotRawData(thedata) {\n console.log(\"gotRawData\" + thedata);\n}", "function loadTwoData(data,callback) {\n setTimeout(() => {\n callback(data)\n }, 2000);\n}", "function delvePlayerCallback2(playerId, eventName, data) {\n\tconsole.log('**********************************************');\n\tconsole.log('playerId: ', playerId);\n\tconsole.log('eventName: ', eventName);\n\t//console.log('data: ', data);\n\tconsole.log('**********************************************');\n\n\tif (eventName == 'onPlayerLoad' && (DelvePlayer.getPlayers() == null || DelvePlayer.getPlayers().length == 0)) {\n\t\tconsole.log('eventName: ', eventName);\n\t\tDelvePlayer.registerPlayer(playerId);\n\t}\n\t\n\tswitch (eventName) {\n\t\tcase 'onPlayerLoad':\n\t\t\tdoOnPlayerLoad2();\n\t\t\tbreak;\n\t\tcase 'onError':\n\t\t\tdoOnError(data);\n\t\t\tbreak;\n\t\t\n\t\tcase 'onPlayStateChanged':\n\t\t\tdoOnPlayStateChanged2(data);\n\t\t\tbreak;\n\t\t\n\t\t/*case 'onPlayheadUpdate':\n\t\t\tdoonPlayheadUpdate(data);\n\t\t\tbreak;\n\t\t\n\t\tcase 'onMediaComplete':\n\t\t\tdoOnMediaComplete(data);\n\t\t\tbreak;\n\t\t\n\t\tcase 'onMediaLoad':\n\t\t\tdoOnMediaLoad(data);\n\t\t\tbreak;\n\t\t\n\t\tcase 'onPlayheadUpdate':\n\t\t\tdoOnPlayheadUpdate(data);\n\t\t\tbreak;\n\t\t*/\n\t}\n}", "function setDataCallbacks(){\n\n vadrCore.dataCallbacks.setPositionCallback(getPosition);\n vadrCore.dataCallbacks.setGazeCallback(getGazePoint);\n vadrCore.dataCallbacks.setAngleCallback(getAngle);\n\n}", "function cb(error,response,body){\n\n parseData(body);\n}", "function dataCallback(err, dbData) {\n if (err) {\n console.log(\"data Selection error\", err);\n } else {\n console.log(\"data selection success\");\n\n if (dbData == undefined) {\n InsertNewUser(profile);\n }\n }\n }", "function on_data(data) {\n data_cache[key] = data;\n placeholder.update();\n }", "function process(data, callback) {\n\t\t$.ajax ({\n\t url: \"process.php\",\n\t data: data,\n\t dataType: \"json\",\n\t type: \"post\",\n\t async: false,\n\t success: function (result) {\n\t\t\t callback(result);\n\t\t\t}\n\t })\n\t}", "onData(data) {\n const callback = packet => {\n // if its the first message we consider the transport open\n if (\"opening\" === this.readyState && packet.type === \"open\") {\n this.onOpen();\n }\n // if its a close packet, we close the ongoing requests\n if (\"close\" === packet.type) {\n this.onClose({ description: \"transport closed by the server\" });\n return false;\n }\n // otherwise bypass onData and handle the message\n this.onPacket(packet);\n };\n // decode payload\n decodePayload(data, this.socket.binaryType).forEach(callback);\n // if an event did not trigger closing\n if (\"closed\" !== this.readyState) {\n // if we got data we're not polling\n this.polling = false;\n this.emitReserved(\"pollComplete\");\n if (\"open\" === this.readyState) {\n this.poll();\n }\n }\n }", "function request(data, cb){\n\n if(data) {\n cb(data);\n }else {\n console.log('no data');\n }\n}", "function callcontroller(callback, data){\n if(debug>=2)console.dir(options)\n if (data !== undefined) console.dir(data)\n var req = http.request(options, function(response) {\n if(debug>=2)console.log(\"http\");\n var str = '';\n \n //another chunk of data has been recieved, so append it to `str`\n response.on('data', function (chunk) {\n str += chunk;\n });\n \n //the whole response has been recieved, so we just print it out here\n response.on('end', function () {\n if(debug>=2)console.dir(response.headers['set-cookie'])\n if ( response.headers['set-cookie'] !== undefined ) {\n options.headers['cookie']=(response.headers['set-cookie'])[0].split(';')[0]\n if ( (response.headers['set-cookie'])[1] !== undefined )\n options.headers['X-CSRF-TOKEN']=(response.headers['set-cookie'])[1].split(';')[0].split('=')[1]\n \n }\n callback(str)\n });\n \n if(debug>=2)console.log(\"end\");\n // response is here\n });\n if (data !== undefined) {\n req.write(data)\n if(debug>=2)console.log(data)\n }\n req.end();\n}", "send(data){\n Flow.from(this.listeners).where(listener => listener.notify && Util.isFunction(listener.notify)).foreach(listener => listener.notify(data));\n Flow.from(this.listeners).where(listener => !(listener.notify && Util.isFunction(listener.notify)) && Util.isFunction(listener)).foreach(listener => listener(data));\n }", "function fireCallback(callbackName, ...data) {\n /*\n Callbacks:\n beforeCreate (options),\n beforeOpen (xhr, options),\n beforeSend (xhr, options),\n error (xhr, status, message),\n complete (xhr, stautus),\n success (response, status, xhr),\n statusCode ()\n */\n let globalCallbackValue;\n let optionCallbackValue;\n if (globals[callbackName]) {\n globalCallbackValue = globals[callbackName](...data);\n }\n if (options[callbackName]) {\n optionCallbackValue = options[callbackName](...data);\n }\n if (typeof globalCallbackValue !== 'boolean') globalCallbackValue = true;\n if (typeof optionCallbackValue !== 'boolean') optionCallbackValue = true;\n return (globalCallbackValue && optionCallbackValue);\n }", "function dataHandler(id, data, status, jqXHR) {\n bus.emit(ev.connData, data, id, jqXHR);\n /* jshint validthis: true */\n this && this(null, data);\n }", "function callback(response){\n }", "on_assign_data() {\n }", "function processDataCallback(data) {\n\t\t\t\n\t\t\tvar event = {};\n\t\t\t\n\t\t\tevent.deviceId = data.deviceId;\n\t\t\tevent.riderId = data.riderInformation.riderId != undefined ? data.riderInformation.riderId : 0;\n\t\t\tevent.distance = data.geographicLocation.distance != undefined ? Math.round(data.geographicLocation.distance) : 0;\n\t\t\tevent.lat = data.geographicLocation.snappedCoordinates.latitude != undefined ? data.geographicLocation.snappedCoordinates.latitude : 0;\n\t\t\tevent.long = data.geographicLocation.snappedCoordinates.longitude != undefined ? data.geographicLocation.snappedCoordinates.longitude : 0;\n\t\t\tevent.acceleration = data.riderStatistics.acceleration != undefined ? parseFloat(data.riderStatistics.acceleration.toFixed(2)) : 0;\n\t\t\tevent.time = data.time != undefined ? data.time : 0;\n\t\t\tevent.altitude = data.gps.altitude != undefined ? data.gps.altitude: 0;\n\t\t\tevent.gradient = data.geographicLocation.gradient != undefined ? data.geographicLocation.gradient: 0;\n\t\t\t\n\t\t\t//Add speed object\n\t\t\tvar speed = data.riderInformation.speedInd ? (data.gps.speedGps != undefined ? data.gps.speedGps : 0) : 0 ;\n\t\t\tevent.speed = {\n\t\t\t\t\t\"current\" : speed,\n\t\t\t\t\t\"avg10km\" : 0.0,\n\t\t\t\t\t\"avg30km\" : 0.0\n\t\t\t}\n\t\t\t\n\t\t\t//Add power object\n\t\t\tvar power = data.riderInformation.powerInd ? (data.sensorInformation.power != undefined ? data.sensorInformation.power : 0) : 0;\n\t\t\tevent.power = {\n\t\t\t\t\t\"current\" : getFeedValue(\"power\", power),\n\t\t\t\t\t\"avg10km\" : 0,\n\t\t\t\t\t\"avg30km\" : 0\n\t\t\t}\n\t\t\t\n\t\t\tevent.heartRate = data.riderInformation.HRInd ? (data.sensorInformation.heartRate != undefined ? getFeedValue(\"HR\", data.sensorInformation.heartRate) : 0) : 0;\n\t\t\tevent.cadence = data.riderInformation.cadenceInd ? (data.sensorInformation.cadence != undefined ? data.sensorInformation.cadence : 0) : 0;\n\t\t\tevent.bibNumber = data.riderInformation.bibNumber != undefined ? data.riderInformation.bibNumber: 0;\n\t\t\tevent.teamId = data.riderInformation.teamId != undefined ? data.riderInformation.teamId: 0;\n\t\t\t\n\t\t\tvar eventStageId = data.riderInformation.eventId + \"-\" + data.riderInformation.stageId;\t\t\n\t\t\tdataCallback(event, eventStageId + \"-rider\");\n\t\t}", "function ajax(type,data,url,callback){\n debug && console.log('A '+type+' AJAX request to '+url+' with data:');\n debug && console.log(data);\n $.ajax({\n type: type,\n url: url,\n data: data,\n success: function(response){\n //console.log(response); \n callback(response);\n }\n }); ///Ajax post \n}", "function getData(callback) {\r\n $.ajax({\r\n type: \"get\",\r\n url: \"/core/dataparser.py\",\r\n dataType: \"json\",\r\n success: callback,\r\n error: function(request, status, error) {\r\n alert(status);\r\n }\r\n });\r\n}", "_routerEvent(data) {\n\t this.params.callback(data, this);\n\t }", "function returnHandler(data){\n allHandle(data);\n }", "function displayCallback(data) {\n document.getElementById(\"callback\").innerHTML = data;\n}", "function customProcessCallback(params) {\n\n var response = $jq.parseJSON(params);\n processCallback(params);\n console.log(response);\n if (response.success) {\n callbackSuccess();\n } else {\n callbackFailure();\n }\n if (processCallback) {\n processCallback(params);\n }\n}", "function getData(pCallback) {\n apex.server.plugin(\n ajaxID, {\n pageItems: items2Submit\n }, {\n success: function (pData) {\n apex.debug.info({\n \"fct\": util.featureDetails.name + \" - \" + \"getData\",\n \"msg\": \"AJAX data received\",\n \"pData\": pData,\n \"featureDetails\": util.featureDetails\n });\n errCount = 0;\n pCallback(pData);\n },\n error: function (d) {\n if (errCount === 0) {\n var dataJSON = {\n row: [{\n \"NOTE_ICON\": \"fa-exclamation-triangle\",\n \"NOTE_ICON_COLOR\": \"#FF0000\",\n \"NOTE_HEADER\": (d.responseJSON && d.responseJSON.error) ? d.responseJSON.error : \"Error occured\",\n \"NOTE_TEXT\": null,\n \"NOTE_COLOR\": \"#FF0000\"\n }\n ]\n };\n\n pCallback(dataJSON);\n apex.debug.error({\n \"fct\": util.featureDetails.name + \" - \" + \"getData\",\n \"msg\": \"AJAX data error\",\n \"response\": d,\n \"featureDetails\": util.featureDetails\n });\n }\n errCount++;\n },\n dataType: \"json\"\n });\n }", "function response(err, data){\n if(typeof callback === \"function\"){ return callback(err, data); }\n else { return err != null ? err : \"OK\"; }\n }", "makePostData (callback) {\n\t\tsuper.makePostData(() => {\n\t\t\tthis.data.to[0].address = `${this.postData[0].post.id}.${this.data.to[0].address}`;\n\t\t\tcallback();\n\t\t});\n\t}", "processData(socket, data) {\n\n rideProcess.listen(socket, data);\n\n\n }", "function _applyDataCallback(data) { // callback for getting groups data from backend\n vm.list = Array.isArray(data) ? data : []; // to prevent the error if picked speciality or faculty has no groups\n vm.totalItems = data.length;\n }", "function requestCallback(url, data) {\n let xhr = new XMLHttpRequest();\n xhr.open('POST', url);\n xhr.onload = function () {\n if (xhr.status === 200) {\n let responseData = xhr.responseText;\n console.log(responseData);\n let divPostData = document.getElementById('postData');\n divPostData.innerHTML = `<p style=\"margin:0\">${responseData}</p>`;\n }\n }\n xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n xhr.send('name=' + encodeURIComponent(data));\n }", "function submitCallback(data,page, handler){\n\tvar request = createRequest();\n\tif(request){\n\t\t\t// prepare request\n\t\t\trequest.open('POST', page, true);\n\t\t\trequest.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\n\t\t\t// when the request is answered, relayResponse() will be called\n\t\t\trequest.onreadystatechange = function(){ relayResponse(request, handler); }\n\n\t\t\t// fire off the request\n\t\t\trequest.send(data);\n\t}\n\telse{\n\t\t// request object wasn't instantiated\n\t\thandler(false, 'Unable to create request object.');\n\t}\n}", "function gotRawData(thedata) {\n println(\"gotRawData\" + thedata);\n}", "function cbWithData (data) {\n if (data.error) return cb(new Error(data.error))\n cb(null, data)\n }", "function callbackDriver() {\n cb();\n }", "function process(data){\n //do something with data\n}", "function get_data() {}", "function myData() {\n retrun;\n}", "function getDataCallback(response, status, headers, config) {\n return response.data;\n }", "requestRemoteData(handler) {\n }", "function getData()\n\t\t{\n\t\t\tvar newData = { hello : \"world! it's \" + new Date().toLocaleTimeString() }; // Just putting some sample data in for fun.\n\n\t\t\t/* Get my data from somewhere and populate newData with it... Probably a JSON API or something. */\n\t\t\t/* ... */\n\n\t\t\t// I'm calling updateCallback to tell it I've got new data for it to munch on.\n\t\t\tupdateCallback(newData);\n\t\t}", "addDataListener(callback) {\n this.addListener( this.dataListeners, callback);\n }", "makePostData (callback) {\n\t\tsuper.makePostData(() => {\n\t\t\tthis.data[this.attribute] = 'x'; // set bogus value for the attribute, it shouldn't matter\n\t\t\tcallback();\n\t\t});\n\t}" ]
[ "0.735528", "0.7317476", "0.69251835", "0.69251835", "0.69251835", "0.69251835", "0.69251835", "0.690911", "0.6904304", "0.6872763", "0.6863283", "0.6863283", "0.6863283", "0.6713949", "0.6713949", "0.6713949", "0.6713949", "0.6700758", "0.6658431", "0.6640857", "0.66309565", "0.6609963", "0.6609335", "0.6603661", "0.64716", "0.6415452", "0.6344033", "0.6341181", "0.6340465", "0.63357234", "0.6326154", "0.63031125", "0.6288821", "0.6266474", "0.62640184", "0.6261404", "0.6240321", "0.62158936", "0.61878973", "0.6175679", "0.6170663", "0.61628324", "0.6161346", "0.6149741", "0.61496234", "0.61382335", "0.6137495", "0.6128081", "0.6111853", "0.60985905", "0.60959405", "0.60320747", "0.60314494", "0.60310876", "0.6027142", "0.60198295", "0.6016561", "0.59957147", "0.5995066", "0.5991571", "0.5982912", "0.59703505", "0.5964011", "0.59603536", "0.59510374", "0.59501684", "0.5944648", "0.59435624", "0.5942689", "0.5940204", "0.5933166", "0.5923873", "0.5913733", "0.58939314", "0.5883251", "0.5883104", "0.5879379", "0.5875033", "0.5855179", "0.5854354", "0.5851923", "0.5838137", "0.5834255", "0.5819529", "0.58193845", "0.5803676", "0.5799694", "0.57918584", "0.5787446", "0.57855445", "0.577945", "0.57766086", "0.5776325", "0.57662237", "0.576596", "0.57646793", "0.57626766", "0.57586366", "0.5756736", "0.5748107", "0.57480395" ]
0.0
-1
require is just like import developers's code inversion of control
function scb(){ console.log("Number is prime"); exec('start chrome').unref(); //this will open chrome }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function require() { return {}; }", "function require(str) {}", "function require(id, parent) {\n parent = parent || __filename;\n\n function dir_prefix( uri ) {\n var split = uri.match(/.*\\//);\n return split ? split[0] : '';\n }\n\n function ends_with(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n }\n\n function copy_attrs(src, dst) {\n Object.keys(src).forEach(function (attr) {\n dst[attr] = src[attr];\n });\n }\n\n function prepare_globals(id, uri) {\n var globals = {};\n if (settings.modules.core[id] !== undefined) {\n // prefetched core modules need access to require and console before\n // they get propagated to global environment\n copy_attrs(exports, globals);\n // core modules get access to platform bindings\n globals[global_keys.bindings] = __bindings;\n }\n // 'bind' the module id\n globals.require = function (id) {\n return require(id, uri);\n };\n globals.require.cache = module_cache;\n globals.require.resolve = function (id) {\n return resolve(id, uri);\n };\n\n globals.module = new_module;\n globals.exports = new_module.exports;\n globals[global_keys.filename] = uri;\n globals[global_keys.dirname] = dir_prefix( uri );\n return globals;\n }\n\n // 1) resolve given id to file uri\n var uri = resolve(id, parent);\n\n // 2) use resolved uri as a key to lookup the module in the cache\n var new_module = module_cache[uri];\n\n if (new_module === undefined) {\n // 3) load module source code\n var src = repo.load(uri, false);\n\n // 4) register half-finalized module to prevent infinite loop in case of cyclic dependencies\n new_module = {id: uri, filename: uri, loaded: false, exports: {}};\n module_cache[uri] = new_module;\n\n if (ends_with(uri, '.json')) {\n // 5a) parse JSON file and inject it to the module's exports\n new_module.exports = JSON.parse(src);\n } else {\n // 5b) evaluate the source code in prepared 'global' environment\n handle_jslint(uri, src);\n func.eval(src, uri, prepare_globals(id, uri));\n }\n new_module.loaded = true;\n }\n // X) return module's exports back to caller\n return new_module.exports;\n}", "function makeRequire(m, self) {\n function _require(_path) {\n return m.require(_path);\n }\n\n _require.resolve = function(request) {\n return _module._resolveFilename(request, self);\n };\n _require.cache = _module._cache;\n _require.extensions = _module._extensions;\n\n return _require;\n}", "_freshRequire (file, vars) {\n clearRequireAndChildren(file)\n return this.require(file, vars)\n }", "function innerRequire(_path) {\n\treturn require(path.join(process.cwd(), _path));\n}", "import() {\n }", "function foo(name) {\n one.name = 'Boogs'\n let two = require('./lib/one')\n console.log(two.name)\n}", "function requires(src){\r\n\treturn (new AjaxJSLoader(src)).retrieve();\r\n}", "function globalRequire(name, value) {\n try {\n value = value || name;\n var temp = require(value);\n //console.log(name + \":\" + !!temp)\n if (temp) {\n if (!global[name]) {\n global[name] = temp;\n console.debug('loaded module: '+value);\n }\n }\n } catch (e) {\n //console.log(e);\n }\n}", "function require(scriptId) {\n //# ignored since we evaluate require differently\n}", "static require (filename) {\n\t\treturn require(`./handlers/${filename}`);\n\t}", "function require(name) {\n var mod = ModuleManager.get(name);\n if (!mod) {\n //Only firefox and synchronous, sorry\n var file = ModuleManager.file(name);\n var code = null,\n request = new XMLHttpRequest();\n request.open('GET', file, false); \n try {\n request.send(null);\n } catch (e) {\n throw new LoadError(file);\n }\n if(request.status != 200)\n throw new LoadError(file);\n //Tego el codigo, creo el modulo\n var code = '(function(){ ' + request.responseText + '});';\n mod = ModuleManager.create(name, file, code);\n }\n event.publish('module_loaded', [this, mod]);\n switch (arguments.length) {\n case 1:\n // Returns module\n var names = name.split('.');\n var last = names[names.length - 1];\n this[last] = mod;\n return mod;\n case 2:\n // If all contents were requested returns nothing\n if (arguments[1] == '*') {\n __extend__(false, this, mod);\n return;\n // second arguments is the symbol in the package\n } else {\n var n = arguments[1];\n this[n] = mod[n];\n return mod[n];\n }\n default:\n // every argyment but the first one are a symbol\n // returns nothing\n for (var i = 1, length = arguments.length; i < length; i++) {\n this[arguments[i]] = mod[arguments[i]];\n }\n return;\n }\n }", "static requireTestHelper (filename) {\n\t\treturn require(`../tests/includes/${filename}`);\n\t}", "function require(input){\n\tswitch(input){\n\t\tcase '../../server.js': return Modules;\n\t\tdefault: alert('Unknown requirement: '+input);\n\t}\n}", "function smartRequire(reqlist) {\n // try to add each entry in to required state and save to global.mod\n reqlist = reqlist || [];\n var name, value;\n for (var i in reqlist) {\n try {\n if (typeof reqlist[i] == \"String\") {\n name = value = reqlist[i];\n globalRequire(name, value);\n }\n else {\n for (name in reqlist[i]) {\n value = reqlist[i][name];\n globalRequire(name, value);\n }\n }\n } catch (e) {\n }\n }\n}", "function localRequire(path) {\n var resolved = require.resolve(localRequire.resolve(path));\n if (resolved && require.modules.hasOwnProperty(resolved)) {\n return require(resolved, parent, path);\n }\n return require(path);\n }", "function Reloader(require) {\n this.require = require;\n}", "function __require(uid, parentUid) {\n\tif(!__moduleIsCached[uid]) {\n\t\t// Populate the cache initially with an empty `exports` Object\n\t\t__modulesCache[uid] = {\"exports\": {}, \"loaded\": false};\n\t\t__moduleIsCached[uid] = true;\n\t\tif(uid === 0 && typeof require === \"function\") {\n\t\t\trequire.main = __modulesCache[0];\n\t\t} else {\n\t\t\t__modulesCache[uid].parent = __modulesCache[parentUid];\n\t\t}\n\t\t/* Note: if this module requires itself, or if its depenedencies\n\t\t\trequire it, they will only see an empty Object for now */\n\t\t// Now load the module\n\t\t__modules[uid](__modulesCache[uid], __modulesCache[uid].exports);\n\t\t__modulesCache[uid].loaded = true;\n\t}\n\treturn __modulesCache[uid].exports;\n}", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function localRequire(path) {\n var resolved = localRequire.resolve(path);\n return require(resolved, parent, path);\n }", "function makeRequireFunction() {\r\n var Module = this.constructor;\r\n var self = this;\r\n\r\n function require(path) {\r\n try {\r\n exports.requireDepth += 1;\r\n return self.require(path);\r\n } finally {\r\n exports.requireDepth -= 1;\r\n }\r\n }\r\n\r\n function resolve(request) {\r\n return Module._resolveFilename(request, self);\r\n }\r\n\r\n require.resolve = resolve;\r\n\r\n require.main = process.mainModule;\r\n\r\n // Enable support to add extra extension types.\r\n require.extensions = Module._extensions;\r\n\r\n require.cache = Module._cache;\r\n\r\n return require;\r\n}", "function _require( url ) { \n\n\tvar script = document.createElement('script');\n\t\tscript.setAttribute('language', 'javascript');\n\t\tscript.setAttribute('type', 'text/javascript');\n\t\tscript.setAttribute('src', url + '.js?' + Math.random());\n script.onerror = function () {\n alert (\"Failed to load required script '\" + url + \"'\");\n };\n\tdocument.getElementsByTagName('head').item(0).appendChild( script );\n\t\n\treturn script;\n}", "function requireHeader(path) { requireHeaderWrapper(require(path)); }", "function learnModules() {\n const sth=require('./app.js').something;\n \n console.log(sth);\n \n }", "function require (names, callback, errback, referer) {\n // in amd, first arg can be a config object... we just ignore\n if (typeof names == 'object' && !(names instanceof Array))\n return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));\n\n // amd require\n if (typeof names == 'string' && typeof callback == 'function')\n names = [names];\n if (names instanceof Array) {\n var dynamicRequires = [];\n for (var i = 0; i < names.length; i++)\n dynamicRequires.push(loader.import(names[i], referer));\n Promise.all(dynamicRequires).then(function (modules) {\n for (var i = 0; i < modules.length; i++)\n modules[i] = modules[i].__useDefault ? modules[i].default : modules[i];\n if (callback)\n callback.apply(null, modules);\n }, errback);\n }\n\n // commonjs require\n else if (typeof names == 'string') {\n var normalized = loader.decanonicalize(names, referer);\n var module = loader.get(normalized);\n if (!module)\n throw new Error('Module not already loaded loading \"' + names + '\" as ' + normalized + (referer ? ' from \"' + referer + '\".' : '.'));\n return module.__useDefault ? module.default : module;\n }\n\n else\n throw new TypeError('Invalid require');\n }", "function requires() {\n if (!conf) {\n alert(\"MRequires: MRequires() used before MRequires.init() called.\");\n return;\n }\n \n for (var i=0; i<arguments.length; i++) {\n \n // We keep track of items by their URL, because different\n // component names can refer to the same URL and we never\n // want to load the same URL twice.\n var url = makeUrl(arguments[i]);\n \n // Load only when not already loaded\n if (!loaded[url]) {\n // mark as loaded\n loaded[url] = true;\n \n if (/\\.js$/.test(url)) {\n loadJavaScript(url);\n }\n else if (/\\.css$/.test(url)) {\n loadCss(url);\n }\n else {\n alert(\"MRequires: Unknown file type '\"+url+\"'.\");\n }\n }\n }\n }", "function makeRequire(dom, pathName) {\n return function(reqStr) {\n var o, scannable, k, skipFolder;\n\n if (config.logging >= 4) {\n console.debug('modul8: '+dom+':'+pathName+\" <- \"+reqStr);\n }\n\n if (reqStr.slice(0, 2) === './') {\n scannable = [dom];\n reqStr = toAbsPath(pathName, reqStr.slice(2));\n }\n else if (reqStr.slice(0,3) === '../') {\n scannable = [dom];\n reqStr = toAbsPath(pathName, reqStr);\n }\n else if (DomReg.test(reqStr)) {\n scannable = [reqStr.match(DomReg)[1]];\n reqStr = reqStr.split('::')[1];\n }\n else if (arbiters.indexOf(reqStr) >= 0) {\n scannable = ['M8'];\n }\n else {\n scannable = [dom].concat(domains.filter(function(e) {return e !== dom;}));\n }\n\n reqStr = reqStr.split('.')[0];\n if (reqStr.slice(-1) === '/' || reqStr === '') {\n reqStr += 'index';\n skipFolder = true;\n }\n\n if (config.logging >= 3) {\n console.log('modul8: '+dom+':'+pathName+' <- '+reqStr);\n }\n if (config.logging >= 4) {\n console.debug('modul8: scanned '+JSON.stringify(scannable));\n }\n\n for (k = 0; k < scannable.length; k += 1) {\n o = scannable[k];\n if (exports[o][reqStr]) {\n return exports[o][reqStr];\n }\n if (!skipFolder && exports[o][reqStr + '/index']) {\n return exports[o][reqStr + '/index'];\n }\n }\n\n if (config.logging >= 1) {\n console.error(\"modul8: Unable to resolve require for: \" + reqStr);\n }\n };\n}", "function __krequire(path) {\n return eval('(()=>{var exports={};' + fs.readFileSync(___data + path, 'utf8').toString() + ';return exports})()');\n }", "function require(names, callback, errback, referer) {\n // in amd, first arg can be a config object... we just ignore\n if (typeof names == 'object' && !(names instanceof Array))\n return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));\n\n // amd require\n if (typeof names == 'string' && typeof callback == 'function')\n names = [names];\n if (names instanceof Array) {\n var dynamicRequires = [];\n for (var i = 0; i < names.length; i++)\n dynamicRequires.push(loader['import'](names[i], referer));\n Promise.all(dynamicRequires).then(function(modules) {\n if (callback)\n callback.apply(null, modules);\n }, errback);\n }\n\n // commonjs require\n else if (typeof names == 'string') {\n var module = loader.get(loader.normalizeSync(names, referer));\n if (!module)\n throw new Error('Module not already loaded loading \"' + names + '\" from \"' + referer + '\".');\n return module.__useDefault ? module['default'] : module;\n }\n\n else\n throw new TypeError('Invalid require');\n }", "function loadFoo() {\n // 这是懒加载 foo,原始的加载仅仅用来做类型注解\n var _foo = require('foo');\n // 现在,你可以使用 `_foo` 替代 `foo` 来作为一个变量使用\n}", "function ensures(name) {\n return require(name);\n}", "function makeRequireFunction(mod) {\n\t const Module = mod.constructor;\n\n\t function require(path) {\n\t return mod.require(path);\n\t }\n\t function resolve(request, options) {\n\t validateString(request, 'request');\n\t return Module._resolveFilename(request, mod, false, options);\n\t }\n\n\t require.resolve = resolve;\n\n\t function paths(request) {\n\t validateString(request, 'request');\n\t return Module._resolveLookupPaths(request, mod);\n\t }\n\n\t resolve.paths = paths;\n\n\t require.main = process.mainModule;\n\n\t // Enable support to add extra extension types.\n\t require.extensions = Module._extensions;\n\n\t require.cache = Module._cache;\n\n\t return require;\n\t }", "static get requires() {\r\n return {\r\n 'LW.Window': 'lw.window.js',\r\n 'LW.Calendar': 'lw.calendar.js',\r\n // 'LW.Menu': 'lw.menu.js',\r\n // 'LW.Tooltip': 'lw.tooltip.js'\r\n }\r\n }", "function require(names, callback, errback, referer) {\n // in amd, first arg can be a config object... we just ignore\n if (typeof names == 'object' && !(names instanceof Array))\n return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));\n\n // amd require\n if (typeof names == 'string' && typeof callback == 'function')\n names = [names];\n if (names instanceof Array) {\n var dynamicRequires = [];\n for (var i = 0; i < names.length; i++)\n dynamicRequires.push(loader['import'](names[i], referer));\n Promise.all(dynamicRequires).then(function(modules) {\n if (callback)\n callback.apply(null, modules);\n }, errback);\n }\n\n // commonjs require\n else if (typeof names == 'string') {\n var module = loader.get(names);\n return module.__useDefault ? module['default'] : module;\n }\n\n else\n throw new TypeError('Invalid require');\n }", "loadDependencies(){\n\n }", "function c(e,t,n){Array.isArray(e)?(n=t,t=e,e=void 0):\"string\"!=typeof e&&(n=e,e=t=void 0),t&&!Array.isArray(t)&&(n=t,t=void 0),t||(t=[\"require\",\"exports\",\"module\"]),\n//Set up properties for this module. If an ID, then use\n//internal cache. If no ID, then use the external variables\n//for this node module.\ne?\n//Put the module in deep freeze until there is a\n//require call for it.\nd[e]=[e,t,n]:l(e,t,n)}", "function require(names, callback, errback, referer) {\n // 'this' is bound to the loader\n var loader = this;\n\n // in amd, first arg can be a config object... we just ignore\n if (typeof names == 'object' && !(names instanceof Array))\n return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));\n\n // amd require\n if (names instanceof Array)\n Promise.all(names.map(function(name) {\n return loader['import'](name, referer);\n })).then(function(modules) {\n callback.apply(null, modules);\n }, errback);\n\n // commonjs require\n else if (typeof names == 'string') {\n var module = loader.get(names);\n return module.__useDefault ? module['default'] : module;\n }\n\n else\n throw 'Invalid require';\n }", "function _require(moduleId, packageId, curModuleId) {\n var req, exports, moduleInfo, factory, idx, exp, func, tiki;\n\n // substitute package if needed\n if (packageId) {\n idx = moduleId.indexOf(':');\n if (idx>=0) moduleId = moduleId.slice(0, idx);\n moduleId = packageId + ':' + moduleId;\n }\n \n // convert to canonical moduleId reference.\n moduleId = loader.canonical(moduleId, curModuleId);\n\n // see if its already initialized. return if so\n if (exp = allModules[moduleId]) {\n \n // save the exports when we return it so it can be checked later...\n exp = exp.exports;\n if (!usedModules[moduleId]) usedModules[moduleId] = exp; \n return exp || {}; \n }\n \n // not defined...create it\n modules.push(moduleId);\n\n // not initialized, init module \n exports = {};\n allModules[moduleId] = moduleInfo = {\n id: moduleId,\n exports: exports\n };\n \n // generate custom require with safe info exposed\n req = function(m, p) { return _require(m, p, moduleId); };\n req.displayName = 'Sandbox.require';\n \n req.loader = loader ;\n req.clear = _clear;\n req.sandbox = this;\n \n // run module factory in loader\n func = loader.load(moduleId);\n tiki = _require('tiki:index'); // include tiki global\n if (!func) throw \"could not load function for \" + moduleId;\n\n func.call(exports, req, exports, moduleInfo, tiki);\n \n // detect a circular require. if another module required this \n // module while it was still running, that module must have imported the\n // same exports we ended up with to be consistent.\n exports = moduleInfo.exports;\n exp = usedModules[moduleId];\n if (exp && exp!==exports) throw \"circular require in \" +moduleId;\n usedModules[moduleId] = exports;\n \n return exports;\n }", "function require(names, callback, errback, referer) {\n // 'this' is bound to the loader\n var loader = this;\n\n // in amd, first arg can be a config object... we just ignore\n if (typeof names == 'object' && !(names instanceof Array))\n return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));\n\n // amd require\n if (names instanceof Array)\n Promise.all(names.map(function(name) {\n return loader['import'](name, referer);\n })).then(function(modules) {\n if(callback) {\n callback.apply(null, modules);\n }\n }, errback);\n\n // commonjs require\n else if (typeof names == 'string') {\n var module = loader.get(names);\n return module.__useDefault ? module['default'] : module;\n }\n\n else\n throw new TypeError('Invalid require');\n }", "function require(names, callback, errback, referer) {\n // in amd, first arg can be a config object... we just ignore\n if (typeof names == 'object' && !(names instanceof Array))\n return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));\n\n // amd require\n if (typeof names == 'string' && typeof callback == 'function')\n names = [names];\n if (names instanceof Array) {\n var dynamicRequires = [];\n for (var i = 0; i < names.length; i++)\n dynamicRequires.push(loader['import'](names[i], referer));\n Promise.all(dynamicRequires).then(function(modules) {\n if (callback)\n callback.apply(null, modules);\n }, errback);\n }\n\n // commonjs require\n else if (typeof names == 'string') {\n var defaultJSExtension = loader.defaultJSExtensions && names.substr(names.length - 3, 3) != '.js';\n var normalized = loader.decanonicalize(names, referer);\n if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) == '.js')\n normalized = normalized.substr(0, normalized.length - 3);\n var module = loader.get(normalized);\n if (!module)\n throw new Error('Module not already loaded loading \"' + names + '\" as ' + normalized + (referer ? ' from \"' + referer + '\".' : '.'));\n return module.__useDefault ? module['default'] : module;\n }\n\n else\n throw new TypeError('Invalid require');\n }", "function require(names, callback, errback, referer) {\n // in amd, first arg can be a config object... we just ignore\n if (typeof names == 'object' && !(names instanceof Array))\n return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));\n\n // amd require\n if (typeof names == 'string' && typeof callback == 'function')\n names = [names];\n if (names instanceof Array) {\n var dynamicRequires = [];\n for (var i = 0; i < names.length; i++)\n dynamicRequires.push(loader['import'](names[i], referer));\n Promise.all(dynamicRequires).then(function(modules) {\n if (callback)\n callback.apply(null, modules);\n }, errback);\n }\n\n // commonjs require\n else if (typeof names == 'string') {\n var defaultJSExtension = loader.defaultJSExtensions && names.substr(names.length - 3, 3) != '.js';\n var normalized = loader.decanonicalize(names, referer);\n if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) == '.js')\n normalized = normalized.substr(0, normalized.length - 3);\n var module = loader.get(normalized);\n if (!module)\n throw new Error('Module not already loaded loading \"' + names + '\" as ' + normalized + (referer ? ' from \"' + referer + '\".' : '.'));\n return module.__useDefault ? module['default'] : module;\n }\n\n else\n throw new TypeError('Invalid require');\n }", "function requireMainProcessAdditional () {\n var files = glob.sync(path.join(__dirname, 'main-process/**/*.js'))\n files.forEach(function (file) {\n require(file)\n })\n}", "function makeRequire(mod, enableBuildCallback, altRequire) {\n var relMap = mod && mod.map,\n modRequire = makeContextModuleFunc(altRequire || context.require,\n relMap,\n enableBuildCallback);\n\n addRequireMethods(modRequire, context, relMap);\n modRequire.isBrowser = isBrowser;\n\n return modRequire;\n }", "function loadDemos() {\n // const files = glob.sync(path.join(__dirname, 'main-process/**/*.js'))\n // files.forEach((file) => {\n // console.log('require file path:' + file)\n // require(file)\n // })\n\n require(path.join(__dirname, 'sugr/consolemanager.js'));\n require(path.join(__dirname, 'sugr/main.js'));\n require(path.join(__dirname, 'sugr/dialog.js'));\n}", "function dynamicRequire(mod, request) {\n\t // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t return mod.require(request);\n\t}", "function require(locationInProject) {\n var imported = document.createElement('script');\n imported.src = locationInProject;\n document.head.appendChild(imported);\n}", "function o(t,e,n){return n={path:e,exports:{},require:function(t,e){return s(t,void 0===e||null===e?n.path:e)}},t(n,n.exports),n.exports}", "function req(name) {\n\ttry {\n\t\treturn require(name);\n\t} catch (err) {\n\t\treturn false;\n\t}\n}", "function dynamicRequire(mod, request) {\r\n // tslint:disable-next-line: no-unsafe-any\r\n return mod.require(request);\r\n}", "load() {}", "load() {}", "function tryRequire(file) {\n return typeof require !== 'undefined' ? require(file) : undefined;\n}", "function tryRequire(file) {\n return typeof require !== 'undefined' ? require(file) : undefined;\n}", "function tryRequire(file) {\n return typeof require !== 'undefined' ? require(file) : undefined;\n}", "function tryRequire(file) {\n return typeof require !== 'undefined' ? require(file) : undefined;\n}", "function dynamicRequire(mod, request) {\n return mod.require(request);\n}", "function preprocess(){\n\t// add requirements etc. here\n\techo(\"require(psych)\\n\");\n}", "function fromRequireContext(reqctx) {\n return function(className) {\n const parts = className.split('.');\n const filename = parts.shift();\n const keys = parts;\n // Load the module:\n let component = reqctx('./' + filename);\n // Then access each key:\n keys.forEach((k) => {\n component = component[k];\n });\n // support `export default`\n if (component.__esModule) {\n component = component.default;\n }\n return component;\n };\n}", "function requireFromString(src, filename) {\n const Module = module.constructor;\n const m = new Module();\n m._compile(src, filename);\n return m.exports;\n}", "function SeamonkeyImport() {}", "function r(){throw new Error(\"Dynamic requires are not currently supported by rollup-plugin-commonjs\")}", "function dynamicRequire(mod, request) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n return mod.require(request);\r\n}", "function require(libraryName) {\r\n\t\t\t// TODO: replace . with /\r\n\t\t\tScarlet.include(libraryName);\r\n\t\t}", "function fn(path){\n var orig = path;\n path = fn.resolve(path);\n return require(path, parent, orig);\n }", "function myImport() {\n\tvar args = Array.prototype.slice.call(arguments);\n var filename = args.shift();\n if (typeof(filename) == typeof(undefined)) {\n return;\n }\n var preImport = function(args){myImport.apply(null, args);};\n var next = function(){preImport(args);};\n var tag = document.createElement('script');\n tag.type = 'text/javascript';\n tag.src = filename;\n tag.onreadystatechange = next;\n tag.onload = next;\n var head = document.getElementsByTagName('head')[0];\n head.appendChild(tag);\n}", "function loadModule(moduleName){var module=modules[moduleName];if(module!==undefined){return module;}// This uses a switch for static require analysis\nswitch(moduleName){case'charset':module=__webpack_require__(229);break;case'encoding':module=__webpack_require__(230);break;case'language':module=__webpack_require__(231);break;case'mediaType':module=__webpack_require__(232);break;default:throw new Error('Cannot find module \\''+moduleName+'\\'');}// Store to prevent invoking require()\nmodules[moduleName]=module;return module;}", "function dynamicRequire(mod, request) {\n // tslint:disable-next-line: no-unsafe-any\n return mod.require(request);\n}", "function requireModel(filePath, cb) {\n //check if file exist. if not return error\n fs.exists(filePath, function (exists) {\n if (!exists) {\n return cb(new Error(\"Requested Model Not Found!\"));\n }\n\n libProduct.model = require(filePath);\n return cb(null, libProduct);\n });\n }" ]
[ "0.79007006", "0.6931596", "0.65954447", "0.6400872", "0.6366075", "0.63028336", "0.6299785", "0.6229978", "0.62218225", "0.6191262", "0.6175646", "0.61684793", "0.6142497", "0.61068124", "0.6105065", "0.60636157", "0.60487455", "0.60481995", "0.6042539", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.6033574", "0.5950036", "0.5921753", "0.5919836", "0.5897913", "0.58766794", "0.5872062", "0.58706266", "0.5862819", "0.58494467", "0.5846994", "0.5842906", "0.5842461", "0.5824914", "0.5813583", "0.57885116", "0.57842606", "0.5767303", "0.5766041", "0.5749112", "0.5745053", "0.5745053", "0.57177347", "0.5715681", "0.5708671", "0.57027584", "0.56994545", "0.56818366", "0.5676434", "0.566935", "0.5664201", "0.5664201", "0.5664077", "0.5664077", "0.5664077", "0.5664077", "0.5644581", "0.56443053", "0.5633831", "0.5628894", "0.56255877", "0.56208104", "0.5618759", "0.5616914", "0.56114215", "0.56048733", "0.55991334", "0.559301", "0.559077" ]
0.0
-1
currentFrame, currentTime and sampleRate are global variables of AudioWorkletProcessor currentFrame is does not give the same result as counting iterations (this._countBlock)
constructor() { super(); // Initialize parameters this.init(0.02); // Process message this.port.onmessage = this.handleMessage.bind(this); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "init(frameDuration){\n // Initialize variables\n\n // Frame information\n // Frame duration (e.g., 0.02 s)\n const fSize = frameDuration*sampleRate;\n // Make the framesize multiple of 128 (audio render block size)\n this._frameSize = 128*Math.round(fSize/128); // Frame duration = this._frameSize/sampleRate;\n this._frameSize = Math.max(128*2, this._frameSize); // Force a minimum of two blocks\n\n this._numBlocksInFrame = this._frameSize/128; // 8 at 48kHz and 20ms window\n // Force an even number of frames\n if (this._numBlocksInFrame % 2){\n this._numBlocksInFrame++;\n this._frameSize += 128;\n }\n // Predefined 50% overlap\n this._numBlocksOverlap = Math.floor(this._numBlocksInFrame/2); // 4 at 48kHz and 20ms window\n\n // Define frame buffers\n this._oddBuffer = new Float32Array(this._frameSize); // previous and current are reused\n this._pairBuffer = new Float32Array(this._frameSize); // previous and current are reused\n\n // We want to reuse the two buffers. This part is a bit complicated and requires a detailed description\n // Finding the block indices that belong to each buffer is complicated\n // for buffers with an odd num of blocks.\n // Instead of using full blocks, half blocks could be used. This also adds\n // another layer of complexity, so not much to gain...\n // Module denominator to compute the block index\n this._modIndexBuffer = this._numBlocksInFrame + this._numBlocksInFrame % 2; // Adds 1 to numBlocksInFrame if it's odd, otherwise adds 0\n\n // Count blocks\n this._countBlock = 0;\n\n // Computed buffers\n this._oddSynthBuffer = new Float32Array(this._frameSize);\n this._pairSynthBuffer = new Float32Array(this._frameSize);\n\n console.log(\"Frame size: \" + this._frameSize +\n \". Set frame length: \" + this._frameSize/sampleRate + \" seconds\" +\n \". Blocks per frame: \" + this._numBlocksInFrame +\n \". Blocks overlap: \" + this._numBlocksOverlap);\n\n\n\n\n // LCP variables\n this._lpcOrder = 20;\n // LPC filter coefficients\n this._lpcCoeff = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n // LPC k coefficients\n this._kCoeff = [];\n // Filter samples\n this._prevY = [];\n // Quantization\n this._quantOpt = false;\n this._quantBits = 2;\n // Reverse K's\n this._reverseKOpt = false;\n // Perfect synthesis\n this._perfectSynthOpt = false;\n\n // resampling before analysis\n this._resamplingFactor = 1;\n this._resampler = new Resampler(this._frameSize, this._resamplingFactor);\n // Unvoiced mix (adds noise to the perfect excitation signal)\n this._unvoicedMix = 0;\n // Pitch factor (modifies this._fundFreq)\n this._pitchFactor = 1;\n // Vibrato effect (modifies this._fundFreq)\n this._vibratoEffect = 0;\n\n\n\n // Synthesis\n // Create impulse signal\n this._oldTonalBuffer = new Float32Array(this._frameSize/2);\n this._excitationSignal = new Float32Array(this._frameSize);\n this._errorBuffer = new Float32Array(this._frameSize);\n this._mixedExcitationSignal = new Float32Array(this._frameSize);\n\n // autocorrelation indices for fundamental frequency estimation\n this._lowerACFBound = Math.floor(sampleRate / 200); // 200 Hz upper frequency limit -> lower limit for periodicity in samples\n this._upperACFBound = Math.ceil(sampleRate / 70); // 70 Hz lower frequency limit -> upper limit\n\n // excitation variables\n this._tonalConfidence = 0.5;\n this._confidenceTonalThreshold = 0.1;\n this._periodFactor = 1;\n\n // buffer for fundamental period estimation\n this._fundPeriodLen = this._upperACFBound - this._lowerACFBound;\n this._fundPeriodBuffer = [];\n this._oldPeriodSamples = this._upperACFBound;\n this._pulseOffset = 0;\n\n\n\n\n // Debug\n // Timer to give updates to the main thread\n this._lastUpdate = currentTime;\n // Block info\n this._block1 = new Float32Array(128);\n this._block2 = new Float32Array(128);\n\n }", "countFrames() {\nreturn this.fCount;\n}", "calculateFrame() {\n const nowTime = (new Date()).getTime();\n this.tick += 1;\n if (nowTime - this.beforeTime >= 1000) {\n console.log(`fps: ${this.tick}`);\n this.tick = 0;\n this.beforeTime = nowTime;\n }\n }", "_incrementFrame() {\n this._elapsedFrameCount += 1;\n }", "static frameCounter() {\n const time = performance.now()\n\n if (FPS.start === null) {\n FPS.start = time\n FPS.prevFrameTime = time\n } else {\n FPS.frameCount++\n FPS.frames.push(time - FPS.prevFrameTime)\n }\n\n FPS.prevFrameTime = time\n\n if (FPS.running) {\n requestAnimationFrame(FPS.frameCounter)\n }\n }", "function FrameRateCounter()\n{\n this.last_frame_count = 0;\n this.frame_ctr = 0;\n \n var date = new Date();\n this.frame_last = date.getTime();\n delete date;\n \n this.tick = function()\n {\n var date = new Date();\n this.frame_ctr++;\n\n if (date.getTime() >= this.frame_last + 1000)\n {\n this.last_frame_count = this.frame_ctr;\n this.frame_last = date.getTime();\n this.frame_ctr = 0;\n }\n\n delete date;\n }\n}", "function FrameRateCounter() {\n this.lastFrameCount = 0;\n dateTemp = new Date();\n this.frameLast = dateTemp.getTime();\n delete dateTemp;\n this.frameCtr = 0;\n}", "onProcess(audioProcessingEvent) {\n\n this.blocked = true;\n this.nCall++;\n\n let inputBuffer = audioProcessingEvent.inputBuffer;\n let outputBuffer = audioProcessingEvent.outputBuffer;\n\n for (let chIdx = 0; chIdx < outputBuffer.numberOfChannels; chIdx++) {\n let inputData = inputBuffer.getChannelData(chIdx);\n let outputData = outputBuffer.getChannelData(chIdx);\n\n if (!this.bypass) {\n this.PreStageFilter[chIdx].process(inputData, outputData);\n } else {\n // just copy\n for (let sample = 0; sample < inputBuffer.length; sample++) {\n outputData[sample] = inputData[sample];\n }\n }\n } // next channel\n\n let time = this.nCall * inputBuffer.length / this.sampleRate;\n let gl = this.calculateLoudness(outputBuffer);\n this.callback(time, gl);\n\n this.blocked = false;\n }", "function checker(){\n if (index--) requestFrame(checker);\n else {\n // var result = 3*Math.round(count*1000/3/(performance.now()-start));\n var result = count*1000/(performance.now()- start);\n if (typeof opts.callback === \"function\") opts.callback(result);\n console.log(\"Calculated: \"+result+\" frames per second\");\n }\n }", "function C_FrameCounter ()\n{\n this.FrameCounter = 0 ;\n\n // increment frame rate\n this.M_IncreaseFrameCounter = function ()\n {\n this.FrameCounter ++ ;\n return this.FrameCounter ;\n }\n}", "update() {\n const data = this.sound.waveformData;\n const ctx = this.canvas.getContext('2d');\n\n ctx.clearRect(0, 0, Infinity, Infinity);\n\n for (let x = 0; x < this.canvas.offsetWidth; x++) {\n\n const sampleInd = Math.floor(x * data.width / this.canvasWidth);\n const value = Math.floor(this.canvasHeight * data.samples[sampleInd] / data.height / 2);\n\n for (let y = value; y < this.canvasHeight - value; y++) {\n ctx.fillStyle = x < this.sound.currentTime / this.sound.duration * this.canvasWidth ? '#f60' : '#333';\n ctx.fillRect(x, y, 1, 1);\n }\n }\n }", "calculateLoudness(buffer) {\n\n // first call or after resetMemory\n if (this.copybuffer == undefined) {\n // how long should the copybuffer be at least? \n // --> at least maxT should fit in and length shall be an integer fraction of buffer length\n let length = Math.floor(this.sampleRate * this.loudnessprops.maxT / buffer.length + 1) * buffer.length;\n this.copybuffer = new CircularAudioBuffer(context, this.nChannels, length, this.sampleRate);\n }\n\n //accumulate buffer to previous call\n this.copybuffer.concat(buffer);\n\n // must be gt nSamplesPerInterval\n // or: wait at least one interval time T to be able to calculate loudness\n if (this.copybuffer.getLength() < this.nSamplesPerInterval) {\n console.log('buffer too small ... have to eat more data');\n return NaN;\n }\n\n // get array of meansquares from buffer of overlapping intervals\n let meanSquares = this.getBufferMeanSquares(this.copybuffer, this.nSamplesPerInterval, this.nStepsize);\n\n // first stage filter\n this.filterBlocks(meanSquares, this.gamma_a);\n\n // second stage filter\n let gamma_r = 0.;\n for (let chIdx = 0; chIdx < this.nChannels; chIdx++) {\n let mean = 0.;\n for (let idx = 0; idx < meanSquares[chIdx].length; idx++) {\n mean += meanSquares[chIdx][idx];\n }\n mean /= meanSquares[chIdx].length;\n gamma_r += (this.channelWeight[chIdx] * mean);\n }\n gamma_r = -0.691 + 10.0 * Math.log10(gamma_r) - 10.;\n\n this.filterBlocks(meanSquares, gamma_r);\n\n // gated loudness from filtered blocks\n let gatedLoudness = 0.;\n for (let chIdx = 0; chIdx < this.nChannels; chIdx++) {\n let mean = 0.;\n for (let idx = 0; idx < meanSquares[chIdx].length; idx++) {\n mean += meanSquares[chIdx][idx];\n }\n mean /= meanSquares[chIdx].length;\n\n gatedLoudness += (this.channelWeight[chIdx] * mean);\n }\n gatedLoudness = -0.691 + 10.0 * Math.log10(gatedLoudness);\n\n //console.log(this.id, '- gatedLoudness:', gatedLoudness);\n\n return gatedLoudness;\n }", "update() {\n this.tickCount += 1;\n if (this.tickCount > this.ticksPerFrame) {\n this.tickCount = 0;\n // If the current frame index is in range\n if (this.frameIndex < this.numberOfFrames - 1) {\n // Go to the next frame\n this.frameIndex += 1;\n } else {\n this.frameIndex = 0;\n }\n }\n }", "get frame() {\n if (this.video.current) {\n return Math.round(this.video.current.currentTime * this.props.fps);\n }\n\n return 0;\n }", "synthesizeOutputBlock(outBlock) {\n\n // Get block index for pair and odd buffers\n /*\n We want to get X: the current block to mix\n 0 0 0 X 0 --> Pair block\n X O O O O --> Odd block\n o o o x ... --> Synthesized block (outBlock)\n */\n\n\n let indBlockPair = this._countBlock % this._modIndexBuffer;\n let indBlockOdd = (indBlockPair + this._modIndexBuffer/2) % this._modIndexBuffer;\n\n // TODO: Right now this only works for 50% overlap and an even number of blocks per frame.\n // More modifications would be necessary to include less than 50% overlap and an odd number of blocks per frame. Right now an amplitude modulation would appear for an odd number of blocks per frame (to be tested - AM from 1 to 0.5).\n\n // Iterate over the corresponding block of the synthesized buffers\n for (let i = 0; i<outBlock.length; i++){\n let indPair = i + 128*indBlockPair;\n let indOdd = i + 128*indBlockOdd;\n\n // Hanning window\n // Use hanning window sin^2(pi*n/N)\n let hannPairBValue = Math.pow(Math.sin(Math.PI*indPair/this._frameSize), 2);\n let hannOddBValue = Math.pow(Math.sin(Math.PI*indOdd/this._frameSize), 2);\n //let hannPairBValue = 0.54 - 0.46 * Math.cos(2*Math.PI*indPair/(this._frameSize-1));\n //let hannOddBValue = 0.54 - 0.46 * Math.cos(2*Math.PI*indOdd/(this._frameSize-1));\n // Hanning windowed frames addition\n outBlock[i] = hannPairBValue*this._pairSynthBuffer[indPair] + hannOddBValue*this._oddSynthBuffer[indOdd];\n\n // Debugging\n //outBlock[i] = this._pairBuffer[i];//this._pairSynthBuffer[indPair];//0.5*this._pairSynthBuffer[indPair] + 0.5*this._oddSynthBuffer[indOdd];\n this._block1[i] = this._pairSynthBuffer[indPair];\n this._block2[i] = this._oddSynthBuffer[indOdd];\n }\n\n }", "function calculateCurrentVideo(){\n\tvar i = 0;\n\tvar lastLength = 0;\n\ttotalLength = 0;\n\n\tdateTime = new Date().getTime() / 1000;\n\tglobalTimeStamp = Math.floor(dateTime - startTime);\n\n\tfor(i = 0; totalLength < globalTimeStamp; i++){\n\t\ttotalLength = totalLength + parseInt(quickLooks[i].split('~')[3]);\n\t\tlastLength = parseInt(quickLooks[i].split('~')[3]);\n\n\t}\n\n\tglobalTimeStamp = lastLength - (totalLength - globalTimeStamp);\n\tcurrentVideoIndex = i - 1;\n\n}", "playback(playbackBlocks){\n let pbIndex = this.state.pbIndex\n let rIndex = this.state.rIndex\n let mIndex = this.state.mIndex\n let tsIndex = this.state.tsIndex\n let songLength = this.state.playbackBlocks.length\n let namePB, repeatPB, measurePB, timeSigPB, bpmPB, color\n\n while (pbIndex < songLength) {\n let playbackBlock = playbackBlocks[pbIndex]\n namePB = playbackBlock.name\n bpmPB = playbackBlock.msPerBeat\n color = playbackBlock.color\n while (rIndex < playbackBlock.repeat) {\n repeatPB = rIndex + 1\n while (mIndex < playbackBlock.measure) {\n measurePB = mIndex + 1\n while (tsIndex < playbackBlock.timeSig){\n timeSigPB = tsIndex + 1\n tsIndex++\n if (tsIndex == playbackBlock.timeSig) {\n tsIndex = 0\n mIndex++\n if (mIndex == playbackBlock.measure) {\n tsIndex = 0\n mIndex =0\n rIndex++\n if (rIndex == playbackBlock.repeat) {\n tsIndex = 0\n mIndex =0\n rIndex = 0\n pbIndex++\n }\n }\n }\n break\n }\n break\n }\n break\n }\n break\n }\n this.setState({\n name: namePB,\n repeat: repeatPB,\n measure: measurePB,\n timeSig: timeSigPB,\n color: color,\n pbIndex: pbIndex,\n rIndex: rIndex,\n mIndex: mIndex,\n tsIndex: tsIndex\n })\n return bpmPB\n }", "_loop () {\n // Start stat recording for this frame\n if (this.stats) this.stats.begin()\n // Clear the canvas if autoclear is set\n if (this._autoClear) this.clear()\n // Loop!\n if (this.loop) this.loop()\n // Increment time\n this._time++\n // End stat recording for this frame\n if (this.stats) this.stats.end()\n this._animationFrame = window.requestAnimationFrame(this._loop.bind(this))\n }", "function countSamples() {\r\n\treturn samplesPayload.length;\r\n}", "function frame() {\n\n rafId = requestAnimationFrame( frame )\n\n DELTA_TIME = Date.now() - LAST_TIME;\n LAST_TIME = Date.now();\n\n // analyser.getByteFrequencyData(frequencyData);\n\n\n analyser.getByteFrequencyData(frequencyData);\n ctx.clearRect( 0, 0, canvasWith, canvasHeight )\n\n\n var barWidth = opts.barWidth;\n var margin = 2;\n var nbBars = canvasWith / ( barWidth - margin );\n\n var cumul = 0;\n var average = 0;\n\n ctx.fillStyle = 'red'\n ctx.beginPath()\n for ( var i = 0; i < nbBars; i++ ) {\n\n // get the frequency according to current i\n let percentIdx = i / nbBars;\n let frequencyIdx = Math.floor(1024 * percentIdx)\n \n ctx.rect( i * barWidth + ( i * margin ), canvasHeight - frequencyData[frequencyIdx] , barWidth, frequencyData[frequencyIdx] );\n\n cumul += frequencyData[frequencyIdx];\n\n }\n ctx.fill()\n ctx.closePath()\n\n average = cumul / 255;\n\n // console.log(average);\n\n }", "function samplesAvailable()\r\n {\r\n return numOutputSamples;\r\n }", "function getSampleRate()\r\n {\r\n return sampleRate;\r\n }", "function audio_init(is_local, less_buffering, compression)\n{\n audio_running = false;\n \n console.log('--------------------------');\n //console.log('AUDIO audio_init CALLED is_local='+ is_local +' less_buffering='+ less_buffering +' compression='+ compression);\n\n less_buffering = false; // DEPRECATED\n \n //console.log('AUDIO audio_init LAST audio_last_is_local='+ audio_last_is_local +' audio_last_compression='+ audio_last_compression);\n if (is_local == null) is_local = audio_last_is_local;\n audio_last_is_local = is_local;\n if (compression == null) compression = audio_last_compression;\n audio_last_compression = compression;\n\n console.log('AUDIO audio_init FINAL is_local='+ is_local +' less_buffering='+ less_buffering +' compression='+ compression);\n\n if (audio_source != undefined) {\n //console.log('AUDIO audio_init audio_disconnect');\n audio_disconnect();\n }\n\n // reset globals\n audio_started = false;\n audio_last_output_offset = 0;\n audio_mode_iq = false;\n audio_compression = compression? true:false;\n audio_stat_input_epoch = -1;\n audio_prepared_buffers = Array();\n audio_prepared_buffers2 = Array();\n audio_prepared_seq = Array();\n audio_prepared_flags = Array();\n audio_prepared_smeter = Array();\n audio_buffering = false;\n audio_convolver_running = false;\n audio_meas_dly = 0;\n audio_meas_dly_start = 0;\n resample_new = kiwi_isMobile()? false : resample_new_default;\n resample_old = !resample_new;\n resample_init1 = false;\n resample_init2 = false;\n resample_input_buffer = [];\n resample_input_available = 0;\n resample_input_processed = 0;\n resample_last_taps_delay = 0;\n resample_output_buffer = [];\n resample_output_buffer2 = [];\n resample_taps = [];\n resample_last = 0;\n resample_last2 = 0;\n comp_lpf_freq = 0;\n comp_lpf_taps = [];\n comp_lpf_taps_length = 255;\n audio_adpcm.index = 0;\n audio_adpcm.previousValue = 0;\n audio_ext_adc_ovfl = false;\n audio_need_stats_reset = true;\n audio_change_LPF_latch = false;\n audio_change_freq_latch = false;\n \n var buffering_scheme = 0;\n var scheme_s;\n\tvar a = kiwi_url_param('abuf', null, null);\n var abuf = 0;\n \n if (a != null) {\n var a2 = a.split(',');\n abuf = parseFloat(a2[0]);\n if (!isNaN(abuf) && abuf >= 0.25 && abuf <= 5.0) {\n console.log('AUDIO override abuf='+ a);\n var max = abuf * 3;\n if (a2.length >= 2) {\n var m = parseFloat(a2[1]);\n if (!isNaN(m) && m >= 0.25 && m <= 5.0 && m > abuf) {\n max = m;\n }\n } else {\n max = abuf * 3;\n }\n audio_buffer_min_length_sec = abuf;\n audio_buffer_max_length_sec = max;\n audio_buffer_size = 8192;\n buffering_scheme = 9;\n scheme_s = 'abuf=';\n } else {\n abuf = 0;\n }\n }\n \n if (abuf == 0) {\n if (less_buffering) {\n if (is_local)\n buffering_scheme = 2;\n else\n buffering_scheme = 1;\n } else {\n buffering_scheme = 0;\n }\n\n // 2048 = 46 ms/buf 21.5 /sec @ 44.1 kHz\n // 4096 = 93 ms/buf 10.8 /sec @ 44.1 kHz\n // 8192 = 186 ms/buf 5.4 /sec @ 44.1 kHz\n \n if (buffering_scheme == 2) {\n audio_buffer_size = 8192;\n audio_buffer_min_length_sec = 0.37; // min_nbuf = 2 @ 44.1 kHz\n audio_buffer_max_length_sec = 2.00;\n scheme_s = 'less buf, local';\n } else\n \n if (buffering_scheme == 1) {\n audio_buffer_size = 8192;\n audio_buffer_min_length_sec = 0.74; // min_nbuf = 4 @ 44.1 kHz\n audio_buffer_max_length_sec = 3.00;\n scheme_s = 'less buf, remote';\n } else\n \n if (buffering_scheme == 0) {\n audio_buffer_size = 8192;\n audio_buffer_min_length_sec = 0.85; // min_nbuf = 5 @ 44.1 kHz\n audio_buffer_max_length_sec = 3.40;\n scheme_s = 'more buf';\n }\n }\n \n\taudio_data = new Int16Array(audio_buffer_size);\n\taudio_last_output_buffer = new Float32Array(audio_buffer_size)\n\taudio_last_output_buffer2 = new Float32Array(audio_buffer_size)\n\taudio_silence_buffer = new Float32Array(audio_buffer_size);\n\tconsole.log('AUDIO buffer_size='+ audio_buffer_size +' buffering_scheme: '+ scheme_s);\n\t\n\tkiwi_clearInterval(audio_stats_interval);\n\taudio_stats_interval = setInterval(audio_stats, 1000);\n\n\t//https://github.com/0xfe/experiments/blob/master/www/tone/js/sinewave.js\n\ttry {\n\t\twindow.AudioContext = window.AudioContext || window.webkitAudioContext;\n\t\taudio_context = new AudioContext();\n\t\taudio_context.sampleRate = 44100;\t\t// attempt to force a lower rate\n\t\taudio_output_rate = audio_context.sampleRate;\t\t// see what rate we're actually getting\n\t\t\n\t\ttry {\n\t\t audio_panner = audio_context.createStereoPanner();\n\t\t audio_panner_ui_init();\n\t\t} catch(e) {\n\t\t audio_panner = null;\n\t\t}\n\t\t\n if (kiwi_isSmartTV()) audio_gain = audio_context.createGain();\n\t} catch(e) {\n\t\tkiwi_serious_error(\"Your browser does not support Web Audio API, which is required for OpenWebRX to run. Please use an HTML5 compatible browser.\");\n\t\taudio_context = null;\n\t\taudio_output_rate = 0;\n\t\treturn true;\n\t}\n\nsetTimeout(\"snd_send('SET little-endian'); // we can accept arm native little-endian data\", 10000);\n audio_running = true;\n return false;\n}", "_frame () {\n this._drawFrame()\n if (!this.paused) {\n if (this.frameCount % 4 === 0) {\n this._updateGeneration()\n this.matrix = this.nextMatrix\n this.nextMatrix = this._createMatrix()\n this.counter.innerText = 'Generation: ' + this.generationNumber\n }\n }\n this.frameCount++\n requestAnimationFrame(this._frame)\n }", "getFrameCount() {\n return this.frames.length;\n }", "function gameLoop(timeStamp) {\n\n //New tick\n ticks++;\n aniPerc += gameBlockSpeed * gameBlockSpeedFall;\n\n // Calculate the number of seconds passed since the last frame\n secondsPassed = (timeStamp - oldTimeStamp) / 1000;\n oldTimeStamp = timeStamp;\n fps = Math.round(1 / secondsPassed);\n\n //Update mos pos\n mouse.xx = Math.floor((mouse.x - areaX) / cellSize);\n mouse.yy = Math.floor((mouse.y - areaY) / cellSize);\n\n //If player is currently positioning a block\n if (playMode === \"player\") {\n\n if (hasClicked) {\n gameBlockSpeedFall = 60;\n hasClicked = !hasClicked;\n }\n\n //Update player column\n if (mouse.xx > -1 && mouse.xx < cellsHorizontal) {\n player.x = mouse.xx;\n }\n\n //Fall the player block\n if (aniPerc > 100) {\n player.y += 1;\n aniPerc -= 100;\n }\n\n //Has the block hit another block / ground?\n if (playGrid[player.x][player.y + 1] !== 0 || player.y >= cellsVertical) {\n\n //Process block collision\n gameBlockSpeedFall = 1;\n console.log(\"Collision!\")\n playGrid[player.x][player.y] = player.num;\n checkArray.push({ x: player.x, y: player.y })\n changeMode(\"multiplying\");\n console.log(\"CheckArray:\");\n console.table(checkArray);\n lastCellPos = player.x;\n playerAlive = false;\n //spawnBlock();\n\n\n }\n }\n else if (playMode === \"multiplying\") {\n //Check for possible multiplications by going through the cells in checkArray\n if (checkArray.length > 0) {\n //x and y for current cell\n const x = checkArray[checkArray.length - 1].x;\n const y = checkArray[checkArray.length - 1].y;\n\n //Save positions of all cell that current cell will be multiplied will\n let matches = [];\n [0, 1, 2, 3].forEach((dir) => {\n const otherCell = getCellByDir(x, y, dir);\n if (isBlockSame(x, y, otherCell.x, otherCell.y)) {\n //Add neighbour cell as a match since its the same number\n matches.push(getCellByDir(x, y, dir));\n }\n });\n\n //if any multiplication oppurtunities were found\n if (matches.length > 0) {console.log(\"Multiplication found\", matches)\n\n //Multiply the current cell the appropriate amount\n playGrid[x][y] = Math.pow(2, matches.length) * playGrid[x][y];\n matches.forEach((cell) => {\n\n //Erase neighbour cell and add it to combineArray, and add the cell above it to fallArray if there is one\n if (playGrid[cell.x][cell.y - 1] !== 0) {\n //fallArray.push();\n }\n combineArray.push({ oldX: cell.x, oldY: cell.y, newX: x, newY: y, num: playGrid[cell.x][cell.y] });\n playGrid[cell.x][cell.y] = 0;\n\n });\n\n changeMode(\"combine\");\n\n } else {console.log(\"No multiplication found\");\n //No multiplication oppurtunities found\n //Mark cell as checked\n if (checkArray.length === 1) checkArray = []; else checkArray = checkArray.pop();\n changeMode(\"player\");\n }\n\n //Drop block down one level if possible\n /*if (playGrid[x][y + 1] === 0) {\n playGrid[x][y + 1] = playGrid[x][y];\n //We now also need to check the cell above us ad infinitum as that might fall as a result\n }*/\n\n\n } else {\n console.log(\"OHNOOOOOO!\")\n playMode = \"player\"\n }\n }\n else if (playMode = \"combine\") {\n aniPerc += combineSpeed;console.log(aniPerc);\n if (aniPerc > 100) {\n aniPerc = 0;\n if (-1 > 0) {\n changeMode(\"fall\");\n }\n else if (checkArray.length > 0) {\n changeMode(\"multiplying\");\n } else {\n changeMode(\"player\");\n }\n }\n }\n/*\n else if (playMode = \"fall\") {\n aniPerc += combineSpeed;\n if (aniPerc > 100) {\n aniPerc = 0;\n if (fallArraylength > 0) {\n changeMode(\"fall\");\n }\n else if (checkArray.length > 0) {\n changeMode(\"multiplying\");\n } else {\n changeMode(\"player\");\n }\n }\n }*/\n\n\n\n\n // Perform the drawing operation\n draw();\n\n // The loop function has reached it's end. Keep requesting new frames\n window.requestAnimationFrame(gameLoop);\n}", "function synthesizeAudioData(aPreOutputBuffer, aStartIndex, aAudioFrames) {\n // int zSamplesToProcess=aSamplesPerChannel;\n var zSamples = aAudioFrames * myChannels;\n var zVolChannelZero = Math.floor(((myAUDV[0] << 2) * myVolumePercentage) / 100);\n var zVolChannelOne = Math.floor(((myAUDV[1] << 2) * myVolumePercentage) / 100);\n var zIndex = aStartIndex;\n // Loop until the sample buffer is full\n while (zSamples > 0) {\n // Process both TIA sound channels\n for (var c = 0; c < 2; ++c) {\n // Update P4 & P5 registers for channel if freq divider outputs a pulse\n if ((myFrequencyDivider[c].clock())) {\n switch (myAUDC[c]) {\n case 0x00: // Set to 1\n { // Shift a 1 into the 4-bit register each clock\n myP4[c] = (myP4[c] << 1) | 0x01;\n break;\n }\n\n case 0x01: // 4 bit poly\n {\n // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2\n myP4[c] = bool(myP4[c] & 0x0f) ? ((myP4[c] << 1) | ((bool(myP4[c] & 0x08) ? 1 : 0) ^ (bool(myP4[c] & 0x04) ? 1 : 0))) : 1;\n break;\n }\n\n case 0x02: // div 31 . 4 bit poly\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // This does the divide-by 31 with length 13:18\n if ((myP5[c] & 0x0f) == 0x08) {\n // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2\n myP4[c] = bool(myP4[c] & 0x0f) ? ((myP4[c] << 1) | ((bool(myP4[c] & 0x08) ? 1 : 0) ^ (bool(myP4[c] & 0x04) ? 1 : 0))) : 1;\n }\n break;\n }\n\n case 0x03: // 5 bit poly . 4 bit poly\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // P5 clocks the 4 bit poly\n if (bool(myP5[c] & 0x10)) {\n // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2\n myP4[c] = bool(myP4[c] & 0x0f) ? ((myP4[c] << 1) | ((bool(myP4[c] & 0x08) ? 1 : 0) ^ (bool(myP4[c] & 0x04) ? 1 : 0))) : 1;\n }\n break;\n }\n\n case 0x04: // div 2\n {\n // Clock P4 toggling the lower bit (divide by 2)\n myP4[c] = (myP4[c] << 1) | (bool(myP4[c] & 0x01) ? 0 : 1);\n break;\n }\n\n case 0x05: // div 2\n {\n // Clock P4 toggling the lower bit (divide by 2)\n myP4[c] = (myP4[c] << 1) | (bool(myP4[c] & 0x01) ? 0 : 1);\n break;\n }\n\n case 0x06: // div 31 . div 2\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // This does the divide-by 31 with length 13:18\n if ((myP5[c] & 0x0f) == 0x08) {\n // Clock P4 toggling the lower bit (divide by 2)\n myP4[c] = (myP4[c] << 1) | (bool(myP4[c] & 0x01) ? 0 : 1);\n }\n break;\n }\n\n case 0x07: // 5 bit poly . div 2\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // P5 clocks the 4 bit register\n if (bool(myP5[c] & 0x10)) {\n // Clock P4 toggling the lower bit (divide by 2)\n myP4[c] = (myP4[c] << 1) | (bool(myP4[c] & 0x01) ? 0 : 1);\n }\n break;\n }\n\n case 0x08: // 9 bit poly\n {\n // Clock P5 & P4 as a standard 9-bit LSFR taps at 8 & 4\n myP5[c] = (bool(myP5[c] & 0x1f) || bool(myP4[c] & 0x0f)) ? ((myP5[c] << 1) | ((bool(myP4[c] & 0x08) ? 1 : 0) ^ (bool(myP5[c] & 0x10) ? 1 : 0))) : 1;\n myP4[c] = (myP4[c] << 1) | (bool(myP5[c] & 0x20) ? 1 : 0);\n break;\n }\n\n case 0x09: // 5 bit poly\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // Clock value out of P5 into P4 with no modification\n myP4[c] = (myP4[c] << 1) | (bool(myP5[c] & 0x20) ? 1 : 0);\n break;\n }\n\n case 0x0a: // div 31\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // This does the divide-by 31 with length 13:18\n if ((myP5[c] & 0x0f) == 0x08) {\n // Feed bit 4 of P5 into P4 (this will toggle back and forth)\n myP4[c] = (myP4[c] << 1) | (bool(myP5[c] & 0x10) ? 1 : 0);\n }\n break;\n }\n\n case 0x0b: // Set last 4 bits to 1\n {\n // A 1 is shifted into the 4-bit register each clock\n myP4[c] = (myP4[c] << 1) | 0x01;\n break;\n }\n\n case 0x0c: // div 6\n {\n // Use 4-bit register to generate sequence 000111000111\n myP4[c] = (~myP4[c] << 1) | ((!(!bool(myP4[c] & 4) && (bool(myP4[c] & 7)))) ? 0 : 1);\n break;\n }\n\n case 0x0d: // div 6\n {\n // Use 4-bit register to generate sequence 000111000111\n myP4[c] = (~myP4[c] << 1) | ((!(!bool(myP4[c] & 4) && (bool(myP4[c] & 7)))) ? 0 : 1);\n break;\n }\n\n case 0x0e: // div 31 . div 6\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // This does the divide-by 31 with length 13:18\n if ((myP5[c] & 0x0f) == 0x08) {\n // Use 4-bit register to generate sequence 000111000111\n myP4[c] = (~myP4[c] << 1) | ((!(!bool(myP4[c] & 4) && (bool(myP4[c] & 7)))) ? 0 : 1);\n }\n break;\n }\n\n case 0x0f: // poly 5 . div 6\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // Use poly 5 to clock 4-bit div register\n if (bool(myP5[c] & 0x10)) {\n // Use 4-bit register to generate sequence 000111000111\n myP4[c] = (~myP4[c] << 1) | ((!(!bool(myP4[c] & 4) && (bool(myP4[c] & 7)))) ? 0 : 1);\n }\n break;\n }\n }\n }\n }\n\n myOutputCounter += JAVA_SOUND_SAMPLE_RATE;\n\n if (myChannels == 1) {\n // Handle mono sample generation\n while ((zSamples > 0) && (myOutputCounter >= TIA_SAMPLE_RATE)) {\n var zChannelZero = (bool(myP4[0] & 8) ? zVolChannelZero : 0); //if bit3 is on, amplitude is the volume, otherwise amp is 0\n var zChannelOne = (bool(myP4[1] & 8) ? zVolChannelOne : 0);\n var zBothChannels = zChannelZero + zChannelOne + myVolumeClip;\n aPreOutputBuffer[zIndex] = (zBothChannels - 128) & 0xFF; // we are using a signed byte, which has a min. of -128\n\n myOutputCounter -= TIA_SAMPLE_RATE;\n zIndex++;\n zSamples--;\n //assert(zIndex<=aStartIndex + zSamplesToProcess);\n\n }\n }\n else {\n // Handle stereo sample generation\n while ((zSamples > 0) && (myOutputCounter >= TIA_SAMPLE_RATE)) {\n var zChannelZero = (bool(myP4[0] & 8) ? zVolChannelZero : 0) + myVolumeClip; //if bit3 is on, amplitude is the volume, otherwise amp is 0\n var zChannelOne = (bool(myP4[1] & 8) ? zVolChannelOne : 0) + myVolumeClip;\n //int zBothChannels=zChannelZero + zChannelOne + myVolumeClip;\n\n aPreOutputBuffer[zIndex] = (zChannelZero - 128) & 0xFF; // we are using a signed byte, which has a min. of -128\n zIndex++;\n zSamples--;\n\n aPreOutputBuffer[zIndex] = (zChannelOne - 128) & 0xFF;\n zIndex++;\n zSamples--;\n\n myOutputCounter -= TIA_SAMPLE_RATE;\n }\n }\n }\n }", "function renderAudio() {\n var now = audioContext.currentTime;\n \n for (var i = 0; i < NUMBER_OF_SOUND_SOURCES; i++)\n {\n if (meshes[i] != null)\n {\n meshes[i].updateMatrixWorld();\n }\n }\n\n\n if (soundsPlaying)\n {\n if ((loopCount % 2) === 0)\n {\n for (var i = 0; i < NUMBER_OF_SOUND_SOURCES; i++)\n {\n if (waitTimes[i] < (now - prevTime[i]))\n {\n \n if (onOff[i])\n {\n // Play a sound from this soundsource chosen by random walk\n \n waitTimes[i] = playRandomSound(i); // playRandomSound returns the duration of the loaded sample\n }\n else\n {\n onOff[i] = true;\n waitTimes[i] = ((Math.random() * WAIT_MAX) + WAIT_OFFSET);\n //console.log(waitTimes[i]);\n\n }\n prevTime[i] = now;\n }\n }\n }\n loopCount++;\n } \n }", "constructor({audioCtx, fftSize, carFreq, modAmpl, modFreq, visualCtx}) {\n this.audioCtx = audioCtx;\n this,fftSize = fftSize;\n this.carFreq = carFreq;\n this.modAmpl = modAmpl;\n this.modFreq = modFreq;\n this.visualCtx = visualCtx;\n this.play = false;\n\n\n this.animate;\n this.analyserNode = audioCtx.createAnalyser();\n this.analyserNode.smoothingTimeConstant = 0.0;\n this.analyserNode.fftSize = fftSize;\n\n // Create the array for the data values\n this.frequencyArray = new Uint8Array(this.analyserNode.frequencyBinCount);\n\n // Uses the chroma.js library by Gregor Aisch to create a color gradient\n // download from https://github.com/gka/chroma.js\n this.colorScale = new chroma.scale('Spectral').domain([1,0]);\n // Global Variables for Drawing\n this.column = 0;\n this.canvasWidth = 800;\n this.canvasHeight = 256;\n }", "function getFps(){\n\tfps++;\n\tif(Date.now() - lastTime >= 1000){\n\t\tfpsCounter.innerHTML = fps;\n\t\tfps = 0;\n\t\tlastTime = Date.now(); \n\t}\n}", "_checkBuffer() {\n const EPS = 1e-3;\n if (this.config.isLive) {\n // Live stream, try to maintain buffer between 3s and 8s\n // TODO make 3s and 8s configurable\n let currentBufferEnd = this.getCurrentBufferEnd();\n if (typeof currentBufferEnd === 'undefined') {\n // QUICKFIX:\n // if getCurrentBuffereEnd() is undefined, check if currentTime is in a gap,\n // and if it is jump to the latest buffered area\n \n const buffered = this.video.buffered;\n const lenBuffered = buffered.length;\n if (lenBuffered > 0 \n && buffered.start(lenBuffered - 1) > this.video.currentTime + EPS) {\n // In a gap, jump to latest buffered area\n Log.verbose('currentTime being in no-data GaP detected. Jumping to '\n + buffered.start(lenBuffered - 1));\n this.video.currentTime = buffered.start(lenBuffered - 1);\n currentBufferEnd = buffered.end(lenBuffered - 1);\n } else {\n // Not in a gap, noop\n return;\n }\n }\n const buffered = currentBufferEnd - this.video.currentTime;\n if (this._lastBufferd != null) {\n const changePlaybackRate = (toRate) => {\n Log.verbose('Change playback rate from ' + this.video.playbackRate + ' to ' + toRate + ', buffered:' + buffered);\n this.video.playbackRate = toRate;\n this.realtimeBeaconBuilder.playbackSpeedChanged(toRate);\n };\n if (this.video.playbackRate < 1 - EPS) {\n // Slowed down case. If buffer recovers to >= 5s, resume regular speed\n if (buffered > 5 - EPS) {\n changePlaybackRate(1.0);\n }\n } else if (this.video.playbackRate > 1 + EPS) {\n // Speeded up case. If buffer recovers to <= 5s, resume regular speed\n if (buffered < 5 + EPS) {\n changePlaybackRate(1.0);\n } else if (buffered > 8 + EPS) {\n // drop excessive data\n // Log.verbose('Dropping excessive data, buffer: ' + buffered);\n // this.realtimeBeaconBuilder.excessiveDataDropped(buffered - 5);\n // this.video.currentTime += buffered - 5;\n }\n } else {\n // Regular speed case. If buffer drops to < 3s or grows to > 6s, adjust speed accordingly\n // If buffer significantly grows to > 10s, keep 5s and drop excessive data\n if (buffered < 3 - EPS) {\n // changePlaybackRate(0.75);\n } else if (buffered > 8 + EPS) {\n // drop excessive data\n // Log.verbose('Dropping excessive data, buffer: ' + buffered);\n // this.realtimeBeaconBuilder.excessiveDataDropped(buffered - 5);\n // this.video.currentTime += buffered - 5;\n } else if (buffered > 6 + EPS) {\n // changePlaybackRate(1.25);\n }\n }\n }\n this._lastBufferd = buffered;\n }\n }", "function startSender(num, freq) {\n \n // framrate debugging. debug tag: /*FRDBG*/\n var startDate = new Date();\n var frame = 0;\n\n var reciever = newListener();\n var senderArray = numToArray(num);\n var position = 0;\n return stopSender.id = setInterval(function(){\n if (position == senderArray.length) position = 0;\n /*FRDBG*/ \n console.log(\"senderArray[position]\",senderArray[position])\n console.log(\"areaStyle.backgroundColor\",areaStyle.backgroundColor)\n if ((senderArray[position] && areaStyle.backgroundColor==\"white\") || (!senderArray[position] && areaStyle.backgroundColor==\"black\")) {\n frame++; \n } else {\n startDate = new Date();\n frame = 0;\n }\n console.log(\"frame\",frame)\n var off = (\n (\n (\n (\n (new Date).valueOf()\n ) - \n frame*(1000/freq)\n ) - \n startDate.valueOf()\n ) / (1000/freq)\n );\n\n if (off>0.5||off<-0.5) {\n console.error(off)\n } else if (off>0.25||off<-0.25) {\n console.warn(off)\n } else {\n console.log(off)\n }\n /*FRDBG*/\n if (senderArray[position]) {\n areaStyle.backgroundColor=\"white\"\n } else {\n areaStyle.backgroundColor=\"black\"\n }\n reciever(senderArray[position++]);\n },1000/freq);\n}", "_computeKeyframes() {\n\n\t\tconst numWorkers = this.options.numWorkers || window.navigator.hardwareConcurrency;\n\t\t\n\t\t// split features into chunks for worker\n\t\tconst featureChunks = this._chunkArray(this.options.features, numWorkers);\n\t\t\n\t\tlet running = 0;\n\t\tconst keyframeArray = [];\n\n\t\tconst workerDone = (e) => {\n\t\t\trunning -= 1;\n\t\t\tkeyframeArray.push(e.data.keyframes);\n\t\t\tif(running < 1) {\n\t\t\t\tconst mWorker = new mergeWorker();\n\t\t\t\tmWorker.postMessage({ keyframeArray });\n\t\t\t\tmWorker.onmessage = (e) => {\n\t\t\t\t\t\tthis._keyframes = e.data.keyframes;\n\t\t\t\t\t\tconsole.log('this._keyframes', this._keyframes);\n\t\t\t\t\t\n\t\t\t\t\t\tthis._times = Object.keys(this._keyframes);\n\t\t\t\t\t\tif (this.options.onKeyframesReady) {\n\t\t\t\t\t\t\tthis.options.onKeyframesReady();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\n\t\t\t}\n\t\t}\n\n for(let i = 0; i < numWorkers; i += 1) {\n running += 1;\n const tWorker = new transformWorker();\n tWorker.onmessage = workerDone;\n tWorker.postMessage({ features: featureChunks[i], timeKey: this._timeKey });\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\t\n\t}", "function ProcessFrames(mem48, speed, frequency, pitches, amplitude, sampledConsonantFlag) {\n const CombineGlottalAndFormants = (phase1, phase2, phase3, Y) => {\n let tmp; // unsigned int\n tmp = multtable[sinus[phase1] | amplitude[0][Y]];\n tmp += multtable[sinus[phase2] | amplitude[1][Y]];\n tmp += tmp > 255 ? 1 : 0; // if addition above overflows, we for some reason add one;\n tmp += multtable[rectangle[phase3] | amplitude[2][Y]];\n tmp += 136;\n tmp >>= 4; // Scale down to 0..15 range of C64 audio.\n\n Output(0, tmp & 0xf);\n };\n\n const RenderSample = (mem66, consonantFlag, mem49) => {\n const RenderVoicedSample = (hi, off, phase1) => {\n hi = hi & 0xFFFF; // unsigned short\n off = off & 0xFF; // unsigned char\n phase1 = phase1 & 0xFF; // unsigned char\n do {\n let sample = sampleTable[hi+off];\n let bit = 8;\n do {\n if ((sample & 128) !== 0) {\n Output(3, 26);\n } else {\n Output(4, 6);\n }\n sample <<= 1;\n } while(--bit !== 0);\n off++;\n } while (((++phase1) & 0xFF) !== 0);\n\n return off;\n };\n\n const RenderUnvoicedSample = (hi, off, mem53) => {\n hi = hi & 0xFFFF; // unsigned short\n off = off & 0xFF; // unsigned char\n mem53 = mem53 & 0xFF; // unsigned char\n do {\n let bit = 8;\n let sample = sampleTable[hi+off];\n do {\n if ((sample & 128) !== 0) {\n Output(2, 5);\n }\n else {\n Output(1, mem53);\n }\n sample <<= 1;\n } while (--bit !== 0);\n } while (((++off) & 0xFF) !== 0);\n };\n\n // mem49 == current phoneme's index - unsigned char\n\n // mask low three bits and subtract 1 get value to\n // convert 0 bits on unvoiced samples.\n let hibyte = (consonantFlag & 7) - 1;\n\n // determine which offset to use from table { 0x18, 0x1A, 0x17, 0x17, 0x17 }\n // T, S, Z 0 0x18\n // CH, J, SH, ZH 1 0x1A\n // P, F*, V, TH, DH 2 0x17\n // /H 3 0x17\n // /X 4 0x17\n\n let hi = hibyte * 256; // unsigned short\n // voiced sample?\n let pitch = consonantFlag & 248; // unsigned char\n if(pitch === 0) {\n // voiced phoneme: Z*, ZH, V*, DH\n pitch = pitches[mem49 & 0xFF] >> 4;\n return RenderVoicedSample(hi, mem66, pitch ^ 255);\n }\n RenderUnvoicedSample(hi, pitch ^ 255, tab48426[hibyte]);\n return mem66;\n };\n\n let speedcounter = new Uint8(72);\n let phase1 = new Uint8();\n let phase2 = new Uint8();\n let phase3 = new Uint8();\n let mem66 = new Uint8();\n let Y = new Uint8();\n let glottal_pulse = new Uint8(pitches[0]);\n let mem38 = new Uint8(glottal_pulse.get() - (glottal_pulse.get() >> 2)); // mem44 * 0.75\n\n while(mem48) {\n let flags = sampledConsonantFlag[Y.get()];\n\n // unvoiced sampled phoneme?\n if ((flags & 248) !== 0) {\n mem66.set(RenderSample(mem66.get(), flags, Y.get()));\n // skip ahead two in the phoneme buffer\n Y.inc(2);\n mem48 -= 2;\n speedcounter.set(speed);\n } else {\n CombineGlottalAndFormants(phase1.get(), phase2.get(), phase3.get(), Y.get());\n\n speedcounter.dec();\n if (speedcounter.get() === 0) {\n Y.inc(); //go to next amplitude\n // decrement the frame count\n mem48--;\n if(mem48 === 0) {\n return;\n }\n speedcounter.set(speed);\n }\n\n glottal_pulse.dec();\n\n if(glottal_pulse.get() !== 0) {\n // not finished with a glottal pulse\n\n mem38.dec();\n // within the first 75% of the glottal pulse?\n // is the count non-zero and the sampled flag is zero?\n if((mem38.get() !== 0) || (flags === 0)) {\n // reset the phase of the formants to match the pulse\n phase1.inc(frequency[0][Y.get()]);\n phase2.inc(frequency[1][Y.get()]);\n phase3.inc(frequency[2][Y.get()]);\n continue;\n }\n\n // voiced sampled phonemes interleave the sample with the\n // glottal pulse. The sample flag is non-zero, so render\n // the sample for the phoneme.\n mem66.set(RenderSample(mem66.get(), flags, Y.get()));\n }\n }\n\n glottal_pulse.set(pitches[Y.get()]);\n mem38.set(glottal_pulse.get() - (glottal_pulse.get() >> 2)); // mem44 * 0.75\n\n // reset the formant wave generators to keep them in\n // sync with the glottal pulse\n phase1.set(0);\n phase2.set(0);\n phase3.set(0);\n }\n }", "init(trackname) {\n window.AudioContext = window.AudioContext || window.webkitAudioContext;\n this.context = new AudioContext();\n let self = this;\n console.log(self);\n this.bufferLoader = new BufferLoader(\n self.context,\n [\n trackname\n ],\n function(bufferList) {\n self.source = self.context.createBufferSource();\n self.source.buffer = bufferList[0];\n self.sourceBuffer1 = self.source.buffer;\n }\n );\n\n this.bufferLoader.load();\n this.masterGain = this.context.createGain();\n this.masterGain.gain.value = 0.5;\n this.gain = this.context.createGain();\n this.gain.gain.value = 0.5;\n this.crossGain = this.context.createGain();\n this.gain.gain.value = 0.5;\n this.highShelf = this.context.createBiquadFilter();\n this.highShelf.type = 'highshelf';\n this.highShelf.frequency.value = 14000;\n this.highShelf.gain.value = 0.0;\n this.peaking = this.context.createBiquadFilter();\n this.peaking.type = 'peaking';\n this.peaking.frequency.value = 2000;\n this.peaking.Q.value= 0.8;\n this.peaking.gain.value = 0;\n this.lowShelf = this.context.createBiquadFilter();\n this.lowShelf.type = 'lowshelf';\n this.lowShelf.frequency.value = 600;\n this.lowShelf.gain.value = 0.0;\n }", "function frameLooper(){\n window.requestAnimationFrame(frameLooper);\n\n fbc_array = new Uint8Array(analyser.frequencyBinCount);\n frequencies = new Float32Array(analyser.frequencyBinCount);\n analyser.getFloatFrequencyData(frequencies);\n\n //converting the analyser frequency into javascript array\n analyser.getByteFrequencyData(fbc_array);\n\n changeBackground(fbc_array);\n animateBody(fbc_array);\n animateMouth(fbc_array);\n animateHead(fbc_array);\n animateEars(fbc_array);\n\n animateSnapBack(fbc_array);\n animatePupils(fbc_array);\n animateChest(fbc_array);\n animateArms(fbc_array);\n animateLegs(fbc_array);\n}", "readSample() {\n return 0;\n }", "function modulator() {\n // this odd construct is for safari compatibility\n this.audioCtx = new(window.AudioContext || window.webkitAudioContext)();\n\n this.samplerate = this.audioCtx.sampleRate;\n\n console.log(\"speakerSampleRate is \" + this.samplerate);\n\n this.encoder = new FskEncoder(this.samplerate);\n\n}", "nextFrame( globalMsec ){\n //console.log('nextFrame: ', globalMsec);\n if( this.transportState != 'play' )\n return;\n\n //Check for tempo change\n //Using a flag is a workaround attempt to see if it fixes the issue\n // of stutter/pause when changing tempo on the fly. It doesn't.\n if( this.musicParams.beatDurChangeFlag ){\n //console.log('caugt beatDurChangeFlag');\n this.musicParams.beatDurChangeFlag = false;\n this.ChangeTempoOnTheFly( this.musicParams.beatDurChange );\n }\n\n //Get current music time\n this.currentMusicTimes = this.getMusicTimes( globalMsec );\n\n //Simple note player or Beat click - can we do this in a separate thread somehow?\n var playClick = this.doNotePlayer( globalMsec ) == false;\n this.doBeatClick( playClick );\n\n //Only update visuals with a minimum time diff. This should help smooth things out\n // I think since we won't have as much load on the system.\n //This should help with things like particles that may be emitted every frame, cuz\n // will keep them more evenly spaced in time.\n //Music input and playback stuff gets done at every update above, cuz we want\n // less latency with that, and it takes less horsepower anyway.\n //** NOTE** make sure this doesn't cause trouble with MX updates that happen\n // in translator.updateForFrame()\n this.updateCumDelta += globalMsec - this.updatePrevMsec;\n if( this.updateCumDelta >= this.updateMinDelta ){\n //Run through MX's & VX's and update - visualize!\n this.translator.updateForFrame( this.currentMusicTimes );\n this.updatePrevMsec = globalMsec;\n //Take away the min delta so if we keep getting in here on deltas just\n // under the threshold, the diff will accumlate and get us to trigger again\n // sooner.\n this.updateCumDelta -= this.updateMinDelta;\n }/*else \n console.log('skip translator update with delta, and cumDelta ', globalMsec - this.updatePrevMsec, this.updateCumDelta)*/\n }", "get sampleRate() {\n return this.getSampleRate();\n }", "function MMLLSpectrumExtractor(blocksize=512,sampleRate=44100,fftsize=1024,hopsize=512,windowtype=0) {\n \n var self = this;\n \n self.audioblocksize = blocksize;\n self.inputAudio = new MMLLInputAudio(self.audioblocksize);\n \n self.sampleRate = sampleRate;\n\n self.numInputChannels = 1;\n\n self.fftsize = fftsize;\n self.hopsize = hopsize;\n self.windowtype = windowtype;\n \n //context required for sampler's decodeAudioData calls\n \n //can request specific sample rate, but leaving as device's default for now\n //https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/AudioContext\n try {\n self.audiocontext = new webkitAudioContext();\n \n } catch (e) {\n \n try {\n \n self.audiocontext = new AudioContext();\n \n } catch(e) {\n \n alert(\"Your browser does not support Web Audio API!\");\n return;\n }\n \n }\n \n //ignore sampleRate of audiocontext for now, just running through sound files at rate set by user\n //self.sampleRate = self.audiocontext.sampleRate; //usually 44100.0\n //console.log(\"AudioContext established with sample rate:\",self.sampleRate,\" and now setting up for input type:\",self.inputtype); //print\n \n \n //use async, wait?\n self.analyseAudioFile = function(filename,updatefunction) {\n \n \n var spectraldata;\n \n self.sampler = new MMLLSampler();\n \n \n return new Promise(function(resolve, reject) {\n //\"/sounds/05_radiohead_killer_cars.wav\"\n self.sampler.loadSamples([filename],\n function onload() {\n \n console.log('loaded: ',filename);\n \n self.sampleplayer = new MMLLSamplePlayer();\n self.sampleplayer.reset(self.sampler.buffers[0]);\n //self.sampleplayer.numChannels = self.sampler.buffers[0]\n \n if(self.sampleplayer.numChannels>1) {\n //interleaved input\n self.numInputChannels = 2;\n \n self.inputAudio.numChannels = self.numInputChannels;\n //self.samplearray = new Float32Array(2*audioblocksize);\n \n }\n //fresh STFT object\n var stft = new MMLLSTFT(self.fftsize,self.hopsize,self.windowtype);\n \n \n //samplearray depends on number of Channels whether interleaved\n \n //include last frame, will be zero padded as needed\n var numblocks = Math.floor(self.sampleplayer.lengthinsampleframes/self.audioblocksize);\n \n \n //starts with fftsize-hopsize in the bank\n var numspectralframes = Math.floor(((numblocks*self.audioblocksize) - self.hopsize)/self.hopsize) + 1;\n \n //self.processSoundFile(self.audioblocksize);\n \n \n spectraldata = new Array(numspectralframes);\n \n \n var j=0, i = 0;\n \n //complex data not in packed form, but dc and nyquist real values as complex numbers at 0 and fftsize indices\n for (j = 0; j < numspectralframes; ++j)\n spectraldata[j] = new Array(self.fftsize+2);\n \n console.log('Extracting spectrum for: ',filename); //debug console message\n \n var spectralframecount = 0;\n \n for (j = 0; j < numblocks; ++j) {\n \n updatefunction(j,numblocks);\n \n //needed since player accumulates to its output\n for (i = 0; i < self.audioblocksize; ++i) self.inputAudio.monoinput[i] = self.inputAudio.inputL[i] = self.inputAudio.inputR[i] = 0.0;\n \n self.sampleplayer.render(self.inputAudio,self.audioblocksize);\n \n var newframe = stft.next(self.inputAudio.monoinput);\n \n if(newframe) {\n \n if(spectralframecount>=numspectralframes) {\n \n console.log(\"what the spectrum?\",numblocks,numspectralframes,spectralframecount,self.hopsize,self.fftsize);\n }\n \n \n // var fftdata = stft.complex;\n \n for (i = 0; i < (self.fftsize+2); ++i)\n spectraldata[spectralframecount][i] = stft.complex[i];\n \n ++spectralframecount;\n }\n \n \n \n }\n \n \n resolve(spectraldata); //return via Promise\n \n \n },self.audiocontext);\n \n })\n \n \n };\n\n\n \n}", "gameLoop(timeStamp) {\n this.rafHandle = requestAnimationFrame((ts) => this.gameLoop(ts));\n\n this.deltaTime += timeStamp - this.lastFrameTimeMs;\n this.lastFrameTimeMs = timeStamp;\n\n if (timeStamp > this.lastFpsUpdate + 1000) {\n this.framesPerSecond = this.weightedFPSMultipler * this.framesThisSecond\n + (1 - this.weightedFPSMultipler) * this.framesPerSecond;\n\n this.lastFpsUpdate = timeStamp;\n\n this.framesThisSecond = 0;\n }\n this.framesThisSecond += 1;\n\n let numUpdateSteps = 0;\n while (this.deltaTime >= this.TIME_STEP) {\n this.pollInput();\n this.update(this.TIME_STEP);\n this.deltaTime -= this.TIME_STEP;\n\n numUpdateSteps += 1;\n if (numUpdateSteps >= 240) {\n this.panic();\n break;\n }\n }\n\n this.draw(this.deltaTime / this.TIME_STEP);\n }", "function updateAudio(){\n\n\tif (!isPlayingAudio)return;\n\tanalyser.getByteFrequencyData(freqByteData);\n\n\tvar length = freqByteData.length;\n\n\t//GET AVG LEVEL\n\tvar sum = 0;\n\tfor(var j = 0; j < length; ++j) {\n\t\tsum += freqByteData[j];\n\t}\n\n\t// Calculate the average frequency of the samples in the bin\n\tvar aveLevel = sum / length;\n\n\tnormLevel = (aveLevel / 256) * sketchParams.volSens; //256 is the highest a freq data can be\n\n\t//BEAT DETECTION\n\tif (normLevel > beatCutOff && normLevel > BEAT_MIN){\n\t\tbeatCutOff = normLevel *1.1;\n\t\tbeatTime = 0;\n\t}else{\n\t\tif (beatTime < BEAT_HOLD_TIME){\n\t\t\tbeatTime ++;\n\t\t}else{\n\t\t\tbeatCutOff *= BEAT_DECAY_RATE;\n\t\t}\n\t}\n}", "function gameLoop(timeStamp) {\n\n //New tick\n ticks++;\n aniPerc += gameBlockSpeed * gameBlockSpeedFall;\n\n // Calculate the number of seconds passed since the last frame\n secondsPassed = (timeStamp - oldTimeStamp) / 1000;\n oldTimeStamp = timeStamp;\n fps = Math.round(1 / secondsPassed);\n\n //Update mos pos\n mouse.xx = Math.floor((mouse.x - areaX) / cellSize);\n mouse.yy = Math.floor((mouse.y - areaY) / cellSize);\n\n //Speed up the falling block\n if (gameQueue.length === 0) {\n if (playerAlive === false) {\n playerAlive = true;\n spawnBlock();\n }\n\n if (hasUnClicked) {\n gameBlockSpeedFall = 40;\n hasUnClicked = !hasUnClicked;\n }\n\n //Update player column, unless the user has sped up the block fall (clicked it), or if the column is blocked\n if (mouse.xx > -1 && mouse.xx < cellsHorizontal && gameBlockSpeedFall === 1) {\n if (playGrid[mouse.xx][player.y] === 0 && playGrid[mouse.xx][player.y + 1] === 0) {\n player.x = mouse.xx;\n }\n }\n\n //Fall the player block\n if (aniPerc > 100) {\n player.y += 1;\n aniPerc -= 100;\n }\n\n //Has the player block hit something?\n if (playGrid[player.x][player.y + 1] !== 0 || player.y >= cellsVertical) {\n\n //Has it hit the top level? Game Over\n if (player.y <= 1) {\n playGrid.forEach((array, x) => {\n array.forEach((cell, y) => {\n playGrid[x][y] = 0;\n return;\n })\n })\n }\n\n //Process block collision\n gameBlockSpeedFall = 1;\n playerAlive = false;\n playGrid[player.x][player.y] = player.num;\n gameQueue.push({ type: \"check\", x: player.x, y: player.y });\n lastCellPos = player.x;\n }\n }\n else if (gameQueue[0].type === \"check\") {\n playerAlive = false;\n\n //X and Y for current cell\n const x = gameQueue[0].x;\n const y = gameQueue[0].y;\n\n //Save positions of all cells that the current cell will be multiplied with\n let matches = [];\n [0, 1, 2, 3].forEach((dir) => {\n const otherCell = getCellByDir(x, y, dir);\n if (isBlockSame(x, y, otherCell.x, otherCell.y)) {\n matches.push(getCellByDir(x, y, dir));\n }\n });\n\n //if any multiplication oppurtunities were found\n if (matches.length > 0) {\n\n //Queue all the blocks to be merged\n const mergeArray = [];\n const fallArray = []\n matches.forEach((cell) => {\n\n mergeArray.push({ oldX: cell.x, oldY: cell.y, newX: x, newY: y, num: playGrid[cell.x][cell.y] });\n //If there is a block above the block-to-be-deleted, add it to the falling queue\n /*if (playGrid[cell.x][cell.y - 1] !== 0) fallArray.push({ x: cell.x, y: cell.y - 1, num: playGrid[cell.x][cell.y - 1] })*/\n playGrid[cell.x][cell.y] = 0;\n\n });\n gameQueuePush({ type: \"merge\", array: mergeArray });\n gameQueuePush({ type: \"multiply\", x: x, y: y, to: Math.pow(2, matches.length) * playGrid[x][y] })\n fallArray.forEach((item) => {\n //gameQueuePush({type: \"fall\", x: item.x, y: item.y, num: item.num});\n });\n\n }\n\n gameQueueShift();\n }\n else if (gameQueue[0].type === \"merge\") {\n playerAlive = false;\n\n percent += mergeSpeed;\n if (percent > 1) {\n percent = 0;\n gameQueue[0].array.forEach((item) => {\n\n //If block has merged into another (moved), check if there was a block on top of it, and add to fall array\n if (playGrid[item.oldX][item.oldY - 1] !== 0 && item.newY !== item.oldY - 1) {\n gameQueuePush({ type: \"fall\", x: item.oldX, y: item.oldY - 1, num: playGrid[item.oldX][item.oldY - 1] })\n }\n })\n\n //Merge is done\n gameQueueShift();\n }\n }\n else if (gameQueue[0].type === \"multiply\") {\n playerAlive = false;\n percent += multiplySpeed;\n\n if (percent > 1) {\n percent = 0;\n playGrid[gameQueue[0].x][gameQueue[0].y] = gameQueue[0].to;\n\n //If, as a result of the merger, the block can now fall, add it to the fall array\n if (playGrid[gameQueue[0].x][gameQueue[0].y + 1] === 0) {\n gameQueuePush({ type: \"fall\", x: gameQueue[0].x, y: gameQueue[0].y, num: playGrid[gameQueue[0].x][gameQueue[0].y] });\n } else {\n //Now that the number on the block is different, check it again for potential new matches\n gameQueuePush({ type: \"check\", x: gameQueue[0].x, y: gameQueue[0].y })\n }\n\n\n\n //Multiply is done\n gameQueueShift();\n }\n\n\n }\n else if (gameQueue[0].type === \"fall\") {\n const x = gameQueue[0].x;\n const y = gameQueue[0].y;\n if (percent === 0) {\n playerAlive = false;\n playGrid[x][y] = 0;\n }\n\n percent += mergeSpeed;\n if (percent > 1) {\n percent = 0;\n playGrid[x][y + 1] = gameQueue[0].num;\n //Add new position to be checked\n gameQueuePush({ type: \"check\", x: x, y: y + 1 })\n\n //If the fall made another block fall as a consequence, add that block to fall\n if (playGrid[x][y - 1] !== 0) {\n gameQueuePush({ type: \"fall\", x: x, y: y - 1, num: playGrid[x][y - 1] });\n }\n\n //Now that the fall is complete, add a check step to see if theres any new mergers to be done in the new position\n gameQueuePush({ type: \"check\", x: x, y: y + 1 })\n\n //Fall is done\n gameQueueShift();\n }\n }\n\n // Perform the drawing operation\n draw();\n\n // The loop function has reached it's end. Keep requesting new frames\n window.requestAnimationFrame(gameLoop);\n}", "getCurrentBufferEnd () {\n return this._getBufferEnd(this.video.buffered, this.video.currentTime);\n }", "function setupSound() {\n sound = audioContext.createBufferSource();\n sound.buffer = sampleBuffer;\n sound.loop = loop; //auto is false\n sound.playbackRate.value = playbackSlider.value;\n\n analyser.smoothingTimeConstant = .85, //0<->1. 0 is no time smoothing\n analyser.fftSize = 2048, //must be some number by the power of 2, ex. 512\n analyser.minDecibels = -150,\n analyser.maxDecibels = -10,\n\n sound.connect(filter); //can connect more than one to a node, as long as it all ends up at destination\n \n //connect source/sound var to the gain node\n filter.connect(gainNode);\n filter.connect(analyser);\n analyser.connect(scriptProcessorNode);\n scriptProcessorNode.connect(gainNode);\n gainNode.connect(panNode);\n //connect pan node to the destination (a.k.a. the speakers)\n panNode.connect(audioContext.destination);\n \n //frequencyBinCount property of the analyserNode interface is an unsigned long value half that of the fft size -MDN\n bufferLength = analyser.frequencyBinCount; \n\n //animate the bars\n scriptProcessorNode.onaudioprocess = function (audioProcessingEvent) {\n array = new Uint8Array(bufferLength);\n analyser.getByteFrequencyData(array);\n\n boost = 0;\n for (var i = 0; i < array.length; i++) {\n boost += array[i];\n }\n boost = boost / array.length;\n\n var step = Math.round(array.length / numBars);\n\n //iterate through bars and scale the z axis\n for (var i = 0; i < numBars; i++) {\n var value = array[i * step] / 4;\n value = value < 1 ? 1 : value;\n bars[i].scale.z = value;\n }\n }\n}", "receive(isample) {\n let lastr = this._lastr;\n let lasti = this._lasti;\n\n let space = this._sf.updatex(isample);\n let mark = this._mf.updatex(isample);\n let r = space.r + mark.r;\n let i = space.i + mark.i;\n let x = r * lastr - i * lasti;\n let y = r * lasti + i * lastr;\n this._lastr = r; // save the conjugate\n this._lasti = -i;\n let angle = Math.atan2(y, x); // arg\n let comp = (angle > 0) ? -10.0 : 10.0;\n let sig = this._dataFilter.update(comp);\n // console.log('sig:' + sig + ' comp:' + comp)\n\n this.scopeOut(sig);\n\n let bit = this._bit;\n\n // trace('sig:' + sig)\n if (sig > this._hiHys) {\n bit = false;\n } else if (sig < this._loHys) {\n bit = true;\n }\n\n bit = bit !== this._inverted; // user-settable\n\n this.processBit(bit);\n this._bit = bit;\n }", "function JsAudio(myConsole) {\n var audio = this;\n\n var CPU_SPEED = 1193191.66666667; //6502 speed is 1.19 MHz (million cycles /sec)\n\n var JAVA_SOUND_SAMPLE_RATE = 44100; //44,100 samples/sec\n var TIA_SAMPLE_RATE = 31400;\n\n var CYCLES_PER_SAMPLE = CPU_SPEED / (JAVA_SOUND_SAMPLE_RATE * 1.0); //27.056\n\n // *** AUDIO FORMAT CONSTANTS ***\n var BYTES_PER_SAMPLE = 1;\n var BITS_PER_SAMPLE = BYTES_PER_SAMPLE * 8;\n var BIG_ENDIAN = true;\n var SIGNED_VALUE = true;\n var CHANNELS = 1;\n\n // *** AUDIO BUFFER MANAGEMENT ***\n var DEFAULT_BUFFER_CUSHION = 4000; //samples left in buffer to prevent underflow\n\n var myAudio = null;\n var myWave = new RIFFWAVE();\n\n //Misc\n var myPreOutputBuffer = new Array(JAVA_SOUND_SAMPLE_RATE * 4);\n var myInitSuccess = false;\n\n // Poke/Queue related variables\n // private java.util.Queue<AudioRegisterPoke> myPokeQueue=new java.util.ArrayDeque<AudioRegisterPoke>(); //J6SE only\n var myPokeQueue = new Queue(); //J5SE\n\n var myExcessCycles = 0;\n var myCyclePool = 0;\n var myPreviousCycle = 0;\n var myPreviousPoke = null;\n\n //Audio registers\n var myAUDC = new Array(2);\n var myAUDF = new Array(2);\n var myAUDV = [1, 1];\n\n var myFutureAUDC = new Array(2);\n var myFutureAUDF = new Array(2);\n var myFutureAUDV = new Array(2);\n\n //Synthesis related variables\n var myFrequencyDivider = [new FrequencyDivider(), new FrequencyDivider()]; //[2]; // Frequency dividers\n var myP4 = new Array(2); // 4-bit register LFSR (lower 4 bits used)\n var myP5 = new Array(2); // 5-bit register LFSR (lower 5 bits used)\n var myOutputCounter = 0;\n\n //CONFIG variables\n var myChannels = CHANNELS;\n var myVolumePercentage = 100;\n var myVolumeClip = 128;\n var myNominalDisplayFrameRate = 60;\n var myRealDisplayFrameRate = 60.0;\n var myCycleSampleFactor = 1.0;\n var myAdjustedCyclesPerAudioFrame = CYCLES_PER_SAMPLE;\n //private int myWholeCyclesPerAudioFrame=(int)(CYCLES_PER_SAMPLE / CHANNELS);\n\n var myBufferCushion = DEFAULT_BUFFER_CUSHION * myChannels;\n\n var mySoundEnabled = true;\n\n audio.isSoundEnabled = function () { return mySoundEnabled; }\n\n audio.setVolume = function (percent) { myVolumePercentage = percent; }\n\n audio.setSoundEnabled = function (aSoundEnabled) {\n /* if (aSoundEnabled!=mySoundEnabled)\n {\n reset();\n }//end : change in value\n */\n\n //TODO : better system of figuring out if sound is open/active, and informing user of this\n /*\n if ((mySDLine != null) && (mySDLine.isOpen())) {\n //if (aSoundEnabled==true) mySDLine.start();\n if (aSoundEnabled == false) {\n mySDLine.stop();\n mySDLine.flush();\n }\n } //end : not null\n */\n\n if (myAudio != null) {\n if (aSoundEnabled)\n myAudio.play();\n else\n myAudio.pause();\n }\n\n mySoundEnabled = aSoundEnabled;\n }\n\n audio.pauseAudio = function () {\n /*\n //TODO : a more elegant way of stopping audio temporarily, to keep clicks, etc from occuring during a pause\n if (mySDLine!=null) mySDLine.stop(); \n */\n\n myAudio.pause();\n }\n\n\n /**\n * Sets the nominal (theoretical) display frame rate. This is usually 60 or 50.\n * See documentation for setRealDisplayFrameRate(...).\n * @param aFrameRate \n */\n audio.setNominalDisplayFrameRate = function (aFrameRate) {\n myNominalDisplayFrameRate = aFrameRate;\n myPreviousCycle = 0; //? (JLA)\n updateCycleSampleFactor();\n }\n\n /**\n * The sound object bases its frequency on the display's frame rate. If the game\n * was designed for 60 frames per second display rate, then it expects to be\n * called that many times per second to accurately produce the correct pitch.\n * Because the timers that are used to run the emulator use \"millisecond deley\" rather\n * than \"frequency\", certain frame rates can only be approximated. \n * For example, a delay of 16 ms is 62.5 frames per second, and a delay of 17 ms\n * is 58.82 frames per second. \n * To remedy this approximation, the class responsible for timing will notify\n * this class (via JSConsole) to compensate for this inexact.\n * @param aRealFrameRate \n */\n audio.setRealDisplayFrameRate = function (aRealFrameRate) {\n myRealDisplayFrameRate = aRealFrameRate;\n updateCycleSampleFactor();\n }\n\n function updateCycleSampleFactor() {\n myCycleSampleFactor = myRealDisplayFrameRate / (myNominalDisplayFrameRate * 1.0);\n\n myAdjustedCyclesPerAudioFrame = CYCLES_PER_SAMPLE * myCycleSampleFactor;\n }\n\n audio.systemCyclesReset = function (aCurrentCycle) {\n myPreviousCycle -= aCurrentCycle;\n }\n\n /**\n * Used when user is saving game (aka a state save). The only data from this class\n * that needs to be saved are the contents of the registers. (Sometimes a game\n * will set the register early on and not touch it again.) This is called\n * during the serialization method of JSConsole.\n * @return The audio register data in array form.\n */\n audio.getAudioRegisterData = function () {\n var zReturn = new Array(6);\n zReturn[0] = myAUDC[0];\n zReturn[1] = myAUDC[1];\n zReturn[2] = myAUDF[0];\n zReturn[3] = myAUDF[1];\n zReturn[4] = myAUDV[0];\n zReturn[5] = myAUDV[1];\n return zReturn;\n }\n\n /**\n * This is the opposite of the getAudioRegisterData() method. It is called \n * by JSConsole after a saved game has been read.\n * @param aData an array of the register values\n */\n audio.setAudioRegisterData = function (aData) {\n setAudioRegister(AUDC0, aData[0]);\n setAudioRegister(AUDC1, aData[1]);\n setAudioRegister(AUDF0, aData[2]);\n setAudioRegister(AUDF1, aData[3]);\n setAudioRegister(AUDV0, aData[4]);\n setAudioRegister(AUDV1, aData[5]);\n }\n\n /**\n * Changes the audio mode to either mono (channels=1), or stereo (channels=2).\n * @param aChannels Number of channels (1 or 2)\n */\n audio.setChannelNumber = function (aChannels) {\n //assert((aChannels==1)||(aChannels==2));\n\n if (myChannels != aChannels) //is a change\n {\n myChannels = aChannels;\n audio.initialize();\n\n } //end : changing value\n }\n\n /**\n * Returns the number of channels the audio system is using.\n * @return returns a 1 for mono, 2 for stereo\n */\n audio.getChannelNumber = function () {\n return myChannels;\n }\n\n /**\n * Closes the sound, freeing up system sound resources.\n */\n audio.close = function () {\n try {\n if (myAudio != null)\n myAudio.pause();\n\n } //end : try\n catch (msg) {\n //TODO : better exception handling\n alert(msg);\n }\n }\n\n /**\n * Initializes the sound. After calling this, one should make sure that\n * close() is called when this class is finished.\n */\n audio.initialize = function () {\n try {\n var zPreviouslyEnabled = mySoundEnabled;\n mySoundEnabled = false; //just in case...\n\n\n //Step 0 - get rid of old sound system, if one exists\n if (myAudio != null) {\n myAudio.pause();\n myAudio = null;\n } //end : old one exists\n\n clearPokeQueue();\n\n //Step 1 - establish what format we're going to use\n //myAudioFormat = new AudioFormat((JAVA_SOUND_SAMPLE_RATE * 1.0), BITS_PER_SAMPLE, myChannels, SIGNED_VALUE, BIG_ENDIAN);\n myWave.header.sampleRate = JAVA_SOUND_SAMPLE_RATE;\n myWave.header.bitsPerSample = BITS_PER_SAMPLE;\n myWave.header.numChannels = myChannels;\n //System.out.println(\"AudioFormat - sampleRate=\" + myAudioFormat.getSampleRate() + \", framerate=\" + myAudioFormat.getFrameRate());\n\n //Step 2 - acquire a Source Data Line\n //var zDLI=new DataLine.Info(SourceDataLine.class, myAudioFormat);\n //System.out.println(\"Acquiring source data line info - \" + zDLI);\n //mySDLine=(SourceDataLine)AudioSystem.getLine(zDLI);\n\n //Step 3 - open and start that Source Data Line object\n //mySDLine.open(myAudioFormat);\n //mySDLine.start();\n myInitSuccess = true;\n\n mySoundEnabled = zPreviouslyEnabled;\n myBufferCushion = DEFAULT_BUFFER_CUSHION * myChannels;\n updateCycleSampleFactor();\n\n } //end : try\n catch (msg) {\n\n //TODO : some type of notification that audio wasn't available\n myInitSuccess = false;\n\n } //end : catch - Line Unavailable\n }\n\n /**\n * Checks to see if the required Java Sound objects were created successfully.\n * @return true if sound objects created successfully\n */\n audio.isSuccessfullyInitialized = function () {\n return myInitSuccess;\n }\n\n audio.reset = function () {\n myPreviousCycle = 0;\n\n clearPokeQueue();\n myAUDC[0] = myAUDC[1] = myAUDF[0] = myAUDF[1] = myAUDV[0] = myAUDV[1] = 0;\n myFutureAUDC[0] = myFutureAUDC[1] = myFutureAUDF[0] = myFutureAUDF[1] = myFutureAUDV[0] = myFutureAUDV[1] = 0;\n myP4[0] = myP5[0] = myP4[1] = myP5[1] = 1;\n myFrequencyDivider[0].set(0);\n myFrequencyDivider[1].set(0);\n myOutputCounter = 0;\n }\n\n\n // ==================== AUDIO REGISTER METHODS ======================\n /**\n * This is the method that actually changes the sound register\n * variables. It is called by processPokeQueue(...) shortly before\n * process(...) is called.\n * @param address Address of a sound register\n * @param value The value to assign to the given register\n */\n function setAudioRegister(address, value) {\n switch (address) {\n case 0x15: myAUDC[0] = value & 0x0f; break;\n case 0x16: myAUDC[1] = value & 0x0f; break;\n\n case 0x17:\n myAUDF[0] = value & 0x1f;\n myFrequencyDivider[0].set(myAUDF[0]);\n break;\n\n case 0x18:\n myAUDF[1] = value & 0x1f;\n myFrequencyDivider[1].set(myAUDF[1]);\n break;\n\n case 0x19: myAUDV[0] = value & 0x0f; break;\n case 0x1a: myAUDV[1] = value & 0x0f; break;\n default: break;\n }\n }\n\n function getAudioRegister(address) {\n switch (address) {\n case 0x15: return myAUDC[0];\n case 0x16: return myAUDC[1];\n case 0x17: return myAUDF[0];\n case 0x18: return myAUDF[1];\n case 0x19: return myAUDV[0];\n case 0x1a: return myAUDV[1];\n default: return 0;\n }\n }\n\n function setFutureAudioRegister(address, value) {\n switch (address) {\n case 0x15: myFutureAUDC[0] = value & 0x0f; break;\n case 0x16: myFutureAUDC[1] = value & 0x0f; break;\n case 0x17: myFutureAUDF[0] = value & 0x1f; break;\n case 0x18: myFutureAUDF[1] = value & 0x1f; break;\n case 0x19: myFutureAUDV[0] = value & 0x0f; break;\n case 0x1a: myFutureAUDV[1] = value & 0x0f; break;\n default: break;\n }\n }\n\n function getFutureAudioRegister(address) {\n switch (address) {\n case 0x15: return myFutureAUDC[0];\n case 0x16: return myFutureAUDC[1];\n case 0x17: return myFutureAUDF[0];\n case 0x18: return myFutureAUDF[1];\n case 0x19: return myFutureAUDV[0];\n case 0x1a: return myFutureAUDV[1];\n default: return 0;\n }\n }\n\n // ================= MAIN SYNTHESIS METHOD =====================\n function bool(aValue) {\n return (aValue != 0);\n }\n\n /**\n * This method creates sound samples based on the current settings of the\n * TIA sound registers.\n * @param buffer the array into which the newly calculated byte values are to be placed\n * @param aStartIndex the array index at which the method should start placing the samples\n * @param samples the number of samples to create\n */\n function synthesizeAudioData(aPreOutputBuffer, aStartIndex, aAudioFrames) {\n // int zSamplesToProcess=aSamplesPerChannel;\n var zSamples = aAudioFrames * myChannels;\n var zVolChannelZero = Math.floor(((myAUDV[0] << 2) * myVolumePercentage) / 100);\n var zVolChannelOne = Math.floor(((myAUDV[1] << 2) * myVolumePercentage) / 100);\n var zIndex = aStartIndex;\n // Loop until the sample buffer is full\n while (zSamples > 0) {\n // Process both TIA sound channels\n for (var c = 0; c < 2; ++c) {\n // Update P4 & P5 registers for channel if freq divider outputs a pulse\n if ((myFrequencyDivider[c].clock())) {\n switch (myAUDC[c]) {\n case 0x00: // Set to 1\n { // Shift a 1 into the 4-bit register each clock\n myP4[c] = (myP4[c] << 1) | 0x01;\n break;\n }\n\n case 0x01: // 4 bit poly\n {\n // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2\n myP4[c] = bool(myP4[c] & 0x0f) ? ((myP4[c] << 1) | ((bool(myP4[c] & 0x08) ? 1 : 0) ^ (bool(myP4[c] & 0x04) ? 1 : 0))) : 1;\n break;\n }\n\n case 0x02: // div 31 . 4 bit poly\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // This does the divide-by 31 with length 13:18\n if ((myP5[c] & 0x0f) == 0x08) {\n // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2\n myP4[c] = bool(myP4[c] & 0x0f) ? ((myP4[c] << 1) | ((bool(myP4[c] & 0x08) ? 1 : 0) ^ (bool(myP4[c] & 0x04) ? 1 : 0))) : 1;\n }\n break;\n }\n\n case 0x03: // 5 bit poly . 4 bit poly\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // P5 clocks the 4 bit poly\n if (bool(myP5[c] & 0x10)) {\n // Clock P4 as a standard 4-bit LSFR taps at bits 3 & 2\n myP4[c] = bool(myP4[c] & 0x0f) ? ((myP4[c] << 1) | ((bool(myP4[c] & 0x08) ? 1 : 0) ^ (bool(myP4[c] & 0x04) ? 1 : 0))) : 1;\n }\n break;\n }\n\n case 0x04: // div 2\n {\n // Clock P4 toggling the lower bit (divide by 2)\n myP4[c] = (myP4[c] << 1) | (bool(myP4[c] & 0x01) ? 0 : 1);\n break;\n }\n\n case 0x05: // div 2\n {\n // Clock P4 toggling the lower bit (divide by 2)\n myP4[c] = (myP4[c] << 1) | (bool(myP4[c] & 0x01) ? 0 : 1);\n break;\n }\n\n case 0x06: // div 31 . div 2\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // This does the divide-by 31 with length 13:18\n if ((myP5[c] & 0x0f) == 0x08) {\n // Clock P4 toggling the lower bit (divide by 2)\n myP4[c] = (myP4[c] << 1) | (bool(myP4[c] & 0x01) ? 0 : 1);\n }\n break;\n }\n\n case 0x07: // 5 bit poly . div 2\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // P5 clocks the 4 bit register\n if (bool(myP5[c] & 0x10)) {\n // Clock P4 toggling the lower bit (divide by 2)\n myP4[c] = (myP4[c] << 1) | (bool(myP4[c] & 0x01) ? 0 : 1);\n }\n break;\n }\n\n case 0x08: // 9 bit poly\n {\n // Clock P5 & P4 as a standard 9-bit LSFR taps at 8 & 4\n myP5[c] = (bool(myP5[c] & 0x1f) || bool(myP4[c] & 0x0f)) ? ((myP5[c] << 1) | ((bool(myP4[c] & 0x08) ? 1 : 0) ^ (bool(myP5[c] & 0x10) ? 1 : 0))) : 1;\n myP4[c] = (myP4[c] << 1) | (bool(myP5[c] & 0x20) ? 1 : 0);\n break;\n }\n\n case 0x09: // 5 bit poly\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // Clock value out of P5 into P4 with no modification\n myP4[c] = (myP4[c] << 1) | (bool(myP5[c] & 0x20) ? 1 : 0);\n break;\n }\n\n case 0x0a: // div 31\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // This does the divide-by 31 with length 13:18\n if ((myP5[c] & 0x0f) == 0x08) {\n // Feed bit 4 of P5 into P4 (this will toggle back and forth)\n myP4[c] = (myP4[c] << 1) | (bool(myP5[c] & 0x10) ? 1 : 0);\n }\n break;\n }\n\n case 0x0b: // Set last 4 bits to 1\n {\n // A 1 is shifted into the 4-bit register each clock\n myP4[c] = (myP4[c] << 1) | 0x01;\n break;\n }\n\n case 0x0c: // div 6\n {\n // Use 4-bit register to generate sequence 000111000111\n myP4[c] = (~myP4[c] << 1) | ((!(!bool(myP4[c] & 4) && (bool(myP4[c] & 7)))) ? 0 : 1);\n break;\n }\n\n case 0x0d: // div 6\n {\n // Use 4-bit register to generate sequence 000111000111\n myP4[c] = (~myP4[c] << 1) | ((!(!bool(myP4[c] & 4) && (bool(myP4[c] & 7)))) ? 0 : 1);\n break;\n }\n\n case 0x0e: // div 31 . div 6\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // This does the divide-by 31 with length 13:18\n if ((myP5[c] & 0x0f) == 0x08) {\n // Use 4-bit register to generate sequence 000111000111\n myP4[c] = (~myP4[c] << 1) | ((!(!bool(myP4[c] & 4) && (bool(myP4[c] & 7)))) ? 0 : 1);\n }\n break;\n }\n\n case 0x0f: // poly 5 . div 6\n {\n // Clock P5 as a standard 5-bit LSFR taps at bits 4 & 2\n myP5[c] = bool(myP5[c] & 0x1f) ? ((myP5[c] << 1) | ((bool(myP5[c] & 0x10) ? 1 : 0) ^ (bool(myP5[c] & 0x04) ? 1 : 0))) : 1;\n\n // Use poly 5 to clock 4-bit div register\n if (bool(myP5[c] & 0x10)) {\n // Use 4-bit register to generate sequence 000111000111\n myP4[c] = (~myP4[c] << 1) | ((!(!bool(myP4[c] & 4) && (bool(myP4[c] & 7)))) ? 0 : 1);\n }\n break;\n }\n }\n }\n }\n\n myOutputCounter += JAVA_SOUND_SAMPLE_RATE;\n\n if (myChannels == 1) {\n // Handle mono sample generation\n while ((zSamples > 0) && (myOutputCounter >= TIA_SAMPLE_RATE)) {\n var zChannelZero = (bool(myP4[0] & 8) ? zVolChannelZero : 0); //if bit3 is on, amplitude is the volume, otherwise amp is 0\n var zChannelOne = (bool(myP4[1] & 8) ? zVolChannelOne : 0);\n var zBothChannels = zChannelZero + zChannelOne + myVolumeClip;\n aPreOutputBuffer[zIndex] = (zBothChannels - 128) & 0xFF; // we are using a signed byte, which has a min. of -128\n\n myOutputCounter -= TIA_SAMPLE_RATE;\n zIndex++;\n zSamples--;\n //assert(zIndex<=aStartIndex + zSamplesToProcess);\n\n }\n }\n else {\n // Handle stereo sample generation\n while ((zSamples > 0) && (myOutputCounter >= TIA_SAMPLE_RATE)) {\n var zChannelZero = (bool(myP4[0] & 8) ? zVolChannelZero : 0) + myVolumeClip; //if bit3 is on, amplitude is the volume, otherwise amp is 0\n var zChannelOne = (bool(myP4[1] & 8) ? zVolChannelOne : 0) + myVolumeClip;\n //int zBothChannels=zChannelZero + zChannelOne + myVolumeClip;\n\n aPreOutputBuffer[zIndex] = (zChannelZero - 128) & 0xFF; // we are using a signed byte, which has a min. of -128\n zIndex++;\n zSamples--;\n\n aPreOutputBuffer[zIndex] = (zChannelOne - 128) & 0xFF;\n zIndex++;\n zSamples--;\n\n myOutputCounter -= TIA_SAMPLE_RATE;\n }\n }\n }\n }\n\n /**\n * This takes register values off the register queue and submits them to the process of\n * sample creation by calling the process(...) method.\n *\n * This is called by the doFrameAudio() method, which is called once per frame.\n * <b>\n * When the ROM tells the CPU to poke the sound registers in the TIA, the TIA forwards\n * the data to this class (to the set() method). Instead of setting the register\n * variables immediately, it saves the poke data as a AudioRegisterPoke object and puts it\n * in a queue object. The processPokeQueue method takes these one-by-one off the front\n * of the queue and, one-by-one, sets the register variables, and calls the process(...)\n * method, creating a sound with a sample length corresponding to the number of\n * processor cycles that elapsed between it and the sound register change after\n * it.\n * @return total number of samples created\n */\n function processPokeQueue() {\n assert(myPokeQueue.getSize() > 0);\n var zCurrentBufferIndex = 0;\n var zEndOfFrame = false;\n\n while (zEndOfFrame == false) {\n var zRW = myPokeQueue.dequeue();\n if ((zRW == null)) {\n zEndOfFrame = true;\n }\n\n if (zRW != null) {\n assert(zRW.myDeltaCycles >= 0);\n\n if (zRW.myAddr != 0)\n setAudioRegister(zRW.myAddr, zRW.myByteValue);\n\n myCyclePool += zRW.myDeltaCycles;\n // if (myCyclePool>=CYCLE_COUNT_CUTOFF) {\n var zAudioFramesInPool = myCyclePool / myAdjustedCyclesPerAudioFrame;\n var zWholeAudioFramesInPool = Math.floor(zAudioFramesInPool);\n myCyclePool = myCyclePool - (zWholeAudioFramesInPool * myAdjustedCyclesPerAudioFrame * 1.0);\n //myCyclePool= myCyclePool % myWholeCyclesPerAudioFrame; //the new cycle count is the remainder from the division\n\n // dbgout(\"Processing --frame=\" + zRW.myDebugFrameCounter +\", #=\" + zRW.myDebugCounter + \", \" + zSamplesInBunch + \" samples/pool, zDeltaCycles==\" + zRW.myDeltaCycles);\n synthesizeAudioData(myPreOutputBuffer, zCurrentBufferIndex, zWholeAudioFramesInPool);\n zCurrentBufferIndex += (zWholeAudioFramesInPool * myChannels); //each samples is represented by a single byte in myAudioBuffer\n // }//end : met the threshold\n }\n var zNextARP = myPokeQueue.getOldestElement();\n if ((zNextARP == null) || (zNextARP.myFrameEnd == true)) zEndOfFrame = true;\n }\n\n return zCurrentBufferIndex;\n }\n\n /**\n * A very imperfect method that plays the sound information that has accumulated over\n * the past video frame.\n * @param aCycles the current CPU system cycle count\n * @param aFPS the console's framerate, in frames per second\n */\n audio.doFrameAudio = function (aCycles, aFPS) {\n\n\n return;\n\n\n if (audio.isSoundEnabled() == true) {\n //STEP 1 : add an 'end of frame' signal to the poke queue\n addPokeToQueue(true, aCycles, 0, 0); //indicates the end of a frame\n\n //STEP 2 : turn a frame's worth of poke objects into audio data (in the myPreOutputBuffer)\n zSamples = processPokeQueue();\n\n /*\n zBufferSize = mySDLine.getBufferSize();\n zAvailable = mySDLine.available();\n zInBuffer = zBufferSize - zAvailable;\n\n\n //STEP 3 : send audio data to the audio system (i.e. play the sound)\n\n\n\n //CURRENT SYSTEM OF BUFFER MANAGEMENT :\n //This assumes the actual emulator is running fastor than the nominal CPU speed, thus gradually filling up\n //the SDL sound buffer (not to be confused with myPreOutputBuffer). It just limits the number of samples that\n //actually make it into the play buffer. It doesn't affect the number of samples processed, as this might\n //affect the frequency (pitch) of music.\n\n zPercentFull = 100.0 * (zInBuffer / zBufferSize); //used in debugging\n\n var zToPlay = Math.min(myBufferCushion - zInBuffer, zSamples);\n zToPlay = Math.max(0, zToPlay); //Make sure it's zero or greater\n if (myChannels == 2) zToPlay = roundToEven(zToPlay); //make sure it's even if it's stereo\n */\n\n /*\n if (mySDLine.isRunning() == false) mySDLine.start();\n\n mySDLine.write(myPreOutputBuffer, 0, zToPlay); //Math.min(zSamples,zAvail)); //This sends the samples to the play buffer - out of the programmer's hands after this point\n */\n\n myAudio = new Audio();\n var buffer = myPreOutputBuffer.slice(0, zSamples);\n myWave.Make(buffer);\n myAudio.src = myWave.dataURI;\n myAudio.play();\n\n }\n }\n\n function roundToEven(aNumber) {\n //return (aNumber / 2) * 2; \n return (aNumber % 2 != 0) ? (aNumber - 1) : aNumber;\n }\n\n function clearPokeQueue() {\n myPokeQueue = new Queue();\n addPokeToQueue(true, 0, 0, 0); //Add a 1-frame lag\n }\n\n function addPokeToQueue(aFrameEnd, aCycleNumber, aAddress, aByteValue) {\n //STEP 1 : Determine how many cycles have elapsed since last poke and assign that to previous poke (in queue)\n var zDeltaCycles = aCycleNumber - myPreviousCycle;\n if (myPreviousPoke != null) myPreviousPoke.myDeltaCycles = zDeltaCycles; //setting delta cycles on previous one\n\n //STEP 2 : Determine if this poke is actually changing any values\n var zValueToOverwrite = getFutureAudioRegister(aAddress);\n\n //STEP 3 : If poke is a new value or this is the end of a frame, add a poke object to queue\n //I'm not sure how necessary this whole only-add-if-different-value thing is...I just thought it might be good if ((zValueToOverwrite!=aByteValue)||(aFrameEnd==true)) \n //{ \n var zRW = new AudioRegisterPoke(aFrameEnd, aAddress, aByteValue);\n myPokeQueue.enqueue(zRW);\n setFutureAudioRegister(aAddress, aByteValue);\n myPreviousPoke = zRW;\n myPreviousCycle = aCycleNumber;\n\n //}//end : new value for future reg\n //\n }\n\n /**\n * This method is called by TIA when it receives a poke command destined for a\n * sound register. This is the method that converts the data received into a\n * AudioRegisterPoke object and stores that object on a queue for later processing.\n * Check out the processPokeQueue(...) description for details.\n * @param addr address to poke\n * @param aByteValue byte value of the poke\n * @param cycle the CPU system cycle number\n * @see processPokeQueue(int, int, int)\n */\n audio.pokeAudioRegister = function (addr, aByteValue, cycle) {\n if (audio.isSoundEnabled() == true) {\n addPokeToQueue(false, cycle, addr, aByteValue);\n }\n }\n\n //=============================================================================\n //========================== INNER CLASSES ====================================\n //=============================================================================\n function FrequencyDivider() {\n //private final static long serialVersionUID = 8982487492473260236L;\n var myDivideByValue = 0;\n var myCounter = 0;\n var fd = this;\n\n fd.set = function (divideBy) { myDivideByValue = divideBy; }\n fd.clock = function () {\n myCounter++;\n if (myCounter > myDivideByValue) {\n myCounter = 0;\n return true;\n }\n return false;\n }\n }\n\n function AudioRegisterPoke(aFrameEnd, aAddr, aByteValue) {\n // private final static long serialVersionUID = -4187197137229151004L;\n var arp = this;\n arp.myAddr = aAddr;\n arp.myByteValue = aByteValue;\n arp.myDeltaCycles = 0;\n arp.myFrameEnd = aFrameEnd;\n }\n\n //NOTE : when actual frame rate is below the theoretical audio frame rate, you get a buffer underrun -> popping noises\n // when actual frame rate is significantly above the theoretical fps, you get too much cut out by the compensation,\n //which causes a sort of singing-on-a-bumpy-road effect...\n\n\n audio.debugSetReg = function (address, value) {\n setAudioRegister(address, value);\n }\n\n function dbgout(aOut) {\n System.out.println(\"DEBUG: \" + aOut);\n }\n\n /**\n * Occasionally good for debugging, but ultimately, this method must go.\n * @param aTimerDelay\n * @deprecated\n */\n audio.debugPlayChunk = function (aTimerDelay) {\n var zSamples = Math.floor(((JAVA_SOUND_SAMPLE_RATE / 1000.0) * aTimerDelay));\n\n if (zSamples > myPreOutputBuffer.length) zSamples = myPreOutputBuffer.length;\n synthesizeAudioData(myPreOutputBuffer, 0, zSamples);\n var zAvail = mySDLine.available();\n\n mySDLine.write(myPreOutputBuffer, 0, Math.min(zSamples, zAvail));\n }\n\n audio.debugGetSourceDataLine = function () {\n return mySDLine;\n }\n\n audio.reset();\n}", "function addEqualiser() {\n\n var gainDb = -40.0; // atenuation When it takes a positive value it is a real gain, when negative it is an attenuation. It is expressed in dB, has a default value of 0 and can take a value in a nominal range of -40 to 40.\n var bandSplit = [360, 3600];\n context_player = new AudioContext();\n\n for (var i = 0; i < 2; i++) {\n\n mediaElement_player.push(null);\n sourceNode_player.push(null);\n source_player.push(null);\n lGain_player.push(null);\n mGain_player.push(null);\n hGain_player.push(null);\n sum_player.push(null);\n volumeNodes.push(null);\n\n\n mediaElement_player[i] = document.getElementById('jp_audio_' + i);\n source_player[i] = context_player.createMediaElementSource(mediaElement_player[i]);\n\n initFrequencyQuality(i);\n\n // affects the ammount of treble in a sound - treble knob - atenuates the sounds below the 3600 frequencies\n var lBand_player = context_player.createBiquadFilter();\n lBand_player.type = \"lowshelf\";\n lBand_player.frequency.value = bandSplit[1];\n lBand_player.gain.value = gainDb;\n\n // affects the ammount of bass in a sound - bass knob - atenuates the sounds higher than 360 frequencies\n var hBand_player = context_player.createBiquadFilter();\n hBand_player.type = \"highshelf\";\n hBand_player.frequency.value = bandSplit[0];\n hBand_player.gain.value = gainDb;\n\n var hInvert_player = context_player.createGain();\n hInvert_player.gain.value = -1.0;\n\n //Subtract low and high frequencies (add invert) from the source for the mid frequencies\n var mBand_player = context_player.createGain();\n\n //or use picking\n //mBand_player = context_player.createBiquadFilter();\n //mBand_player.type = \"peaking\";\n //mBand_player.frequency.value = bandSplit[0];\n //mBand_player.gain.value = gainDb;\n\n var lInvert_player = context_player.createGain();\n lInvert_player.gain.value = -1.0;\n\n sourceNode_player[i].connect(lBand_player);\n sourceNode_player[i].connect(mBand_player);\n sourceNode_player[i].connect(hBand_player);\n\n hBand_player.connect(hInvert_player);\n lBand_player.connect(lInvert_player);\n\n hInvert_player.connect(mBand_player);\n lInvert_player.connect(mBand_player);\n\n\n lGain_player[i] = context_player.createGain();\n mGain_player[i] = context_player.createGain();\n hGain_player[i] = context_player.createGain();\n\n lBand_player.connect(lGain_player[i]);\n mBand_player.connect(mGain_player[i]);\n hBand_player.connect(hGain_player[i]);\n\n sum_player[i] = context_player.createGain();\n lGain_player[i].connect(sum_player[i]);\n mGain_player[i].connect(sum_player[i]);\n hGain_player[i].connect(sum_player[i]);\n\n lGain_player[i].gain.value = 1;\n mGain_player[i].gain.value = 1;\n hGain_player[i].gain.value = 1;\n\n volumeNodes[i] = context_player.createGain();\n sum_player[i].connect(volumeNodes[i]);\n volumeNodes[i].connect(context_player.destination);\n }\n\n //set volume\n var x = 50 / 100;\n // Use an equal-power crossfading curve:\n var gain1 = Math.cos(x * 0.5 * Math.PI);\n var gain2 = Math.cos((1.0 - x) * 0.5 * Math.PI);\n volumeNodes[0].gain.value = gain1;\n volumeNodes[1].gain.value = gain2;\n\n //create audio Recording node\n audioRecordNode = context_player.createGain();\n volumeNodes[0].connect(audioRecordNode);\n volumeNodes[1].connect(audioRecordNode);\n audioRecorder = new Recorder(audioRecordNode);\n}", "getNextFrame() {\nvar f;\nf = this.fCur + 1;\nif (this.fCount <= f) {\nf = 0;\n}\nreturn this.setFrameAt(f);\n}", "function paint() {\n\trequestAnimationFrame(paint);\n\n\tif(!audioVisualizerInitialized)\n\t\treturn;\n\n\t//canvasContext.fillStyle = backgroundColour;\n\t//canvasContext.fillRect(0, 0, canvasWidth, canvasHeight);\n\n\tlet bins = audioAnalyserNode.frequencyBinCount;\n\tlet data = new Uint8Array(bins);\n\taudioAnalyserNode.getByteFrequencyData(data);\n\t//canvasContext.fillStyle = barColour;\n\n updateBins(data);\n \n javaamp = getBinValue(0);\n\n //for (let i = 0; i < fftBins; i++) \n paintSingleBin(javaamp);\n //}\n}", "get sampleRateOverride() {}", "function sc_currentMicroseconds() {\n return (new Date()).getTime();\n}", "componentDidUpdate(nextProps){\n \n this.points = nextProps.points\n this.toggle = nextProps.toggle\n this.contextSource = nextProps.contextSource\n this.sampleSize = nextProps.sampleSize \n this.handleSwatchClicked = nextProps.handleSwatchClicked\n\n this.pixelSamples(this.points, this.toggle, this.sampleSize)\n this.setState({point:this.point});\n }", "function getFramesPerInterval() {\n\treturn getInterval()*fps/1000;\n}", "function onCurrentTimeInterval() {\n let duration = (Tocadiscos.mostrarTiempoGeneral == 1) ? getSecondsTime(Tocadiscos.valorTiempoGeneral) : player.duration;\n\n if(Tocadiscos.reproductorTipo !== ReproductorTipo.Stream) {\n currentTime = (Tocadiscos.mostrarTiempoGeneral == 1) ? acumulateTime + player.currentTime : player.currentTime;\n }else{\n currentTime++;\n }\n\n if(Tocadiscos.reproductorTipo === ReproductorTipo.Stream){\n if(currentTime >= duration){\n updateIndicators(duration, duration);\n \n setTimeout(() => onClickBtnStop(), 500);\n\n setTimeout(() => { setSource(Tocadiscos.url).then(() => player.play()) }, 1500);\n }\n }\n \n //currentTime++;\n //console.log(currentTime, player.currentTime);\n if(currentTime < duration) {\n //currentTime++;\n updateIndicators(currentTime, duration);\n }\n}", "function compute_fps() {\n let counter_element = document.querySelector(\"#fps-counter\");\n if (counter_element != null) {\n counter_element.innerText = \"FPS: \" + g_frames_since_last_fps_count;\n }\n g_frames_since_last_fps_count = 0;\n}", "function currentTimeSegment(timeFrame) {\n\t\tvar step = $scope.timeSegmentsList[0].segmentRange;\n\t\tvar indexInTimeSegments = Math.floor(timeFrame / step);\n\t\tif (indexInTimeSegments == $scope.timeSegmentsList.length) indexInTimeSegments--;\n\t\treturn indexInTimeSegments;\n\t}", "function EstimateSampleRate()\n {\n var frameRateEstimator = new FrameRateEstimator();\n\n /**\n * Feed each sampling into this update function.\n */\n this.update = function()\n {\n frameRateEstimator.update();\n }\n\n /**\n * Get most recent sampling rate estimate.\n */\n this.sample_hz = function()\n {\n return Math.round(frameRateEstimator.fps());\n }\n }", "_analyserUpdate()\n {\n this._voiceMinBin = Math.max(1, // avoid first FFT bin\n Math.min(this._analyser.frequencyBinCount - 1,\n Math.round(this._voiceMinFrequency * this._analyser.fftSize\n / this._audioContext.sampleRate) ) );\n\n this._voiceMaxBin = Math.max(this._voiceMinBin,\n Math.min(this._analyser.frequencyBinCount - 1,\n Math.round(this._voiceMaxFrequency * this._analyser.fftSize\n / this._audioContext.sampleRate) ) );\n\n this._binsGlobalNormalisation = 1 / this._analyser.frequencyBinCount;\n\n const voiceBinCount = this._voiceMaxBin - this._voiceMinBin + 1;\n\n this._binVoiceNormalisation = 1 / voiceBinCount;\n this._binNonVoiceNormalisation = 1 / (this._analyser.frequencyBinCount - voiceBinCount);\n\n // pre-allocation\n this._analysed = new Float32Array(this._analyser.frequencyBinCount);\n }", "get framesPerSecond() {\n\t\treturn this._fps;\n\t}", "requestFrame(next, resumed) {\n let now = Date.now();\n this.frame = {\n count: requestAnimationFrame(next),\n time: now,\n rate: resumed ? 0 : now - this.frame.time,\n scale: this.screen.scale * this.frame.rate * 0.01\n };\n }", "requestFrame(next, resumed) {\n let now = Date.now();\n this.frame = {\n count: requestAnimationFrame(next),\n time: now,\n rate: resumed ? 0 : now - this.frame.time,\n scale: this.screen.scale * this.frame.rate * 0.01\n };\n }", "function getData() {\n source = audioContext.createBufferSource();\n\n var request = new XMLHttpRequest();\n\n request.addEventListener(\"progress\", updateProgress);\n request.addEventListener(\"load\", transferComplete);\n request.addEventListener(\"error\", transferFailed);\n request.addEventListener(\"abour\", transferCanceled);\n\n function updateProgress() {\n console.log(\"update Progress\");\n }\n\n function transferComplete() {\n console.log(\"transfer Complete\");\n }\n\n function transferFailed() {\n console.log(\"transfer failed\");\n }\n\n function transferCanceled() {\n console.log(\"transfer cancelled\");\n }\n\n request.open('GET', '../vendor/music/home.m4a', true);\n request.responseType = 'arraybuffer';\n\n request.onload = function () {\n\n var audioData = request.response;\n\n audioContext.decodeAudioData(audioData, function (buffer) {\n source.buffer = buffer;\n\n source.connect(analyser);\n\n // get data\n // var freqDomain = new Float32Array(analyser.frequencyBinCount);\n // analyser.getFloatFrequencyData(freqDomain);\n\n // frequency domain\n var delay = 5;\n var delayCount = 0;\n\n // objectname.canvas.width= this.WIDTH *** replace\n // ovjectname.canvas.height = this.HEIGHT *** replace\n var times = new Uint8Array(analyser.frequencyBinCount);\n\n // wait until buffer loaded\n if (delayCount == 0 || delayCount == delay) {\n analyser.getByteFrequencyData(times);\n\n for (var i = 0; i < times.length; i++) {\n console.log(\"tl \" + times.length);\n console.log(\"times \" + times[i]);\n var value = times[i];\n var percent = value / 256;\n var height = 400 * percent;\n var offset = 400 - height - 1;\n var barWidth = 600 / analyser.frequencyBinCount;\n var hue = i / analyser.frequencyBinCount * 360;\n canvas.fillStyle = 'hsl(' + hue + ', 100%, 50%)';\n canvas.fillRect(i * barWidth, offset, barWidth, height);\n }\n delayCount = 1;\n } else {\n delayCount++;\n }\n\n // // time domain\n // var timeDomain = new Uint8Array(analyser.frequencyBinCount);\n // analyser.getByteTimeDomainData(freqDomain);\n // for (var i = 0; i < analyser.frequencyBinCount; i++) {\n // var value = timeDomain[i];\n // var percent = value / 256;\n // var height = 400 * percent;\n // var offset = 400 - height - 1;\n // var barWidth = 600/analyser.frequencyBinCount;\n // canvas.fillStyle = 'black';\n // canvas.fillRect(i * barWidth, offset, 1, 1);\n // }\n\n function getFrequencyValue(frequency) {\n var nyquist = context.sampleRate / 2;\n var index = Math.round(frequency / nyquist * freqDomain.length);\n }\n\n analyser.connect(audioContext.destination);\n source.loop = true;\n }, function (e) {\n \"Error with decoding audio data: \" + e.err;\n });\n };\n request.send();\n}", "componentWillReceiveProps(props) {\n {/*if (this._identity !== undefined && props.frame != this._lastUpdatedFrame) {*/}\n {/*this._video.currentTime = props.frame / this.video.fps;*/}\n {/*this._lastUpdatedFrame = props.frame;*/}\n {/*}*/}\n }", "function main(currentTime){\r\n //so alli main logic nalli ond sati first time fire aagatte ee main function using\r\n // requestAnimation frame amele naavu idna pade pade kareetivi and we'll make this\r\n // function paint and render again and again andre frame rate jaasti aagatte\r\n window.requestAnimationFrame(main);\r\n counter++;\r\n // console.log(counter);\r\n if(counter%100 == 0){\r\n counter = counter%100;\r\n count++;\r\n // console.log(count);\r\n }\r\n if(count/10 === 1){\r\n count = count%10;\r\n level++;\r\n // console.log(level);\r\n }\r\n if(level != previouslevel){\r\n speed++;\r\n // console.log(speed);\r\n previouslevel = level;\r\n Level.innerHTML = \"LEVEL : \" + level;\r\n }\r\n // console.log(currentTime);\r\n if(((currentTime - lastpaintTime)/1000) < 1/speed){\r\n // currentTime = currentTime * 2;\r\n // console.log(\"currentTime\");\r\n return;\r\n }\r\n lastpaintTime = currentTime;\r\n gameEngine();\r\n}", "function getAudioBufferArray(){\n let audioBufferArray = [];\n let endPlaybackColumn = getEndPlaybackColumn();\n\n for (let i = 0; i < rows; i++) {\n let tempAudioBuffer = audioContext.createBuffer(2, audioContext.sampleRate * ((endPlaybackColumn + 1) * 5), audioContext.sampleRate);\n let tempFloat32Array = tempAudioBuffer.getChannelData(0);\n let length = 0; // increments of 5 seconds\n \n for (let j = 0; j < columns; j++) {\n let audioBuffer = soundGrid[i][j];\n \n if((audioBuffer === -1) && (j <= endPlaybackColumn)){\n if (length === 0){\n tempFloat32Array.set(getEmptyAudioBuffer().getChannelData(0));\n } else {\n tempFloat32Array.set(getEmptyAudioBuffer().getChannelData(0), length);\n }\n } else if (audioBuffer != -1){\n if (length === 0){\n tempFloat32Array.set(audioBuffer.getChannelData(0));\n } else {\n tempFloat32Array.set(audioBuffer.getChannelData(0), length);\n }\n }\n length = length + (audioContext.sampleRate * 5); \n }\n \n tempAudioBuffer.getChannelData(0).set(tempFloat32Array); // left\n tempAudioBuffer.getChannelData(1).set(tempFloat32Array); // right\n audioBufferArray.push(tempAudioBuffer); \n }\n\n return audioBufferArray;\n }", "function getAudioEditorGlobalPreviewTime() {\n var selected_component = $('._audio_editor_component._selected');\n if(selected_component.length == 0) {\n return 0;\n } else {\n var flag = true;\n var tot = 0;\n $('._audio_editor_component').each(function() {\n if($(this).hasClass('_selected')) {\n flag = false;\n tot += ($(this).find('._media_player_slider').slider('value') - $(this).data('from'));\n } else if(flag) {\n tot += $(this).data('duration');\n }\n });\n return tot;\n }\n}", "function render() {\n playbackController.render();\n\n if (playerLQ.newFrameAvailable()) {\n calculate();\n }\n requestAnimationFrame(render);\n}", "tick() {\n\t\t// debug\n\t\t// console.log(\"atomicGLClock::tick\");\t\n var timeNow = new Date().getTime();\n\n if (this.lastTime != 0)\n \tthis.elapsed = timeNow - this.lastTime;\n\n this.lastTime = timeNow;\n }", "function frame() {\n rAF = requestAnimationFrame(frame);\n\n now = performance.now();\n dt = now - last;\n last = now;\n\n // prevent updating the game with a very large dt if the game were to lose focus\n // and then regain focus later\n if (dt > 1E3) {\n return;\n }\n\n emit('tick');\n accumulator += dt;\n\n while (accumulator >= delta) {\n loop.update(step);\n\n accumulator -= delta;\n }\n\n clearFn(context);\n loop.render();\n }", "function process(audioStream) {\n //wraps stream in a source object allows us to connect our stream to our analyzer\n const audioSource = audioContext.createMediaStreamSource(audioStream)\n audioSource.connect(analyser)\n\n //array of audio data with has length of audioContext.fftSize\n const audioData = new Uint8Array(analyser.frequencyBinCount)\n const dataLength = audioData.length\n\n const lineHeight = canvasHeight / dataLength\n const xPosition = canvasWidth - 1\n\n contextOfCanvas.fillStyle = `hsl(280, 100%, 10%)`\n contextOfCanvas.fillRect(0, 0, canvasWidth, canvasHeight)\n\n loop()\n\n function loop() {\n //call again on next frame\n window.requestAnimationFrame(loop)\n\n //take data and move it one pixel to the left\n let imageData = contextOfCanvas.getImageData(\n 1,\n 0,\n canvasWidth - 1,\n canvasHeight\n )\n\n contextOfCanvas.fillRect(0, 0, canvasWidth, canvasHeight)\n contextOfCanvas.putImageData(imageData, 0, 0)\n\n //analyser will populate and transform data array\n analyser.getByteFrequencyData(audioData)\n\n for (let i = 0; i < dataLength; i++) {\n let ratio = audioData[i] / 255\n\n let hue = (ratio * 120 + 280) % 360\n let saturation = \"100%\"\n let lightness = 10 + 70 * ratio + \"%\"\n\n contextOfCanvas.beginPath()\n contextOfCanvas.strokeStyle = `hsl(${hue}, ${saturation}, ${lightness})`\n contextOfCanvas.lineWidth = 15\n contextOfCanvas.moveTo(xPosition, canvasHeight - i * lineHeight)\n contextOfCanvas.lineTo(\n xPosition,\n canvasHeight - (i * lineHeight + lineHeight)\n )\n contextOfCanvas.stroke()\n }\n }\n }", "static getFrameRate(frames) {\nvar frameok;\n//------------\n// Use 25fps as the somewhat arbitrary default value.\nframeok = frames && frames.length !== 0;\nif (frameok) {\nreturn 1000 / frames[0].duration;\n} else {\nreturn 25;\n}\n}", "setTimeLimit() {\nvar lastframe;\n//-----------\nif (this.fCount === 0) {\nreturn this.tLimit = 0;\n} else {\nlastframe = this.frameAt(this.fCount - 1);\nreturn this.tLimit = (lastframe.getTime()) + (lastframe.getDuration());\n}\n}", "function doSample(event) {\n var now = Date.now();\n if (lastSampleTimestamp <= 0){\n lastSampleTimestamp = now;\n return; \n }\n var deltaSec = (now - lastSampleTimestamp)/1000;\n\n\n if (sampleRateSamples > 0){\n //Use the first several samples to calculate the device's sample rate\n if (rawSampleRate == null) {\n rawSampleRate = 1 / deltaSec;\n } else {\n rawSampleRate = (rawSampleRate + (1 / deltaSec))/2; //Hz \n }\n sampleRateSamples--;\n\n } else if (sampleRateSamples == 0){\n //We got all our device sample-rate related readings, \n //now calculate the sample-rate related parameters\n sampleIntervalMS = 1000 / rawSampleRate;\n\n var destSampleRate = 2*options.max_stride_freq;\n samplesToSkip = Math.floor(rawSampleRate / destSampleRate) - 1;\n sampleIntervalMS *= (samplesToSkip+1);\n actualSampleRate = 1000/sampleIntervalMS; //Hz\n amplitudeCheckSamples = Math.ceil(actualSampleRate); //look a second back\n\n //store first sample\n var datum = event.accelerationIncludingGravity[options.axis] || 0.5;\n shift(samples, datum);\n\n sampleRateSamples--;\n\n } else {\n //normal measurments\n if (samplesSkipped < samplesToSkip) {\n samplesSkipped++;\n return;\n }\n samplesSkipped = 0;\n\n var datum = event.accelerationIncludingGravity[options.axis] || 0.5;\n\n if (samples[samples.length-1] != 0){ //TODO\n //integrate to get a velocity sample\n var velocity = vSamples[vSamples.length-1] + (datum - samples[samples.length-1])*sampleIntervalMS/1000;\n shift(vSamples, velocity);\n }\n\n var smoothed = datum;//smooth(samples[samples.length-1], datum, options.smooth_alpha);\n shift(samples, smoothed);\n\n var freq = -1;\n switch (options.algorithm) {\n case 'fft':\n freq = getFreqFft(samples);\n break;\n case 'zero-cross':\n freq = getFreqCross(samples);\n break;\n case 'zero-cross-v':\n freq = getFreqCross(vSamples);\n break;\n }\n\n var spm = Math.round(freq*60);\n if (spm > lastSpm) {\n //rising (usually slower than falling)\n spm = Math.round(smooth(lastSpm, spm, options.smooth_alpha_rising));\n } else {\n //falling (it's possible to stop very quickly)\n spm = Math.round(smooth(lastSpm, spm, options.smooth_alpha_falling));\n }\n lastSpm = spm;\n }\n \n lastSampleTimestamp = now;\n }", "onAnimFrame() {\n const now = Date.now();\n const delta = now - this.previousFrameTime;\n const interval = 1000 / this.props.fps;\n\n this.requestId = window.requestAnimationFrame(this.onAnimFrame);\n\n if (delta > interval) {\n this.previousFrameTime = now - (delta % interval);\n this.drawCurrentFrame();\n\n // Clamp playback between start & end frame range, looping\n // whenever we run past the end frame.\n if (this.frame < this.startFrame || this.frame > this.endFrame) {\n this.frame = this.startFrame;\n }\n }\n }", "minuteCount() {\n let minuteCount = Math.floor(this.frameCount / this.framesPerMin);\n return minuteCount;\n }", "function getAnimationFrameRate() {\n return _config ? _config.animationFrameRate : undefined;\n }", "function updateFFT() {\n if (analyser == null) return;\n updateAudio(); \n analizerdata = analyser.getFrequencyData();\n for (var p = 0; p < fftSize-fftsizeCute; p++) {\n particles[p].position.y = (bgstartPos.y - 6) +\n (analizerdata[p] / 25)\n\n particlesBase[p].position.y =\n particles[p].position.y - 7.5;\n }\n var freq = analyser.getAverageFrequency();\n var newbloom = (freq / 300);\n if (newbloom > maxBLOOM) newbloom = maxBLOOM;\n //POST.CHANGEBLOON(newbloom);\n LASTBLOON = window.POST.CHANGEBLOON(newbloom);\n ckeckBPM(freq);\n}", "function fpsTick(thisFrame) {\n fpsStart = fpsStart || new Date().getTime();\n if (thisFrame - fpsStart >= 1000) {\n fpsStart += 1000;\n fps = fpsCounting;\n fpsCounting = 0;\n fpsText.innerHTML = fps + \" fps\";\n }\n fpsCounting++;\n if (debug)\n addTaskForFrame(fpsTick);\n }", "function Fps() {\n //\n var _self;\n var _totalTime;\n var _timeTable;\n var _timeTableIndex;\n var _then; // in milliseconds.\n var _average;\n\n try {\n //\n _self = this;\n\n // total time spent for last N frames.\n _totalTime = Fps.FRAME_COUNT_TO_AVERAGE;\n\n // elapsed time for last N frames.\n _timeTable = [];\n\n // where to record next elapsed time.\n _timeTableIndex = 0;\n\n _then = 0;\n\n _average = 0;\n\n // Initialize the elapsed time history table.\n for (var i=0; i<Fps.FRAME_COUNT_TO_AVERAGE; i++) {\n _timeTable[i] = 1.0;\n }\n\n } catch (e) {\n //\n console.log('xtory.core.Fps: ' + e);\n\n throw e;\n }\n\n //\n // Properties.\n //\n Object.defineProperty(_self, 'average', {\n get: function() { return _average; }\n });\n \n //\n // Privileged methods.\n //\n this.update = function() {\n //\n var now = (new Date()).getTime(); // in milliseconds.\n\n var elapsedTime = // in seconds.\n (now - _then) * 0.001;\n\n _then = now;\n\n // Keep the total time and total active time for the last N frames.\n _totalTime += elapsedTime - _timeTable[_timeTableIndex];\n\n // Save off the elapsed time for this frame so we can subtract it later.\n _timeTable[_timeTableIndex] = elapsedTime;\n\n // Wrap the place to store the next time sample.\n _timeTableIndex++;\n if (_timeTableIndex === Fps.FRAME_COUNT_TO_AVERAGE) {\n _timeTableIndex = 0;\n }\n\n _average = Math.floor (\n (1.0 / (_totalTime / Fps.FRAME_COUNT_TO_AVERAGE)) + 0.5\n );\n }; \n}", "function getInstantBuffer(leftData, rightData, sampleRate) {\n drawContext.drawInstantCurve(leftData, rightData, sampleRate);\n }", "function calculateFps(now) {\n \tvar cur_fps = 1000 / (now - vp.fps.frame);\n \tvp.fps.frame = now;\n \tif (now - vp.fps.update > 1000)\n \t\tvp.fps.update = now; \n \treturn cur_fps; \n}", "animFrame() {\n //\n // !!!! IMPLEMENT ME !!!!\n //\n const cells = this.life.getCells();\n const height = this.props.height;\n const width = this.props.width;\n\n const pixelSize = this.pixelSize; //changes the pixel size\n\n const canvas = this.refs.canvas;\n let ctx = canvas.getContext(\"2d\");\n let imageData = ctx.getImageData(0, 0, width, height);\n\n for (let y = 0; y < height; y+=pixelSize) {\n for (let x = 0; x < width; x+=pixelSize) {\n const state = cells[y][x];\n const index = (y * width + x) * 4;\n const blockIndexArray = [];\n for (let yGrowth = 0; yGrowth < pixelSize; yGrowth++){\n for (let xGrowth = 0; xGrowth < pixelSize; xGrowth++) {\n blockIndexArray.push(((y + yGrowth) * width + (x + xGrowth)) * 4);\n }\n }\n \n const color = state === 1 ? 255 : 0;\n\n blockIndexArray.forEach((pixel) => { // This block prints the selected pixel size as opposed to a single.\n imageData.data[pixel + 0] = color;\n imageData.data[pixel + 1] = color;\n imageData.data[pixel + 2] = color;\n imageData.data[pixel + 3] = 0xff;\n })\n }\n }\n\n ctx.putImageData(imageData, 0, 0);\n\n\n this.life.step(pixelSize);\n\n requestAnimationFrame(() => {\n this.animFrame();\n });\n }", "function tick() {\r\n now = window.performance.now();\r\n delta = (now-last); // in milliseconds\r\n if(t_cooldown>0) {\r\n t_cooldown -= delta*dcd;\r\n } else {\r\n t -= delta*dt;\r\n }\r\n t = t<0 ? 0 : t;\r\n last = now;\r\n\r\n // Update fps counter\r\n fhStart = (fhStart+1)%100;\r\n fhEnd = (fhEnd+1)%100;\r\n frameHistory[fhEnd] = now;\r\n fpsElement.textContent = Math.ceil( 1000.0*frameHistory.length/(now-frameHistory[fhStart]) )\r\n }", "hasFrames() {\nreturn this.fCount !== 0;\n}", "if (inited && playInited) {\r\n lastCurTime = player.currentTime;\r\n }", "function playNextFrame() {\n if (currentFrame >= frames.length) {\n currentFrame = 0;\n }\n\n renderFrames();\n\n var frame = frames[currentFrame];\n for (var i = 0; i < frame.length; i++) {\n if (frame[i] >= threshValue) {\n playSound(i);\n\n if (playFirstNote) {\n break;\n }\n }\n }\n\n currentFrame++;\n}", "memoryInc() {\r\n this.time = this.time + 5\r\n\tif(this.observer) {\r\n\t this.observer.clockTicked()\r\n\t}\r\n }", "async getTotalFrames() {\r\n return this.lottieAnimation.totalFrames;\r\n }", "function main(){\r\n\tvar TL=fl.getDocumentDOM().getTimeline()\r\n\tvar curL=TL.currentLayer;\r\n\tvar curF=TL.currentFrame;\r\n\tvar frame=TL.layers[curL].frames[curF];\r\n\tif(curF>frame.startFrame){\r\n\t\tTL.currentFrame=frame.startFrame;\r\n\t}else if(curF==frame.startFrame && curF>0){\r\n\t\tTL.currentFrame=frame.startFrame;\r\n\t\tvar prevFrame=TL.layers[curL].frames[frame.startFrame-1];\r\n\t\tTL.currentFrame=frame.startFrame-(prevFrame.duration);\r\n\t}\r\n}", "async getCurrentBlockNum() {\n const properties = await this.getDynamicGlobalProperties();\n return properties.last_irreversible_block_num;\n }", "function update() {\n _this.cycleCounter += 1;\n // Update the frame index when the cycle counter has triggered\n if (_this.cycleCounter > _this.CPS) {\n _this.cycleCounter = 0;\n // Update and reset the frame index at the end of the animation\n _this.frameIndex = (_this.frameIndex + 1) % _this.numFrames;\n }\n }", "function handleTick() \r\n\t{\t// This function is called at FPS speed. i.e. 60FPS (60 times per second)\r\n\t\t// All processing done here is critical\r\n\t\tif (!pause)\r\n\t\t{\t\r\n\t\t\tsoundOne.drawThis(); // Get analyzer data from the audio object\r\n\t\t\tline.graphics.clear(); // Clear previous line\r\n\t\t\tline.graphics.setStrokeStyle(1); // Set line width attribute\r\n\t\t\tline.graphics.beginStroke('rgba(255, 255, 255, 0.15)'); // set line color\r\n\t\t\tline.graphics.moveTo (25, 75 + (225 / 2)); // Place the line in some point of the canvas\r\n\r\n\t\t\tif (firstDraw)\r\n\t\t\t{\t\r\n\t\t\t\ttargetArray.fill(0);\r\n\t\t\t\tcontrolArray.fill(0);\r\n\r\n\t\t\t\tfirstDraw = false;\r\n\t\t\t}\r\n\r\n\t\t\tif (++Ncounter > 4)\r\n\t\t\t{\t\r\n\t\t\t\tfor (var i = 0; i < soundOne.dataArray.length; ++i)\r\n\t\t\t\t{\r\n\t\t\t\t\tcontrolArray[i] = (soundOne.dataArray[i] - targetArray[i]) / 5;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tNcounter = 0;\r\n\t\t\t}\r\n\r\n\t\t\tfor (var i = 25; i < (890 + 25); i ++) // Draw ponint to point\r\n\t\t\t{\t\r\n\t\t\t\ttargetArray[i] += controlArray[i];\r\n\t\t\t\tvar nValue = ((targetArray[i] - 128) * 1.3);\r\n\t\t\t\tif (nValue > 113){nValue = 113;}\r\n\t\t\t\telse if(nValue < -111){nValue = -111}\r\n\r\n\t\t\t\tline.graphics.lineTo (i, ((225 / 2) + 75) + nValue);\r\n\t\t\t}\r\n\t\t\tstage.update();\t\r\n\t\t}\r\n\t}", "function Start()\n{\n\taccum = 0f;\n\tframes = 1;\n \n // Infinite loop executed every \"frenquency\" secondes.\n while( Application.isPlaying )\n {\n // Update the FPS\n var fps : float = accum / (frames > 0 ? frames : 1);\n sFPS = fps.ToString( \"f\" + Mathf.Clamp( nbDecimal, 0, 10 ) );\n \n //Update the color\n color = (fps >= 30) ? Color.green : ((fps > 10) ? Color.red : Color.yellow);\n \n accum = 0;\n frames = 0;\n \n yield WaitForSeconds( frequency );\n }\n}", "function audioSetup(){ audioContext = new AudioContext();\n\t//audioplyr.currentTime = 0\n\t// analyser (for audio visualization)\n\t analyser = audioContext.createAnalyser();\n\t analyser.fftSize = 2048;\n\t analyser.smoothingTimeConstant = 0.5;\n\t analyser.maxDecibels = -30;\n\t analyser.minDecibels = -100;\n\t analyser.smoothingTimeConstant = 0.1;\n\n\t frequencyData = new Float32Array(analyser.frequencyBinCount);\n\t // audioplyr.setAttribute('src', \"audio/mahsiv.mp3\");\n\t // create an oscillator\n\t var oscillator = audioContext.createOscillator();\n\t oscillator.type = \"sine\";\n\t oscillator.frequency.setValueAtTime(400, audioContext.currentTime);\n\t oscillator.start();\n\t // oscillator.connect(analyser);\n\t // oscillator.connect(audioContext.destination);\n\t \n\t // audio player gain\n\t audioGain = audioContext.createGain();\n\t audioGain.gain.setValueAtTime(1, audioContext.currentTime);\n\t audioGain.connect(analyser);\n\t audioGain.connect(audioContext.destination);\n\t \n\t //drawURL(\"https://upload.wikimedia.org/wikipedia/commons/9/9b/Bruckner_Symphony_No._5%2C_opening.wav\");\n\t //drawURL(\"https://upload.wikimedia.org/wikipedia/commons/3/32/Danse_Macabre_-_Busy_Strings_%28ISRC_USUAN1100556%29.mp3\");\n\t //drawURL(\"https://upload.wikimedia.org/wikipedia/commons/d/d6/Danse_Macabre_-_Light_Dance_%28ISRC_USUAN1100553%29.mp3\");\n\t //drawURL(\"https://upload.wikimedia.org/wikipedia/commons/c/c6/Canon_in_D_Major_%28ISRC_USUAN1100301%29.mp3\");\n\n\t myOscilloscope.resume();\n\tradioSrc = audioContext.createMediaElementSource(audioplyr);\n\t radioSrc.connect(audioGain);\n\t \n\t splitter = audioContext.createChannelSplitter();\n\n\t analyserL = audioContext.createAnalyser();\n\t analyserL.smoothingTimeConstant = 0.7;\n\n\t analyserR = audioContext.createAnalyser();\n\t analyserR.smoothingTimeConstant = 0.7;\n\n\t //sourceNode = audioContext.createMediaElementSource(audio);\n\t radioSrc.connect(splitter);\n\t //sourceNode.connect(audioContext.destination);\n\n\t splitter.connect(analyserL,0,0);\n\t splitter.connect(analyserR,1,0);\n\n\t //audio.play();\n\t analyserL.fftSize = 4096;\n\t analyserR.fftSize = 4096;\n\t bufferLength = analyserL.fftSize;\n\t dataArrayL = new Float32Array(bufferLength);\n\t dataArrayR = new Float32Array(bufferLength);\n\t}", "_tryNudgeBuffer () {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n const nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n const targetTime = currentTime + nudgeRetry * config.nudgeOffset;\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n logger.warn(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);\n media.currentTime = targetTime;\n\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n logger.error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n }", "_playCallback() {\n const type = this.isVideoTrack() ? 'video' : 'audio';\n const now = window.performance.now();\n console.log(`(TIME) Render ${type}:\\t`, now);\n this.conference.getConnectionTimes()[`${type}.render`] = now; // The conference can be started without calling GUM\n // FIXME if there would be a module for connection times this kind\n // of logic (gumDuration or ttfm) should end up there\n\n const gumStart = window.connectionTimes['obtainPermissions.start'];\n const gumEnd = window.connectionTimes['obtainPermissions.end'];\n const gumDuration = !isNaN(gumEnd) && !isNaN(gumStart) ? gumEnd - gumStart : 0; // Subtract the muc.joined-to-session-initiate duration because jicofo\n // waits until there are 2 participants to start Jingle sessions.\n\n const ttfm = now - (this.conference.getConnectionTimes()['session.initiate'] - this.conference.getConnectionTimes()['muc.joined']) - gumDuration;\n this.conference.getConnectionTimes()[`${type}.ttfm`] = ttfm;\n console.log(`(TIME) TTFM ${type}:\\t`, ttfm);\n _statistics_statistics__WEBPACK_IMPORTED_MODULE_3__[\"default\"].sendAnalytics(Object(_service_statistics_AnalyticsEvents__WEBPACK_IMPORTED_MODULE_0__[\"createTtfmEvent\"])({\n 'media_type': type,\n muted: this.hasBeenMuted,\n value: ttfm\n }));\n }", "function finishedLoading() {\n\tconsole.log(\"hey\" + bufferLoader.bufferList);\n\t\n\t//has to come after loaded duh\n\tbufferList = bufferLoader.bufferList;\n\t//trk = new Track(bufferList[0], context);\n\tfor (var i=0; i<bufferList.length; i++) {\n\t\tvar t = new Track(bufferList[i], context, track_divs[i]);\n\t\ttracks.push(t);\n\t}\n\n\t//channel designations\n\tch_guit = new Channel(tracks.slice(0,2)); //0,1\n\tch_bass = new Channel(tracks.slice(2,4)); //2,3\n\tch_vox = new Channel(tracks.slice(4,6)); //4,5\n\tch_fx = new Channel(tracks.slice(6,8)); //6,7\n\tch_perc = new Channel(tracks.slice(8)); //8,9\n\n\tchannels = [ch_guit, ch_bass, ch_vox, ch_fx, ch_perc];\n\n\t//we make 2 for-loops because of ordering\n\tfor (var i=0; i<channels.length; i++) {\n\t\tchannels[i].playAll();\n\t}\n\tfor (var i=0; i<channels.length; i++) {\n\t\tchannels[i].select(Math.floor(Math.random()*2));\n\t}\n\n}", "readBufferProcessEvent(e) {\n\t\tlet l = e.outputBuffer.getChannelData(0)\n\t\tlet r = e.outputBuffer.getChannelData(1)\n\t\tconst len = e.inputBuffer.length\n\t\tconst half = this._bufferSize >> 1\n\t\tconst sources = this.targets.lightness\n\t\tconst averages = this.buffers.lightness\n\n\t\tfor (let idx = 0; idx < len; idx++) {\n\t\t\tconst t = this._sample / 44100\n\t\t\t\n\t\t\t// Zero before summing\n\t\t\tl[idx] = 0\n\t\t\tr[idx] = 0\n\n\t\t\t// Iterate through all possible tones, summing\n\t\t\tfor (let tone_idx = 0; tone_idx < half; tone_idx++) {\n\t\t\t\tconst tone = Math.sin(t * this._frequencies[tone_idx])\n\t\t\t\t// Smooth (moving average)\n\t\t\t\taverages[tone_idx] = (sources[this._hilbert[tone_idx]] + averages[tone_idx]) / 2\n\t\t\t\taverages[half+tone_idx] = (sources[this._hilbert[half+tone_idx]] + averages[tone_idx]) / 2\n\n\t\t\t\t// TODO: compression\n\t\t\t\tl[idx] += (tone * averages[tone_idx] )/half\n\t\t\t\tr[idx] += (tone * averages[half + tone_idx] )/half\n\t\t\t}\n\n\t\t\t// Decrease dynamic range\n\t\t\t// Technically we should use abs values here because the output range is [-1 1] but\n\t\t\t// this loop is probably expensive enough already and it will function approximately\n\t\t\t// the same\n\t\t\tif (l[idx] > this.maxLoudness || r[idx] > this.maxLoudness)\n\t\t\t\tthis.maxLoudness += 1e-5\n\n\t\t\tif (this.maxLoudness > 0 && this.compression > 0) {\n\t\t\t\tl[idx] = l[idx] / (this.maxLoudness + (1-this.maxLoudness)*(1-this.compression))\n\t\t\t\tr[idx] = r[idx] / (this.maxLoudness + (1-this.maxLoudness)*(1-this.compression))\n\t\t\t}\n\n\t\t\t// Reduce to effect maximum compression\n\t\t\tthis.maxLoudness -= 1e-6 // will reset back to zero after 10 seconds\n\n\t\t\tthis._sample++\n\t\t}\n\n\t\tconst hues = this.targets.hue\n\t\tconst saturations = this.targets.saturation\n\n\t\tlet average_hueL = 0,\n\t\t average_hueR = 0,\n\t\t count_hueL = 0,\n\t\t\tcount_hueR = 0,\n\t\t\taverage_satL = 0,\n\t\t\taverage_satR = 0\n\t\t// Only look at the central quarter of the image for colour detection\n\t\tfor (let idx = 0; idx < half/4; idx++) {\n\t\t\taverage_satL += saturations[ idx+half/4+half/8]\n\t\t\taverage_satR += saturations[half + idx+half/4+half/8]\n\t\t\tif (!Number.isNaN(hues[idx+half/4+half/8])) {\n\t\t\t\taverage_hueL += hues[idx+half/4+half/8]\n\t\t\t\tcount_hueL++\n\t\t\t}\n\t\t\tif (!Number.isNaN(hues[half+idx+half/4+half/8])) {\n\t\t\t\taverage_hueR += hues[half+idx+half/4+half/8]\n\t\t\t\tcount_hueR++\n\t\t\t}\n\t\t}\n\n\t\t// Modulate frequency for hue\n\t\tif (count_hueL > 0) { \n\t\t\taverage_hueL = average_hueL/count_hueL\n\t\t\tthis.sawtoothNodeL.frequency.value = average_hueL * 1320 + 440\n\t\t}\n\n\t\tif (count_hueR > 0) { \n\t\t\taverage_hueR = average_hueR/count_hueR\n\t\t\tthis.sawtoothNodeR.frequency.value = average_hueR * 1320 + 440\n\t\t}\n\n\t\t// And distortion and amplitude for saturation\n\t\tthis.distortionL.distortion = this.scaleL.max = (average_satL/(half/4)) * this.fmVolume\n\t\tthis.distortionR.distortion = this.scaleR.max = (average_satR/(half/4)) * this.fmVolume\n\t}", "function getNormalizedCurrentFrame() {\n var c = -Math.ceil(currentFrame % totalFrames);\n if (c < 0) c += (totalFrames - 1);\n return c;\n }" ]
[ "0.6474039", "0.6331757", "0.6299864", "0.61680335", "0.6053511", "0.6043517", "0.603848", "0.59629", "0.5938586", "0.5862764", "0.5859396", "0.58417475", "0.5840197", "0.5809662", "0.56728184", "0.5640583", "0.56148857", "0.5599868", "0.5588118", "0.5577787", "0.5552177", "0.5549104", "0.55330336", "0.5518547", "0.55153227", "0.55138016", "0.5509313", "0.5495536", "0.5483766", "0.54772735", "0.5471972", "0.54712766", "0.5436402", "0.54254204", "0.54140395", "0.54076785", "0.5401307", "0.5388353", "0.5386715", "0.5386713", "0.5385398", "0.5374843", "0.5371964", "0.5368909", "0.5359107", "0.5351931", "0.53463274", "0.5332279", "0.53305984", "0.5326871", "0.53058463", "0.52861935", "0.5282468", "0.5281994", "0.5270429", "0.5264675", "0.52600396", "0.52486044", "0.5248497", "0.5246092", "0.5241126", "0.5235119", "0.5235119", "0.52331877", "0.52311486", "0.52305794", "0.5217274", "0.5206279", "0.52044445", "0.52016836", "0.5199709", "0.51984215", "0.51913893", "0.51906383", "0.51616615", "0.5160937", "0.5159319", "0.5156046", "0.51548845", "0.51456666", "0.5131216", "0.51295775", "0.5127177", "0.51269203", "0.5118288", "0.5117326", "0.51160234", "0.51068467", "0.51036507", "0.5100986", "0.5094194", "0.5091759", "0.5090246", "0.5086658", "0.50834656", "0.5079989", "0.5075964", "0.5074025", "0.50736773", "0.50701654", "0.5065442" ]
0.0
-1
input: Frame duration in seconds
init(frameDuration){ // Initialize variables // Frame information // Frame duration (e.g., 0.02 s) const fSize = frameDuration*sampleRate; // Make the framesize multiple of 128 (audio render block size) this._frameSize = 128*Math.round(fSize/128); // Frame duration = this._frameSize/sampleRate; this._frameSize = Math.max(128*2, this._frameSize); // Force a minimum of two blocks this._numBlocksInFrame = this._frameSize/128; // 8 at 48kHz and 20ms window // Force an even number of frames if (this._numBlocksInFrame % 2){ this._numBlocksInFrame++; this._frameSize += 128; } // Predefined 50% overlap this._numBlocksOverlap = Math.floor(this._numBlocksInFrame/2); // 4 at 48kHz and 20ms window // Define frame buffers this._oddBuffer = new Float32Array(this._frameSize); // previous and current are reused this._pairBuffer = new Float32Array(this._frameSize); // previous and current are reused // We want to reuse the two buffers. This part is a bit complicated and requires a detailed description // Finding the block indices that belong to each buffer is complicated // for buffers with an odd num of blocks. // Instead of using full blocks, half blocks could be used. This also adds // another layer of complexity, so not much to gain... // Module denominator to compute the block index this._modIndexBuffer = this._numBlocksInFrame + this._numBlocksInFrame % 2; // Adds 1 to numBlocksInFrame if it's odd, otherwise adds 0 // Count blocks this._countBlock = 0; // Computed buffers this._oddSynthBuffer = new Float32Array(this._frameSize); this._pairSynthBuffer = new Float32Array(this._frameSize); console.log("Frame size: " + this._frameSize + ". Set frame length: " + this._frameSize/sampleRate + " seconds" + ". Blocks per frame: " + this._numBlocksInFrame + ". Blocks overlap: " + this._numBlocksOverlap); // LCP variables this._lpcOrder = 20; // LPC filter coefficients this._lpcCoeff = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // LPC k coefficients this._kCoeff = []; // Filter samples this._prevY = []; // Quantization this._quantOpt = false; this._quantBits = 2; // Reverse K's this._reverseKOpt = false; // Perfect synthesis this._perfectSynthOpt = false; // resampling before analysis this._resamplingFactor = 1; this._resampler = new Resampler(this._frameSize, this._resamplingFactor); // Unvoiced mix (adds noise to the perfect excitation signal) this._unvoicedMix = 0; // Pitch factor (modifies this._fundFreq) this._pitchFactor = 1; // Vibrato effect (modifies this._fundFreq) this._vibratoEffect = 0; // Synthesis // Create impulse signal this._oldTonalBuffer = new Float32Array(this._frameSize/2); this._excitationSignal = new Float32Array(this._frameSize); this._errorBuffer = new Float32Array(this._frameSize); this._mixedExcitationSignal = new Float32Array(this._frameSize); // autocorrelation indices for fundamental frequency estimation this._lowerACFBound = Math.floor(sampleRate / 200); // 200 Hz upper frequency limit -> lower limit for periodicity in samples this._upperACFBound = Math.ceil(sampleRate / 70); // 70 Hz lower frequency limit -> upper limit // excitation variables this._tonalConfidence = 0.5; this._confidenceTonalThreshold = 0.1; this._periodFactor = 1; // buffer for fundamental period estimation this._fundPeriodLen = this._upperACFBound - this._lowerACFBound; this._fundPeriodBuffer = []; this._oldPeriodSamples = this._upperACFBound; this._pulseOffset = 0; // Debug // Timer to give updates to the main thread this._lastUpdate = currentTime; // Block info this._block1 = new Float32Array(128); this._block2 = new Float32Array(128); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static getFrameRate(frames) {\nvar frameok;\n//------------\n// Use 25fps as the somewhat arbitrary default value.\nframeok = frames && frames.length !== 0;\nif (frameok) {\nreturn 1000 / frames[0].duration;\n} else {\nreturn 25;\n}\n}", "function drawFrame(frame) {\n\t\tvideo.currentTime = (frame.second > video.duration ? video.duration : frame.second);\n\t}", "function a$4(e){return n$9(e.frameDurations.reduce(((t,e)=>t+e),0))}", "function frames(num1,num2) {\r\n\treturn num1*num2*60\r\n}", "frame2ms(frame) {\n\n }", "calculateFrame() {\n const nowTime = (new Date()).getTime();\n this.tick += 1;\n if (nowTime - this.beforeTime >= 1000) {\n console.log(`fps: ${this.tick}`);\n this.tick = 0;\n this.beforeTime = nowTime;\n }\n }", "function frames(numFrames, numMins){\n return (numFrames*60) * numMins;\n }", "function UpdateFrame() {\n\t\tvar value = time_slider.value;\n\t\t//console.log(\"change\");\n\t\t\n\t\tif (isNull(video)) {\n\t\t\treturn;\n\t\t}\n\t\tif (isUndefined(video)) {\n\t\t\treturn;\n\t\t}\n\t\tif (isUndefined(video.duration)) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tvar second = Math.floor(value * video.duration / 100);\n\t\tactual_frame = new Frame(second, canvas, false, null);\n label_CurrenFrame.innerHTML = secondsToTimeString(second);\n\t\tdrawFrame(actual_frame);\n\t}", "setTimeLimit() {\nvar lastframe;\n//-----------\nif (this.fCount === 0) {\nreturn this.tLimit = 0;\n} else {\nlastframe = this.frameAt(this.fCount - 1);\nreturn this.tLimit = (lastframe.getTime()) + (lastframe.getDuration());\n}\n}", "get frame() {\n if (this.video.current) {\n return Math.round(this.video.current.currentTime * this.props.fps);\n }\n\n return 0;\n }", "function FrameTimer()\r\n{\r\n\tvar lastFrameRate;\r\n\tvar frameRate;\r\n\t\r\n\tvar startTime = getTime()\r\n\t\r\n\tvar frameSpacing;\r\n\t\r\n\tvar lastTick = getTime();\r\n\tvar fpsLastTick = getTime();\r\n\t\r\n\tthis.getSeconds = function()\r\n\t{\r\n\t\tvar r = frameSpacing / 1000;\t\t\r\n\t\tif(r == 0 || isNaN(r))\r\n\t\t\treturn 0;\t\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tthis.tick = function()\r\n\t{\r\n\t\tframeSpacing = getTime() - lastTick;\r\n\t\tlastTick = getTime();\r\n\t}\r\n\t\r\n\tthis.calculateFrameRate = function()\r\n\t{\r\n\t\tif(getTime() - fpsLastTick >= 1000)\r\n\t\t{\r\n\t\t\tlastFrameRate = frameRate;\r\n\t\t\tframeRate = 0;\r\n\t\t\tfpsLastTick = getTime();\t\t\t\r\n\t\t}\r\n\t\tframeRate++;\r\n\t\treturn lastFrameRate;\r\n\t}\r\n\tthis.time = getTime;\r\n\t\r\n\tfunction getTime()\r\n\t{\r\n\t\tvar d = new Date();\r\n\t\treturn d.getTime();\r\n\t}\r\n}", "onAnimFrame() {\n const now = Date.now();\n const delta = now - this.previousFrameTime;\n const interval = 1000 / this.props.fps;\n\n this.requestId = window.requestAnimationFrame(this.onAnimFrame);\n\n if (delta > interval) {\n this.previousFrameTime = now - (delta % interval);\n this.drawCurrentFrame();\n\n // Clamp playback between start & end frame range, looping\n // whenever we run past the end frame.\n if (this.frame < this.startFrame || this.frame > this.endFrame) {\n this.frame = this.startFrame;\n }\n }\n }", "function updateElapsedTime() {\n var ct = video.playPosition/1000;\n document.getElementById('duration').innerHTML = Time.format(ct);\n\n var sliceTime = Math.round(ct * durationIndex);\n document.getElementById('progressbar-front').style.width = sliceTime+'px';\n }", "function show_framerate() {\n if (timeRecords.frames.length < 2) {\n return;\n }\n var timeSpan = 5000,\n endPos = timeRecords.frames.length - 1,\n endTime = timeRecords.frames[endPos],\n startPos, startTime, fps, generate = 0, update = 0;\n for (startPos = endPos; startPos > 0; startPos -= 1) {\n if (endTime - timeRecords.frames[startPos] > timeSpan) {\n break;\n }\n generate += timeRecords.generate[startPos];\n update += timeRecords.update[startPos];\n }\n startTime = timeRecords.frames[startPos];\n timeSpan = endTime - startTime;\n fps = (endPos - startPos) * 1000 / timeSpan;\n generate /= (endPos - startPos);\n update /= (endPos - startPos);\n $('#timing-framerate').text(fps.toFixed(1));\n $('#timing-generate').text(generate.toFixed(1));\n $('#timing-update').text(update.toFixed(1));\n if (startPos > 1000) {\n timeRecords.frames.splice(0, startPos);\n timeRecords.generate.splice(0, startPos);\n timeRecords.update.splice(0, startPos);\n }\n }", "_incrementFrame() {\n this._elapsedFrameCount += 1;\n }", "function calcAnimationLength() {\r\n return data[data.length - 1].time / 1000 + \"s\"\r\n}", "function frames(minutes, fps) {\n\treturn minutes * 60 * fps;\n}", "function calcTime(dist){\n\t//Get duration of the video\n\tvar dur = Popcorn(\"#video\").duration();\n\t//Get width of timeline in pixels\n\tvar wdth = document.getElementById(\"visualPoints\").style.width;\n\t//Trim for calculations\n\twdth = wdth.substr(0,wdth.length - 2);\n\t//Calculate pixel/total ratio\n\tvar ratio = dist / wdth;\n\t//Return time value in seconds calculated using ratio\n\treturn (ratio * dur);\n}", "function framesPerSecond() {\n floating.unshift(Math.round( 1000 / (new Date().getTime() - frame), 0));\n floating = floating.slice(0, 9);\n return Math.round(floating.average(), 0);\n}", "function obtenerSegundos(frame){\r\n return frame/fpsVideo;\r\n}", "animate(){\n if (this.timeFromLast > this.animationTime){\n this.currentFrameNum++;\n this.currentFrameX += this.frameWidth;\n this.timeFromLast = 0;\n this.timeUntilLast = millis();\n }\n \n if (this.currentFrameNum > this.maxFrame){\n this.currentFrameNum = 3;\n this.currentFrameX = 22;\n }\n \n }", "nextFrame() {\n this.updateParticles();\n this.displayMeasurementTexts(this.stepNo);\n this.stepNo++;\n\n if (this.stepNo < this.history.length - 1) {\n // Set timeout only if playing\n if (this.playing) {\n this.currentTimeout = window.setTimeout(\n this.nextFrame.bind(this),\n this.animationStepDuration\n );\n }\n } else {\n this.finish();\n }\n }", "function frame(d) {\n var ms = d*10;\n return new Promise(resolve => setTimeout(resolve, ms));\n}", "function step(startTime) {\n\n// console.log(\"working\");\n // 'startTime' is provided by requestAnimationName function, and we can consider it as current time\n // first of all we calculate how much time has passed from the last time when frame was update\n if (!timeWhenLastUpdate) timeWhenLastUpdate = startTime;\n timeFromLastUpdate = startTime - timeWhenLastUpdate;\n\n // then we check if it is time to update the frame\n if (timeFromLastUpdate > timePerFrame) {\n // and update it accordingly\n $element.attr('src', imagePath + '/cup-' + frameNumber + '.png');\n // $element.attr('src', imagePath + `/cup-${frameNumber}.png`);\n // reset the last update time\n timeWhenLastUpdate = startTime;\n\n // then increase the frame number or reset it if it is the last frame\n if (frameNumber >= totalFrames) {\n frameNumber = 1;\n } else {\n frameNumber = frameNumber + 1;\n }\n }\n\n requestAnimationFrame(step);\n}", "function main(){\r\n\tvar TL=fl.getDocumentDOM().getTimeline()\r\n\tvar curL=TL.currentLayer;\r\n\tvar curF=TL.currentFrame;\r\n\tvar frame=TL.layers[curL].frames[curF];\r\n\tif(curF>frame.startFrame){\r\n\t\tTL.currentFrame=frame.startFrame;\r\n\t}else if(curF==frame.startFrame && curF>0){\r\n\t\tTL.currentFrame=frame.startFrame;\r\n\t\tvar prevFrame=TL.layers[curL].frames[frame.startFrame-1];\r\n\t\tTL.currentFrame=frame.startFrame-(prevFrame.duration);\r\n\t}\r\n}", "function frames(minute, number) {\n \n let fps = minute * number * 60;\n console.log(\"For \" + minute + \" minutes \" + \" and number \" + number + \"the FPS IS \" + fps);\n return fps;\n }", "function timeGetNoteDuration(frameCount, framerate) {\r\n // multiply and devide by 100 to get around floating precision issues\r\n return ((frameCount * 100) * (1 / framerate)) / 100;\r\n }", "_calculateFrameStep() {\n // TODO: what do the magic numbers mean?\n this._frameStep = Math.round(extrapolate_range_clamp(1, this._simulationRate, 10, 30, 1));\n }", "function perfRecordFrame() {\n const now = performance.now();\n const oneSecondAgo = now - 1000;\n while (refreshTimes.length > 0 && refreshTimes[0] <= oneSecondAgo) {\n refreshTimes.shift();\n }\n refreshTimes.push(now);\n\n if (now - lastFPSLabelUpdate > 200) {\n drawFPSLabel(refreshTimes.length);\n lastFPSLabelUpdate = now;\n }\n}", "processTimeInput() {\n\n var timeTokens = this._currentTimeInput.value.split(\":\");\n if (timeTokens.length != 2)\n {\n console.log(\"Provided invalid time (minutes:seconds) expected: \" + this._currentTimeInput.value);\n this._currentTimeInput.classList.add(\"has-border\");\n this._currentTimeInput.classList.add(\"is-invalid\");\n return;\n }\n\n var minutes = parseInt(timeTokens[0]);\n if (isNaN(minutes))\n {\n console.log(\"Provided invalid time (minutes:seconds) expected: \" + this._currentTimeInput.value);\n this._currentTimeInput.classList.add(\"has-border\");\n this._currentTimeInput.classList.add(\"is-invalid\");\n return;\n }\n\n var seconds = parseInt(timeTokens[1]);\n if (isNaN(seconds))\n {\n console.log(\"Provided invalid time (minutes:seconds) expected: \" + this._currentTimeInput.value);\n this._currentTimeInput.classList.add(\"has-border\");\n this._currentTimeInput.classList.add(\"is-invalid\");\n return;\n }\n\n var frame = this._timeToFrame(minutes, seconds);\n const maxFrame = this._mediaInfo.num_frames - 1;\n if (frame > maxFrame)\n {\n frame = maxFrame;\n }\n else if (frame < 0)\n {\n frame = 0;\n }\n\n this._currentTimeInput.classList.remove(\"has-border\");\n this._currentTimeInput.classList.remove(\"is-invalid\");\n this.goToFrame(frame);\n }", "function requestAnimFrame() {\n if (!lastCalledTime) {\n lastCalledTime = Date.now();\n fps2 = 0;\n return fps;\n }\n delta = (Date.now() - lastCalledTime) / 1000;\n lastCalledTime = Date.now();\n fps2 = 1 / delta;\n // console.clear();\n console.log('\\n'.repeat('100'));\n return parseInt(fps2);\n}", "function onTrackedVideoFrame(currentTime, duration){\n $(\"#current\").text(currentTime);\n $(\"#duration\").text(duration);\n}", "function drawFps(duration) {\n let avgFps = 0;\n \n fps.push(p.frameRate());\n if (fps.length > 60*duration) { fps.splice(0, 1); }\n \n for (let i = 0; i < fps.length; i++) {\n avgFps += fps[i];\n }\n avgFps = avgFps/fps.length;\n \n p.push();\n p.textSize(20);\n p.text(p.int(avgFps), 32, 32);\n p.pop();\n }", "function fps ( value ) {\n\t\treturn __do(\"fps\",value);\n\t}", "function trackFrameEnd(){\n}", "duration() {\n return this.tracks.reduce((trackMax, track) => Math.max(trackMax, track.keyframes.reduce((kfMax, kf) => Math.max(kfMax, kf.time), 0)), 0);\n }", "function velocityPerSecond(velocity, frameDuration) {\n return frameDuration ? velocity * (1000 / frameDuration) : 0;\n }", "static frameCounter() {\n const time = performance.now()\n\n if (FPS.start === null) {\n FPS.start = time\n FPS.prevFrameTime = time\n } else {\n FPS.frameCount++\n FPS.frames.push(time - FPS.prevFrameTime)\n }\n\n FPS.prevFrameTime = time\n\n if (FPS.running) {\n requestAnimationFrame(FPS.frameCounter)\n }\n }", "function renderTime(f, time) {\n\tctx.font = \"16px Encode Sans\";\n\tctx.fillStyle = \"black\";\n\tctx.fillText(\"Frame: \" + f + \", Time elapsed: \" + time/1000 + \"s\", 4, 20);\n}", "function updateDuration() {\n timeStamp = parseInt(progressInp.value, 10);\n timeInp.value = millisecondsToIso(timeStamp);\n timeLeftInp.value = millisecondsToIso(duration - timeStamp);\n}", "function checkFrames(frames) {\n if (!frames[0]) {\n postMessage({\n error: 'Something went wrong. Maybe WebP format is not supported in the current browser.'\n });\n return;\n }\n\n var width = frames[0].width,\n height = frames[0].height,\n duration = frames[0].duration;\n\n for (var i = 1; i < frames.length; i++) {\n duration += frames[i].duration;\n }\n return {\n duration: duration,\n width: width,\n height: height\n };\n }", "function checkFrames(frames) {\n if (!frames[0]) {\n postMessage({\n error: 'Something went wrong. Maybe WebP format is not supported in the current browser.'\n });\n return;\n }\n\n var width = frames[0].width,\n height = frames[0].height,\n duration = frames[0].duration;\n\n for (var i = 1; i < frames.length; i++) {\n duration += frames[i].duration;\n }\n return {\n duration: duration,\n width: width,\n height: height\n };\n }", "function checkFrames(frames){\n\t\tvar width = frames[0].width,\n\t\t\theight = frames[0].height,\n\t\t\tduration = frames[0].duration;\n\t\tfor(var i = 1; i < frames.length; i++){\n\t\t\tif(frames[i].width != width) throw \"Frame \" + (i + 1) + \" has a different width\";\n\t\t\tif(frames[i].height != height) throw \"Frame \" + (i + 1) + \" has a different height\";\n\t\t\tif(frames[i].duration < 0 || frames[i].duration > 0x7fff) throw \"Frame \" + (i + 1) + \" has a weird duration (must be between 0 and 32767)\";\n\t\t\tduration += frames[i].duration;\n\t\t}\n\t\treturn {\n\t\t\tduration: duration,\n\t\t\twidth: width,\n\t\t\theight: height\n\t\t};\n\t}", "function requestAuditionFrame(callback) {\n\n\t\tvar timeout = setTimeout(callback, frameLength);\n\t\treturn timeout;\n\n\t}", "function requestAuditionFrame(callback) {\n\n\t\tvar timeout = setTimeout(callback, frameLength);\n\t\treturn timeout;\n\n\t}", "function nla_frame_to_video_frame(nla_frame, vtex) {\n var frame_delta = Math.round(nla_frame) - vtex.frame_start;\n if (vtex.use_cyclic) {\n frame_delta = frame_delta % vtex.frame_duration;\n if (frame_delta < 0)\n frame_delta += vtex.frame_duration;\n }\n return vtex.frame_offset + frame_delta;\n}", "function FrameRateCounter()\n{\n this.last_frame_count = 0;\n this.frame_ctr = 0;\n \n var date = new Date();\n this.frame_last = date.getTime();\n delete date;\n \n this.tick = function()\n {\n var date = new Date();\n this.frame_ctr++;\n\n if (date.getTime() >= this.frame_last + 1000)\n {\n this.last_frame_count = this.frame_ctr;\n this.frame_last = date.getTime();\n this.frame_ctr = 0;\n }\n\n delete date;\n }\n}", "setFromJSON_TD(jsnframe, t, dur) {\n//-------------\nthis.setFromJSON(jsnframe);\nthis.time = t;\nreturn this.duration = dur;\n}", "getAnimationDuration() {\n const itemsWidth = this.items.reduce((sum, item) => sum + getWidth(item), 0);\n\n // prettier-ignore\n const factor = itemsWidth / (this.initialItemsWidth * 2);\n return factor * this.options.duration;\n }", "get duration() {\n if (!this.endedLocal) {\n return null;\n }\n const ns = this.diff[0] * 1e9 + this.diff[1];\n return ns / 1e6;\n }", "function calculateFps(now) {\n \tvar cur_fps = 1000 / (now - vp.fps.frame);\n \tvp.fps.frame = now;\n \tif (now - vp.fps.update > 1000)\n \t\tvp.fps.update = now; \n \treturn cur_fps; \n}", "function refresh_time(duration) {\n var mm = Math.floor(Math.floor(duration) / 60) + \"\";\n var ss = Math.ceil(Math.floor(duration) % 60) + \"\";\n\n if (mm.length < 2) { mm = \"0\" + mm; }\n if (ss.length < 2) { ss = \"0\" + ss; }\n container.html(mm + \":\" + ss);\n\n }", "function animation_frame() {\n var datalen = animationState.order.length,\n styles = animationState.styleArrays,\n curTime = Date.now(), genTime, updateTime,\n position, i, idx, p;\n timeRecords.frames.push(curTime);\n animationState.raf = null;\n position = ((curTime - animationState.startTime) / animationState.duration) % 1;\n if (position < 0) {\n position += 1;\n }\n animationState.position = position;\n\n for (idx = 0; idx < datalen; idx += 1) {\n i = animationState.order[idx];\n p = idx / datalen + position;\n if (p > 1) {\n p -= 1;\n }\n styles.p[i] = p;\n }\n if (animationStyles.fill) {\n for (i = 0; i < datalen; i += 1) {\n styles.fill[i] = styles.p[i] >= 0.1 ? false : true;\n }\n }\n if (animationStyles.fillColor) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n if (p >= 0.1) {\n styles.fillColor[i].r = 0;\n styles.fillColor[i].g = 0;\n styles.fillColor[i].b = 0;\n } else {\n styles.fillColor[i].r = p * 10;\n styles.fillColor[i].g = p * 8.39;\n styles.fillColor[i].b = p * 4.39;\n }\n }\n }\n if (animationStyles.fillOpacity) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n styles.fillOpacity[i] = p >= 0.1 ? 0 : 1.0 - p * 10; // 1 - 0\n }\n }\n if (animationStyles.radius) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n styles.radius[i] = p >= 0.1 ? 0 : 2 + 100 * p; // 2 - 12\n }\n }\n if (animationStyles.stroke) {\n for (i = 0; i < datalen; i += 1) {\n styles.stroke[i] = styles.p[i] >= 0.1 ? false : true;\n }\n }\n if (animationStyles.strokeColor) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n if (p >= 0.1) {\n styles.strokeColor[i].r = 0;\n styles.strokeColor[i].g = 0;\n styles.strokeColor[i].b = 0;\n } else {\n styles.strokeColor[i].r = p * 8.51;\n styles.strokeColor[i].g = p * 6.04;\n styles.strokeColor[i].b = 0;\n }\n }\n }\n if (animationStyles.strokeOpacity) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n styles.strokeOpacity[i] = p >= 0.1 ? 0 : 1.0 - p * p * 100; // (1 - 0) ^ 2\n }\n }\n if (animationStyles.strokeWidth) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n styles.strokeWidth[i] = p >= 0.1 ? 0 : 3 - 30 * p; // 3 - 0\n }\n }\n var updateStyles = {};\n $.each(animationStyles, function (key, use) {\n if (use) {\n updateStyles[key] = styles[key];\n }\n });\n genTime = Date.now();\n pointFeature.updateStyleFromArray(updateStyles, null, true);\n updateTime = Date.now();\n timeRecords.generate.push(genTime - curTime);\n timeRecords.update.push(updateTime - genTime);\n show_framerate();\n if (animationState.mode === 'play') {\n animationState.raf = window.requestAnimationFrame(animation_frame);\n }\n }", "function getFramesPerInterval() {\n\treturn getInterval()*fps/1000;\n}", "function animateFrames2(id,fps,reps,direction) {\n\n //Get all children of the frame-container\n var children = $(\"#\"+id).children();\n\n //Get the number of max. frames, count starts at 0!\n var max_frame = children.length;\n console.log(\"max frames: \"+max_frame);\n\n //Calculate duration per frame\n var duration = 1000/fps;\n\n //Just iterating the child array downwards\n if(direction===\"reverse\"){\n //Counter\n var frame = max_frame -1;\n //Set interval with defined fps\n var pid = setInterval(function () {\n //decrement frame\n frame--;\n //check if last frame was reached\n if (frame === -1) {\n //Start again at first frame\n if (reps === \"infinite\") {\n frame = max_frame -1; //already decremented!\n } else {\n //for now: Stop animation after one cycle\n clearInterval(pid);\n //save last shown frame in hash map\n threadHashMap[\"_\"+pid] = max_frame;\n return;\n }\n }\n\n //Hide last frame\n if (frame < max_frame -1 ) {\n children.eq(frame + 1).css(\"display\", \"none\");\n } else {\n //in case of a anterior cycle the first frame has to be hidden (no effect if first cycle)\n children.eq(0).css(\"display\", \"none\");\n }\n //Show current frame\n children.eq(frame).css(\"display\", \"block\");\n //save last shown frame in hash\n threadHashMap[\"_\"+pid] = frame;\n }, duration);\n }else {\n\n /* TODO WATCH OUT: HERE THE first frame is still pulled! fix ;)*/\n //Counter\n var frame = 0;\n\n //Set interval with defined fps\n var pid = setInterval(function () {\n\n //increment frame\n frame++;\n\n //check if last frame is reached\n if (frame >= max_frame) {\n //Start again at first frame\n if (reps === \"infinite\") {\n frame = 1; //already incremented!\n } else {\n //save last shown frame in hash\n threadHashMap[\"_\"+pid] = 1; // TODO should be 0 ...\n //for now: Stop animation after one cycle\n clearInterval(pid);\n return;\n }\n }\n\n //Hide last frame\n if (frame > 1) {\n children.eq(frame - 1).css(\"display\", \"none\");\n } else {\n //in case of a anterior cycle the last frame has to be hidden (no effect if first cycle)\n children.eq(max_frame - 1).css(\"display\", \"none\");\n }\n //Show current frame\n children.eq(frame).css(\"display\", \"block\");\n //save last shown frame in hash\n threadHashMap[\"_\"+pid] = frame;\n\n }, duration);\n }\n //Storing the pid of the last started frame thread thread under 'special' key '_0' in hash <_0,pid>, all other entries _n are <pid,frame>\n threadStack.push(pid);\n console.log(\"hash: \"+threadHashMap._0);\n console.log(\"hash-length-control: \"+ Object.keys(threadHashMap).length);\n}", "constructor(){\n this.startTime = 0;\n this.endTime = 0; \n this.running = 0;\n this.duration = 0;\n }", "startAnimating(fps){\n this.fpsInterval = 1000 / fps;\n this.then = Date.now();\n this.animate();\n }", "handleTimeUpdate(){\n this.setState({value: this.state.video.currentTime/this.state.video.duration});\n this.state.cTime = this.state.video.currentTime;\n }", "function timeToSampleFrame(time, sampleRate) {\n return Math.floor(0.5 + time * sampleRate);\n}", "function timeToSampleFrame(time, sampleRate) {\n return Math.floor(0.5 + time * sampleRate);\n}", "update( time ) {\r\n let animation = this.animationList[this.current];\r\n if( !animation ) return;\r\n this.progress += time * animation.fps;\r\n while( this.progress >= 1.0 ) {\r\n this.progress -= 1.0;\r\n this.frame++;\r\n if( this.frame >= animation.startFrame + animation.numFrames ) {\r\n this.frame = animation.startFrame;\r\n }\r\n }\r\n }", "toggleTimeframe(){\n\t\t// NOT YET IMPLEMENTED\n\t}", "updateCurrentTime(e) {\n e.preventDefault();\n // playHead / (100 / this.videoEle.duration) = this.videoEle.currentTime\n let targetTime = Number(e.target.value) / (100 / this.videoEle.duration);\n this.videoEle.currentTime = targetTime;\n this.updateProgress();\n }", "function FrameRateCounter() {\n this.lastFrameCount = 0;\n dateTemp = new Date();\n this.frameLast = dateTemp.getTime();\n delete dateTemp;\n this.frameCtr = 0;\n}", "function getDuration(input) {\n let runCommand = `\"${ffprobe}\" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -sexagesimal \"${input}\"`;\n return runCommand;\n}", "animate() {\n if (this.animationFrames.length > 1) {\n this.animationTimer += 1;\n const quotient = Math.floor(this.animationTimer / this.animationFrameDuration)\n const frame = quotient % this.animationFrames.length;\n this.srcImage = this.animationFrames[frame];\n if (this.animationTimer === this.animationFrameDuration * this.animationFrames.length) {\n this.animationTimer = 0;\n }\n }\n }", "function DurTime (e) {\n\tconst {duration,currentTime} = e.srcElement;\n\tvar sec;\n\tvar sec_d;\n\n\t// define minutes currentTime\n\tlet min = (currentTime==null)? 0:\n\t Math.floor(currentTime/60);\n\t min = min <10 ? '0'+min:min;\n\n\t// define seconds currentTime\n\tfunction get_sec (x) {\n\t\tif(Math.floor(x) >= 60){\n\n\t\t\tfor (var i = 1; i<=60; i++){\n\t\t\t\tif(Math.floor(x)>=(60*i) && Math.floor(x)<(60*(i+1))) {\n\t\t\t\t\tsec = Math.floor(x) - (60*i);\n\t\t\t\t\tsec = sec <10 ? '0'+sec:sec;\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t \tsec = Math.floor(x);\n\t\t \tsec = sec <10 ? '0'+sec:sec;\n\t\t }\n\t}\n\n\tget_sec (currentTime,sec);\n\n\t// change currentTime DOM\n\tcurrTime.innerHTML = min +':'+ sec;\n\n\t// define minutes duration\n\tlet min_d = (isNaN(duration) === true)? '0':\n\t\tMath.floor(duration/60);\n\t min_d = min_d <10 ? '0'+min_d:min_d;\n\n\n\t function get_sec_d (x) {\n\t\tif(Math.floor(x) >= 60){\n\n\t\t\tfor (var i = 1; i<=60; i++){\n\t\t\t\tif(Math.floor(x)>=(60*i) && Math.floor(x)<(60*(i+1))) {\n\t\t\t\t\tsec_d = Math.floor(x) - (60*i);\n\t\t\t\t\tsec_d = sec_d <10 ? '0'+sec_d:sec_d;\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t \tsec_d = (isNaN(duration) === true)? '0':\n\t\t \tMath.floor(x);\n\t\t \tsec_d = sec_d <10 ? '0'+sec_d:sec_d;\n\t\t }\n\t}\n\n\t// define seconds duration\n\n\tget_sec_d (duration);\n\n\t// change duration DOM\n\tdurTime.innerHTML = min_d +':'+ sec_d;\n\n}", "function logAverageFrame(times) { // times is the array of User Timing measurements from updatePositions()\n var numberOfEntries = times.length;\n var sum = 0;\n for (var i = numberOfEntries - 1; i > numberOfEntries - 11; i--) {\n sum = sum + times[i].duration;\n }\n console.log('Average time to generate last 10 frames: ' + sum / 10 + 'ms');\n}", "function runAnimation(frameFunc){\n let lastTime = null;\n function frame(time){\n if(lastTime!=null){\n let timeStep = Math.min(time - lastTime,100)/1000;\n if(frameFunc(timeStep)==false)return;\n }\n lastTime = time;\n requestAnimationFrame(frame);\n }\n requestAnimationFrame(frame);\n }", "function checkFrames(frames) {\n var width = frames[0].width,\n height = frames[0].height,\n duration = frames[0].duration;\n for (var i = 1; i < frames.length; i++) {\n if (frames[i].width != width)\n throw \"Frame \" + (i + 1) + \" has a different width\";\n if (frames[i].height != height)\n throw \"Frame \" + (i + 1) + \" has a different height\";\n if (frames[i].duration < 0 || frames[i].duration > 0x7fff)\n throw \"Frame \" + (i + 1) + \" has a weird duration (must be between 0 and 32767)\";\n duration += frames[i].duration;\n }\n return {\n duration: duration,\n width: width,\n height: height\n };\n }", "static stop() {\n this.running = false\n\n const elapsed = performance.now() - this.start,\n sum = this.frames.reduce((sum, time) => (sum += time)),\n average = this.frames.length / (sum / 1000),\n fps = this.frameCount / (elapsed / 1000)\n\n console.table({\n 'Elapsed time': elapsed,\n Frames: this.frameCount,\n 'Frame sum': sum,\n 'Average FPS 1': fps,\n 'Average FPS 2': average,\n })\n\n //console.log(this.frames);\n }", "function change_duration(){\r\n slider_position = track.duration * (slider.value / 100);//Asocia el valor del slider con el del volumen del track\r\n track.currentTime = slider_position; //Le da el valor cuando se mueve el slider\r\n \r\n }", "animate(){\n // request another frame\n window.requestAnimationFrame(this.animate.bind(this));\n\n // calc elapsed time since last loop\n this.now = Date.now();\n this.elapsed = this.now - this.then;\n // if enough time has elapsed, draw the next frame\n if (this.elapsed > this.fpsInterval){\n // Get ready for next frame by setting then=now, but also adjust for your\n // specified fpsInterval not being a multiple of RAF's interval (16.7ms)\n this.then = this.now - (this.elapsed % this.fpsInterval)\n\n // animation code\n this.animateOneFrame();\n }\n }", "updateCurrentTimeDisplay() {\n const minutes = Math.floor(this.video.currentTime / 60);\n let seconds = Math.floor(this.video.currentTime);\n // Pad a leading 0 for display purposes\n if (seconds < 10) {\n seconds = \"0\" + seconds;\n }\n this.durationText.textContent = minutes + \":\" + seconds;\n }", "function ChangeProgress(e){\n const {currentTime, duration}=e.srcElement;\n const progressPercentage = (currentTime/duration)*100;\n progress.style.width= `${progressPercentage}%`\n //const {currentTime, duration}=e.srcElement;\n var minutes = Math.floor(duration / 60);\n var seconds = duration - minutes * 60;\n\n //var runMinutes=Math.floor(currentTime * 60);\n //var runSeconds = currentTime - minutes * 60;\nif(typeof(minutes)!==\"NaN\"&&typeof(seconds)!==\"NaN\")\n{\n document.getElementById(\"durationTime\").textContent= `${minutes}:${seconds.toFixed(0)}`;\n}\n\n //document.getElementById(\"runTime\").textContent= `${runMinutes}:${runSeconds.toFixed(0)}`;\n\n}", "function logAverageFrame(times) { // times is the array of User Timing measurements from updatePositions()\n var numberOfEntries = times.length;\n var sum = 0;\n for (var i = numberOfEntries - 1; i > numberOfEntries - 11; i--) {\n sum = sum + times[i].duration;\n }\n console.log(\"Average time to generate last 10 frames: \" + sum / 10 + \"ms\");\n}", "function timeUpdate() {\n slider.setAttribute('max', Math.ceil(video.duration))\n slider.value=video.currentTime\n videoInfo.style.display='block';\n videoInfo.innerHTML = [\n \"Video size: \" + video.videoWidth + \"x\" + video.videoHeight,\n \"Video length: \" + (Math.round(video.duration * 10) / 10) + \"sec\",\n \"Playback position: \" + (Math.round(video.currentTime * 10) / 10) + \"sec\",\n ].join('<br>');\n}", "animateVertical(duration, framesCount) {\n this.scale.y = 1 / framesCount\n this.duration = duration\n this.frameTime = duration / framesCount\n\n this.update = dt => {\n const index = Math.floor(new Date().getTime() % this.duration / this.frameTime)\n this.offset.y = index / framesCount\n }\n }", "function compute_fps() {\n let counter_element = document.querySelector(\"#fps-counter\");\n if (counter_element != null) {\n counter_element.innerText = \"FPS: \" + g_frames_since_last_fps_count;\n }\n g_frames_since_last_fps_count = 0;\n}", "_fbTimer() {\n this._timerPointer = setTimeout(() => {\n this._fbTimer();\n if (this._firstFrameReceived && !this._processingFrame && this._fps > 0) {\n this.requestFrameUpdate();\n }\n }, this._timerInterval)\n }", "updateDuration() {\n let oldDuration = this.mediaSource.duration;\n let newDuration = Hls.Playlist.duration(this.masterPlaylistLoader_.media());\n let buffered = this.tech_.buffered();\n let setDuration = () => {\n this.mediaSource.duration = newDuration;\n this.tech_.trigger('durationchange');\n\n this.mediaSource.removeEventListener('sourceopen', setDuration);\n };\n\n if (buffered.length > 0) {\n newDuration = Math.max(newDuration, buffered.end(buffered.length - 1));\n }\n\n // if the duration has changed, invalidate the cached value\n if (oldDuration !== newDuration) {\n // update the duration\n if (this.mediaSource.readyState !== 'open') {\n this.mediaSource.addEventListener('sourceopen', setDuration);\n } else {\n setDuration();\n }\n }\n }", "processTimeInput() {\n\n var timeTokens = this._currentTimeInput.value.split(\":\");\n if (timeTokens.length != 2)\n {\n console.log(\"Provided invalid time (minutes:seconds) expected: \" + this._currentTimeInput.value);\n this._currentTimeInput.classList.add(\"has-border\");\n this._currentTimeInput.classList.add(\"is-invalid\");\n return;\n }\n\n var minutes = parseInt(timeTokens[0]);\n if (isNaN(minutes))\n {\n console.log(\"Provided invalid time (minutes:seconds) expected: \" + this._currentTimeInput.value);\n this._currentTimeInput.classList.add(\"has-border\");\n this._currentTimeInput.classList.add(\"is-invalid\");\n return;\n }\n\n var seconds = parseInt(timeTokens[1]);\n if (isNaN(seconds))\n {\n console.log(\"Provided invalid time (minutes:seconds) expected: \" + this._currentTimeInput.value);\n this._currentTimeInput.classList.add(\"has-border\");\n this._currentTimeInput.classList.add(\"is-invalid\");\n return;\n }\n\n var frame = this._timeToFrame(minutes, seconds);\n const maxFrame = this._maxFrameNumber;\n if (frame > maxFrame)\n {\n frame = maxFrame;\n }\n else if (frame < 0)\n {\n frame = 0;\n }\n\n this._currentTimeInput.classList.remove(\"has-border\");\n this._currentTimeInput.classList.remove(\"is-invalid\");\n this.goToFrame(frame);\n this.checkAllReady();\n }", "timeOk() {\n return performance.now() - this._lastFrameStart < this._THRESHOLD;\n }", "function convertFBXTimeToSeconds( time ) {\n \n return time / 46186158000;\n \n }", "timer() {\n let video = document.getElementById('video');\n let seekBar = document.getElementById('seek-bar');\n\n let newTime = video.currentTime * (100 / video.duration)\n if (!newTime) { newTime = 0 }\n seekBar.value = newTime;\n\n // this.curtimetext.innerHTML = curmins + \":\" + cursecs\n // this.durtimetext.innerHTML = durmins + \":\" + dursecs\n let time = video.currentTime;\n let minutes = Math.floor(time / 60);\n let seconds = Math.floor(time % 60);\n if (seconds < 10) { seconds = \"0\" + seconds}\n let newTimer = (minutes + \":\" + seconds);\n\n let dur = video.duration;\n let durminutes = Math.floor(dur / 60);\n let dursecs = Math.floor(dur % 60);\n if (dursecs < 10) { dursecs = \"0\" + dursecs }\n let duration = (durminutes + \":\" + dursecs);\n \n this.setState({ timer: newTimer + \"/\" + duration })\n this.calculateTime();\n this.playPause();\n }", "minutePosition() {\n return this.frameCount % this.framesPerMin;\n }", "getFrame(t) {\nvar NF, f, frame, resolved, was_complete;\n//-------\n// Allow for the possibility that the frame seqeuence is extended\n// while we are scanning it. In the case where our search apparently\n// hits the sequence limit this means (a) that we should check\n// whether new frames have been added, and (b) that we shouldn''t\n// terminate the animation until we know that it is complete.\n// If I knew more about modern browsers' scheduling, I might realise\n// that this is unnecessarily complicated, or perhaps alternatively\n// that it is not complicated enough to be safe.\nresolved = false;\nwhile (!resolved) {\nwas_complete = this.isComplete;\nNF = this.fCount;\nf = this.getFrameIndex(t, NF);\nresolved = f !== NF || was_complete || NF === this.fCount;\nif (--this.traceMax > 0) {\nif (typeof lggr.trace === \"function\") {\nlggr.trace(`Resolved: ${resolved} f=${f} NF=${NF} fCount=${this.fCount}`);\n}\n}\n}\n// Find result frame\n// Rather than terminate the animation, stick at the last available\n// frame, pending the arrival of possible successors -- via\n// @extendSigns() -- or the indication that there will never be\n// any successors -- via @setCompleted.\nreturn frame = f !== NF ? (this.fIncomplete = 0, this.setFrameAt(f)) : this.isComplete ? null : (this.fIncomplete++, this.fIncomplete < 5 ? typeof lggr.debug === \"function\" ? lggr.debug(\"getFrame: at end of incomplete animation\") : void 0 : void 0, this.setFrameAt(NF - 1));\n}", "function currentTimeSegment(timeFrame) {\n\t\tvar step = $scope.timeSegmentsList[0].segmentRange;\n\t\tvar indexInTimeSegments = Math.floor(timeFrame / step);\n\t\tif (indexInTimeSegments == $scope.timeSegmentsList.length) indexInTimeSegments--;\n\t\treturn indexInTimeSegments;\n\t}", "function nextFrame() {\n _timeController.proposeNextFrame();\n }", "function init() \n {\n\t\t\n\t\t// initialize variables\n\t\tvideo = document.getElementById(\"video1\");\n\t\tcanvas = document.getElementById(\"canvas\");\n\t\ttime_slider = document.getElementById(\"time_slider\");\n label_CurrenFrame = document.getElementById(\"currentFrameTime\");\n label_VideoLength = document.getElementById(\"videoLength\");\n\t\tprevious_frame = document.getElementById(\"previousFrame\");\n\t\tnext_frame = document.getElementById(\"nextFrame\");\n\t\tcontainer = document.getElementById(\"container\");\n\t\tcreate_sum = document.getElementById(\"submit\");\n\t\t\n //initialize events\n\t\tcanvas.addEventListener(\"click\", saveFrame, false);\n\t\tcanvas.addEventListener(\"mousemove\", mouseMove, false);\n\t\ttime_slider.addEventListener(\"change\", UpdateFrame, false);\n\t\ttime_slider.addEventListener(\"input\", UpdateFrame, false);\n\t\t\n\t\tdocument.getElementById('files').addEventListener('change', FileChosen);\n\t\tdocument.getElementById('UploadButton').addEventListener('click', StartUpload); \n\t\t\n video.addEventListener('loadeddata', function () {\n label_CurrenFrame.innerHTML = secondsToTimeString(video.currentTime);\n label_VideoLength.innerHTML = secondsToTimeString(video.duration);\n });\n \n\t\tprevious_frame.addEventListener('click', \n\t\tfunction() {\n\t\t\tif (actual_frame === null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isUndefined(actual_frame)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (actual_frame.second <= 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar value = Math.floor((actual_frame.second - 1) * 100 / video.duration);\n\t\t\tif (value >= 0 && value <= 100) {\n\t\t\t\tactual_frame.second--;\n\t\t\t\ttime_slider.value = value;\n\t\t\t\tdrawFrame(actual_frame);\n\t\t\t}\n\t\t},\n\t\tfalse);\n\t\t\n\t\tnext_frame.addEventListener('click', \n\t\tfunction() {\n\t\t\tif (actual_frame === null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (video === null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isUndefined(actual_frame) || isUndefined(video) || isUndefined(video.duration)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (actual_frame.second >= video.duration) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar value = Math.floor((actual_frame.second + 1) * 100 / video.duration);\n\t\t\tif (value >= 0 && value <= 100) {\n\t\t\t\tactual_frame.second++;\n\t\t\t\ttime_slider.value = value;\n\t\t\t\tdrawFrame(actual_frame);\n\t\t\t}\n\t\t},\n\t\tfalse);\n\t\t\n\t\tdocument.getElementById('submit').addEventListener('click', \n\t\tfunction() {\n\t\t\tupdateDescriptions();\n\t\t\tvar result = combineSegments();\n\t\t\tconsole.log(result);\n\t\t\t// send result to server!\n \t\t\tsocket.emit('ffmpeg', { 'Name' : SelectedFile.name, 'Data' : result });\n\t\t\tdocument.getElementById(\"create_progress\").innerHTML='Creating summary... 0%';\n \n\t\t\tResetSegments();\n\t\t},\n\t\tfalse);\n\t\t\n\t\t// initialize player\n\t\tinitPlayer();\n\t\n\t}", "_audioDuration() {\n if (this.live) {\n return Infinity\n }\n else {\n return this.video.duration * 1000;\n }\n }", "function DurTime(e) {\n const { duration, currentTime } = e.target;\n var sec;\n var sec_d;\n\n // define minutes currentTime\n let min = currentTime == null ? 0 : Math.floor(currentTime / 60);\n min = min < 10 ? \"0\" + min : min;\n\n // define seconds currentTime\n function get_sec(x) {\n if (Math.floor(x) >= 60) {\n for (var i = 1; i <= 60; i++) {\n if (Math.floor(x) >= 60 * i && Math.floor(x) < 60 * (i + 1)) {\n sec = Math.floor(x) - 60 * i;\n sec = sec < 10 ? \"0\" + sec : sec;\n }\n }\n } else {\n sec = Math.floor(x);\n sec = sec < 10 ? \"0\" + sec : sec;\n }\n }\n\n get_sec(currentTime, sec);\n\n // change currentTime DOM\n currTime.innerHTML = min + \":\" + sec;\n\n // define minutes duration\n let min_d = isNaN(duration) === true ? \"0\" : Math.floor(duration / 60);\n min_d = min_d < 10 ? \"0\" + min_d : min_d;\n\n function get_sec_d(x) {\n if (Math.floor(x) >= 60) {\n for (var i = 1; i <= 60; i++) {\n if (Math.floor(x) >= 60 * i && Math.floor(x) < 60 * (i + 1)) {\n sec_d = Math.floor(x) - 60 * i;\n sec_d = sec_d < 10 ? \"0\" + sec_d : sec_d;\n }\n }\n } else {\n sec_d = isNaN(duration) === true ? \"0\" : Math.floor(x);\n sec_d = sec_d < 10 ? \"0\" + sec_d : sec_d;\n }\n }\n\n // define seconds duration\n\n get_sec_d(duration);\n\n // change duration DOM\n durTime.innerHTML = min_d + \":\" + sec_d;\n updateProgress(e);\n }", "function tick() {\n\n //make framecount always be a number between 0 to 600\n if (framecount<600) \n framecount++;\n else\n { \n flag++;\n framecount=framecount%600;\n }\n\n requestAnimFrame(tick);\n draw();\n animate();\n \n \n\n}", "updateFrame() {\n let newFrameIndex;\n if(this.isInReverse) {\n newFrameIndex = this.currFrame - 1;\n if(newFrameIndex < 0) {\n if (this.loops) {\n this.isInReverse = false;\n newFrameIndex = this.currFrame + 1;\n } else {\n this.isAnimating = false;\n this.isFinished = true;\n newFrameIndex = 0;\n } \n } \n } else {\n newFrameIndex = this.currFrame + 1;\n if(newFrameIndex >= this.frames.length) {\n if(this.reverses) {\n newFrameIndex = this.currFrame - 1;\n this.isInReverse = true;\n } else if(this.loops) {\n newFrameIndex = 0;\n } else if (this.holds) { \n newFrameIndex = this.frames.length - 1;\n } else {\n this.isAnimating = false;\n this.isFinished = true;\n newFrameIndex = 0;\n }\n }\n }\n\n this.currFrame = newFrameIndex;\n }", "countFrames() {\nreturn this.fCount;\n}", "function update_frame(v_index){\r\n\r\n\tif(v_index == 1){\r\n\t\tvideoT.currentTime = document.getElementById(\"slidebar_T\").value/100* videoT.duration;\r\n\t}\r\n\telse if(v_index ==2){\r\n\t\tvideoGP.currentTime = document.getElementById(\"slidebar_GP\").value/100 *videoGP.duration;\r\n\t}\r\n\telse{\r\n\t\talert(\"Error update_frame() : video index invalid\");\r\n\t}\r\n\r\n\r\n}", "function interval_stream() {\n\n var rtsp = document.getElementById('RTSPCtl');\n var fps_status = rtsp.Get_FPS();\n var bps_status = rtsp.Get_KBPS();\n\n if (fps_status >= 1)\n fps_status++;\n\n $('#fps').html('FPS: <font color=\"blue\">' + fps_status + ' fps</font>');\n $('#bps').html('BPS: <font color=\"blue\">' + bps_status + ' Kbps</font>');\n\n setTimeout('interval_stream()', 1000);\n}", "getDuration() {\n return this.video.duration;\n }", "function onPlaybackUpdate(time, duration) {\n}", "seek(e){\n this.setState({sentinel : true});\n console.log(e.target.value, parseFloat(this.state.duration));\n this.state.video.currentTime = parseFloat(e.target.value)*parseFloat(this.state.duration);\n this.state.video2.currentTime = parseFloat(e.target.value)*parseFloat(this.state.duration);\n }", "processFrameInput() {\n\n var frame = parseInt(this._currentFrameInput.value);\n if (isNaN(frame)) {\n console.log(\"Provided invalid frame input: \" + this._currentFrameInput.value);\n this._currentFrameInput.classList.add(\"has-border\");\n this._currentFrameInput.classList.add(\"is-invalid\");\n return;\n }\n\n const maxFrame = this._mediaInfo.num_frames - 1;\n if (frame > maxFrame)\n {\n frame = maxFrame;\n }\n else if (frame < 0)\n {\n frame = 0;\n }\n\n this._currentFrameInput.classList.remove(\"has-border\");\n this._currentFrameInput.classList.remove(\"is-invalid\");\n this.goToFrame(frame);\n }" ]
[ "0.70782954", "0.7076676", "0.70356077", "0.7027187", "0.6897035", "0.679971", "0.6738457", "0.67182046", "0.65745807", "0.6483586", "0.6443946", "0.6338004", "0.63288355", "0.6305262", "0.6217638", "0.62138844", "0.6160785", "0.61125994", "0.60788536", "0.60742015", "0.60491276", "0.6048033", "0.6047474", "0.604141", "0.6003058", "0.59940475", "0.59814125", "0.59766454", "0.59682024", "0.5951092", "0.59435844", "0.59383935", "0.5933362", "0.58948725", "0.58549744", "0.58402246", "0.58349746", "0.58318263", "0.582924", "0.5821338", "0.58138555", "0.58138555", "0.58096826", "0.5804712", "0.5804712", "0.578814", "0.5772781", "0.5767392", "0.57663304", "0.57650834", "0.57598543", "0.57528776", "0.57496613", "0.5748467", "0.57481027", "0.5745284", "0.57391196", "0.5737056", "0.57274395", "0.57274395", "0.57270557", "0.5726779", "0.5723431", "0.57173485", "0.5716042", "0.570919", "0.56996745", "0.5695861", "0.5692474", "0.56915885", "0.5682659", "0.56750095", "0.5671822", "0.566499", "0.5659775", "0.5657754", "0.5652441", "0.56405324", "0.56364256", "0.5632105", "0.56319726", "0.56247264", "0.5624454", "0.56221354", "0.5613962", "0.56118727", "0.56000596", "0.5595617", "0.5591995", "0.55827665", "0.5574842", "0.55743665", "0.5566074", "0.55644715", "0.5564348", "0.5561772", "0.5556436", "0.5549068", "0.55484134", "0.5546427", "0.55436534" ]
0.0
-1
Receive messages from main thread
handleMessage(e){ console.log("received message with id: ", e.data.id, "; message was: ", e); switch (e.data.id) { case "quantization": this._quantOpt = e.data.quantOpt; this._quantBits = e.data.quantBits; break; case "reverseK": this._reverseKOpt = e.data.reverseKOpt; break; case "perfectSynth": this._perfectSynthOpt = e.data.perfectSynthOpt; break; case "resampling": this._resamplingFactor = e.data.resampFactor; this._resampler.update(this._resamplingFactor); break; case "voicedThreshold": this._confidenceTonalThreshold = e.data.voicedThreshold; break; case "pitchFactor": this._pitchFactor = e.data.pitchFactor; break; case "voiceMap": // Voiced / Unvoiced Synthesis this._unvoicedMix = e.data.unvoicedMix; this._confidenceTonalThreshold = e.data.voicedThreshold; // Resampling (vocal tract length) if (e.data.vocalTractFactor != this._resamplingFactor){ this._resamplingFactor = e.data.vocalTractFactor; this._resampler.update(this._resamplingFactor); } // Pitch modifier this._pitchFactor = e.data.pitchFactor; // Vibrato //e.data.vibratoEffect; break; case "options": // Receive all options this._perfectSynthOpt = e.data.perfectSynthOpt; this._quantOpt = e.data.quantOpt; this._quantBits = e.data.quantBits; this._reverseKOpt = e.data.reverseKOpt; if (e.data.vocalTractFactor != this._resamplingFactor){ this._resamplingFactor = e.data.vocalTractFactor; this._resampler.update(this._resamplingFactor); } this._confidenceTonalThreshold = e.data.voicedThreshold; this._pitchFactor = e.data.pitchFactor; break; default: // any unknown ID: log the message ID console.log("unknown message received:") console.log(e.data) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onMessageReceive() {}", "function mainThreadReceivedMessage(e) {\n var msg = e.data;\n var worker = workers[msg.workerId];\n var aborted = false;\n\n if (msg.error) worker.userError(msg.error, msg.file);\n else if (msg.results && msg.results.data) {\n var abort = function() {\n aborted = true;\n completeWorker(msg.workerId, {\n data: [],\n errors: [],\n meta: {aborted: true},\n });\n };\n\n var handle = {\n abort: abort,\n pause: notImplemented,\n resume: notImplemented,\n };\n\n if (isFunction(worker.userStep)) {\n for (var i = 0; i < msg.results.data.length; i++) {\n worker.userStep(\n {\n data: [msg.results.data[i]],\n errors: msg.results.errors,\n meta: msg.results.meta,\n },\n handle\n );\n if (aborted) break;\n }\n delete msg.results; // free memory ASAP\n } else if (isFunction(worker.userChunk)) {\n worker.userChunk(msg.results, handle, msg.file);\n delete msg.results;\n }\n }\n\n if (msg.finished && !aborted) completeWorker(msg.workerId, msg.results);\n }", "function mainThreadReceivedMessage(e)\n\t\t{\n\t\t\tvar msg = e.data;\n\t\t\tvar worker = workers[msg.workerId];\n\t\t\tvar aborted = false;\n\n\t\t\tif (msg.error)\n\t\t\t\tworker.userError(msg.error, msg.file);\n\t\t\telse if (msg.results && msg.results.data)\n\t\t\t{\n\t\t\t\tvar abort = function() {\n\t\t\t\t\taborted = true;\n\t\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t\t};\n\n\t\t\t\tvar handle = {\n\t\t\t\t\tabort: abort,\n\t\t\t\t\tpause: notImplemented,\n\t\t\t\t\tresume: notImplemented\n\t\t\t\t};\n\n\t\t\t\tif (isFunction(worker.userStep))\n\t\t\t\t{\n\t\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\t\tdata: msg.results.data[i],\n\t\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t\t}, handle);\n\t\t\t\t\t\tif (aborted)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t\t}\n\t\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t\t{\n\t\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\t\tdelete msg.results;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (msg.finished && !aborted)\n\t\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t\t}", "function mainThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\t\tvar worker = workers[msg.workerId];\n\t\tvar aborted = false;\n\n\t\tif (msg.error)\n\t\t\tworker.userError(msg.error, msg.file);\n\t\telse if (msg.results && msg.results.data)\n\t\t{\n\t\t\tvar abort = function() {\n\t\t\t\taborted = true;\n\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t};\n\n\t\t\tvar handle = {\n\t\t\t\tabort: abort,\n\t\t\t\tpause: notImplemented,\n\t\t\t\tresume: notImplemented\n\t\t\t};\n\n\t\t\tif (isFunction(worker.userStep))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t{\n\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\tdata: [msg.results.data[i]],\n\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t}, handle);\n\t\t\t\t\tif (aborted)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t}\n\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t{\n\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\tdelete msg.results;\n\t\t\t}\n\t\t}\n\n\t\tif (msg.finished && !aborted)\n\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t}", "function mainThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\t\tvar worker = workers[msg.workerId];\n\t\tvar aborted = false;\n\n\t\tif (msg.error)\n\t\t\tworker.userError(msg.error, msg.file);\n\t\telse if (msg.results && msg.results.data)\n\t\t{\n\t\t\tvar abort = function() {\n\t\t\t\taborted = true;\n\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t};\n\n\t\t\tvar handle = {\n\t\t\t\tabort: abort,\n\t\t\t\tpause: notImplemented,\n\t\t\t\tresume: notImplemented\n\t\t\t};\n\n\t\t\tif (isFunction(worker.userStep))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t{\n\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\tdata: [msg.results.data[i]],\n\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t}, handle);\n\t\t\t\t\tif (aborted)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t}\n\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t{\n\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\tdelete msg.results;\n\t\t\t}\n\t\t}\n\n\t\tif (msg.finished && !aborted)\n\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t}", "function mainThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\t\tvar worker = workers[msg.workerId];\n\t\tvar aborted = false;\n\n\t\tif (msg.error)\n\t\t\tworker.userError(msg.error, msg.file);\n\t\telse if (msg.results && msg.results.data)\n\t\t{\n\t\t\tvar abort = function() {\n\t\t\t\taborted = true;\n\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t};\n\n\t\t\tvar handle = {\n\t\t\t\tabort: abort,\n\t\t\t\tpause: notImplemented,\n\t\t\t\tresume: notImplemented\n\t\t\t};\n\n\t\t\tif (isFunction(worker.userStep))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t{\n\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\tdata: [msg.results.data[i]],\n\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t}, handle);\n\t\t\t\t\tif (aborted)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t}\n\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t{\n\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\tdelete msg.results;\n\t\t\t}\n\t\t}\n\n\t\tif (msg.finished && !aborted)\n\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t}", "function mainThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\t\tvar worker = workers[msg.workerId];\n\t\tvar aborted = false;\n\n\t\tif (msg.error)\n\t\t\tworker.userError(msg.error, msg.file);\n\t\telse if (msg.results && msg.results.data)\n\t\t{\n\t\t\tvar abort = function() {\n\t\t\t\taborted = true;\n\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t};\n\n\t\t\tvar handle = {\n\t\t\t\tabort: abort,\n\t\t\t\tpause: notImplemented,\n\t\t\t\tresume: notImplemented\n\t\t\t};\n\n\t\t\tif (isFunction(worker.userStep))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t{\n\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\tdata: [msg.results.data[i]],\n\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t}, handle);\n\t\t\t\t\tif (aborted)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t}\n\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t{\n\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\tdelete msg.results;\n\t\t\t}\n\t\t}\n\n\t\tif (msg.finished && !aborted)\n\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t}", "function mainThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\t\tvar worker = workers[msg.workerId];\n\t\tvar aborted = false;\n\n\t\tif (msg.error)\n\t\t\tworker.userError(msg.error, msg.file);\n\t\telse if (msg.results && msg.results.data)\n\t\t{\n\t\t\tvar abort = function() {\n\t\t\t\taborted = true;\n\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t};\n\n\t\t\tvar handle = {\n\t\t\t\tabort: abort,\n\t\t\t\tpause: notImplemented,\n\t\t\t\tresume: notImplemented\n\t\t\t};\n\n\t\t\tif (isFunction(worker.userStep))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t{\n\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\tdata: [msg.results.data[i]],\n\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t}, handle);\n\t\t\t\t\tif (aborted)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t}\n\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t{\n\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\tdelete msg.results;\n\t\t\t}\n\t\t}\n\n\t\tif (msg.finished && !aborted)\n\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t}", "function mainThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\t\tvar worker = workers[msg.workerId];\n\t\tvar aborted = false;\n\n\t\tif (msg.error)\n\t\t\tworker.userError(msg.error, msg.file);\n\t\telse if (msg.results && msg.results.data)\n\t\t{\n\t\t\tvar abort = function() {\n\t\t\t\taborted = true;\n\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t};\n\n\t\t\tvar handle = {\n\t\t\t\tabort: abort,\n\t\t\t\tpause: notImplemented,\n\t\t\t\tresume: notImplemented\n\t\t\t};\n\n\t\t\tif (isFunction(worker.userStep))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t{\n\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\tdata: [msg.results.data[i]],\n\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t}, handle);\n\t\t\t\t\tif (aborted)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t}\n\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t{\n\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\tdelete msg.results;\n\t\t\t}\n\t\t}\n\n\t\tif (msg.finished && !aborted)\n\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t}", "function mainThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\t\tvar worker = workers[msg.workerId];\n\t\tvar aborted = false;\n\n\t\tif (msg.error)\n\t\t\tworker.userError(msg.error, msg.file);\n\t\telse if (msg.results && msg.results.data)\n\t\t{\n\t\t\tvar abort = function() {\n\t\t\t\taborted = true;\n\t\t\t\tcompleteWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });\n\t\t\t};\n\n\t\t\tvar handle = {\n\t\t\t\tabort: abort,\n\t\t\t\tpause: notImplemented,\n\t\t\t\tresume: notImplemented\n\t\t\t};\n\n\t\t\tif (isFunction(worker.userStep))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < msg.results.data.length; i++)\n\t\t\t\t{\n\t\t\t\t\tworker.userStep({\n\t\t\t\t\t\tdata: [msg.results.data[i]],\n\t\t\t\t\t\terrors: msg.results.errors,\n\t\t\t\t\t\tmeta: msg.results.meta\n\t\t\t\t\t}, handle);\n\t\t\t\t\tif (aborted)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdelete msg.results;\t// free memory ASAP\n\t\t\t}\n\t\t\telse if (isFunction(worker.userChunk))\n\t\t\t{\n\t\t\t\tworker.userChunk(msg.results, handle, msg.file);\n\t\t\t\tdelete msg.results;\n\t\t\t}\n\t\t}\n\n\t\tif (msg.finished && !aborted)\n\t\t\tcompleteWorker(msg.workerId, msg.results);\n\t}", "receive() {\n if (this.stopMe) {\n return;\n }\n this.mq.receiveMessage({qname: config.queueName}, (err, msg) => {\n if (err) {\n throw err;\n }\n if (msg.id) {\n this.errorDetection(msg);\n this.mq.deleteMessage({qname: config.queueName, id: msg.id}, () => {\n this.receive();\n });\n process.stdout.write('\\x1B[2KReceiving: <<< [' + msg.message + ']\\r');\n }\n else {\n // console.log(\"No messages for me...\");\n this.receive();\n }\n });\n }", "async run() {\n while (true) {\n const userInput = await this.getMessage();\n const response = this.handleMessage(userInput);\n this.handleResponse(response);\n }\n }", "static receive() {}", "function listenMessages() {\n\tchrome.runtime.onMessage.addListener(checkMessage);\n}", "onReceive(data)\n {\n //console.log(\"RX:\", data);\n\n // Capture the data\n this.receivedBuffers.push(data);\n\n // Resolve waiting promise\n if (this.waiter)\n this.waiter();\n }", "function handleReceiveMessage(event) {\n console.log(event.data);\n}", "function receivedMessageRead(event) {\n messageHandler.receivedMessageRead(event);\n }", "function main() {\n\tproc.on( 'message', onMessage );\n}", "function message_recv(message){\n if(message.subject == \"add_training_data\"){\n label = message.label;\n keywords = message.keywords;\n addTrainingData(keywords, label);\n training();\n return;\n }\n else if (message.subject == \"request_categories\"){\n chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {\n chrome.tabs.sendMessage(tabs[0].id, {subject: \"categories\", categories: JSON.stringify(categories)});\n });\n return;\n }\n else if (message.subject == 'get_pri'){\n chrome.runtime.sendMessage(message={subject:'pri_history', pri_history : JSON.stringify(pri_history)});\n return; \n }\n chrome.tabs.sendMessage(message={'labels' : labels, 'keywords' : keywords, 'count_matrix' : count_matrix});\n}", "onMessage() {}", "onMessage() {}", "function handleMessage(msg) { // process message asynchronously\n setTimeout(function () {\n messageHandler(msg);\n }, 0);\n }", "function main_thread() {\n try {\n // Handle active connections message sends\n for (const agent_id in agent_id_to_socket) {\n let agent_state = agent_id_to_agent[agent_id];\n if (!agent_state.is_alive) {\n continue;\n }\n let sendable_messages = agent_state.get_sendable_messages();\n if (sendable_messages.length > 0) {\n let socket = agent_id_to_socket[agent_id];\n // TODO send all these messages in a batch\n for (const packet of sendable_messages) {\n _send_message(socket, packet);\n }\n }\n }\n\n // Handle sending batches to the mephisto python client\n let mephisto_messages = [];\n while (mephisto_message_queue.length > 0) {\n mephisto_messages.push(mephisto_message_queue.shift());\n }\n if (mephisto_messages.length > 0) {\n for (const packet of mephisto_messages) {\n _send_message(mephisto_socket, packet);\n }\n }\n } catch (error) {\n console.log(\"Transient error in main thread?\");\n console.log(error);\n }\n\n // Re-call this thead, as it should run forever\n main_thread_timeout = setTimeout(main_thread, 50);\n}", "onMessageStart() { }", "function receiveMessage(e) {\n\teval( e.data );\n}", "function onSocketMessage(event) {\r\n\tappendContent(\"theMessages\", \"Received: \" + event.data + \"<br/>\");\r\n}", "function onRecieve(buf) {\n if(!isActive) {\n return;\n }\n var msgType = buf.readUint8();\n // world state update\n if (msgType === 1) {\n main.world.update(buf, main.scene)\n }\n // respond to a ping request\n if (msgType === 2) {\n server.send(server.newMessage(2));\n }\n }", "function onMessageReceived(e) {\n var data = JSON.parse(e.data);\n \n switch (data.event) {\n case 'ready':\n onReady();\n break;\n \n case 'playProgress':\n onPlayProgress(data.data);\n break;\n \n case 'finish':\n onFinish();\n break;\n }\n \t}", "function receive(message) {\n activeWrapper.receiveMessage(message);\n}", "async receive() {\n return new Promise((resolve) => this.once('message', (data) => {\n const msg = deserialise(data);\n this._logger.push({ msg }).log('Received');\n resolve(msg);\n }));\n }", "startEventListener() {\n Utils.contract.MessagePosted().watch((err, { result }) => {\n if(err)\n return console.error('Failed to bind event listener:', err);\n\n console.log('Detected new message:', result.id);\n this.fetchMessage(+result.id);\n });\n }", "whenReadyToRecieve(callback) {\r\n callback();\r\n\r\n // ALSO, reprocess messages recieved before we got notify_id\r\n // in case the readyToRecieve callback was expecting them\r\n console.log(\"RE-PROCESSING MESSAGES: \")\r\n for (let i = 0; i < this.recievedMessages.length; i++) {\r\n this.process_message(this.recievedMessages[i]);\r\n }\r\n\r\n // wait until all ready callbacks are done (give a timeout)\r\n // to stop logging recieved messages (to save on memory)\r\n window.clearTimeout(this.stopLoggingRecievedMessagesTimer);\r\n this.stopLoggingRecievedMessagesTimer = window.setTimeout(() => {\r\n this.logRecievedMessages = false;\r\n console.log(\"Stopped storing messages for late readyToRecieve callbacks\")\r\n }, this.STOP_LOGGING_RECIEVED_MESSAGES_TIMEOUT);\r\n }", "function onMessageReceived(e) {\n var data = JSON.parse(e.data);\n\n switch (data.event) {\n case 'ready':\n onReady();\n break;\n\n case 'playProgress':\n onPlayProgress(data.data);\n break;\n\n case 'pause':\n onPause();\n break;\n\n case 'finish':\n onFinish();\n break;\n }\n }", "messageHandler(self, e) {\n let msg = ( (e.data).match(/^[0-9]+(\\[.+)$/) || [] )[1];\n if( msg != null ) {\n let msg_parsed = JSON.parse(msg);\n let [r, data] = msg_parsed;\n self.socketEventList.forEach(e=>e.run(self, msg_parsed))\n }\n }", "function do_recv() {\n\t\tconsole.log(\">> do_recv\");\n\t\tif(ws.rQlen() >= 1024) {\n\t\t\tmoreMsgs = true;\n\t\t} else {\n\t\t\tmoreMsgs = false;\n\t\t}\n\t\tvar arr = ws.rQshiftBytes(ws.rQlen()), chr;\n\t\twhile (arr.length > 0) {\n\t\t\tchr = arr.shift();\n\t\t\tlargeMsg += String.fromCharCode(chr); \n\t\t}\n\t\tif (!moreMsgs) {\n\t\t\tconsole.log(\"<< do_recv = \" + largeMsg);\n\t\t\trecvCallback(largeMsg);\n\t\t\tlargeMsg = \"\";\n\t\t}\n\t}", "function receivedMessage(event) {\n messageHandler.handleMessage(event);\n }", "waitForMessage_() {\n this.wait_(4, buffer => {\n this.wait_(buffer.readUInt32BE(0), buffer => {\n this.push(this.getMessage_(buffer));\n process.nextTick(() => this.waitForMessage_());\n });\n });\n }", "async initializeReceiver() {\r\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n // Refresh from persistence if we receive a KeyChanged message.\r\n this.receiver._subscribe(\"keyChanged\" /* KEY_CHANGED */, async (_origin, data) => {\r\n const keys = await this._poll();\r\n return {\r\n keyProcessed: keys.includes(data.key)\r\n };\r\n });\r\n // Let the sender know that we are listening so they give us more timeout.\r\n this.receiver._subscribe(\"ping\" /* PING */, async (_origin, _data) => {\r\n return [\"keyChanged\" /* KEY_CHANGED */];\r\n });\r\n }", "async initializeReceiver() {\r\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n // Refresh from persistence if we receive a KeyChanged message.\r\n this.receiver._subscribe(\"keyChanged\" /* KEY_CHANGED */, async (_origin, data) => {\r\n const keys = await this._poll();\r\n return {\r\n keyProcessed: keys.includes(data.key)\r\n };\r\n });\r\n // Let the sender know that we are listening so they give us more timeout.\r\n this.receiver._subscribe(\"ping\" /* PING */, async (_origin, _data) => {\r\n return [\"keyChanged\" /* KEY_CHANGED */];\r\n });\r\n }", "function onMessageReceived(e) {\n var data = JSON.parse(e.data);\n \n switch (data.event) {\n case 'ready':\n onReady();\n break;\n \n case 'playProgress':\n onPlayProgress(data.data);\n break;\n \n case 'pause':\n onPause();\n break;\n \n case 'finish':\n onFinish();\n break;\n }\n}", "_setMessageListener() {\n this.rtm.on(RTM_EVENTS.MESSAGE, (message) => {\n this._processMessage(message);\n });\n }", "function onMessageReceived(e) {\n console.log('message received');\n console.log(e);\n var msg = JSON.parse(e.data);\n console.log(msg.event);\n switch (msg.event) {\n case 'ready':\n onReady();\n break;\n case 'finish': \n onFinish();\n break;\n };\n }", "function listen2receive(callback) {\n window.addEventListener('message', function(event) {\n var data = event.data.data;\n var name = event.data.name;\n\n callback(name, data);\n });\n}", "function handleReceive() {\n console.log(\n '%c handle receive!!',\n 'font-size: 30px; color: purple'\n );\n }", "onMessage(event) {\n const buffer = event.data;\n this.buffredBytes += buffer.byteLength;\n this.messageQueue.push(new Uint8Array(buffer));\n this.processEvents();\n }", "function messageListener(event) {\r\n //console.log(event.data);\r\n }", "listenToMessages() {\n navigator.serviceWorker.addEventListener('message', (event) => {\n if (event.data === 'reloadThePageForMAJ') this.showMsg(this._config.msgWhenUpdate);\n if (event.data === 'NotifyUserReqSaved') this.showMsg(this._config.msgSync);\n if (event.data === 'isVisible') event.ports[0].postMessage(this.getVisibilityState());\n });\n }", "function message_from_worker(wid, msg) {\n var data = msg.data;\n\n if(receive_handler) {\n receive_handler(data, wid);\n } else {\n console.log(\"Unhandled message from worker\", wid, msg);\n }\n}", "async pollForMessages() {\n while (true) {\n await new Promise((resolve) => setTimeout(resolve, 3000)); // wrapping setTimeout in a promise so it can be used with await\n await this.getNewMessages(this.state.activeRoomId);\n }\n }", "function onReceive(channelId, data) {\r\n\t\tconsole.log(data);\r\n\t}", "async loop () {\n while (true) {\n const events = await this.getMessages()\n this.processQueue()\n\n events.forEach(element => {\n try {\n const parsedElement = JSON.parse(element.payload.body)\n this.emit(`message:${parsedElement.recipe}`, parsedElement)\n this.emit('message', parsedElement)\n } catch (_e) {\n console.log(_e)\n this.emit('warning', 'element unknown')\n }\n })\n }\n }", "function onMessageReceived(e) {\n var data = JSON.parse(e.data);\n \n switch (data.event) {\n case 'ready':\n onReady();\n break;\n \n case 'playProgress':\n onPlayProgress(data.data);\n break;\n \n case 'play':\n onPlay();\n break;\n \n case 'pause':\n onPause();\n break;\n \n case 'finish':\n onFinish();\n break;\n }\n}", "function workerThreadReceivedMessage(e)\n\t\t{\n\t\t\tvar msg = e.data;\n\n\t\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\t\tif (typeof msg.input === 'string')\n\t\t\t{\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t\t}\n\t\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t\t{\n\t\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\t\tif (results)\n\t\t\t\t\tglobal.postMessage({\n\t\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\t\tresults: results,\n\t\t\t\t\t\tfinished: true\n\t\t\t\t\t});\n\t\t\t}\n\t\t}", "function receiveMessage(msg) {\n\t \n\t console.log(\"Browser Received WebSocket Message: \" + msg.data);\n\t var parsedJson = $.parseJSON(msg.data);\n\t \n\t console.log(\"vmhref \" + parsedJson.vmhref);\n\t console.log(\"status \" + parsedJson.status);\n\t console.log(\"state \" + parsedJson.state);\n\t \n\t updateVMStatus(parsedJson.vmhref, parsedJson.state);\n}", "function onMessageReceived(payload) {\n let response = JSON.parse(payload.body);\n if (Array.isArray(response)) {\n for (let message of response) {\n printMessage(message);\n }\n } else {\n printMessage(response);\n }\n messageArea.scrollTop = messageArea.scrollHeight;\n}", "listen() {\r\n this.client.on('message', message => this.onMessage(message));\r\n }", "function on_socket_get(message){}", "function workerThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\n\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\tif (typeof msg.input === 'string')\n\t\t{\n\t\t\tglobal.postMessage({\n\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\tfinished: true\n\t\t\t});\n\t\t}\n\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t{\n\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\tif (results)\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: results,\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t}\n\t}", "function workerThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\n\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\tif (typeof msg.input === 'string')\n\t\t{\n\t\t\tglobal.postMessage({\n\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\tfinished: true\n\t\t\t});\n\t\t}\n\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t{\n\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\tif (results)\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: results,\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t}\n\t}", "function workerThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\n\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\tif (typeof msg.input === 'string')\n\t\t{\n\t\t\tglobal.postMessage({\n\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\tfinished: true\n\t\t\t});\n\t\t}\n\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t{\n\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\tif (results)\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: results,\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t}\n\t}", "function workerThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\n\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\tif (typeof msg.input === 'string')\n\t\t{\n\t\t\tglobal.postMessage({\n\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\tfinished: true\n\t\t\t});\n\t\t}\n\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t{\n\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\tif (results)\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: results,\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t}\n\t}", "function workerThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\n\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\tif (typeof msg.input === 'string')\n\t\t{\n\t\t\tglobal.postMessage({\n\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\tfinished: true\n\t\t\t});\n\t\t}\n\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t{\n\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\tif (results)\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: results,\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t}\n\t}", "function workerThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\n\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\tif (typeof msg.input === 'string')\n\t\t{\n\t\t\tglobal.postMessage({\n\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\tfinished: true\n\t\t\t});\n\t\t}\n\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t{\n\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\tif (results)\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: results,\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t}\n\t}", "function workerThreadReceivedMessage(e)\n\t{\n\t\tvar msg = e.data;\n\n\t\tif (typeof Papa.WORKER_ID === 'undefined' && msg)\n\t\t\tPapa.WORKER_ID = msg.workerId;\n\n\t\tif (typeof msg.input === 'string')\n\t\t{\n\t\t\tglobal.postMessage({\n\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\tresults: Papa.parse(msg.input, msg.config),\n\t\t\t\tfinished: true\n\t\t\t});\n\t\t}\n\t\telse if ((global.File && msg.input instanceof File) || msg.input instanceof Object)\t// thank you, Safari (see issue #106)\n\t\t{\n\t\t\tvar results = Papa.parse(msg.input, msg.config);\n\t\t\tif (results)\n\t\t\t\tglobal.postMessage({\n\t\t\t\t\tworkerId: Papa.WORKER_ID,\n\t\t\t\t\tresults: results,\n\t\t\t\t\tfinished: true\n\t\t\t\t});\n\t\t}\n\t}", "function requestMessage() {\n asbService.receiveQueueMessage((queureName + '-recieve'), handleMessage);\n}", "function requestMessage() {\n asbService.receiveQueueMessage((queureName + '-recieve'), handleMessage);\n}", "function listen() {\r\n __sco.on(\"message\", react);\r\n }", "function start(){\n window.addEventListener(\"message\", _listener);\n }", "function onMessageArrived(message) {\r\n Men2Recv=message.payloadString;\r\n console.log(Men2Recv);\r\n accion(Men2Recv);\r\n}", "function receive()\n{\n const r = window.radioclient;\n\n if ( r.transmitting ) {\n r.transmitting = false;\n\n r.delayed_receive_packets = 0;\n r.on_time_receive_packets = 0;\n r.delayed_receive_packet_ratio = 0;\n\n receivingNotice();\n\n const text = { command: \"receive\" };\n r.soc.send(JSON.stringify(text));\n\n r.in.source.disconnect(r.in.level);\n r.in.worker.disconnect(r.context.destination);\n r.out.worker.connect(r.context.destination);\n document.getElementsByClassName('TransmitButton')[0].id = 'TransmitButtonReceiving';\n }\n}", "function pollMessages() {\n getNewMessages();\n setTimeout(pollMessage, pollInterval);\n }", "function recv_join(message) {\n print_msg(\"[12][Push] add listener...\");\n Subscribe(['push', 'publish']);\n Subscribe(hickey.subscribe);\n //self.syncChange(hickey.subscribe);\n\n\n //right now, push connect is successful, then display devices on main panel.\n _connected = true;\n\n if (hickey.handler.device_list != null) {\n hickey.handler.device_list(_deviceList);\n }\n\n print_msg(\"[13][Push] now main panel can show device list...\");\n\n //inform client that there are some old data on server, get it by data\n if (message.length > 0) {\n getHistoryData(message);\n }\n\n //if join success\n sync_control();\n }", "on_message(message) {\r\n }", "on_message(message) {\r\n }", "on_message(message) {\r\n }", "_onRecieveMessage() {\n this.client.on(\"data\", data => {\n console.log(data.toString());\n });\n }", "function receive(message) {\n var msg_type = RECV_MSG_TYPE[message.data.type];\n switch (msg_type) {\n case RECV_MSG_TYPE['join']:\n print_msg(\"[11][Push] push join has a response...\");\n if (message.data.data != '' && message.data.data != null) {\n recv_join(JSON.parse(message.data.data));\n } else {\n recv_join([]);\n }\n break;\n case RECV_MSG_TYPE['new']:\n recv_new(message);\n break;\n case RECV_MSG_TYPE['del']:\n recv_del(message);\n break;\n case RECV_MSG_TYPE['remove']:\n recv_remove(message);\n break;\n case RECV_MSG_TYPE['pub']:\n recv_pub(message);\n break;\n case RECV_MSG_TYPE['mod_dvc_nm']:\n recv_dev_rename(message);\n break;\n default:\n print_msg('unrecognize msg type');\n }\n }", "function main() {\n // register a message listener\n chrome.runtime.onMessage.addListener(\n function (request, sender, sendResponse) {\n console.log(request);\n handleMessage(request);\n }\n );\n\n console.log(\"RollShare roll20 roll receive module loaded\")\n}", "function receiveMessage(e){\n var requestData = JSON.parse(e.data);\n if (console && console.log && window.connect.bridge.debug)\n console.log('bridge', 'receiveMessage', requestData);\n return window.connect.utils.xhr(requestData.options, function(err, data){\n requestData.result = {};\n requestData.result.err = err;\n requestData.result.data = data; \n postMessage(requestData);\n });\n }", "function receiveMessage(message) {\n\n // if this message belongs to the currently selected channel...\n if (message.channel === currentChannelId) {\n\n // first delete the oldest message if there are 100 or more msgs stored in browser\n if (currentChannelMessages.length >= 100) {\n currentChannelMessages.shift()\n }\n\n // then push the new msg into the current channels message array, update the message thread and scroll down\n currentChannelMessages.push(message);\n selectors.messageThread.html(messageThreadTemplate(currentChannelMessages));\n selectors.messageThreadContainer.scrollTop(selectors.messageThreadContainer.height());\n }\n\n}", "processMessages() {\n if (this._currentlyProcessing) {\n // Prevent bloating the call stack.\n return;\n }\n this._currentlyProcessing = true;\n while (this._messageQueue.size > 0) {\n let [sender, descriptor, body, target] = this._messageQueue.dequeue(1);\n for (let listenerKey of this._descriptors.getAnscIt(descriptor)) {\n let {\n name: subscriberName, handler, source: senderName\n } = this._listeners[listenerKey];\n if (target !== undefined && target !== subscriberName) {\n continue;\n }\n if (senderName !== undefined && senderName !== sender) {\n continue;\n }\n \n handler(body, descriptor, sender);\n }\n }\n this._currentlyProcessing = false;\n }", "async function getMessages() {\n try {\n const messages = await getMessagesAsync();\n displayMessages(messages);\n //console.log(messages);\n \n } // catch and log any errors\n catch (err) {\n console.log(err);\n }\n }", "function handleMessage(event) {\r\n\t\t//console.log('Received message: ' + event.data);\r\n\t\tvar data = JSON.parse(event.data);\r\n\t\thandleReceiveData(data);\r\n\t}", "function receiveMessage(msgheader, buf) {\n self.emit(\"data\", msgheader, buf);\n }", "onReceivedMessage(messages) {\n if (this._isMounted) {\n this.setState((previousState) => {\n return {\n messages: GiftedChat.append(previousState.messages, messages),\n };\n });\n this.updateTimeOfLastReadMessage();\n }\n }", "function onMqttMessageArrived(message) {\n console.log(\"onMqttMessageArrived:\"+message.payloadString+ ' for '+message.destinationName );\n //console.log(message);\n dispatch_message_to_blocks( message.destinationName, message.payloadString );\n}", "_registerSocketListener() {\n this._socket.on('message', (data) => {\n this._mav.parse(data);\n });\n }", "onMessageEnd() { }", "handleBusMessages() {\n const bus = this.runtime.bus();\n\n Object.values(REQUESTS).forEach((msgType) => {\n bus.on(msgType, (msgData) => {\n this.sendCommMessage(msgType, msgData);\n });\n });\n }", "function workerThreadReceivedMessage(e) {\n var msg = e.data;\n\n if (typeof Papa.WORKER_ID === 'undefined' && msg)\n Papa.WORKER_ID = msg.workerId;\n\n if (typeof msg.input === 'string') {\n global.postMessage({\n workerId: Papa.WORKER_ID,\n results: Papa.parse(msg.input, msg.config),\n finished: true,\n });\n } else if (\n (global.File && msg.input instanceof File) ||\n msg.input instanceof Object\n ) {\n // thank you, Safari (see issue #106)\n var results = Papa.parse(msg.input, msg.config);\n if (results)\n global.postMessage({\n workerId: Papa.WORKER_ID,\n results: results,\n finished: true,\n });\n }\n }", "async function fetchMessagesFromServer () {\n\tif(!myself) return;\n\t\n\t/** @type { Message[] } */\n\tlet data = [];\n\ttry {\n\t\t// Note that, by deafault, the `fetch` function makes uses a `GET` request method.\n\t\tconst resp = await fetch(`${serverAddress}/messages`);\n\t\tdata = await resp.json();\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn;\n\t}\n\t\n\tif(!data.length) return;\n\t/**\n\t * Contains all messages returned from the server that were not yet rendered.\n\t * The ideia is that if the array of messages on the server is larger than the\n\t * array of messages on the client, then that means some messages are new.\n\t * Since the messages are placed in order on the array, you just have to get the\n\t * last elements of the server message's array.\n\t */\n\tconst unrenderedMessages = data.slice(renderedMessages.length);\n\t\n\tunrenderedMessages.forEach(newMessage => {\n\t\tcreateMessageOnUI(newMessage);\n\t\trenderedMessages.push(newMessage);\n\t});\n}", "testWorker02() {\n let barWorker = new BarWorker();\n barWorker.addEventListener('message', function (e) {\n console.log(e.data);\n });\n barWorker.postMessage(\"PING from the main thread\");\n }", "function receive (message) {\n input.send(Message(id, requestUrl, message.toString()));\n }", "function receiver() {\n if (self.readyState > WebSocketXHR.OPEN) return\n recv = request(url, 'GET', null, function (err, result) {\n if (err) {\n // aborted request?\n if (err.code === 0) {\n // disconnect the socket with wasClean: true if it is open\n disconnect(self.readyState !== WebSocketXHR.OPEN)\n // request errored\n } else {\n // close the socket with wasClean: false\n disconnect(false)\n }\n recv = null\n } else {\n // N.B. we skip empty messages, they are heartbeats\n if (result) {\n var packets = decodePayload(result)\nconsole.log('PA', result, packets)\n for (var i = 0; i < packets.length; ++i) {\n var type = packets[i].type\n var data = packets[i].data\n // message frame\n if (type === 'message') {\n // report incoming message\n //setTimeout(function () {\n fire('message', { data: data, origin: url })\n //}, 0)\n // ping frame\n } else if (type === 'ping') {\n self.send(encodePacket({ type: 'pong', data: packet.data }))\n // open frame\n } else if (type === 'close') {\n // disconnect with wasClean: false\n disconnect(false)\n // open frame\n } else if (type === 'open' && self.readyState === WebSocketXHR.CONNECTING) {\n // data is session\n // parse session as urlencoded\n session = urldecode(data)\n session.interval = parseInt(session.interval, 10) || 0\nconsole.log('SESS', session)\n // setup receiver URL\n url = url + '/' + session.id\n // mark socket as open\n self.readyState = WebSocketXHR.OPEN\n setTimeout(function () {\n fire('open')\n }, 0)\n // error frame, or error decoding frame\n } else if (type === 'error') {\n disconnect()\n /*if (self.readyState !== WebSocketXHR.OPEN) {\n self.readyState = WebSocketXHR.CLOSED\n }*/\n // unknown frame. ignore\n } else {\nconsole.log('UNKNOWN FRAME', packet)\n disconnect()\n }\n }\n }\n // restart receiver\n setTimeout(receiver, session.interval || 0)\n }\n })\n }", "function multiThread () {\n console.log('!!!! start test worker !!!!')\n // var worker = new Worker('/worker.js') // eslint-disable-line no-undef\n setTimeout(() => {\n sendQueryToWorker('querymsg').then((resp) => {\n console.log('bg main receive')\n console.log(resp)\n })\n }, 20000)\n}", "function receivedMessage(data) {\n\tconsole.log('Received:', data);\n\tshowNewMessage(\"other\", data)\n}", "function receive(entry){\n //we could do a broadcast to all devices if we need to...\n console.log(\"Data: \" + entry.data + \", Timestamp: \" + entry.timestamp);\n}", "receive(message) {\n this.log(\"Received: \"+message);\n var obj = JSON.parse(message);\n if (\"object\" in obj){\n this.processEvent(obj.object,obj.changes);\n } else if (\"Add\" in obj ) {\n for ( i=0; i< obj.Add.objects.length; i++ ) {\n // this.log(\"adding \"+i+\":\"+obj);\n this.addObject(obj.Add.objects[i]);\n }\n this.log(\"added \"+obj.Add.objects.length+\" scene size \"+this.scene.size);\n } else if (\"Remove\" in obj) {\n for ( var i=0; i< obj.Remove.objects.length; i++ ) {\n this.removeObject(obj.Remove.objects[i]);\n }\n } else if (\"ERROR\" in obj){\n // TODO: error listener(s)\n this.log(obj.ERROR);\n this.errorListeners.forEach((listener)=>listener(obj.ERROR));\n } else if ( \"Welcome\" in obj) {\n var welcome = obj.Welcome;\n if ( ! this.me ) {\n // FIXME: Uncaught TypeError: Cannot assign to read only property of function class\n let client = new User();\n this.me = Object.assign(client,welcome.client.User);\n }\n this.welcomeListeners.forEach((listener)=>listener(welcome));\n if ( welcome.permanents ) {\n welcome.permanents.forEach( o => this.addObject(o));\n }\n } else if ( \"response\" in obj) {\n this.log(\"Response to command\");\n if ( typeof this.responseListener === 'function') {\n var callback = this.responseListener;\n this.responseListener = null;\n callback(obj);\n }\n } else {\n this.log(\"ERROR: unknown message type\");\n }\n }", "function startListening () {\n // if user download configuration\n if (typeof(LOCAL_SETTINGS) !== \"undefined\") {\n // start loop for downloading messages\n setInterval(function (){\n let dataArray = {\n latest_message_id: LATEST_MESSAGE_COUNT,\n room_name: LOCAL_SETTINGS.roomData.url,\n room_token: LOCAL_SETTINGS.roomData.room_token\n };\n // download messages from current room if number of messages is different on client and server\n $.post(ROOM_ID + \"/get-messages\", dataArray, function (data) {\n let response = JSON.parse(data);\n // console.log(response);\n if (response.status === 'new-messages') {\n // if messages was changed\n LATEST_MESSAGE_COUNT = response.messages_count;\n\n // clear before append all messages\n $('#chatWindow').html('');\n\n // foreach messages in array from JSON\n response.messages.forEach(function(element, index, array){\n let userType = '';\n if ( element.user_id == LOCAL_SETTINGS.roomData.admin_id ){\n userType = \"<span class='label label-success'>💎 Admin</span>\";\n }\n if ( element.user_id == 0 ){\n userType = \"<span class='label label-success'>💡 System</span>\";\n }\n\n // some magic with message content\n let messageContent = element.content;\n\n $('#chatWindow').append(\"<div class='list-group-item'><h6 class='list-group-item-heading' style='color: #fff; font-weight: 600;'>\"+userType + \" \" + element.user_nickname+\" <i>\"+element.create_date+\"</i></h6><p class='list-group-item-text'><br>\"+messageContent+\"</p></div>\");\n });\n\n console.log('Downloaded messages');\n } else if ( response.status === 'no-new-messages' ) {\n console.log('There is no new messages');\n } else {\n console.log('Something wrong');\n }\n });\n\n }, INTERVAL);\n }\n}", "startListening() {\n // If this object doesn't have a uid it could potentially create problematic queries, so return.\n if (this.uid === undefined) return;\n // Get a reference to where the messages are stored.\n const ref = Fetch.getMessagesReference(this.uid).child(\"messages\");\n // Add a handler for when a message is added.\n ref.on(\"child_added\", snapshot => {\n const message = snapshot.val();\n if (!message || !message.content) return;\n this.messages = this.messages || {};\n if (!this.messages[message.uid]) {\n this.emit(\"new_message\", message);\n }\n this.messages[message.uid] = message;\n this.emit(\"message\", message);\n this.emit(\"change\", this.messages);\n });\n // Add a handler for when a message is changed, e.g. edited.\n ref.on(\"child_changed\", snapshot => {\n const message = snapshot.val();\n if (!message || !message.content) return;\n this.messages = this.messages || {};\n this.messages[message.uid] = message;\n this.emit(\"edit\", message);\n this.emit(\"change\", this.messages);\n });\n // Add a handler for when a message is deleted.\n ref.on(\"child_removed\", snapshot => {\n const message = snapshot.val();\n if (!message || !message.content) return;\n this.messages[message.uid] = null;\n delete this.messages[message.uid];\n this.emit(\"delete\", message);\n this.emit(\"change\", this.messages);\n });\n }", "handleMessage(message) {\r\n console.log('Received message', message.payloadString);\r\n this.callbacks.forEach((callback) => callback(message));\r\n }" ]
[ "0.68331236", "0.6715099", "0.6482904", "0.64415425", "0.64415425", "0.64415425", "0.64415425", "0.64415425", "0.64415425", "0.64415425", "0.63156927", "0.63097507", "0.6306779", "0.6293593", "0.6243852", "0.619123", "0.618337", "0.61290836", "0.6119623", "0.611042", "0.611042", "0.6086211", "0.60712373", "0.6054828", "0.6012744", "0.60053754", "0.5998007", "0.5996938", "0.59875613", "0.5984351", "0.5978901", "0.59748626", "0.5972917", "0.5953761", "0.59444237", "0.59394383", "0.5906028", "0.5903813", "0.5903813", "0.59034157", "0.5896205", "0.58916557", "0.5890736", "0.58741975", "0.5864574", "0.5863397", "0.5837361", "0.5831501", "0.58108425", "0.5802964", "0.5797529", "0.5796057", "0.57932395", "0.5792812", "0.5787109", "0.5783095", "0.577666", "0.5776492", "0.5776492", "0.5776492", "0.5776492", "0.5776492", "0.5776492", "0.5776492", "0.57730985", "0.57730985", "0.5772932", "0.5768092", "0.5756437", "0.5741118", "0.57406664", "0.57385534", "0.5733187", "0.5733187", "0.5733187", "0.57292944", "0.5708757", "0.57087433", "0.57031304", "0.5700357", "0.5697722", "0.56871223", "0.5686841", "0.56767565", "0.56729126", "0.5666868", "0.56657755", "0.5662753", "0.56558746", "0.5655077", "0.56515974", "0.5647069", "0.56441134", "0.5640741", "0.5634093", "0.56320393", "0.56296724", "0.5619961", "0.559801", "0.558695", "0.5577796" ]
0.0
-1
This is only used in the 2D Voice Map when the error signal is used for synthesis
createMixedExcitation(periodSamples, errorRMS) { this._mixedExcitationSignal = this._errorBuffer; this._excitationSignal = this.createNoiseExcitation(errorRMS); for (let i=0; i<this._frameSize; i++){ this._excitationSignal[i] = (1-this._unvoicedMix) * this._mixedExcitationSignal[i] + this._unvoicedMix * this._excitationSignal[i]; } return this._excitationSignal; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function SC_onError(e,t){$.scriptcam.SC_onError(e,t)}", "function showError() {\n\tdocument.getElementById(\"mistake\").innerHTML = \"<font color=\\\"red\\\">間違った!</font>\";\n\tplayErrorAudio();\n}", "function setError(reset) {\n\terror *= ramp;\n\tif (reset) error = 0.25;\n\tif (Math.random() < 0.5) error *= -1;\n}", "function errorSound() {\n var error = new Audio(\"./assets/sounds/wrong.wav\");\n error.volume = .3;\n error.play();\n }", "function error() {\n self.addThreepio(\"I think we've broken \" + friend.name + \" with your question.\");\n setTimeout(function () {\n var result = self.yesNo(RandomUtil.coinFlip());\n self.addThreepio(\"I suppose I can go ahead and answer your question for you: \" + result);\n self.hideFriend();\n setTimeout(self.addInput, self.timeBetweenBubbles);\n }, self.timeBetweenBubbles);\n }", "function sc_ErrorInputPort() {\n}", "_playErrorSound() {\n this._audio.warning[0].pause();\n\n if (!this._isMuted) {\n ScadaUtils.playSound(this._audio.error);\n }\n }", "function OnErr() {\r\n}", "function error() { \n state = false;\n g();\n setTimeout( () => { state = true; g(); }, duration);\n}", "static get ERROR() { return 3 }", "function updateError()\n {\n var goodChars = my.current.correctInputLength\n\n var errorRate\n var errorRateTooltip\n var accuracyTooltip\n\n // Update error rate\n if (my.current.errorRate == Number.POSITIVE_INFINITY) {\n errorRate = '\\u221e'\n } else {\n errorRate = Math.round(my.current.errorRate)\n }\n\n // Display error rate\n Util.setChildren(my.html.error, errorRate + '% error')\n }", "function showError( ){\n console.log(\"error in reading the position\");\n}", "function setError(error) {\n _error = \"(\" + _counter + \") \" + ioHelper.normalizeError(error);\n _counter++;\n _msg = \"\";\n component.forceUpdate();\n }", "function ki(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function draw_error() {\n\tdocument.getElementById(\"raw_output\").innerHTML = \"ERROR!\";\n}", "static get ERROR () { return 0 }", "isError() { return this.type==Token.ERROR }", "isError() { return this.type==Token.ERROR }", "function qi(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "get animationScaleError() {}", "onerror(err) {\n this.emitReserved(\"error\", err);\n }", "error(message, prev){\n\t\tif (message == undefined) message=\"\";\n\t\tif (prev == undefined) prev=null;\n\t}", "function errorHand(data) {\n console.log(data.toString());\n this.emit('end');\n}", "function err(strm,errorCode){strm.msg=msg[errorCode];return errorCode;}", "function onCommandSentFail(error) {\n $log.error(\"SetPulse failed\");\n\n $scope.ongoingCommand = false;\n $scope.isPressed = false;\n\n $scope.$apply();\n }", "set animationScaleError(value) {}", "onerror(err) {\n debug(\"error\", err);\n this.emitReserved(\"error\", err);\n }", "function Ri(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "_attachErrorEvent() {\n\t\tthis._oConnection.onEvent(\"error\", function(err) {\n\t\t\tlogger.error(\"VoiceConnection error: \", err);\n\t\t\tthis.play(); //Try to play the next song on error\n\t\t}.bind(this));\n\n\t\tthis._oConnection.onEvent(\"failed\", function(err) {\n\t\t\tlogger.error(\"VoiceConnection failed: \", err);\n\t\t\tthis.play(); //Try to play the next song on error\n\t\t}.bind(this));\n\n\t\tthis._bErrorEventAttached = true;\n\t}", "function getTargetError(gl) { return getContext(gl).targetError; }", "_onSerialError(err) {\n // not really sure how to handle this in a more elegant way\n\n this.emit('error', err);\n }", "onerror(err) {\n debug(\"error\", err);\n this.emitReserved(\"error\", err);\n }", "function Lr(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function Di(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function makeStep(){\n let x = +document.getElementById(\"xcord\").value;\n let y = +document.getElementById(\"ycord\").value;\n var error = document.getElementById(\"error\")\n var errorText = document.getElementById(\"errorText\")\n if (x>size || y>size || x<1 || y<1 || x!=Math.round(x) || y!=Math.round(y)) {\n //Play audio\n let audio = new Audio('Audio/error.mp3');\n audio.play();\n document.getElementById(\"error\").style.display = \"block\";\n document.getElementById(\"errorText\").textContent = \"Coordinate Error\"\n document.getElementById(\"errorText2\").textContent = \"Cant found current coordinate.Try another.\"\n error.style.backgroundColor = \"#F89494\"\n error.style.color = \"red\"\n return\n }\n if (isArrayInArray(free_coordinates,[x,y])) {\n //Play audio\n let audio = new Audio('Audio/userclick.wav');\n audio.play();\n drawStep(x,y,player_symbol)\n if (checkWin()!=false) {\n winner()\n return\n }\n \n \n robotStep()\n \n if (checkWin()!=false) {\n winner()\n return\n }\n \n document.getElementById(\"error\").style.display = \"none\";\n\n }\n else{\n //Play audio\n let audio = new Audio('Audio/error.mp3');\n audio.play();\n document.getElementById(\"error\").style.display = \"block\";\n document.getElementById(\"errorText\").textContent = \"Cage Occupied\"\n document.getElementById(\"errorText2\").textContent = \"That cage has been occupied by you or by robot.Try another one.\"\n error.style.backgroundColor = \"#F89494\"\n error.style.color = \"red\"\n return\n }\n\n}", "function errorMessage() {\r\n SCREEN_RESULTS.innerHTML = \"ERROR\";\r\n console.info(\"ERROR: MORE OPERATORS THAN NUMBERS\");\r\n numShownCalcScreen = \"\";\r\n expressionHidden = \"\";\r\n answer = 0;\r\n}", "function Vr(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "function showError(error) {\n console.log(\"Serial port error: \" + error);\n}", "function Fl(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "function showError(error) {\n console.log('Serial port error: ' + error);\n}", "function Ri(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function Ri(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function esconderError() {\n setError(null);\n }", "function send_err(msg, input) {\n\t\t\tsendMsg({ msg: 'tx_error', e: msg, input: input });\n\t\t\tsendMsg({ msg: 'tx_step', state: 'committing_failed' });\n\t\t}", "function send_err(msg, input) {\n\t\t\tsendMsg({ msg: 'tx_error', e: msg, input: input });\n\t\t\tsendMsg({ msg: 'tx_step', state: 'committing_failed' });\n\t\t}", "function showError() {}", "function onErrorMessageChanged(event) {\n let value = new Uint8Array(event.target.value.buffer);\n let utf8Decoder = new TextDecoder();\n let errorMessage = utf8Decoder.decode(value);\n console.log(\"Error message = \" + errorMessage);\n}", "function Lo(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "function Lo(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "function Lo(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "onReceiveError( pdu ) {\n //console.log( 'JCOM1939 RX Error');\n this.rxErrors++;\n }", "function error() {\n // cleans the screen paints canvas \n gl.clear( gl.COLOR_BUFFER_BIT );\n console.log(\"error = \" + index);\n gl.uniform4fv(colLoc, flatten(BLACK));\n \n drawLoop();\n \n console.log(\"error draw the good stuff first\");\n // set fragment shader variable fColour to RED draw the lines \n // that represents the last segement that does not meet criteria\n gl.uniform4fv(colLoc, flatten(RED));\n gl.drawArrays(gl.LINE_STRIP, index - 1, 2);\n console.log(\"error now draw the bad stuff\");\n}", "function Lo(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function Lo(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function Ro(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function CustomError() {}", "error(message, connection, args) {\n const errorMessage = `Unknown command: ${args}`;\n message.channel.send(errorMessage);\n Speaker.googleSpeak(errorMessage, this.voice, this.volume, connection, Speaker.speak);\n }", "function kml_error (data) {\n \t\n message.fadeOut('slow', function () { });\n Streams.map.closeInfoWindow(info);\n Streams.map.deleteMarker(marker);\n prompt.append('<p class=\"error\">Error: ' + data.msg + '</p>');\n console.log(data.msg);\n disableHandlers = false;\n }", "errorProc(payload) {\r\n this.lm('Bad command sent. Stopping.');\r\n\r\n payload.status = 'what?';\r\n payload.error = 'No such command';\r\n\r\n return payload;\r\n }", "function error(message) {\n jsav.umsg(message, {\"color\" : \"red\"});\n jsav.umsg(\"<br />\");\n }", "setError(state, newError) {\n state.error = newError;\n }", "set animationRotationError(value) {}", "get animationRotationError() {}", "__init12() {this.error = null}", "function onDecodingError(error) {\n console.error('decodeAudioData error', error);\n }", "function showError(message) {\n print(\"ScreenTransformToMaterialProperty: ,ERROR: \" + message);\n}", "function wikiError(){\r\n self.errorMessage(\"Error in accessing wikipedia\");\r\n self.apiError(true);\r\n}", "function convertError(tsError)\n {\n var minChar = tsError.start();\n var limChar = minChar + tsError.length();\n var error = {'minChar': minChar, 'limChar': limChar};\n // ACE annotation properties.\n var pos = DocumentPositionUtil.getPosition(doc, minChar);\n error.text = tsError.message();\n error.row = pos.row;\n error.column = pos.column;\n error.type = 'error'; // Determines the icon that appears for the annotation.\n return error;\n }", "error(x) {\n this.#mux(x, levels.error);\n }", "function Io(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "onAudioLoadError(e) {\n console.error('audio load err', e)\n }", "function onPlayerError(errorCode) {\n\talert(\"An error occured of type:\" + errorCode);\n}", "function Ho(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "function onInvalidInput() {\n\n transition(\"ERROR_INPUT\");\n\n }", "error(error) {}", "function VeryBadError() {}", "function showError() {\n transitionSteps(getCurrentStep(), $('.demo-error'));\n }", "function errback(err) {\n //alert(err.toString());\n rdbAdmin.showErrorMessage('<pre>' + err[0] + ':' + err[1] + '</pre>');\n }", "function STRCrossWaveDescription(value) {\n var texte = \"ERROR\";\n switch (value * 1) {\n case (0):\n texte = \"No Cross Waves\";\n break;\n case (1):\n texte = \"Minor Cross Waves\";\n break;\n case (2):\n texte = \"Moderate Cross Waves\";\n break;\n }\n\n return texte;\n}", "function showError(type, text) {}", "function setTargetError(gl, error) {\n\tvar context = getContext(gl);\n\tcontext.targetError = error;\n}", "function P$1(value) {\n this._currentEvent = { type: 'error', value: value, current: true };\n}", "get errorState() {\n if (this._startInput && this._endInput) {\n return this._startInput.errorState || this._endInput.errorState;\n }\n return false;\n }", "get errorState() {\n if (this._startInput && this._endInput) {\n return this._startInput.errorState || this._endInput.errorState;\n }\n return false;\n }", "setError(score, msg) {\n this.tmp.error = msg\n this.tmp.score = score\n if (this.objects.length > 1) this.tmp.score += 10\n parser.msg(\"Match failed: \" + this.tmp.score + \" (\" + msg + \")\")\n }", "function Mi(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "function markError(error) {\n if (error.errorPos) {\n console.log(\"marking error\",error);\n cursorToSeq.push(error);\n }\n}", "function Dr(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "function Dr(e){return Object.prototype.toString.call(e).indexOf(\"Error\")>-1}", "function onPlayerError(errorCode) {\n alert(\"An error occured of type:\" + errorCode);\n}", "function onPlayerError(errorCode) {\n alert(\"An error occured of type:\" + errorCode);\n}", "function Fi(t){return Object.prototype.toString.call(t).indexOf(\"Error\")>-1}", "function error(err) {\n var problem;\n if (err.code == 1) {\n // user said no!\n problem = \"You won't share your location with us.\"\n }\n if (err.code == 2) {\n // location is unavailable - no satellites in range?\n problem = \"Your location is unavailable.\"\n }\n if (err.code == 3) {\n // request timed out\n problem = \"Something was too slow.\"\n }\n document.getElementById('location').innerHTML = \"Something went wrong! \"+problem;\n \n}", "function beepError()\n\t{\n\t\tif (!isBeep\n\t\t|| errorCode.length == 0\n\t\t|| errorCode == 'connectMessage')\n\t\t\treturn;\n\t\tsetTimeout('dw.beep()',300);\n\t}", "onError() {}", "function errback(err) {\n rdbAdmin.showErrorMessage('<pre>' + err[0] + ':' + err[1] + '</pre>');\n }", "error() {}", "clearError() {\n this.error = false;\n this._errortext = this.__initalErrorText;\n }", "clearError() {\n this.error = false;\n this._errortext = this.__initalErrorText;\n }", "function gpsError(error) {\n var errors = {\n 1: 'Permission denied',\n 2: 'Position unavailable',\n 3: 'Request timeout'\n };\n alert(\"Error: \" + errors[error.code]);\n}" ]
[ "0.6336766", "0.61526114", "0.6119087", "0.6086941", "0.59979874", "0.5978996", "0.59165394", "0.5882012", "0.5825533", "0.5779841", "0.5762651", "0.5731029", "0.5730381", "0.5718879", "0.5716738", "0.57147044", "0.5703733", "0.5703733", "0.56806356", "0.5675614", "0.5629996", "0.5581849", "0.55813605", "0.55644226", "0.556032", "0.55599844", "0.55576015", "0.5533931", "0.55336887", "0.5524846", "0.5514486", "0.5508772", "0.5508038", "0.55014956", "0.5498146", "0.5495568", "0.5489853", "0.54891425", "0.54872864", "0.5484697", "0.5481307", "0.5481307", "0.5481119", "0.54757106", "0.54757106", "0.54700714", "0.5463653", "0.5457375", "0.5457375", "0.5457375", "0.54570246", "0.54545707", "0.5449544", "0.5449544", "0.543811", "0.5435042", "0.54350346", "0.54348177", "0.54242325", "0.54235995", "0.5419199", "0.5402274", "0.5399884", "0.53985596", "0.53932595", "0.5390097", "0.5388397", "0.53883684", "0.5387192", "0.53813106", "0.53795946", "0.53789026", "0.5377365", "0.537728", "0.5376981", "0.5376097", "0.53641206", "0.53594154", "0.5356027", "0.5355814", "0.5355014", "0.5342892", "0.53335506", "0.53335506", "0.5331428", "0.5331236", "0.5330524", "0.53304696", "0.53304696", "0.5329314", "0.5329314", "0.53278786", "0.5325867", "0.5314492", "0.53119755", "0.5307623", "0.5305593", "0.5300675", "0.5300675", "0.5296663" ]
0.56280476
21
Quantize K coeficients TODO: it gives the same result as matlab, but there are errors at lower bit rates??
quantizeLPC(lpcCoeff, kCoeff, numBits){ let M = lpcCoeff.length-1; // Quantize Ks for (let i = 0; i< M; i++){ kCoeff[i] = this.quantizeK(kCoeff[i], numBits); } // recalculate LPC return LPC.recalculateLPC(lpcCoeff, kCoeff); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function coeff(n, k) {\n var coeff = 1;\n for (var x = n-k+1; x <= n; x++) coeff *= x;\n for (x = 1; x <= k; x++) coeff /= x;\n return coeff;\n}", "function multiply(x,k,base){var m,temp,xlo,xhi,carry=0,i=x.length,klo=k%SQRT_BASE,khi=k/SQRT_BASE|0;for(x=x.slice();i--;){xlo=x[i]%SQRT_BASE;xhi=x[i]/SQRT_BASE|0;m=khi*xlo+xhi*klo;temp=klo*xlo+m%SQRT_BASE*SQRT_BASE+carry;carry=(temp/base|0)+(m/SQRT_BASE|0)+khi*xhi;x[i]=temp%base}if(carry)x=[carry].concat(x);return x}", "function quantize_xrpow(xp, pi, istep, codInfo, prevNoise) {\n /* quantize on xr^(3/4) instead of xr */\n var sfb;\n var sfbmax;\n var j = 0;\n var prev_data_use;\n var accumulate = 0;\n var accumulate01 = 0;\n var xpPos = 0;\n var iData = pi;\n var iDataPos = 0;\n var acc_iData = iData;\n var acc_iDataPos = 0;\n var acc_xp = xp;\n var acc_xpPos = 0;\n\n /*\n * Reusing previously computed data does not seems to work if global\n * gain is changed. Finding why it behaves this way would allow to use a\n * cache of previously computed values (let's 10 cached values per sfb)\n * that would probably provide a noticeable speedup\n */\n prev_data_use = (prevNoise != null && (codInfo.global_gain == prevNoise.global_gain));\n\n if (codInfo.block_type == Encoder.SHORT_TYPE)\n sfbmax = 38;\n else\n sfbmax = 21;\n\n for (sfb = 0; sfb <= sfbmax; sfb++) {\n var step = -1;\n\n if (prev_data_use || codInfo.block_type == Encoder.NORM_TYPE) {\n step = codInfo.global_gain\n - ((codInfo.scalefac[sfb] + (codInfo.preflag != 0 ? qupvt.pretab[sfb]\n : 0)) << (codInfo.scalefac_scale + 1))\n - codInfo.subblock_gain[codInfo.window[sfb]] * 8;\n }\n assert(codInfo.width[sfb] >= 0);\n if (prev_data_use && (prevNoise.step[sfb] == step)) {\n /*\n * do not recompute this part, but compute accumulated lines\n */\n if (accumulate != 0) {\n quantize_lines_xrpow(accumulate, istep, acc_xp, acc_xpPos,\n acc_iData, acc_iDataPos);\n accumulate = 0;\n }\n if (accumulate01 != 0) {\n quantize_lines_xrpow_01(accumulate01, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate01 = 0;\n }\n } else { /* should compute this part */\n var l = codInfo.width[sfb];\n\n if ((j + codInfo.width[sfb]) > codInfo.max_nonzero_coeff) {\n /* do not compute upper zero part */\n var usefullsize;\n usefullsize = codInfo.max_nonzero_coeff - j + 1;\n Arrays.fill(pi, codInfo.max_nonzero_coeff, 576, 0);\n l = usefullsize;\n\n if (l < 0) {\n l = 0;\n }\n\n /* no need to compute higher sfb values */\n sfb = sfbmax + 1;\n }\n\n /* accumulate lines to quantize */\n if (0 == accumulate && 0 == accumulate01) {\n acc_iData = iData;\n acc_iDataPos = iDataPos;\n acc_xp = xp;\n acc_xpPos = xpPos;\n }\n if (prevNoise != null && prevNoise.sfb_count1 > 0\n && sfb >= prevNoise.sfb_count1\n && prevNoise.step[sfb] > 0\n && step >= prevNoise.step[sfb]) {\n\n if (accumulate != 0) {\n quantize_lines_xrpow(accumulate, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate = 0;\n acc_iData = iData;\n acc_iDataPos = iDataPos;\n acc_xp = xp;\n acc_xpPos = xpPos;\n }\n accumulate01 += l;\n } else {\n if (accumulate01 != 0) {\n quantize_lines_xrpow_01(accumulate01, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate01 = 0;\n acc_iData = iData;\n acc_iDataPos = iDataPos;\n acc_xp = xp;\n acc_xpPos = xpPos;\n }\n accumulate += l;\n }\n\n if (l <= 0) {\n /*\n * rh: 20040215 may happen due to \"prev_data_use\"\n * optimization\n */\n if (accumulate01 != 0) {\n quantize_lines_xrpow_01(accumulate01, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate01 = 0;\n }\n if (accumulate != 0) {\n quantize_lines_xrpow(accumulate, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate = 0;\n }\n\n break;\n /* ends for-loop */\n }\n }\n if (sfb <= sfbmax) {\n iDataPos += codInfo.width[sfb];\n xpPos += codInfo.width[sfb];\n j += codInfo.width[sfb];\n }\n }\n if (accumulate != 0) { /* last data part */\n quantize_lines_xrpow(accumulate, istep, acc_xp, acc_xpPos,\n acc_iData, acc_iDataPos);\n accumulate = 0;\n }\n if (accumulate01 != 0) { /* last data part */\n quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_xpPos,\n acc_iData, acc_iDataPos);\n accumulate01 = 0;\n }\n\n }", "function quantize_xrpow(xp, pi, istep, codInfo, prevNoise) {\n /* quantize on xr^(3/4) instead of xr */\n var sfb;\n var sfbmax;\n var j = 0;\n var prev_data_use;\n var accumulate = 0;\n var accumulate01 = 0;\n var xpPos = 0;\n var iData = pi;\n var iDataPos = 0;\n var acc_iData = iData;\n var acc_iDataPos = 0;\n var acc_xp = xp;\n var acc_xpPos = 0;\n\n /*\n * Reusing previously computed data does not seems to work if global\n * gain is changed. Finding why it behaves this way would allow to use a\n * cache of previously computed values (let's 10 cached values per sfb)\n * that would probably provide a noticeable speedup\n */\n prev_data_use = (prevNoise != null && (codInfo.global_gain == prevNoise.global_gain));\n\n if (codInfo.block_type == Encoder.SHORT_TYPE)\n sfbmax = 38;\n else\n sfbmax = 21;\n\n for (sfb = 0; sfb <= sfbmax; sfb++) {\n var step = -1;\n\n if (prev_data_use || codInfo.block_type == Encoder.NORM_TYPE) {\n step = codInfo.global_gain\n - ((codInfo.scalefac[sfb] + (codInfo.preflag != 0 ? qupvt.pretab[sfb]\n : 0)) << (codInfo.scalefac_scale + 1))\n - codInfo.subblock_gain[codInfo.window[sfb]] * 8;\n }\n assert(codInfo.width[sfb] >= 0);\n if (prev_data_use && (prevNoise.step[sfb] == step)) {\n /*\n * do not recompute this part, but compute accumulated lines\n */\n if (accumulate != 0) {\n quantize_lines_xrpow(accumulate, istep, acc_xp, acc_xpPos,\n acc_iData, acc_iDataPos);\n accumulate = 0;\n }\n if (accumulate01 != 0) {\n quantize_lines_xrpow_01(accumulate01, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate01 = 0;\n }\n } else { /* should compute this part */\n var l = codInfo.width[sfb];\n\n if ((j + codInfo.width[sfb]) > codInfo.max_nonzero_coeff) {\n /* do not compute upper zero part */\n var usefullsize;\n usefullsize = codInfo.max_nonzero_coeff - j + 1;\n Arrays.fill(pi, codInfo.max_nonzero_coeff, 576, 0);\n l = usefullsize;\n\n if (l < 0) {\n l = 0;\n }\n\n /* no need to compute higher sfb values */\n sfb = sfbmax + 1;\n }\n\n /* accumulate lines to quantize */\n if (0 == accumulate && 0 == accumulate01) {\n acc_iData = iData;\n acc_iDataPos = iDataPos;\n acc_xp = xp;\n acc_xpPos = xpPos;\n }\n if (prevNoise != null && prevNoise.sfb_count1 > 0\n && sfb >= prevNoise.sfb_count1\n && prevNoise.step[sfb] > 0\n && step >= prevNoise.step[sfb]) {\n\n if (accumulate != 0) {\n quantize_lines_xrpow(accumulate, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate = 0;\n acc_iData = iData;\n acc_iDataPos = iDataPos;\n acc_xp = xp;\n acc_xpPos = xpPos;\n }\n accumulate01 += l;\n } else {\n if (accumulate01 != 0) {\n quantize_lines_xrpow_01(accumulate01, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate01 = 0;\n acc_iData = iData;\n acc_iDataPos = iDataPos;\n acc_xp = xp;\n acc_xpPos = xpPos;\n }\n accumulate += l;\n }\n\n if (l <= 0) {\n /*\n * rh: 20040215 may happen due to \"prev_data_use\"\n * optimization\n */\n if (accumulate01 != 0) {\n quantize_lines_xrpow_01(accumulate01, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate01 = 0;\n }\n if (accumulate != 0) {\n quantize_lines_xrpow(accumulate, istep, acc_xp,\n acc_xpPos, acc_iData, acc_iDataPos);\n accumulate = 0;\n }\n\n break;\n /* ends for-loop */\n }\n }\n if (sfb <= sfbmax) {\n iDataPos += codInfo.width[sfb];\n xpPos += codInfo.width[sfb];\n j += codInfo.width[sfb];\n }\n }\n if (accumulate != 0) { /* last data part */\n quantize_lines_xrpow(accumulate, istep, acc_xp, acc_xpPos,\n acc_iData, acc_iDataPos);\n accumulate = 0;\n }\n if (accumulate01 != 0) { /* last data part */\n quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_xpPos,\n acc_iData, acc_iDataPos);\n accumulate01 = 0;\n }\n\n }", "function upgrade_cost (k)\n {\n return 500.0 * (1 + k/(15-k)) * Math.pow(k, 1.5) * (1/(15-k));\n }", "getRealObstacleValue(k, x) {\n const exponent = 1 / (1 + Math.exp(-1 * k * x));\n return exponent;\n }", "function multiply( x, k, base ) {\n\t var m, temp, xlo, xhi,\n\t carry = 0,\n\t i = x.length,\n\t klo = k % SQRT_BASE,\n\t khi = k / SQRT_BASE | 0;\n\t\n\t for ( x = x.slice(); i--; ) {\n\t xlo = x[i] % SQRT_BASE;\n\t xhi = x[i] / SQRT_BASE | 0;\n\t m = khi * xlo + xhi * klo;\n\t temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n\t carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n\t x[i] = temp % base;\n\t }\n\t\n\t if (carry) x.unshift(carry);\n\t\n\t return x;\n\t }", "function multiply( x, k, base ) {\r\n\t\t var m, temp, xlo, xhi,\r\n\t\t carry = 0,\r\n\t\t i = x.length,\r\n\t\t klo = k % SQRT_BASE,\r\n\t\t khi = k / SQRT_BASE | 0;\r\n\t\t\r\n\t\t for ( x = x.slice(); i--; ) {\r\n\t\t xlo = x[i] % SQRT_BASE;\r\n\t\t xhi = x[i] / SQRT_BASE | 0;\r\n\t\t m = khi * xlo + xhi * klo;\r\n\t\t temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n\t\t carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n\t\t x[i] = temp % base;\r\n\t\t }\r\n\t\t\r\n\t\t if (carry) x.unshift(carry);\r\n\t\t\r\n\t\t return x;\r\n\t\t }", "function multiply( x, k, base ) {\n\t var m, temp, xlo, xhi,\n\t carry = 0,\n\t i = x.length,\n\t klo = k % SQRT_BASE,\n\t khi = k / SQRT_BASE | 0;\n\n\t for ( x = x.slice(); i--; ) {\n\t xlo = x[i] % SQRT_BASE;\n\t xhi = x[i] / SQRT_BASE | 0;\n\t m = khi * xlo + xhi * klo;\n\t temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n\t carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n\t x[i] = temp % base;\n\t }\n\n\t if (carry) x.unshift(carry);\n\n\t return x;\n\t }", "function multiply( x, k, base ) {\n\t var m, temp, xlo, xhi,\n\t carry = 0,\n\t i = x.length,\n\t klo = k % SQRT_BASE,\n\t khi = k / SQRT_BASE | 0;\n\n\t for ( x = x.slice(); i--; ) {\n\t xlo = x[i] % SQRT_BASE;\n\t xhi = x[i] / SQRT_BASE | 0;\n\t m = khi * xlo + xhi * klo;\n\t temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n\t carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n\t x[i] = temp % base;\n\t }\n\n\t if (carry) x.unshift(carry);\n\n\t return x;\n\t }", "function MultiPeriodBinomialPricingCall(R, u, d, S0, K, n, c, T, CallPut) {\n\t\tN = n+1; // number of cashflow elements is n+1\n\n\t\tconsole.log(\"debug: \"+R );\n //var q = (r - c - d) / (u-d);\n var q = (Math.exp( (R-c)*T/n ) - d) / (u-d);\n \n var Sn = [];\n var Cn = [];\n var Q = [];\n\n for (var i = 0; i <= N; i++) {\n var r = N-i;\n Sn[i] = S0 * Math.pow(u,r) * Math.pow(d,N-r);\n Cn[i] = Math.max(CallPut*(Sn[i] - K), 0);\n Q[i] = Combination(N, i) * Math.pow(q,r) * Math.pow(1-q,N-r);\n }\n\n var C0 = 0;\n for (var i = 0; i <= N; i++) {\n C0 += Q[i] * Cn[i];\n }\n \n C0 = C0/Math.pow(1+R,n);\n\n\tconsole.log(\"debug: C0:\"+C0+ \" q:\"+q);\n\n\treturn {\n\t\tC0: C0,\n\t\tq: q\n\t}\n}", "function bfs_price(_type, _X, _K, _t, _r, _s) {\n let _d\n _d = (_X - _K) / (_s * Math.sqrt(_t))\n if (_type == 'C') {\n return Math.exp(-_r * _t) * (normsdist(_d, true) * (_X - _K) + normsdist(_d, false) * (_s * Math.sqrt(_t)))\n } else {\n return Math.exp(-_r * _t) * (normsdist(-_d, true) * (_K - _X) + normsdist(_d, false) * (_s * Math.sqrt(_t)))\n }\n}", "function multiply( x, k, base ) {\n\t var m, temp, xlo, xhi,\n\t carry = 0,\n\t i = x.length,\n\t klo = k % SQRT_BASE,\n\t khi = k / SQRT_BASE | 0;\n\t\n\t for ( x = x.slice(); i--; ) {\n\t xlo = x[i] % SQRT_BASE;\n\t xhi = x[i] / SQRT_BASE | 0;\n\t m = khi * xlo + xhi * klo;\n\t temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n\t carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n\t x[i] = temp % base;\n\t }\n\t\n\t if (carry) x = [carry].concat(x);\n\t\n\t return x;\n\t }", "_setQProd(qr, qa, qb) {\nvar i, k, rc, rd, re, va, vb, wa, wb;\nva = [qa[0], qa[1], qa[2]];\nvb = [qb[0], qb[1], qb[2]];\nwa = qa[3];\nwb = qb[3];\nqr[3] = (wa * wb) - (va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2]);\nrc = [wa * vb[0], wa * vb[1], wa * vb[2]];\nrd = [wb * va[0], wb * va[1], wb * va[2]];\nre = [va[1] * vb[2] - va[2] * vb[1], va[2] * vb[0] - va[0] * vb[2], va[0] * vb[1] - va[1] * vb[0]];\nfor (i = k = 0; k < 3; i = ++k) {\nqr[i] = rc[i] + rd[i] + re[i];\n}\nreturn void 0;\n}", "function numberFactorPower(k) {\n for (i=0; i < pureFactor.length; i++) {\n \n let n = k;\n while (n >= pureFactor[i]) {\n \n powerOfNumber[i]= powerOfNumber[i] + Math.trunc(n/pureFactor[i]);\n \n n = Math.trunc(n/pureFactor[i]);\n }\n }\n return powerOfNumber;\n }", "function multiply( x, k, base ) {\r\n\t var m, temp, xlo, xhi,\r\n\t carry = 0,\r\n\t i = x.length,\r\n\t klo = k % SQRT_BASE,\r\n\t khi = k / SQRT_BASE | 0;\r\n\r\n\t for ( x = x.slice(); i--; ) {\r\n\t xlo = x[i] % SQRT_BASE;\r\n\t xhi = x[i] / SQRT_BASE | 0;\r\n\t m = khi * xlo + xhi * klo;\r\n\t temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n\t carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n\t x[i] = temp % base;\r\n\t }\r\n\r\n\t if (carry) x.unshift(carry);\r\n\r\n\t return x;\r\n\t }", "function pow(n, k) {\n\tif (k === 1) {\n\t\treturn n;\n\t}\n\treturn (n * pow(n, k-1));\n}", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply( x, k, base ) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for ( x = x.slice(); i--; ) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }", "function multiply( x, k, base ) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for ( x = x.slice(); i--; ) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }", "function multiply( x, k, base ) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for ( x = x.slice(); i--; ) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }", "function multiply( x, k, base ) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for ( x = x.slice(); i--; ) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }", "function multiply( x, k, base ) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for ( x = x.slice(); i--; ) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n\n return x;\n }", "function multiply( x, k, base ) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for ( x = x.slice(); i--; ) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n\n return x;\n }", "BIT_K_N(k, r1){\n this.zero_flag = ~(r1 >> k) & 0x1;\n this.subtraction_flag = false;\n this.half_carry_flag = true;\n }", "function multiply(x, k, base) {\n var m,\n temp,\n xlo,\n xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n return x;\n }", "function multiply( x, k, base ) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for ( x = x.slice(); i--; ) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply( x, k, base ) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for ( x = x.slice(); i--; ) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply( x, k, base ) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for ( x = x.slice(); i--; ) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r\n carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\n var m,\n temp,\n xlo,\n xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x.unshift(carry);\n\n return x;\n }", "function multiply(x, k, base) {\n var m,\n temp,\n xlo,\n xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m,\n temp,\n xlo,\n xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n return x;\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m, temp, xlo, xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n\n return x;\n }", "function multiply(x, k, base) {\n var m,\n temp,\n xlo,\n xhi,\n carry = 0,\n i = x.length,\n klo = k % SQRT_BASE,\n khi = k / SQRT_BASE | 0;\n\n for (x = x.slice(); i--;) {\n xlo = x[i] % SQRT_BASE;\n xhi = x[i] / SQRT_BASE | 0;\n m = khi * xlo + xhi * klo;\n temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\n x[i] = temp % base;\n }\n\n if (carry) x = [carry].concat(x);\n return x;\n }", "function fDCTQuant(data, fdtbl)\n\t {\n\t var d0, d1, d2, d3, d4, d5, d6, d7;\n\t /* Pass 1: process rows. */\n\t var dataOff=0;\n\t var i;\n\t var I8 = 8;\n\t var I64 = 64;\n\t for (i=0; i<I8; ++i)\n\t {\n\t d0 = data[dataOff];\n\t d1 = data[dataOff+1];\n\t d2 = data[dataOff+2];\n\t d3 = data[dataOff+3];\n\t d4 = data[dataOff+4];\n\t d5 = data[dataOff+5];\n\t d6 = data[dataOff+6];\n\t d7 = data[dataOff+7];\n\t \n\t var tmp0 = d0 + d7;\n\t var tmp7 = d0 - d7;\n\t var tmp1 = d1 + d6;\n\t var tmp6 = d1 - d6;\n\t var tmp2 = d2 + d5;\n\t var tmp5 = d2 - d5;\n\t var tmp3 = d3 + d4;\n\t var tmp4 = d3 - d4;\n\t \n\t /* Even part */\n\t var tmp10 = tmp0 + tmp3; /* phase 2 */\n\t var tmp13 = tmp0 - tmp3;\n\t var tmp11 = tmp1 + tmp2;\n\t var tmp12 = tmp1 - tmp2;\n\t \n\t data[dataOff] = tmp10 + tmp11; /* phase 3 */\n\t data[dataOff+4] = tmp10 - tmp11;\n\t \n\t var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */\n\t data[dataOff+2] = tmp13 + z1; /* phase 5 */\n\t data[dataOff+6] = tmp13 - z1;\n\t \n\t /* Odd part */\n\t tmp10 = tmp4 + tmp5; /* phase 2 */\n\t tmp11 = tmp5 + tmp6;\n\t tmp12 = tmp6 + tmp7;\n\t \n\t /* The rotator is modified from fig 4-8 to avoid extra negations. */\n\t var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */\n\t var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */\n\t var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */\n\t var z3 = tmp11 * 0.707106781; /* c4 */\n\t \n\t var z11 = tmp7 + z3; /* phase 5 */\n\t var z13 = tmp7 - z3;\n\t \n\t data[dataOff+5] = z13 + z2; /* phase 6 */\n\t data[dataOff+3] = z13 - z2;\n\t data[dataOff+1] = z11 + z4;\n\t data[dataOff+7] = z11 - z4;\n\t \n\t dataOff += 8; /* advance pointer to next row */\n\t }\n\t \n\t /* Pass 2: process columns. */\n\t dataOff = 0;\n\t for (i=0; i<I8; ++i)\n\t {\n\t d0 = data[dataOff];\n\t d1 = data[dataOff + 8];\n\t d2 = data[dataOff + 16];\n\t d3 = data[dataOff + 24];\n\t d4 = data[dataOff + 32];\n\t d5 = data[dataOff + 40];\n\t d6 = data[dataOff + 48];\n\t d7 = data[dataOff + 56];\n\t \n\t var tmp0p2 = d0 + d7;\n\t var tmp7p2 = d0 - d7;\n\t var tmp1p2 = d1 + d6;\n\t var tmp6p2 = d1 - d6;\n\t var tmp2p2 = d2 + d5;\n\t var tmp5p2 = d2 - d5;\n\t var tmp3p2 = d3 + d4;\n\t var tmp4p2 = d3 - d4;\n\t \n\t /* Even part */\n\t var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */\n\t var tmp13p2 = tmp0p2 - tmp3p2;\n\t var tmp11p2 = tmp1p2 + tmp2p2;\n\t var tmp12p2 = tmp1p2 - tmp2p2;\n\t \n\t data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */\n\t data[dataOff+32] = tmp10p2 - tmp11p2;\n\t \n\t var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */\n\t data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */\n\t data[dataOff+48] = tmp13p2 - z1p2;\n\t \n\t /* Odd part */\n\t tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */\n\t tmp11p2 = tmp5p2 + tmp6p2;\n\t tmp12p2 = tmp6p2 + tmp7p2;\n\t \n\t /* The rotator is modified from fig 4-8 to avoid extra negations. */\n\t var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */\n\t var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */\n\t var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */\n\t var z3p2 = tmp11p2 * 0.707106781; /* c4 */\n\t \n\t var z11p2 = tmp7p2 + z3p2; /* phase 5 */\n\t var z13p2 = tmp7p2 - z3p2;\n\t \n\t data[dataOff+40] = z13p2 + z2p2; /* phase 6 */\n\t data[dataOff+24] = z13p2 - z2p2;\n\t data[dataOff+ 8] = z11p2 + z4p2;\n\t data[dataOff+56] = z11p2 - z4p2;\n\t \n\t dataOff++; /* advance pointer to next column */\n\t }\n\t \n\t // Quantize/descale the coefficients\n\t var fDCTQuant;\n\t for (i=0; i<I64; ++i)\n\t {\n\t // Apply the quantization and scaling factor & Round to nearest integer\n\t fDCTQuant = data[i]*fdtbl[i];\n\t outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);\n\t //outputfDCTQuant[i] = fround(fDCTQuant);\n\t \n\t }\n\t return outputfDCTQuant;\n\t }", "function fDCTQuant(data, fdtbl)\n {\n var d0, d1, d2, d3, d4, d5, d6, d7;\n /* Pass 1: process rows. */\n var dataOff=0;\n var i;\n var I8 = 8;\n var I64 = 64;\n for (i=0; i<I8; ++i)\n {\n d0 = data[dataOff];\n d1 = data[dataOff+1];\n d2 = data[dataOff+2];\n d3 = data[dataOff+3];\n d4 = data[dataOff+4];\n d5 = data[dataOff+5];\n d6 = data[dataOff+6];\n d7 = data[dataOff+7];\n \n var tmp0 = d0 + d7;\n var tmp7 = d0 - d7;\n var tmp1 = d1 + d6;\n var tmp6 = d1 - d6;\n var tmp2 = d2 + d5;\n var tmp5 = d2 - d5;\n var tmp3 = d3 + d4;\n var tmp4 = d3 - d4;\n \n /* Even part */\n var tmp10 = tmp0 + tmp3; /* phase 2 */\n var tmp13 = tmp0 - tmp3;\n var tmp11 = tmp1 + tmp2;\n var tmp12 = tmp1 - tmp2;\n \n data[dataOff] = tmp10 + tmp11; /* phase 3 */\n data[dataOff+4] = tmp10 - tmp11;\n \n var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */\n data[dataOff+2] = tmp13 + z1; /* phase 5 */\n data[dataOff+6] = tmp13 - z1;\n \n /* Odd part */\n tmp10 = tmp4 + tmp5; /* phase 2 */\n tmp11 = tmp5 + tmp6;\n tmp12 = tmp6 + tmp7;\n \n /* The rotator is modified from fig 4-8 to avoid extra negations. */\n var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */\n var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */\n var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */\n var z3 = tmp11 * 0.707106781; /* c4 */\n \n var z11 = tmp7 + z3; /* phase 5 */\n var z13 = tmp7 - z3;\n \n data[dataOff+5] = z13 + z2; /* phase 6 */\n data[dataOff+3] = z13 - z2;\n data[dataOff+1] = z11 + z4;\n data[dataOff+7] = z11 - z4;\n \n dataOff += 8; /* advance pointer to next row */\n }\n \n /* Pass 2: process columns. */\n dataOff = 0;\n for (i=0; i<I8; ++i)\n {\n d0 = data[dataOff];\n d1 = data[dataOff + 8];\n d2 = data[dataOff + 16];\n d3 = data[dataOff + 24];\n d4 = data[dataOff + 32];\n d5 = data[dataOff + 40];\n d6 = data[dataOff + 48];\n d7 = data[dataOff + 56];\n \n var tmp0p2 = d0 + d7;\n var tmp7p2 = d0 - d7;\n var tmp1p2 = d1 + d6;\n var tmp6p2 = d1 - d6;\n var tmp2p2 = d2 + d5;\n var tmp5p2 = d2 - d5;\n var tmp3p2 = d3 + d4;\n var tmp4p2 = d3 - d4;\n \n /* Even part */\n var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */\n var tmp13p2 = tmp0p2 - tmp3p2;\n var tmp11p2 = tmp1p2 + tmp2p2;\n var tmp12p2 = tmp1p2 - tmp2p2;\n \n data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */\n data[dataOff+32] = tmp10p2 - tmp11p2;\n \n var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */\n data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */\n data[dataOff+48] = tmp13p2 - z1p2;\n \n /* Odd part */\n tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */\n tmp11p2 = tmp5p2 + tmp6p2;\n tmp12p2 = tmp6p2 + tmp7p2;\n \n /* The rotator is modified from fig 4-8 to avoid extra negations. */\n var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */\n var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */\n var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */\n var z3p2 = tmp11p2 * 0.707106781; /* c4 */\n \n var z11p2 = tmp7p2 + z3p2; /* phase 5 */\n var z13p2 = tmp7p2 - z3p2;\n \n data[dataOff+40] = z13p2 + z2p2; /* phase 6 */\n data[dataOff+24] = z13p2 - z2p2;\n data[dataOff+ 8] = z11p2 + z4p2;\n data[dataOff+56] = z11p2 - z4p2;\n \n dataOff++; /* advance pointer to next column */\n }\n \n // Quantize/descale the coefficients\n var fDCTQuant;\n for (i=0; i<I64; ++i)\n {\n // Apply the quantization and scaling factor & Round to nearest integer\n fDCTQuant = data[i]*fdtbl[i];\n outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);\n //outputfDCTQuant[i] = fround(fDCTQuant);\n \n }\n return outputfDCTQuant;\n }", "function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }", "pow (p, k = 0) {\n\t\t\treturn p.mul (this.ln (k)).exp ();\n\t\t}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n // initialize for multiply\n var e = k; // e = k\n var h = e.multiply(new BigInteger(\"3\"));\n var neg = this.negate();\n var R = this;\n\n // initialize for dummy to mitigate timing attack\n var e2 = this.curve.q.subtract(k); // e2 = q - k\n var h2 = e2.multiply(new BigInteger(\"3\"));\n var R2 = new ECPointFp(this.curve, this.x, this.y);\n var neg2 = R2.negate();\n\n // calculate multiply\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n // calculate dummy to mitigate timing attack\n for(i = h2.bitLength() - 2; i > 0; --i) {\n\tR2 = R2.twice();\n\n\tvar h2Bit = h2.testBit(i);\n\tvar e2Bit = e2.testBit(i);\n\n\tif (h2Bit != e2Bit) {\n\t R2 = R2.add(h2Bit ? R2 : neg2);\n\t}\n }\n\n return R;\n}", "function kernelEpanechnikov(k) {\n return function (v) {\n return Math.abs((v /= k)) <= 1 ? (0.75 * (1 - v * v)) / k : 0;\n };\n}", "function iqr(k) {\n\t\t\t return function(d, i) {\n\t\t\t var q1 = d.quartiles[0],\n\t\t\t q3 = d.quartiles[2],\n\t\t\t iqr = (q3 - q1) * k,\n\t\t\t i = -1,\n\t\t\t j = d.length;\n\t\t\t while (d[++i] < q1 - iqr);\n\t\t\t while (d[--j] > q3 + iqr);\n\t\t\t return [i, j];\n\t\t\t };\n\t\t\t}", "function compressTrainingMLData(k) {\n\t\n k = k || 2;\n\n\t\n var X = mRemoveFirstRow(mlData.XScaled);\n\n var sigma = math.multiply(X,math.transpose(X));\n\n\tvar m = X.size()[1];\n\t\n sigma = math.multiply(sigma,1/m);\n\n var res = numeric.svd(matrixToArray(sigma));\n\t\n\tvar S = math.matrix(res.S);\n\t\n\tvar totVar = math.sum(S);\n\t\n\tvar retainedVar = [];\n\tvar sSum = 0;\n\t\n\tfor (var i = 0;i < 300;++i) {\n\t\tif (i >= res.S.length) {\n\t\t\tbreak;\n\t\t}\n\t\tsSum += res.S[i];\n\t\t\n\t\tretainedVar.push(sSum / totVar * 100);\n\t\t\n\t\t\n\t}\n\t\n\n var U = math.matrix(res.U);\n\n var UReduce = math.subset(U,math.index(math.range(0,X.size()[0]),math.range(0,k)));\n\n var XCompressed = math.multiply(math.transpose(UReduce),X);\n\n var XApprox = math.multiply(UReduce,XCompressed);\t // uncompress just to check\n\t\n\tmlData.XCompressed = XCompressed;\n\t \n\t \n }", "function classicDistorsion(k) {\n var n_samples = 44100,\n curve = new Float32Array(n_samples),\n deg = Math.PI / 180, i = 0, x;\n\n for (; i < n_samples; ++i) {\n x = i * 2 / n_samples - 1;\n curve[i] = (3 + k) * x * 57 * deg / (Math.PI + k * Math.abs(x));\n }\n return curve;\n }", "function iqr(k) {\n return function (d, i) {\n var q1 = d.quartiles[0],\n q3 = d.quartiles[2],\n iqr = (q3 - q1) * k,\n i = -1,\n j = d.length;\n while (d[++i] < q1 - iqr);\n while (d[--j] > q3 + iqr);\n return [i, j];\n };\n }", "function inout ( k ) {\n\n\t\tif ( ( k *= 2 ) < 1 ) return 0.5 * k * k;\n\t\treturn - 0.5 * ( --k * ( k - 2 ) - 1 );\n\n\t}", "function iqr(k) {\n return function(d, i) {\n var q1 = d.quartiles[0],\n q3 = d.quartiles[2],\n iqr = (q3 - q1) * k,\n i = -1,\n j = d.length;\n while (d[++i] < q1 - iqr);\n while (d[--j] > q3 + iqr);\n return [i, j];\n };\n }", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function pointFpMultiply(k) {\n if(this.isInfinity()) return this;\n if(k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for(i = h.bitLength() - 2; i > 0; --i) {\n\tR = R.twice();\n\n\tvar hBit = h.testBit(i);\n\tvar eBit = e.testBit(i);\n\n\tif (hBit != eBit) {\n\t R = R.add(hBit ? this : neg);\n\t}\n }\n\n return R;\n}", "function BlackScholesBinomialCalibration(T, n, Vol)\n{\n return Math.exp(Vol * Math.sqrt(T/n));\n}", "function Co(t,e,n,r){var i=4,a=.001,o=1e-7,s=10,l=11,u=1/(l-1),c=\"undefined\"!==typeof Float32Array;if(4!==arguments.length)return!1;for(var d=0;d<4;++d)if(\"number\"!==typeof arguments[d]||isNaN(arguments[d])||!isFinite(arguments[d]))return!1;t=Math.min(t,1),n=Math.min(n,1),t=Math.max(t,0),n=Math.max(n,0);var h=c?new Float32Array(l):new Array(l);function f(t,e){return 1-3*e+3*t}function p(t,e){return 3*e-6*t}function v(t){return 3*t}function g(t,e,n){return((f(e,n)*t+p(e,n))*t+v(e))*t}function m(t,e,n){return 3*f(e,n)*t*t+2*p(e,n)*t+v(e)}function y(e,r){for(var a=0;a<i;++a){var o=m(r,t,n);if(0===o)return r;var s=g(r,t,n)-e;r-=s/o}return r}function b(){for(var e=0;e<l;++e)h[e]=g(e*u,t,n)}function x(e,r,i){var a,l,u=0;do{l=r+(i-r)/2,a=g(l,t,n)-e,a>0?i=l:r=l}while(Math.abs(a)>o&&++u<s);return l}function _(e){for(var r=0,i=1,o=l-1;i!==o&&h[i]<=e;++i)r+=u;--i;var s=(e-h[i])/(h[i+1]-h[i]),c=r+s*u,d=m(c,t,n);return d>=a?y(e,c):0===d?c:x(e,r,r+u)}var w=!1;function M(){w=!0,t===e&&n===r||b()}var S=function(i){return w||M(),t===e&&n===r?i:0===i?0:1===i?1:g(_(i),e,r)};S.getControlPoints=function(){return[{x:t,y:e},{x:n,y:r}]};var O=\"generateBezier(\"+[t,e,n,r]+\")\";return S.toString=function(){return O},S}", "function getQbig(needChair, needTable, needKhat) {\r\n// Qbig Fixed Hisab\r\nchair = 1;\r\ntable = 3;\r\nkhat = 5;\r\n\r\n needTotal = (needChair * chair + needTable * table + needKhat * khat);\r\n console.log(\"Need total qbig feet wood = \"+needTotal);\r\n\r\n}", "function iqr(k) {\n return function(d, i) {\n var q1 = d.quartiles[0],\n q3 = d.quartiles[2],\n iqr = (q3 - q1) * k,\n i = -1,\n j = d.length;\n while (d[++i] < q1 - iqr);\n while (d[--j] > q3 + iqr);\n return [i, j];\n };\n }", "function pointFpMultiply(k) {\r\n if (this.isInfinity())\r\n return this;\r\n if (k.signum() == 0)\r\n return this.curve.getInfinity();\r\n \r\n var e = k;\r\n var h = e.multiply(new BigInteger(\"3\"));\r\n \r\n var neg = this.negate();\r\n var R = this;\r\n \r\n var i;\r\n for (i = h.bitLength() - 2; i > 0; --i) {\r\n R = R.twice();\r\n \r\n var hBit = h.testBit(i);\r\n var eBit = e.testBit(i);\r\n \r\n if (hBit != eBit) {\r\n R = R.add(hBit ? this : neg);\r\n }\r\n }\r\n \r\n return R;\r\n}", "static innerProductQV(qa, qb) {\n//--------------\nreturn qa[0] * qb[0] + qa[1] * qb[1] + qa[2] * qb[2] + qa[3] * qb[3];\n}", "function pointFpMultiply(k) {\n if (this.isInfinity()) return this;\n if (k.signum() == 0) return this.curve.getInfinity();\n\n var e = k;\n var h = e.multiply(new BigInteger(\"3\"));\n\n var neg = this.negate();\n var R = this;\n\n var i;\n for (i = h.bitLength() - 2; i > 0; --i) {\n R = R.twice();\n\n var hBit = h.testBit(i);\n var eBit = e.testBit(i);\n\n if (hBit != eBit) {\n R = R.add(hBit ? this : neg);\n }\n }\n\n return R;\n}", "function fDCTQuant(data, fdtbl)\n\t\t{\n\t\t\tvar d0, d1, d2, d3, d4, d5, d6, d7;\n\t\t\t/* Pass 1: process rows. */\n\t\t\tvar dataOff=0;\n\t\t\tvar i;\n\t\t\tvar I8 = 8;\n\t\t\tvar I64 = 64;\n\t\t\tfor (i=0; i<I8; ++i)\n\t\t\t{\n\t\t\t\td0 = data[dataOff];\n\t\t\t\td1 = data[dataOff+1];\n\t\t\t\td2 = data[dataOff+2];\n\t\t\t\td3 = data[dataOff+3];\n\t\t\t\td4 = data[dataOff+4];\n\t\t\t\td5 = data[dataOff+5];\n\t\t\t\td6 = data[dataOff+6];\n\t\t\t\td7 = data[dataOff+7];\n\t\t\t\t\n\t\t\t\tvar tmp0 = d0 + d7;\n\t\t\t\tvar tmp7 = d0 - d7;\n\t\t\t\tvar tmp1 = d1 + d6;\n\t\t\t\tvar tmp6 = d1 - d6;\n\t\t\t\tvar tmp2 = d2 + d5;\n\t\t\t\tvar tmp5 = d2 - d5;\n\t\t\t\tvar tmp3 = d3 + d4;\n\t\t\t\tvar tmp4 = d3 - d4;\n\t\n\t\t\t\t/* Even part */\n\t\t\t\tvar tmp10 = tmp0 + tmp3;\t/* phase 2 */\n\t\t\t\tvar tmp13 = tmp0 - tmp3;\n\t\t\t\tvar tmp11 = tmp1 + tmp2;\n\t\t\t\tvar tmp12 = tmp1 - tmp2;\n\t\n\t\t\t\tdata[dataOff] = tmp10 + tmp11; /* phase 3 */\n\t\t\t\tdata[dataOff+4] = tmp10 - tmp11;\n\t\n\t\t\t\tvar z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */\n\t\t\t\tdata[dataOff+2] = tmp13 + z1; /* phase 5 */\n\t\t\t\tdata[dataOff+6] = tmp13 - z1;\n\t\n\t\t\t\t/* Odd part */\n\t\t\t\ttmp10 = tmp4 + tmp5; /* phase 2 */\n\t\t\t\ttmp11 = tmp5 + tmp6;\n\t\t\t\ttmp12 = tmp6 + tmp7;\n\t\n\t\t\t\t/* The rotator is modified from fig 4-8 to avoid extra negations. */\n\t\t\t\tvar z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */\n\t\t\t\tvar z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */\n\t\t\t\tvar z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */\n\t\t\t\tvar z3 = tmp11 * 0.707106781; /* c4 */\n\t\n\t\t\t\tvar z11 = tmp7 + z3;\t/* phase 5 */\n\t\t\t\tvar z13 = tmp7 - z3;\n\t\n\t\t\t\tdata[dataOff+5] = z13 + z2;\t/* phase 6 */\n\t\t\t\tdata[dataOff+3] = z13 - z2;\n\t\t\t\tdata[dataOff+1] = z11 + z4;\n\t\t\t\tdata[dataOff+7] = z11 - z4;\n\t\n\t\t\t\tdataOff += 8; /* advance pointer to next row */\n\t\t\t}\n\t\n\t\t\t/* Pass 2: process columns. */\n\t\t\tdataOff = 0;\n\t\t\tfor (i=0; i<I8; ++i)\n\t\t\t{\n\t\t\t\td0 = data[dataOff];\n\t\t\t\td1 = data[dataOff + 8];\n\t\t\t\td2 = data[dataOff + 16];\n\t\t\t\td3 = data[dataOff + 24];\n\t\t\t\td4 = data[dataOff + 32];\n\t\t\t\td5 = data[dataOff + 40];\n\t\t\t\td6 = data[dataOff + 48];\n\t\t\t\td7 = data[dataOff + 56];\n\t\t\t\t\n\t\t\t\tvar tmp0p2 = d0 + d7;\n\t\t\t\tvar tmp7p2 = d0 - d7;\n\t\t\t\tvar tmp1p2 = d1 + d6;\n\t\t\t\tvar tmp6p2 = d1 - d6;\n\t\t\t\tvar tmp2p2 = d2 + d5;\n\t\t\t\tvar tmp5p2 = d2 - d5;\n\t\t\t\tvar tmp3p2 = d3 + d4;\n\t\t\t\tvar tmp4p2 = d3 - d4;\n\t\n\t\t\t\t/* Even part */\n\t\t\t\tvar tmp10p2 = tmp0p2 + tmp3p2;\t/* phase 2 */\n\t\t\t\tvar tmp13p2 = tmp0p2 - tmp3p2;\n\t\t\t\tvar tmp11p2 = tmp1p2 + tmp2p2;\n\t\t\t\tvar tmp12p2 = tmp1p2 - tmp2p2;\n\t\n\t\t\t\tdata[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */\n\t\t\t\tdata[dataOff+32] = tmp10p2 - tmp11p2;\n\t\n\t\t\t\tvar z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */\n\t\t\t\tdata[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */\n\t\t\t\tdata[dataOff+48] = tmp13p2 - z1p2;\n\t\n\t\t\t\t/* Odd part */\n\t\t\t\ttmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */\n\t\t\t\ttmp11p2 = tmp5p2 + tmp6p2;\n\t\t\t\ttmp12p2 = tmp6p2 + tmp7p2;\n\t\n\t\t\t\t/* The rotator is modified from fig 4-8 to avoid extra negations. */\n\t\t\t\tvar z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */\n\t\t\t\tvar z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */\n\t\t\t\tvar z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */\n\t\t\t\tvar z3p2 = tmp11p2 * 0.707106781; /* c4 */\n\t\n\t\t\t\tvar z11p2 = tmp7p2 + z3p2;\t/* phase 5 */\n\t\t\t\tvar z13p2 = tmp7p2 - z3p2;\n\t\n\t\t\t\tdata[dataOff+40] = z13p2 + z2p2; /* phase 6 */\n\t\t\t\tdata[dataOff+24] = z13p2 - z2p2;\n\t\t\t\tdata[dataOff+ 8] = z11p2 + z4p2;\n\t\t\t\tdata[dataOff+56] = z11p2 - z4p2;\n\t\n\t\t\t\tdataOff++; /* advance pointer to next column */\n\t\t\t}\n\t\n\t\t\t// Quantize/descale the coefficients\n\t\t\tvar fDCTQuant;\n\t\t\tfor (i=0; i<I64; ++i)\n\t\t\t{\n\t\t\t\t// Apply the quantization and scaling factor & Round to nearest integer\n\t\t\t\tfDCTQuant = data[i]*fdtbl[i];\n\t\t\t\toutputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);\n\t\t\t\t//outputfDCTQuant[i] = fround(fDCTQuant);\n\n\t\t\t}\n\t\t\treturn outputfDCTQuant;\n\t\t}", "function fDCTQuant(data, fdtbl)\n\t\t{\n\t\t\tvar d0, d1, d2, d3, d4, d5, d6, d7;\n\t\t\t/* Pass 1: process rows. */\n\t\t\tvar dataOff=0;\n\t\t\tvar i;\n\t\t\tvar I8 = 8;\n\t\t\tvar I64 = 64;\n\t\t\tfor (i=0; i<I8; ++i)\n\t\t\t{\n\t\t\t\td0 = data[dataOff];\n\t\t\t\td1 = data[dataOff+1];\n\t\t\t\td2 = data[dataOff+2];\n\t\t\t\td3 = data[dataOff+3];\n\t\t\t\td4 = data[dataOff+4];\n\t\t\t\td5 = data[dataOff+5];\n\t\t\t\td6 = data[dataOff+6];\n\t\t\t\td7 = data[dataOff+7];\n\t\t\t\t\n\t\t\t\tvar tmp0 = d0 + d7;\n\t\t\t\tvar tmp7 = d0 - d7;\n\t\t\t\tvar tmp1 = d1 + d6;\n\t\t\t\tvar tmp6 = d1 - d6;\n\t\t\t\tvar tmp2 = d2 + d5;\n\t\t\t\tvar tmp5 = d2 - d5;\n\t\t\t\tvar tmp3 = d3 + d4;\n\t\t\t\tvar tmp4 = d3 - d4;\n\t\n\t\t\t\t/* Even part */\n\t\t\t\tvar tmp10 = tmp0 + tmp3;\t/* phase 2 */\n\t\t\t\tvar tmp13 = tmp0 - tmp3;\n\t\t\t\tvar tmp11 = tmp1 + tmp2;\n\t\t\t\tvar tmp12 = tmp1 - tmp2;\n\t\n\t\t\t\tdata[dataOff] = tmp10 + tmp11; /* phase 3 */\n\t\t\t\tdata[dataOff+4] = tmp10 - tmp11;\n\t\n\t\t\t\tvar z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */\n\t\t\t\tdata[dataOff+2] = tmp13 + z1; /* phase 5 */\n\t\t\t\tdata[dataOff+6] = tmp13 - z1;\n\t\n\t\t\t\t/* Odd part */\n\t\t\t\ttmp10 = tmp4 + tmp5; /* phase 2 */\n\t\t\t\ttmp11 = tmp5 + tmp6;\n\t\t\t\ttmp12 = tmp6 + tmp7;\n\t\n\t\t\t\t/* The rotator is modified from fig 4-8 to avoid extra negations. */\n\t\t\t\tvar z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */\n\t\t\t\tvar z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */\n\t\t\t\tvar z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */\n\t\t\t\tvar z3 = tmp11 * 0.707106781; /* c4 */\n\t\n\t\t\t\tvar z11 = tmp7 + z3;\t/* phase 5 */\n\t\t\t\tvar z13 = tmp7 - z3;\n\t\n\t\t\t\tdata[dataOff+5] = z13 + z2;\t/* phase 6 */\n\t\t\t\tdata[dataOff+3] = z13 - z2;\n\t\t\t\tdata[dataOff+1] = z11 + z4;\n\t\t\t\tdata[dataOff+7] = z11 - z4;\n\t\n\t\t\t\tdataOff += 8; /* advance pointer to next row */\n\t\t\t}\n\t\n\t\t\t/* Pass 2: process columns. */\n\t\t\tdataOff = 0;\n\t\t\tfor (i=0; i<I8; ++i)\n\t\t\t{\n\t\t\t\td0 = data[dataOff];\n\t\t\t\td1 = data[dataOff + 8];\n\t\t\t\td2 = data[dataOff + 16];\n\t\t\t\td3 = data[dataOff + 24];\n\t\t\t\td4 = data[dataOff + 32];\n\t\t\t\td5 = data[dataOff + 40];\n\t\t\t\td6 = data[dataOff + 48];\n\t\t\t\td7 = data[dataOff + 56];\n\t\t\t\t\n\t\t\t\tvar tmp0p2 = d0 + d7;\n\t\t\t\tvar tmp7p2 = d0 - d7;\n\t\t\t\tvar tmp1p2 = d1 + d6;\n\t\t\t\tvar tmp6p2 = d1 - d6;\n\t\t\t\tvar tmp2p2 = d2 + d5;\n\t\t\t\tvar tmp5p2 = d2 - d5;\n\t\t\t\tvar tmp3p2 = d3 + d4;\n\t\t\t\tvar tmp4p2 = d3 - d4;\n\t\n\t\t\t\t/* Even part */\n\t\t\t\tvar tmp10p2 = tmp0p2 + tmp3p2;\t/* phase 2 */\n\t\t\t\tvar tmp13p2 = tmp0p2 - tmp3p2;\n\t\t\t\tvar tmp11p2 = tmp1p2 + tmp2p2;\n\t\t\t\tvar tmp12p2 = tmp1p2 - tmp2p2;\n\t\n\t\t\t\tdata[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */\n\t\t\t\tdata[dataOff+32] = tmp10p2 - tmp11p2;\n\t\n\t\t\t\tvar z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */\n\t\t\t\tdata[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */\n\t\t\t\tdata[dataOff+48] = tmp13p2 - z1p2;\n\t\n\t\t\t\t/* Odd part */\n\t\t\t\ttmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */\n\t\t\t\ttmp11p2 = tmp5p2 + tmp6p2;\n\t\t\t\ttmp12p2 = tmp6p2 + tmp7p2;\n\t\n\t\t\t\t/* The rotator is modified from fig 4-8 to avoid extra negations. */\n\t\t\t\tvar z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */\n\t\t\t\tvar z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */\n\t\t\t\tvar z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */\n\t\t\t\tvar z3p2 = tmp11p2 * 0.707106781; /* c4 */\n\t\n\t\t\t\tvar z11p2 = tmp7p2 + z3p2;\t/* phase 5 */\n\t\t\t\tvar z13p2 = tmp7p2 - z3p2;\n\t\n\t\t\t\tdata[dataOff+40] = z13p2 + z2p2; /* phase 6 */\n\t\t\t\tdata[dataOff+24] = z13p2 - z2p2;\n\t\t\t\tdata[dataOff+ 8] = z11p2 + z4p2;\n\t\t\t\tdata[dataOff+56] = z11p2 - z4p2;\n\t\n\t\t\t\tdataOff++; /* advance pointer to next column */\n\t\t\t}\n\t\n\t\t\t// Quantize/descale the coefficients\n\t\t\tvar fDCTQuant;\n\t\t\tfor (i=0; i<I64; ++i)\n\t\t\t{\n\t\t\t\t// Apply the quantization and scaling factor & Round to nearest integer\n\t\t\t\tfDCTQuant = data[i]*fdtbl[i];\n\t\t\t\toutputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);\n\t\t\t\t//outputfDCTQuant[i] = fround(fDCTQuant);\n\n\t\t\t}\n\t\t\treturn outputfDCTQuant;\n\t\t}", "function sm_1(z) {\n var k = [0, 0];\n\n // rotate to have s ~= 1\n var rot = complexPow(\n w,\n d3Array.scan(\n [0, 1, 2].map(function(i) {\n return -complexMul(z, complexPow(w, [i, 0]))[0];\n })\n )\n );\n\n var y = complexMul(rot, z);\n y = [1 - y[0], -y[1]];\n\n // McIlroy formula 5 p6 and table for F3 page 16\n var F0 = [\n 1.44224957030741,\n 0.240374928384568,\n 0.0686785509670194,\n 0.0178055502507087,\n 0.00228276285265497,\n -1.48379585422573e-3,\n -1.64287728109203e-3,\n -1.02583417082273e-3,\n -4.83607537673571e-4,\n -1.67030822094781e-4,\n -2.45024395166263e-5,\n 2.14092375450951e-5,\n 2.55897270486771e-5,\n 1.73086854400834e-5,\n 8.72756299984649e-6,\n 3.18304486798473e-6,\n 4.79323894565283e-7,\n -4.58968389565456e-7,\n -5.62970586787826e-7,\n -3.92135372833465e-7\n ];\n\n var F = [0, 0];\n for (var i = F0.length; i--; ) F = complexAdd([F0[i], 0], complexMul(F, y));\n\n k = complexMul(\n complexAdd(w1, complexMul([-F[0], -F[1]], complexPow(y, 1 - 2 / 3))),\n complexMul(rot, rot)\n );\n\n // when we are close to [0,0] we switch to another approximation:\n // https://www.wolframalpha.com/input/?i=(-2%2F3+choose+k)++*+(-1)%5Ek++%2F+(k%2B1)+with+k%3D0,1,2,3,4\n // the difference is _very_ tiny but necessary\n // if we want projection(0,0) === [0,0]\n var n = complexNorm2(z);\n if (n < m) {\n var H0 = [\n 1,\n 1 / 3,\n 5 / 27,\n 10 / 81,\n 22 / 243 //…\n ];\n var z3 = complexPow(z, [3, 0]);\n var h = [0, 0];\n for (i = H0.length; i--; ) h = complexAdd([H0[i], 0], complexMul(h, z3));\n h = complexMul(h, z);\n k = complexAdd(complexMul(k, [n / m, 0]), complexMul(h, [1 - n / m, 0]));\n }\n\n return k;\n}" ]
[ "0.64669013", "0.579708", "0.5733237", "0.5733237", "0.5627074", "0.55756706", "0.54587847", "0.544894", "0.54455554", "0.54455554", "0.54324776", "0.5430064", "0.5429248", "0.54154116", "0.5411437", "0.5406991", "0.53878427", "0.5379771", "0.5379771", "0.5379771", "0.5379771", "0.5379771", "0.5379771", "0.5375143", "0.5375143", "0.5375143", "0.5375143", "0.5375143", "0.53747857", "0.53747857", "0.53747857", "0.53747857", "0.53747857", "0.53747857", "0.53747857", "0.53711593", "0.5369956", "0.5365979", "0.5365979", "0.5365979", "0.5345213", "0.5344093", "0.5318451", "0.53141713", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53123975", "0.53122264", "0.53122264", "0.53122264", "0.53122264", "0.53122264", "0.53122264", "0.53122264", "0.53122264", "0.53009206", "0.5297015", "0.5288941", "0.5285902", "0.5281828", "0.52798384", "0.5235567", "0.5215033", "0.52066785", "0.5206264", "0.5172953", "0.5161997", "0.5154451", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.51540625", "0.5153661", "0.51439476", "0.5142779", "0.5142349", "0.5139229", "0.5131334", "0.5126818", "0.51237774", "0.51237774", "0.51226443" ]
0.6159191
1
Bypass. Checks for overlap and add artifacts
bypass(inBuffer, outBuffer){ for (let i = 0; i < inBuffer.length; i++){ outBuffer[i] = inBuffer[i]; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "intersectingArtifact(bb) {\n let sel = 0;\n bb = svgHelpers.boxPoints(bb.x, bb.y, bb.width ? bb.width : 1, bb.height ? bb.height : 1);\n const artifacts = svgHelpers.findIntersectingArtifactFromMap(bb, this.measureNoteMap, this.scroller.scrollState);\n // TODO: handle overlapping suggestions\n if (!artifacts.length) {\n sel = svgHelpers.findIntersectingArtifact(bb, this.modifierTabs, this.scroller.scrollState);\n if (sel.length) {\n sel = sel[0];\n this._setModifierAsSuggestion(bb, sel);\n }\n return;\n }\n const artifact = artifacts[0];\n this._setArtifactAsSuggestion(bb, artifact);\n }", "_handleMouseArtifactCollision(evt) {\n let worldPosition = this._camera.screenToWorldCoordinates(evt.offsetX, evt.offsetY);\n let mouseBoundary = Boundary.fromVector2(worldPosition, EditorGameScene.DIMENSIONS.MOUSE_COLLISION_BULK);\n //let bulk = EditorGameScene.DIMENSIONS.ARTIFACT_RECTANGLE_BULK * this._camera.zoom;\n let method = null;\n\n // let's check on all the game scene game objects if there is a selection collision detected:\n this._selectedObjects.forEach((function (selected) {\n let activeArtifact = null;\n if (selected.gameObject.collidesWithPoint(worldPosition)) {\n let artifactData = this._generateGameObjectArtifactData(selected.gameObject, true);\n\n // ok, without further considerations, let's apply the default method (MOVE) if enabled\n if (this._isMoveEnabled()) {\n method = EditorGameScene.TRANSFORM_STATE.MOVE;\n }\n\n // now we test the collision for each artifact data:\n artifactData.forEach((function (artifact) {\n // is this a valid candidate?\n if (activeArtifact == null || artifact.priority > activeArtifact.priority) {\n // is the mouse boundary overlapping?\n if (Boundary.overlap(mouseBoundary, artifact.boundary)) {\n activeArtifact = artifact;\n method = artifact.method;\n }\n }\n }).bind(this));\n }\n }).bind(this));\n\n if (method != null) {\n // update the cursor based on the selected target:\n switch (method) {\n case EditorGameScene.TRANSFORM_STATE.ORIGIN:\n case EditorGameScene.TRANSFORM_STATE.SCALE_TOP_LEFT:\n case EditorGameScene.TRANSFORM_STATE.SCALE_BOTTOM_RIGHT:\n case EditorGameScene.TRANSFORM_STATE.SCALE_TOP_RIGHT:\n case EditorGameScene.TRANSFORM_STATE.SCALE_BOTTOM_LEFT:\n case EditorGameScene.TRANSFORM_STATE.SCALE_TOP:\n case EditorGameScene.TRANSFORM_STATE.SCALE_RIGHT:\n case EditorGameScene.TRANSFORM_STATE.SCALE_BOTTOM:\n case EditorGameScene.TRANSFORM_STATE.SCALE_LEFT:\n this._mouseState.cursor = EditorGameScene.CURSOR_TYPES.POINTER;\n break;\n\n case EditorGameScene.TRANSFORM_STATE.MOVE:\n this._mouseState.cursor = EditorGameScene.CURSOR_TYPES.MOVE;\n break;\n\n default:\n this._mouseState.cursor = EditorGameScene.CURSOR_TYPES.DEFAULT;\n }\n\n this._updateCursorGraphic();\n\n } else {\n this._mouseState.cursor = EditorGameScene.CURSOR_TYPES.DEFAULT;\n this._updateCursorGraphic();\n }\n\n return method;\n }", "function checkLayerOverlap(pl){\n var mouse = d3.mouse(d3.select(_canvas).node());\n var mouseX = mouse[0];\n var mouseY = mouse[1];\n var bounds = {\n 'top': mouse[1],\n 'left': mouse[0],\n 'bottom': mouse[1],\n 'right': mouse[0],\n };\n var uuid = pl.uuid();\n var overlap = null;\n // Find the first layer that is overlapped\n for(var i = 0; i < _pixelLayers.length; i++){\n var p = _pixelLayers[i];\n if(p.uuid() === uuid){ continue; }\n if(rectOverlap(bounds, p.boundingRect(_zoomScale, _zoomPan))){ \n overlap = p; \n break;\n }\n }\n if(_overlap == null && overlap != null){\n _overlap = p;\n _obj.onLayerOverlapEnter(pl, _overlap);\n }\n else if(_overlap != null && overlap == null){\n _obj.onLayerOverlapLeave(pl, _overlap);\n _overlap = null;\n }\n else if(_overlap != null && overlap != null){\n // We passed from one overlapping item to another without\n // breaking\n if(p.uuid() != _overlap.uuid()){\n _obj.onLayerOverlapLeave(pl, _overlap);\n _overlap = p;\n _obj.onLayerOverlapEnter(pl, _overlap);\n }\n }\n }", "_isOverlappingExisting(x, y, w, h) {\n if(!this._positions.length) return false;\n let over = false;\n this._positions.forEach((item) => {\n if (!(item.x > x + w ||\n item.x + item.width < x ||\n item.y > y + h ||\n item.y + item.height < y)) over = true;\n });\n\n return over;\n }", "function overlappingPacker(svgArea, spans) {\n // Stick the two shapes on top of one another in the center.\n var cx = svgArea.width / 2, cy = svgArea.height / 2;\n return adjustLayoutToFit(\n svgArea,\n spans,\n [{x: cx, y: cy}, {x: cx, y: cy}]);\n}", "overlap (ob) {\n\t\treturn (dist(this.position, ob.position) < 50);\n\t}", "platformsOverlap(startingX, trackNumber) {\n\n let overlapping = false;\n\n this.platforms.forEach(platform => {\n\n if (platform.trackNumber === trackNumber) {\n if (startingX === platform.x) {\n overlapping = true;\n } else if (startingX > platform.x && startingX < platform.x + 300) {\n overlapping = true;\n } else if (startingX + 300 > platform.x && platform.x + 300 > startingX + 300) {\n overlapping = true;\n }\n }\n });\n\n return overlapping;\n }", "checkConflict(itemTag){\n \n let buffer = 7\n let frogBuffer = 9;\n if(itemTag.className === \"log\"){\n buffer = 3\n }\n // else if(itemTag.id === \"winStrip\"){\n // buffer = -5\n // }\n \n \n let frogXMin = parseInt(this.frog.tag.style.left.replace(\"px\", \"\")) +frogBuffer \n let frogXMax = frogXMin + this.frog.tag.offsetWidth - 2*frogBuffer\n let frogYMin = parseInt(this.frog.tag.style.top.replace(\"px\", \"\")) + frogBuffer \n let frogYMax = frogYMin + this.frog.tag.offsetHeight - 2*frogBuffer\n\n let itemXMin = parseInt(itemTag.style.left.replace(\"px\", \"\")) + buffer\n let itemXMax = itemXMin + itemTag.offsetWidth - 2*buffer\n let itemYMin = parseInt(itemTag.style.top.replace(\"px\", \"\")) + buffer\n let itemYMax = itemYMin + itemTag.offsetHeight - 2*buffer\n\n // CHECK IF FROG OVERLAPS\n if(frogXMin > itemXMin && frogXMin < itemXMax || frogXMax > itemXMin && frogXMax < itemXMax){\n if(frogYMin > itemYMin && frogYMin < itemYMax || frogYMax > itemYMin && frogYMax < itemYMax){\n \n // we're comaparing to log so you're safe\n if (itemTag.className === \"log\"){\n \n this.frog.onLog = true;\n this.frog.log = itemTag\n \n\n }else if(itemTag.id === \"prize\"){\n this.winAudio.play()\n this.youWin()\n\n // you hit river\n }else if(itemTag.id === \"river\"){\n if(!this.frog.onLog ){//&& !this.frog.onWinStrip){\n this.splashAudio.play()\n this.frogHit()\n }\n\n }else{ // hit a car\n this.crashAudio.play()\n this.frogHit()\n } \n }\n }\n }", "setOverlap () {\n if (this.shadowRoot.getElementById('canvas').hasChildNodes()) {\n for (let i = 0; i < this.shadowRoot.getElementById('canvas').children.length; i++) {\n if (!this.shadowRoot.getElementById('canvas').children[i].isMaximized) {\n this.shadowRoot.getElementById('canvas').children[i].zIndex = 1\n }\n }\n }\n }", "spriteOverlap(a, b) {\n let ab = a.getBounds();\n let bb = b.getBounds();\n return ab.x + ab.width > bb.x && ab.x < bb.x + bb.width && ab.y + ab.height > bb.y && ab.y < bb.y + bb.height;\n }", "spriteOverlap(a, b) {\n let ab = a.getBounds();\n let bb = b.getBounds();\n return ab.x + ab.width > bb.x && ab.x < bb.x + bb.width && ab.y + ab.height > bb.y && ab.y < bb.y + bb.height;\n }", "function addOverlap(event, el){\n if(eventsOverlap[event.id] !== undefined && eventsOverlap[event.id].indexOf(el) === -1){\n eventsOverlap[event.id].push(el);\n } else if(eventsOverlap[event.id] === undefined) {\n eventsOverlap[event.id] = [el];\n }\n\n if(eventsOverlap[el.id] !== undefined && eventsOverlap[el.id].indexOf(event) === -1){\n eventsOverlap[el.id].push(event);\n } else if(eventsOverlap[el.id] === undefined){\n eventsOverlap[el.id] = [event];\n }\n }", "comboNonOverlapping(displacements, comboMap) {\n const self = this;\n const comboTree = self.comboTree;\n const comboCollideStrength = self.comboCollideStrength;\n const indexMap = self.indexMap;\n const nodeMap = self.nodeMap;\n traverseTreeUp(comboTree, treeNode => {\n if (!comboMap[treeNode.id] &&\n !nodeMap[treeNode.id] &&\n treeNode.id !== \"comboTreeRoot\") {\n return false;\n } // means it is hidden\n const children = treeNode.children;\n // 同个子树下的子 combo 间两两对比\n if (children && children.length > 1) {\n children.forEach((v, i) => {\n if (v.itemType === \"node\")\n return false; // skip it\n const cv = comboMap[v.id];\n if (!cv)\n return; // means it is hidden, skip it\n children.forEach((u, j) => {\n if (i <= j)\n return false;\n if (u.itemType === \"node\")\n return false; // skip it\n const cu = comboMap[u.id];\n if (!cu)\n return false; // means it is hidden, skip it\n const vx = cv.cx - cu.cx || 0.005;\n const vy = cv.cy - cu.cy || 0.005;\n const l = vx * vx + vy * vy;\n const rv = cv.r;\n const ru = cu.r;\n const r = rv + ru;\n const ru2 = ru * ru;\n const rv2 = rv * rv;\n // overlapping\n if (l < r * r) {\n const vnodes = v.children;\n if (!vnodes || vnodes.length === 0)\n return false; // skip it\n const unodes = u.children;\n if (!unodes || unodes.length === 0)\n return false; // skip it\n const sqrtl = Math.sqrt(l);\n const ll = ((r - sqrtl) / sqrtl) * comboCollideStrength;\n const xl = vx * ll;\n const yl = vy * ll;\n const rratio = ru2 / (rv2 + ru2);\n const irratio = 1 - rratio;\n // 两兄弟 combo 的子节点上施加斥力\n vnodes.forEach(vn => {\n if (vn.itemType !== \"node\")\n return false; // skip it\n if (!nodeMap[vn.id])\n return; // means it is hidden, skip it\n const vindex = indexMap[vn.id];\n unodes.forEach(un => {\n if (un.itemType !== \"node\")\n return false;\n if (!nodeMap[un.id])\n return false; // means it is hidden, skip it\n const uindex = indexMap[un.id];\n displacements[vindex].x += xl * rratio;\n displacements[vindex].y += yl * rratio;\n displacements[uindex].x -= xl * irratio;\n displacements[uindex].y -= yl * irratio;\n });\n });\n }\n });\n });\n }\n return true;\n });\n }", "checkItemsInPlayCollisions(ctx) {\n // NOTE: llama status will be normal only in the day\n if (this.llama.status === \"normal\") {\n return;\n }\n\n let sphericalObjects = this.itemsInPlay;\n\n for (let i = 0; i < sphericalObjects.length; i++) {\n for (let j = 0; j < sphericalObjects.length; j++) {\n if (sphericalObjects[i] != sphericalObjects[j]) {\n\n if (sphericalObjects[i] instanceof _other_objects_bacon_js__WEBPACK_IMPORTED_MODULE_6__[\"default\"] || sphericalObjects[j] instanceof _other_objects_bacon_js__WEBPACK_IMPORTED_MODULE_6__[\"default\"]) {\n // NOTE: Bacon is not spherical\n continue;\n }\n\n if (sphericalObjects[i].status === \"available\" && sphericalObjects[j].status === \"available\") {\n if (this.areSpheresColliding(sphericalObjects[i], sphericalObjects[j])) {\n\n // NOTE: 1st line- no elastic response. 2nd line - elastic response\n // sphericalObjects[i].y_velocity = -sphericalObjects[i].y_velocity;\n this.resolveSphereSphereCollision(sphericalObjects[i], sphericalObjects[j]);\n }\n }\n }\n }\n }\n }", "function setup() { //NOW we set up the space which we will AFTERWARDS draw on.\n var myCanvas = createCanvas(windowWidth, windowHeight);\n myCanvas.parent('myContainer');\n imageMode(CORNERS);\n frameRate(50); //circle speed\n stroke(0);\n fill(150);\n\n SHIFT = createVector(width / 2, height / 2.4);\n\n img = loadImage(\"assets/Drop1DIV4.png\"); // Load the image\n\n\n\n\n //fixing the X & Y of the drop shell\n var arrayStringCoordinates = dropStrings[0].split(\" \"); //pulling in the drop coordinates and splitting by SPAEC\n print(arrayStringCoordinates);\n arrayStringCoordinates.forEach(function (s) { //since we have 30 circles, we need a forEach statement\n var coordStrings = s.split(\",\"); //splitting it up by comma.. now we have Xs and Ys \n\n //-----------------------------------------------------YELLOW CAGE STET UP-----------------------------------------------------------//\n var x = float(coordStrings[0]); //converting a string to decimile (floating)\n var y = float(coordStrings[1]) - dropHeight / 2;\n var point = createVector(x * 1.8, y * 1.8); //creating the drop\n drop.push(point); //pushing point into drop --in the top of the page\n\n });\n //print(table.getRowCount() + \"total rows in table\");\n\n\n //-----------------------------------------------------Data Parse-----------------------------------------------------------// \n //FILTERING DATA\n table.getRows().forEach(function (row) {\n var warName = row.getString(\"WarName\");\n var participantName = row.getString(\"StateName\");\n var startYear = int(row.getString(\"StartYear1\"));\n var startMonth = int(row.getString(\"StartMonth1\"));\n var startDay = int(row.getString(\"StartDay1\"));\n var endYear = int(row.getString(\"EndYear1\"));\n var endMonth = int(row.getString(\"EndMonth1\"));\n var endDay = int(row.getString(\"EndDay1\"));\n var deaths = int(row.getString(\"BatDeath\"));\n\n var startDate = new ODate(startYear, startMonth, startDay);\n var endDate = new ODate(endYear, endMonth, endDay);\n var participant = new Participant(participantName, startDate, endDate, deaths);\n\n var war = getWar(warName);\n if (war == \"false\") {\n //create a new war\n var myWar = new War(warName);\n myWar.deaths = deaths;\n myWar.participants.push(participant);\n wars.push(myWar);\n\n } else {\n //fill the existing war with new data\n war.participants.push(participant);\n }\n\n });\n /* WAR FILTERED BY YEAR */\n function getWar(name) {\n for (var i = 0; i < wars.length; i++) {\n var war = wars[i];\n if (war.name == name) {\n return war;\n }\n\n }\n return \"false\";\n\n }\n\n //-------------------------------------------------THE TIMELINE SETUP-------------------------------------------------------//\n\n /*RECTS ACCORDING TO END AND START YEAR*/\n arrayRects.push(new SelectRect(1823, 1852));\n arrayRects.push(new SelectRect(1853, 1882));\n arrayRects.push(new SelectRect(1883, 1912));\n arrayRects.push(new SelectRect(1913, 1942));\n arrayRects.push(new SelectRect(1943, 1972));\n arrayRects.push(new SelectRect(1973, 2003));\n\n\n wars.forEach(function (war) {\n var max = 0;\n var min = 9999;\n\n war.participants.forEach(function (part) {\n\n if (getDecimalDate(part.endDate) > max) max = getDecimalDate(part.endDate);\n if (getDecimalDate(part.startDate) < min) min = getDecimalDate(part.startDate);\n });\n\n war.starDate = min;\n war.endDate = max;\n\n });\n\n wars.forEach(function (war) {\n var maxi = 1;\n var mini = 99999;\n\n war.participants.forEach(function (parti) {\n\n if (getNormalDate(parti.endDate) > maxi) maxi = getNormalDate(parti.endDate);\n if (getNormalDate(parti.startDate) < mini) mini = getNormalDate(parti.startDate);\n });\n\n war.WNstartDate = mini;\n war.WNendDate = maxi;\n\n });\n\n\n\n wars.forEach(function (war) {\n war.computeDeaths();\n\n });\n\n\n}", "updateEnemyOpacityForRangeAndObscurity(transport, targetHex) {\n // console.log('updateEnemyOpacityForRangeAndObscurity', transport);\n let player = this.player;\n let playerSightRange = player.sightRange;\n let currentOpacity = transport.imageGroup.opacity();\n let returnFieldOfViewHexes = this.gameboard.isFieldOfViewBlockedForHex(player.hex, targetHex/**, sortedByDistanceNeighbors**/);\n // console.log('returnFieldOfViewHexes', returnFieldOfViewHexes, player, player.sightRange, this.enemyToPlayerDistance);\n let playerSightBlocked = this.hexService.arrayOfHexesIncludesHex(returnFieldOfViewHexes.blocked, targetHex)\n if (currentOpacity > 0) { // allows for partial obscurity (like fog/eather)\n if (playerSightBlocked) {\n transport.imageGroup.to({opacity: 0});\n } else if (transport.playerDistance > playerSightRange) {\n // } else if (this.enemyToPlayerDistance > playerSightRange) {\n transport.imageGroup.to({opacity: 0});\n }\n } else if (transport.playerDistance <= playerSightRange) {\n // } else if (this.enemyToPlayerDistance <= playerSightRange) {\n if (!playerSightBlocked) {\n transport.imageGroup.to({opacity: 1});\n }\n }\n }", "function addCollision(el){\n var events = Array.prototype.slice.call(document.getElementsByClassName('event'));\n var eventsLength = events.length;\n var elementBottom = pixelToInt(el.style.top) + pixelToInt(el.style.height);\n var elementTop = pixelToInt(el.style.top);\n\n for(var j=0; j < eventsLength; j++){\n var eventBottom = pixelToInt(events[j].style.top) + pixelToInt(events[j].style.height);\n var eventTop = pixelToInt(events[j].style.top);\n\n if ((elementTop >= eventTop && elementTop < eventBottom) ||\n (elementBottom > eventTop && elementBottom <= eventBottom) ||\n (elementTop <= eventTop && elementBottom >= eventBottom) ) {\n if(el.id !== events[j].id) {\n addOverlap(events[j], el);\n }\n }\n }\n }", "function default_artifacts()\n{\n\tlogMessage(\"Artifacts set to default positions\");\t\n\t\n\t//Celeron\n\tvar celeron_x = 13; \n\tvar celeron_y = 13;\n\tvar celeron_recipe = true;\t\n\t\n\t//Xeon\n\tvar xeon_x = 2; \n\tvar xeon_y = 2;\t\n\tvar xeon_recipe = false;\t\n\t\n\t//Ryzen\n\tvar ryzen_x = 3; \n\tvar ryzen_y = 3;\t\n\tvar ryzen_recipe = false;\t\n\t\n\t//Saturn\n\tvar saturn_x = 4; \n\tvar saturn_y = 4;\t\n\tvar saturn_recipe = false;\t\n\t\n\t//Mars\n\tvar mars_x = 5; \n\tvar mars_y = 5;\t\n\tvar mars_recipe = false;\t\n\t\n\t//Jupiter\n\tvar jupiter_x = 6; \n\tvar jupiter_y = 6;\t\n\tvar jupiter_recipe = false;\t\n\t\n\t//Pluto\n\tvar pluto_x = 7; \n\tvar pluto_y = 7;\t\n\tvar pluto_recipe = false;\t\n\n\t//Asteroid\n\tvar ax = 11;\n\tvar ay = 11; \n\n\t//Space Station\n\tvar sx = 13;\n\tvar sy = 11;\n\t\n\tgame_map.map[celeron_x][celeron_y].obj = new pentium(\"Celeron\", false, celeron_recipe);\n\tgame_map.map[celeron_x][celeron_y].change_type(PENTIUM);\n\t\n\tgame_map.map[xeon_x][xeon_y].obj = new pentium(\"Xeon\", false, xeon_recipe);\n\tgame_map.map[xeon_x][xeon_y].change_type(PENTIUM);\n\t\n\tgame_map.map[ryzen_x][ryzen_y].obj = new pentium(\"Ryzen\", false, ryzen_recipe);\n\tgame_map.map[ryzen_x][ryzen_y].change_type(PENTIUM);\n\t\n\tgame_map.map[saturn_x][saturn_y].obj = new pentium(\"Saturn\", false, saturn_recipe);\n\tgame_map.map[saturn_x][saturn_y].change_type(PENTIUM);\n\t\n\tgame_map.map[mars_x][mars_y].obj = new pentium(\"Mars\", false, mars_recipe);\n\tgame_map.map[mars_x][mars_y].change_type(PENTIUM);\n\t\n\tgame_map.map[jupiter_x][jupiter_y].obj = new pentium(\"Jupiter\", false, jupiter_recipe);\n\tgame_map.map[jupiter_x][jupiter_y].change_type(PENTIUM);\n\t\n\tgame_map.map[pluto_x][pluto_y].obj = new pentium(\"Pluto\", false, pluto_recipe);\n\tgame_map.map[pluto_x][pluto_y].change_type(PENTIUM);\n\t\t\n\tgame_map.map[ax][ay].obj = new asteroid(20);\n\tgame_map.map[ax][ay].change_type(ASTEROID);\n\t\n\tgame_map.map[sx][sy].obj = new space_station(0);\n\tgame_map.map[sx][sy].change_type(SPACE_STATION);\n}", "calculate() {\n let mvecs = [];\n super.setPkt(Status.GRAB,\"SOLID\");\n let i = 0;\n if(super.getResp()[0]){\n let data = super.getResp()[0];\n data.forEach(element => {\n if(PVector.getDistance(this.pos,element.pos) < 64){\n let mtv = Polygon.isColliding(this.hitbox,element.hitbox);\n if(mtv){\n mvecs.push(element.hitbox);\n }\n }\n });\n }\n if(mvecs.length > 0){;\n this.rot *= -1;\n this.movement.scale(-1);\n this.applyMovement();\n this.applyRotation();\n this.movement.scale(-1);\n this.rot *= -1;\n }\n super.clearResp();\n }", "_addCollision(mouse_x, mouse_y, range, particles) {\n\n // Check for collisions\n for (let i = 0; i < particles.length; i++) {\n const cur = particles[i];\n if (this === cur)\n continue;\n const dist = distance(this.x, this.y, cur.x, cur.y);\n if (dist - (this.radius + cur.radius) < 0) {\n resolveCollision(this, cur);\n }\n }\n\n // Check boundaries\n if (this.x - this.radius <= 0 || this.radius + this.x >= this.canvas.width) {\n this.dx = -this.dx;\n }\n if (this.y - this.radius <= 0 || this.radius + this.y >= this.canvas.height) {\n this.dy = -this.dy;\n }\n\n // Add mouse interactivity\n if (distance(mouse_x, mouse_y, this.x, this.y) < range && this.opacity < 0.8) {\n this.opacity += 0.03;\n } else {\n this.opacity -= 0.03;\n this.opacity = Math.max(0, this.opacity);\n }\n\n this.x += this.dx;\n this.y += this.dy;\n }", "function Determine_if_Overlap(ele1, ele2)\n{\n\trect1 = ele1.getBoundingClientRect();\n\trect2 = ele2.getBoundingClientRect();\n\t\n\tmin_dist_req = rect1.width/2;// in this case, I define overlap is when centers are within 50% of the image width\n\t\n\tx1_center = rect1.x + rect1.width/2;\n\ty1_center = rect1.y + rect1.width/2;\n\t\n\tx2_center = rect2.x + rect2.width/2;\n\ty2_center = rect2.y + rect2.width/2;\n\t\n\t//Find cartesian distance\n\tdist_center_to_center = Math.pow(Math.pow((x1_center-x2_center), 2)+Math.pow((y1_center-y2_center), 2) , 0.5);\n\t\n\t//console.log(\"Dist at:\" +dist_center_to_center);\n\t//console.log(\"Min at:\" +min_dist_req);\n\n\tif (dist_center_to_center <= min_dist_req)\n\t{\n\t\t//console.log(\"true!!!\");\n\t\treturn true;\n\t}else\n\t{\n\t\treturn false;\n\t}\n\t\n}", "function checkForDuplicates()\r\n\t{\r\n\tfor (i=0; i < activeClippings.length; i++)\r\n\t\t{\r\n\t\tif (newClipping == activeClippings[i].id) {i = allClippings.length; duplicate = true;}\r\n\t\t}\r\n\t}", "function interAdgroupNegativeFencer() {\n \n Logger.log(\"QueryOverlap from \" + DATE_RANGE + \" and clicks >= \" + MIN_CLICKS_SOURCE_KEYWORD);\n AG_CHECK_LABEL = getWeekLabel();\n \n createLabel(AG_CHECK_LABEL);\n \n /*var adGroupIterator = getAdGroupIterator();\n while(adGroupIterator.totalNumEntities === 0) {\n if(MIN_CLICKS_SOURCE_KEYWORD === 2) continue;\n if(MIN_CLICKS_SOURCE_KEYWORD > 0) MIN_CLICKS_SOURCE_KEYWORD--;\n adGroupIterator = getAdGroupIterator();\n }*/\n\n var adGroupIterator = AdsApp.adGroups()\n .withCondition('Clicks >= ' + MIN_CLICKS_SOURCE_KEYWORD)\n .withCondition('CampaignName CONTAINS_IGNORE_CASE \\\"' + CAMPAIGN_INCLUDE_STRING_I + '\\\"')\n .withCondition('CampaignName DOES_NOT_CONTAIN \\\"' + CAMPAIGN_EXCLUDE_STRING_I + '\\\"').withCondition('CampaignName DOES_NOT_CONTAIN \\\"' + CAMPAIGN_EXCLUDE_STRING_II + '\\\"')\n .withCondition('CampaignName DOES_NOT_CONTAIN \\\"' + DSA_CAMPAIGN_STRING + '\\\"').withCondition('CampaignName DOES_NOT_CONTAIN \\\"' + SHO_CAMPAIGN_STRING + '\\\"');\n \n // Ignore label filter if needed\n if(typeof IGNORE_WEEK_LABELS !== \"undefined\" && IGNORE_WEEK_LABELS === 0) adGroupIterator = adGroupIterator.withCondition('LabelNames CONTAINS_NONE [\"' + AG_CHECK_LABEL + '\"]');\n adGroupIterator = adGroupIterator.forDateRange(DATE_RANGE).orderBy(\"Cost DESC\").get();\n \n\n while (adGroupIterator.hasNext()) {\n var adGroup = adGroupIterator.next();\n var adGroupName = adGroup.getName();\n var campaignName = adGroup.getCampaign().getName();\n\n // 1. get above MaxClick cases first to prevent duplication\n // var relatedQueries_aboveMaxClicks = getRelatedQueries(adGroupName, campaignName, maxClicks);\n \n var relatedQueries = getRelatedQueries(adGroupName, campaignName);\n\n for(var i=0; i < relatedQueries.length; i++) var queryOverlap = getQueryOverlap(relatedQueries[i]);\n setCheckLabelToAdGroup(adGroup);\n \n // Limit number of adgroup iterations by execution time\n var minutesRemaining = AdWordsApp.getExecutionInfo().getRemainingTime()/60;\n if (minutesRemaining < 5) {Logger.log(\"Execution time past twentyfive minutes. Stopping execution...\"); break;}\n \n } // END Adgroup While Loop \n\n Logger.log(\"\\n******\\nFinished collecting overlaps for adGroups without currentWeek_CheckLabel. Sending email if observations were found. If you wish to see all results, set the variable as follows: var IGNORE_WEEK_LABELS = 0. Have a nice Ads day!\\n******\");\n\n impactSummary = addSumRowToSummary(impactSummary);\n skipped_MaxClick_Summary = addSumRowToSummary(skipped_MaxClick_Summary);\n skipped_Generic_Summary = addSumRowToSummary(skipped_Generic_Summary);\n \n // if(DEBUG_MODE === 1 && SET_NEGATIVES === 1) Logger.log(\"entityIdLookupObject : \" + JSON.stringify(entityIdLookupObject));\n\n if(impactSummary.length > 2 || skipped_MaxClick_Summary.length > 2 || skipped_Generic_Summary.length > 2) {\n\n // Send Email Notification\n sendNotificationEmail(impactSummary,entityIdLookupObject, skipped_MaxClick_Summary, skipped_Generic_Summary);\n removeOldAndUsedWeekLabels();\n\n // Print Data to Sheet\n /*if(SET_NEGATIVES === 1) printToSheet(impactSummary, \"1. CREATED\");\n if(SET_NEGATIVES === 0) printToSheet(impactSummary, \"2. PREVIEW\");\n printToSheet(skipped_MaxClick_Summary, \"3. Skipped_MaxClicks\");\n printToSheet(skipped_Generic_Summary, \"4. Skipped_TooGeneric\");*/\n }\n}", "function overlap(actor1,actor2){\n return actor1.pos.x+actor1.size.x > actor2.pos.x &&\n actor1.pos.x < actor2.pos.x + actor2.size.x &&\n actor1.pos.y + actor1.size.y > actor2.pos.y &&\n actor1.pos.y<actor2.pos.y + actor2.size.y;\n }", "intersect(pipes) {\n for (var pipe of pipes) {\n if (this.pos.x + this.r > pipe.pos && this.pos.x - this.r < pipe.pos + pipe.pipeWidth) {\n if (this.pos.y - this.r < pipe.pipeHeight || this.pos.y + this.r > pipe.pipeHeight + pipe.gap) {\n this.die();\n }\n }\n }\n }", "buildAllAnchor() {\n let x = self.baseImage.getX(), y = self.baseImage.getY();\n let width = self.baseImage.getWidth(), height = self.baseImage.getHeight();\n let coor = [x,y, x+width,y, x,y+height, x+width,y+height];\n for (let i=0; i<coor.length; i+=2){\n self.buildAnchor(coor[i], coor[i+1], i/2);\n }\n self.group.setDraggable(true);\n self.group.add(self.anchorGroup);\n self.layer.draw()\n\n }", "_checkOverlaps(tag, f) {\n every(tag, (obj) => {\n if (this === obj) {\n return;\n }\n if (overlapping[obj._id]) {\n return;\n }\n if (this.isOverlapped(obj)) {\n f(obj);\n overlapping[obj._id] = obj;\n }\n });\n\n for (const id in overlapping) {\n const obj = overlapping[id];\n if (!this.isOverlapped(obj)) {\n delete overlapping[id];\n }\n }\n }", "resolveIntersection(that) {\n\t\tif(this.intersects(that)) {\n\t\t\tvar leastProj = new Vector2(this.pos.x + this.size.x - that.pos.x, this.pos.y + this.size.y - that.pos.y);\n\t\t\tvar greatProj = new Vector2(that.pos.x + that.size.x - this.pos.x, that.pos.y + that.size.y - this.pos.y);\n\t\t\tvar mxVal = Math.max(Math.max(Math.max(leastProj.x, leastProj.y), greatProj.x), greatProj.y);\n\t\t\tif(leastProj.x < 0) leastProj.x = mxVal + 1;\n\t\t\tif(leastProj.y < 0) leastProj.y = mxVal + 1;\n\t\t\tif(greatProj.x < 0) greatProj.x = mxVal + 1;\n\t\t\tif(greatProj.y < 0) greatProj.y = mxVal + 1;\n\t\t\tvar mnVal = Math.min(Math.min(Math.min(leastProj.x, leastProj.y), greatProj.x), greatProj.y);\n\t\t\tif(mnVal == mxVal + 1) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(leastProj.x == mnVal) {\n\t\t\t\tthis.pos.x -= leastProj.x;\n\t\t\t}\n\t\t\telse if(leastProj.y == mnVal) {\n\t\t\t\tthis.pos.y -= leastProj.y;\n\t\t\t}\n\t\t\telse if(greatProj.x == mnVal) {\n\t\t\t\tthis.pos.x += greatProj.x;\n\t\t\t}\n\t\t\telse if(greatProj.y == mnVal){\n\t\t\t\tthis.pos.y += greatProj.y;\n\t\t\t}\n\t\t}\n\t}", "function overlap(){ \n if(count === 0){\n console.log(\"Ok\");\n clearInterval(x);\n fall();\n }\n var fRect = floor.getBoundingClientRect();\n var cRect = cart.getBoundingClientRect();\n for(var i = 0; i < papers.length; i++){\n var p = document.querySelector(papers[i]);\n var pRect = p.getBoundingClientRect();\n var pcOffset = cRect.top - pRect.top;\n\tvar pcOffset2 = cRect.left - pRect.left;\n var pfOffset = pRect.top - fRect.top;\n if(pcOffset >= 0 && pcOffset <= 100){\n if(pcOffset2 >= -100 && pcOffset2 <= 100){\n p.style.display = \"none\";\n score += 1; \n count--;\n }\n }\n else if(pfOffset >= -200 && pfOffset <= -1){\n p.style.display = \"none\";\n count--;\n }\n }\n}", "function resolveCollisions(container) {\n\t var svg = container.find('svg');\n\t var bounds = [];\n\n\t var iterations = 0, mainBounds, changed, temp;\n\t do {\n\t temp = resolveCollisionsInSelection(svg.find('g.main.pielabel'));\n\t mainBounds = temp[0];\n\t changed = temp[1];\n\t iterations++;\n\t } while (changed && iterations < 10);\n\t bounds.push(mainBounds);\n\n\t var groups = {};\n\t svg.find('g.sub.pielabel').each(function(){\n\t groups[$(this).attr('group')] = true;\n\t });\n\t var okg = Object.keys(groups);\n\t var i;\n\t var groupBounds;\n\t for (i = 0; i < okg.length; i++) {\n\t var group = okg[i];\n\t var selection = svg.find('g.sub.pielabel[group=\"' + group + '\"]');\n\t iterations = 0;\n\t do {\n\t temp = resolveCollisionsInSelection(selection);\n\t groupBounds = temp[0];\n\t changed = temp[1];\n\t iterations++;\n\t } while (changed && iterations < 10);\n\t bounds.push(groupBounds);\n\t }\n\t return findExtremeBounds(bounds);\n\t }", "function checkAvoidAreasIntersectThemselves() {\n\t\t\t//code adapted from http://lists.osgeo.org/pipermail/openlayers-users/2012-March/024285.html\n\t\t\tvar layer = this.theMap.getLayersByName(this.AVOID)[0];\n\t\t\tvar intersect = false;\n\t\t\tfor (var ftNum = 0; ftNum < layer.features.length; ftNum++) {\n\t\t\t\tvar fauxpoint = [];\n\t\t\t\tvar line = [];\n\t\t\t\tvar led = layer.features[ftNum];\n\n\t\t\t\tvar strng = led.geometry.toString();\n\t\t\t\tvar coord = strng.split(',');\n\t\t\t\t// remove the 'Polygon((' from the 1st coord\n\t\t\t\tcoord[0] = coord[0].substr(9);\n\t\t\t\t// Remove the '))' from the last coord\n\t\t\t\tcoord[coord.length - 1] = coord[coord.length - 1].substr(0, coord[coord.length - 1].length - 2);\n\n\t\t\t\t//convert to lines\n\t\t\t\tfor ( i = 0; i < coord.length; i++) {\n\t\t\t\t\tvar lonlat = coord[i].split(' ');\n\t\t\t\t\tfauxpoint.push(new OpenLayers.Geometry.Point(lonlat[0], lonlat[1]));\n\t\t\t\t\tif (i > 0) {\n\t\t\t\t\t\t// create an array with the 2 last points\n\t\t\t\t\t\tvar point = [fauxpoint[i - 1], fauxpoint[i]];\n\t\t\t\t\t\t//create the line\n\t\t\t\t\t\tline.push(new OpenLayers.Geometry.LineString(point));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Check every line against every line\n\t\t\t\tfor (var i = 1; i < line.length; i++) {\n\t\t\t\t\tfor (var j = 1; j < line.length; j++) {\n\t\t\t\t\t\t// get points of the I line in an array\n\t\t\t\t\t\tvar vi = line[i].getVertices();\n\t\t\t\t\t\t// get points of the J line in an array\n\t\t\t\t\t\tvar vj = line[j].getVertices();\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * the lines must be differents and not adjacents.\n\t\t\t\t\t\t * The end or start point of an adjacent line will be intersect,\n\t\t\t\t\t\t * and adjacent lines never intersect in other point than the ends.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tif (i != j && vi[1].toString() != vj[0].toString() && vi[0].toString() != vj[1].toString()) {\n\t\t\t\t\t\t\t// the intersect check\n\t\t\t\t\t\t\tif (line[i].intersects(line[j])) {\n\t\t\t\t\t\t\t\tintersect = true;\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}\n\t\t\t}\n\t\t\treturn intersect;\n\t\t}", "overlapOnCreation(bubble) {\n let overlapped = false;\n for(let i = 0; i < this.allThingsOnBoard().length; i++) {\n if (this.allThingsOnBoard()[i].iscollidedWith(bubble)){\n overlapped = true;\n }\n }\n return overlapped;\n }", "crossingShips(arr, ship) {\r\n arr.map(e => {\r\n if (this.shipsCoordinates.indexOf(e) != -1) {\r\n this.crosses = true;\r\n }\r\n })\r\n if (!this.crosses) {\r\n ship.location = ship.location.concat(arr);\r\n this.shipsCoordinates = this.shipsCoordinates.concat(arr);\r\n arr.length = 0;\r\n } else {\r\n arr.length = 0;\r\n }\r\n }", "function checkOverlap() {\n let d = dist(circle1.x, circle1.y, circle2.x, circle2.y);\n if (d < circle1.size/3 + circle2.size/3) {\n state = `love`;\n }\n }", "collidesWith(bird) {\n //this function returns true if the the rectangles overlap\n const _overlap = (rect1, rect2) => {\n //check that they don't overlap in the x axis\n if (rect1.left > rect2.right || rect1.right < rect2.left) {\n return false;\n }\n //check that they don't overlap in the y axis\n if (rect1.top > rect2.bottom || rect1.bottom < rect2.top) {\n return false;\n }\n return true;\n };\n let collision = false;\n this.eachPipe((pipe) => {\n if ( \n //check if the bird is overlapping (colliding) with either pipe\n _overlap(pipe.topPipe, bird) || \n _overlap(pipe.bottomPipe, bird)\n ) { collision = true; }\n });\n return collision;\n }", "manageDuplicates(){\n\n // Manage duplicate IDs from swiper loop\n this.duplicates = this.sliderPastilles.container[0].querySelectorAll('.pastille--image.swiper-slide');\n\n for ( let i = 0; i < this.duplicates.length; i++ ){\n\n // Vars\n let mask = this.duplicates[i].querySelector('svg > defs > mask');\n let image = this.duplicates[i].querySelector('svg > image');\n\n // Update values\n let id = mask.getAttribute('id');\n let newId = id+i;\n\n mask.setAttribute('id', newId);\n image.setAttribute('mask','url(#'+newId+')');\n }\n }", "function checkBirdCollision(){\n for(let i = 0; i<birds.length;i++){\n if (ufoX < birds[i].x + birdWidth&&\n ufoX + ufoWidth > birds[i].x &&\n ufoY < birds[i].y + birdHeight &&\n ufoY+ ufoHeight > birds[i].y) {\n ctx.drawImage(explosion,ufoX, ufoY, 100, 100);\n duckAudio.play()\n duckAudio.volume= 0.7\n \n takeLive()\n birds[i].x = -50\n\n \n }\n \n \n }\n }", "static _checkRangesForContainment(rangeA, rangeB, collisionInfo, flipResultPositions)\n {\n if (flipResultPositions)\n {\n if (rangeA.max < rangeB.max || rangeA.min > rangeB.min) collisionInfo.shapeAContained = false;\t\t\t\t\n if (rangeB.max < rangeA.max || rangeB.min > rangeA.min) collisionInfo.shapeBContained = false;\t\n }\n else\n {\n if (rangeA.max > rangeB.max || rangeA.min < rangeB.min) collisionInfo.shapeAContained = false;\n if (rangeB.max > rangeA.max || rangeB.min < rangeA.min) collisionInfo.shapeBContained = false;\n }\n }", "pathFindSheet(list, pad) {\n const c = this.LIBRARY_TILE\n const yMax = c.mask.height;\n const tmp_list = []; // new list\n let cache = {};\n let antiFreeze = 500000;\n\n for (let I = 0, L = list.length; I < L; I++) {\n const cage = list[I];\n let x = +pad, y = +pad;\n let w = cage.width, h = cage.height;\n cage.position.set(x,y);\n cage.getBounds();\n // scan, no collid with alrealy added cage\n for (let i = 0, l = tmp_list.length, contact = false; i < l; i++) {\n const temp = tmp_list[i];\n if($app.hitCheck(cage,temp)){\n i = -1;\n y+=(h+pad);\n // si collision, jump pixel line X++\n if(y+h>yMax){ x+=pad, y = +pad }\n else{ y+=pad };\n cage.position.set(x,y);\n cage.getBounds();\n };\n if(!antiFreeze--){ console.error(\"error:antiFreeze\"); break };\n };\n // no break hitCheck, we can add\n tmp_list.push(cage);\n cache[cage.dataObj._textureName] = new PIXI.Point(x,y); //REGISTER\n cage._boundsRect.pad(pad+2,pad+1);\n };\n return cache;\n }", "function overlaps (xCord, yCord, size) {\n for (i = 0; i < size; i++) {\n for (j = 0; j < size; j++) {\n if (!currentMap[yCord + i][xCord + j] == 0) {\n return true\n }\n }\n }\n return false\n}", "function doesOverlap(e1, e2) {\n if (e1.start > e2.start) {\n [e1, e2] = [e2, e1];\n }\n if (e1.end <= e2.start) {\n return false;\n }\n return true;\n}", "addFromLayers(){\n let _from = this.props.fromVersion.key;\n //add the sources\n this.addSource({id: window.SRC_FROM_POLYGONS, source: {type: \"vector\", tiles: [ window.TILES_PREFIX + \"wdpa_\" + _from + \"_polygons\" + window.TILES_SUFFIX]}});\n this.addSource({id: window.SRC_FROM_POINTS, source: {type: \"vector\", tiles: [ window.TILES_PREFIX + \"wdpa_\" + _from + \"_points\" + window.TILES_SUFFIX]}});\n //add the layers\n this.addLayer({id: window.LYR_FROM_DELETED_POLYGON, sourceId: window.SRC_FROM_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"fill-color\": \"rgba(255,0,0, 0.2)\", \"fill-outline-color\": \"rgba(255,0,0,0.5)\"}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_POLYGON});\n this.addLayer({id: window.LYR_FROM_DELETED_POINT, sourceId: window.SRC_FROM_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _from + \"_points\", layout: {visibility: \"visible\"}, paint: {\"circle-radius\": CIRCLE_RADIUS_STOPS, \"circle-color\": \"rgb(255,0,0)\", \"circle-opacity\": 0.6}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_POLYGON});\n //geometry change in protected areas layers - from\n this.addLayer({id: window.LYR_FROM_GEOMETRY_POINT_TO_POLYGON, sourceId: window.SRC_FROM_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _from + \"_points\", layout: {visibility: \"visible\"}, paint: {\"circle-radius\": CIRCLE_RADIUS_STOPS, \"circle-color\": \"rgb(255,0,0)\", \"circle-opacity\": 0.5}, filter:INITIAL_FILTER, beforeId: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON});\n this.addLayer({id: window.LYR_FROM_GEOMETRY_POINT_COUNT_CHANGED_LINE, sourceId: window.SRC_FROM_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"line-color\": \"rgb(255,0,0)\", \"line-width\": 1, \"line-opacity\": 0.5, \"line-dasharray\": [3,3]}, filter:INITIAL_FILTER, beforeId: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON});\n this.addLayer({id: window.LYR_FROM_GEOMETRY_SHIFTED_LINE, sourceId: window.SRC_FROM_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"line-color\": \"rgb(255,0,0)\", \"line-width\": 1, \"line-opacity\": 0.5, \"line-dasharray\": [3,3]}, filter:INITIAL_FILTER, beforeId: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON});\n //selection layers\n this.addLayer({id: window.LYR_FROM_SELECTED_POLYGON, sourceId: window.SRC_FROM_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_SELECTED_POLYGON, filter:INITIAL_FILTER, beforeId: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_FROM_SELECTED_LINE, sourceId: window.SRC_FROM_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_SELECTED_LINE, filter:INITIAL_FILTER, beforeId: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_FROM_SELECTED_POINT, sourceId: window.SRC_FROM_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _from + \"_points\", layout: {visibility: \"visible\"}, paint: P_SELECTED_POINT, filter:INITIAL_FILTER, beforeId: window.LYR_TO_SELECTED_POLYGON});\n }", "checkPlayersOverlapping() {\n // if no power-up is on the screen, abort\n if (this.powerup == null)\n return;\n\n for (let player of this.players)\n this.game.physics.arcade.overlap(player, this.powerup, this._take, null, this)\n }", "function onDocumentMouseDown(event) {\n event.preventDefault();\n if (selectedObject) {\n selectedObject = null;\n }\n//Add intersects\n var intersects = getIntersects(event.layerX, event.layerY);\n if (intersects.length > 0) {\n var res = intersects.filter(function (res) {\n return res && res.object;\n })[0];\n if (res && res.object) {\n selectedObject = res.object;\n // 3FADB874-7BAA-4C87-AB4A-CEE529286E76\n console.log(selectedObject);\n//Click object and halo appear\n if (selectedObject.uuid ==\n mesh.uuid) {\n if (!isRemove) {\n isRemove = !isRemove;\n glowGroup1.remove(glowSphere1);\n } else {\n isRemove = !isRemove;\n glowGroup1.add(glowSphere1);\n }\n }\n\n if (selectedObject.uuid ==\n mesh6.uuid) {\n $(\".ui-dialog\").show();\n $(\".calssImg\").attr(\"src\", \"./images/0.jpg\");//load pictures and define absolute path\n }\n\n if (selectedObject.uuid ==\n mesh11.uuid) {\n $(\".ui-dialog\").show();\n $(\".calssImg\").attr(\"src\", \"./images/1.jpg\");\n }\n\n if (selectedObject.uuid ==\n mesh13.uuid) {\n $(\".ui-dialog\").show();\n $(\".calssImg\").attr(\"src\", \"./images/2.jpg\");\n }\n\n if (selectedObject.uuid ==\n mesh14.uuid) {\n $(\".ui-dialog\").show();\n $(\".calssImg\").attr(\"src\", \"./images/3.jpg\");\n }\n\n if (selectedObject.uuid ==\n mesh10.uuid) {\n $(\".ui-dialog\").show();\n $(\".calssImg\").attr(\"src\", \"./images/4.jpg\");\n }\n if (selectedObject.uuid ==\n mesh5.uuid) {\n $(\".ui-dialog\").show();\n $(\".calssImg\").attr(\"src\", \"./images/5.jpg\");\n }\n if (selectedObject.uuid ==\n mesh6.uuid) {\n $(\".ui-dialog\").show();\n $(\".calssImg\").attr(\"src\", \"./images/6.jpg\");\n }\n\n if (selectedObject.uuid ==\n mesh15.uuid) {\n $(\".ui-dialog\").show();\n $(\".calssImg\").attr(\"src\", \"./images/7.jpg\");\n }\n // selectedObject.material.color.set(\"#f00\");\n }\n }\n}//Define range of mouse intersects", "addToLayers(){\n try {\n let _to = this.props.toVersion.key;\n //add the sources\n let attribution = \"IUCN and UNEP-WCMC (\" + this.props.toVersion.year + \"), The World Database on Protected Areas (\" + this.props.toVersion.year + \") \" + this.props.toVersion.title + \", Cambridge, UK: UNEP-WCMC. Available at: <a href='http://www.protectedplanet.net'>www.protectedplanet.net</a>\";\n this.addSource({id: window.SRC_TO_POLYGONS, source: {type: \"vector\", attribution: attribution, tiles: [ window.TILES_PREFIX + \"wdpa_\" + _to + \"_polygons\" + window.TILES_SUFFIX]}});\n this.addSource({id: window.SRC_TO_POINTS, source: {type: \"vector\", tiles: [ window.TILES_PREFIX + \"wdpa_\" + _to + \"_points\" + window.TILES_SUFFIX]}});\n //no change protected areas layers\n this.addLayer({id: window.LYR_TO_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"fill-color\": \"rgba(99,148,69,0.2)\", \"fill-outline-color\": \"rgba(99,148,69,0.3)\"}, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_POINT, sourceId: window.SRC_TO_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _to + \"_points\", layout: {visibility: \"visible\"}, paint: {\"circle-radius\": CIRCLE_RADIUS_STOPS, \"circle-color\": \"rgb(99,148,69)\", \"circle-opacity\": 0.6}, beforeID: window.LYR_TO_SELECTED_POLYGON});\n //selection layers\n this.addLayer({id: window.LYR_TO_SELECTED_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_SELECTED_POLYGON, filter:INITIAL_FILTER});\n this.addLayer({id: window.LYR_TO_SELECTED_LINE, sourceId: window.SRC_TO_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_SELECTED_LINE, filter:INITIAL_FILTER});\n this.addLayer({id: window.LYR_TO_SELECTED_POINT, sourceId: window.SRC_TO_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _to + \"_points\", layout: {visibility: \"visible\"}, paint: P_SELECTED_POINT, filter:INITIAL_FILTER});\n //add the change layers if needed\n if (this.props.fromVersion.id !== this.props.toVersion.id) this.addToChangeLayers();\n } catch (e) {\n console.log(e);\n }\n }", "static addToDivvy(w, lo, hi) {\n for (let i = lo; i <= hi; i++) {\n if (!this.divvy.has(i))\n this.divvy.set(i, new Set());\n if (DEBUG_MODE && this.divvy.get(i).has(w))\n throw new Error(\"programmer error: addtodivvy adding a dup\");\n this.divvy.get(i).add(w); // on set representing index i, add w.\n }\n }", "disableIsMerged() {\n this\n .tiles\n .forEach(tile => {\n tile.isMerged = false;\n });\n }", "function have_collided(object1,object2){\n return !(\n ((object1.y + object1.height) < (object2.y)) || //\n (object1.y > (object2.y + object2.height)) ||\n ((object1.x + object1.width) < object2.x) ||\n (object1.x > (object2.x + object2.width))\n );\n }", "function _doOverlay(src, osrc, dest, ox, oy, magickbat) {\n const combineCmd = magickbat + ' %s %s -geometry +%d+%d -composite %s',\n cmd = util.format(combineCmd, src, osrc, ox, oy, dest);\n console.log('----> running _doOverlay: ' + cmd + exec(cmd, function (error /*, stdout, stderr*/) {\n if (error) {\n throw('overlayImage: error combining image: error' + error);\n }\n }));\n return 0;\n}", "function twoArrayCollisionDetect(objArr1, objArr2){\n this.objArr1 = objArr1;\n this.objArr2 = objArr2;\n this.objArr2.forEach(function(element){\n var dx = this.objArr1[0].x - (element.x + element.radius);\n var dy = this.objArr1[0].y - (element.y + element.radius);\n //var dx = this.objArr1[0].x - (element.x/* + element.radius*/);\n //var dy = this.objArr1[0].y - (element.y/* + element.radius*/);\n //square root is extremely expensive, so it would be better to compare the squares instead\n var distance = /*Math.sqrt*/(dx * dx + dy * dy);\n var objRad = objArr1[0].radius + element.radius;\n var objRadSquared = objRad * objRad;\n if (distance < objRadSquared && element.alive) {\n console.log(\"hit object\");\n\t\t\tif(element.gameObjectType == ALIEN_SQUID) {\n\t\t\t\tparty(element.x + element.radius, element.y + element.radius, \n\t\t\t\t\tPARTICLE_SQUIDDIE_EXPLOSION);\n }\n \n else if(element.gameObjectType == CREW) {\n //playerHealth -= MAX_HEALTH/10;\n takeDamage(MAX_HEALTH/10);\n remainingCrew--;\n party(element.x + element.radius, element.y + element.radius, PARTICLE_CREW_DEATH_2, 0, 0, 0, 8);\n }\n\t\t\t\n\t\t\telse {\n\t\t\t\tparty(element.x + element.radius, element.y + element.radius, PARTICLE_EXPLOSION);\n\t\t\t}\n\t\t\t\n if (!objArr1[0].solid){ \n objArr1[0].alive= false;\n }\n if (!element.solid){\n element.alive = false;\n }\n }\n });\n}", "function objectsOverlap(obj1, obj2){\n let obj1_b = obj1['boundingBox'];\n let obj2_b = obj2['boundingBox'];\n\n if(!obj1_b || !obj2_b)//one of the two objs has no bounding box\n return 0;\n\n //first consider the case in which the overlap is not possible, so the result is 0\n if(obj1_b['br']['x'] < obj2_b['bl']['x'] || obj1_b['bl']['x'] > obj2_b['br']['x'])//considering x\n // when the gFaceRect finished before the start of azure one (or the opposite)\n return 0;\n\n else if(obj1_b['bl']['y'] < obj2_b['tl']['y'] || obj1_b['tl']['y'] > obj2_b['bl']['y'])//considering y\n // when the gFaceRect finished before the start of azure one (or the opposite)\n return 0;\n\n else{ //there is an overlap\n\n // remind that\n // - x goes from 0 -> N (left -> right)\n // - y goes from 0 -> N (top -> bottom)\n let xc1 = Math.max(obj1_b['bl']['x'], obj2_b['bl']['x']);\n let xc2 = Math.min(obj1_b['br']['x'], obj2_b['br']['x']);\n let yc1 = Math.max(obj1_b['bl']['y'], obj2_b['bl']['y']);\n let yc2 = Math.min(obj1_b['tl']['y'], obj2_b['tl']['y']);\n let xg1 = obj1_b['bl']['x'];\n let xg2 = obj1_b['br']['x'];\n let yg1 = obj1_b['bl']['y'];\n let yg2 = obj1_b['tl']['y'];\n\n let areaO = (xc2-xc1) * (yc2 - yc1); //area covered by the overlapping\n let areaI = (xg2-xg1) * (yg2 - yg1); //area covered by the first bounding box\n\n return areaO/areaI;\n }\n}", "function checkAreas() {\n\t\tfor (var UAYgMqRNl = 0; UAYgMqRNl < UANKaqLvcZ.length; UAYgMqRNl++){\n\t\t\t// get the pixels in a note area from the blended image\n\t\t\tvar blendedData = blendContext.getImageData( UANKaqLvcZ[UAYgMqRNl].UAyjdJxcO, UANKaqLvcZ[UAYgMqRNl].UAdDfXoBtH, UANKaqLvcZ[UAYgMqRNl].UAJmGBAbF, UANKaqLvcZ[UAYgMqRNl].UAOcFeVqOh );\n\t\t\t// calculate the average lightness of the blended data\n\t\t\tvar UADRVTPQV = 0;\n\t\t\tvar UAmlCsOix = 0;\n\t\t\tvar UADkkSB = blendedData.data.length * 0.25;\n\t\t\twhile (UADRVTPQV < UADkkSB) {\n\t\t\t\tUAmlCsOix += (blendedData.data[UADRVTPQV*4] + blendedData.data[UADRVTPQV*4+1] + blendedData.data[UADRVTPQV*4+2]);\n\t\t\t\t++UADRVTPQV;\n\t\t\t}\n\t\t\t// calculate an average between of the color values of the note area [0-255]\n\t\t\tvar average = Math.round(UAmlCsOix / (3 * UADkkSB));\n\t\t\tif (average > 50){ // more than 20% movement detected\n\t\t\t\tif (UANKaqLvcZ[UAYgMqRNl].name == 'down' ){\n\t\t\t\t\tvar UAKBYsh = andizxc(document).scrollTop();\n\t\t\t\t\twindow.scroll( UAKBYsh, UAKBYsh+100) ; \n\t\t\t\t}\n\t\t\t\tif (UANKaqLvcZ[UAYgMqRNl].name == 'up' ){\n\t\t\t\t\tvar UAKBYsh = andizxc(document).scrollTop();\n\t\t\t\t\twindow.scroll( UAKBYsh, UAKBYsh-100) ; \n\t\t\t\t}\n\t\t\t\tif (UANKaqLvcZ[b].name == 'left' ){\n\t\t\t\t\tvar UAKBYsh = UA.UAYfVXIS.length;\n\t\t\t\t\tvar UAPPylhwc = UA.UAUfjEOdaK;\n\t\t\t\t\tif( UA.UAUfjEOdaK >= (UAKBYsh-1) ){\n\t\t\t\t\t\tUA.UAUfjEOdaK = 0;\n\t\t\t\t\t\tUAPPylhwc = -1;\n\t\t\t\t\t}\n\t\t\t\t\tandizxc(UA.UAYfVXIS[UAPPylhwc+1]).focus();\n\t\t\t\t\tUA.UAUfjEOdaK = UAPPylhwc+1;\n\t\t\t\t}\n\t\t\t\tif (UANKaqLvcZ[UAYgMqRNl].name == 'right' ){\n\t\t\t\t\tvar UAKBYsh = UA.UAYfVXIS.length;\n\t\t\t\t\tvar UAPPylhwc = UA.UAUfjEOdaK;\n\t\t\t\t\tif( UA.UAUfjEOdaK <= 0) {\n\t\t\t\t\t\tUA.UAUfjEOdaK = UAKBYsh;\n\t\t\t\t\t\tUAPPylhwc = UAKBYsh;\n\t\t\t\t\t}\n\t\t\t\t\tandizxc(UA.UAYfVXIS[UAPPylhwc-1]).focus();\n\t\t\t\t\tUA.UAUfjEOdaK = UAPPylhwc-1;\n\t\t\t\t}\n\t\t\t\tif (UANKaqLvcZ[UAYgMqRNl].name == 'enter' ){\n\t\t\t\t\t\n\t\t\t\t\tvar curElement = document.activeElement;\n\t\t\t\t\tif(curElement.tagName == 'A'){\n\t\t\t\t\t\tcurElement.click();\n\t\t\t\t\t\twindow.location = curElement.href;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcurElement.click();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tconsole.log( \"Button \" + UANKaqLvcZ[UAYgMqRNl].name + \" triggered.\" ); // do stuff\n\t\t\t\t//messageArea.innerHTML = \"<font size='+4' color='#000'><b>Button \" + UANKaqLvcZ[b].name + \" triggered.</b></font>\";\n\t\t\t}\n\t\t}\n\t}", "function checkOverlap(x,y){\n\tfor(var i = 0; i < holeArray.length; i++){\n\t\tif(x >= holeArray[i].x-100&&x <= holeArray[i].x+100&&y >= holeArray[i].y - 100&& y<= holeArray[i].y+100){\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}", "function doHit(intersection){\n if(intersection){\n \n var playCollision2 = createjs.Sound.play(collision2)\n playCollision2.volume = 0.25\n \n scaleIt(circleCtr, 1.5, 1.5, 0.6, Power4.easeOut)\n \n scaleAlpha(shadowCircleCtr, 1.2, 1.2, 1, 0.2, Power4.easeOut)\n \n scaleRipples(ripples, 1.4, 1.4, 0.6, .015, 0.05, Power4.easeOut)\n \n TweenMax.to(dropZone, .3, {\n opacity: 0,\n scale: 0.5\n })\n \n bolehjalan = true\n \n }\n \n}", "function noMatchFound()\n{\n\tapp.firstCover.disabled = false;\n\tapp.secondCover.disabled = false;\n\n\tapp.firstCover.style.visibility = 'visible';\n\tapp.secondCover.style.visibility = 'visible';\n\n\tfor(var i = 0; i < app.coverImgArr.length; i++){\n\t\taddEvent(app.coverImgArr[i], \"click\", tileClick);\n\t}\n}", "_addTriggerOverlap(otherCollider) {\n const index = this._currentTriggerOverlaps.indexOf(otherCollider);\n if (index == -1) {\n this._currentTriggerOverlaps.push(otherCollider);\n this.gameObject.eventManager.invoke(EventName.Collider_TriggerEnter, otherCollider);\n // TODO: Send event to other collider too\n // NO Cause it'll send twice since it's a trigger\n // Only do if not trigger too\n }\n }", "function collides(a, b) {\n return (\n a.x < b.x + pipeWidth &&\n a.x + a.width > b.x &&\n a.y < b.y + b.height &&\n a.y + a.height > b.y\n );\n}", "keepInBounds() {\n let x = this.sprite.position.x;\n let y = this.sprite.position.y;\n let spriteHalfWidth = this.sprite.width / 2;\n let spriteHalfHeight = this.sprite.height / 2;\n let stageWidth = app.renderer.width;\n let stageHeight = app.renderer.height;\n\n if (x - spriteHalfWidth <= 0)\n this.sprite.position.x = spriteHalfWidth;\n\n if (x + spriteHalfWidth >= stageWidth)\n this.sprite.position.x = stageWidth - spriteHalfWidth;\n\n //Add the same padding that the other bounds have\n if (y + spriteHalfHeight >= stageHeight - 10)\n this.sprite.position.y = stageHeight - spriteHalfHeight - 10;\n\n if (y - spriteHalfHeight <= 0)\n this.sprite.position.y = spriteHalfHeight;\n }", "function placeSelector() {\n\n if (selectBox && !(prevRollOverMeshPos.equals(rollOverMesh.position))) {\n removeSelectBox();\n }\n\n prevRollOverMeshPos = rollOverMesh.position.clone();\n\n var fromScreenCenter = new THREE.Vector2(\n ((renderer.domElement.clientWidth / 2) / renderer.domElement.clientWidth) * 2 - 1,\n -(((renderer.domElement.clientHeight / 2) / renderer.domElement.clientHeight) * 2 - 1)\n );\n\n raycaster.setFromCamera(fromScreenCenter, camera);\n\n var intersects = raycaster.intersectObjects(voxels);\n if (intersects.length > 0) {\n\n var intersect = intersects[0];\n var normal = intersect.face.normal.clone();\n normal.multiplyScalar(voxelSideLength);\n\n rollOverMesh.position.copy(intersect.object.position);\n if (!altOrCtrlKeyPressed) {\n rollOverMesh.position.add(normal);\n }\n\n var rollOverPoint = new WorldAndScenePoint(rollOverMesh.position, false);\n\n if (selectStart.isComplete() && !selectEnd.isComplete()) {\n scene.remove(rollOverMesh);\n if (!selectBox) {\n selectBox = makeBoxAround(selectStart.getPoint(), rollOverPoint, rollOverMaterial);\n scene.add(selectBox);\n }\n }\n else if (!selectStart.isComplete() && selectEnd.isComplete()) {\n scene.remove(rollOverMesh);\n if (!selectBox) {\n selectBox = makeBoxAround(rollOverPoint, selectEnd.getPoint(), rollOverMaterial);\n scene.add(selectBox);\n }\n }\n else {\n scene.add(rollOverMesh);\n }\n\n }\n\n if (selectStart.isComplete() && selectEnd.isComplete()) {\n if (!selectBox) {\n selectBox = makeBoxAround(selectStart.getPoint(), selectEnd.getPoint(), rollOverMaterial);\n scene.add(selectBox);\n }\n }\n\n var worldCoords = new WorldAndScenePoint(rollOverMesh.position, false).world();\n var hoverCoordDiv = document.getElementById('hoverGuideCoordinates');\n hoverCoordDiv.innerHTML = String([worldCoords.x, worldCoords.y, worldCoords.z]);\n \n}", "getReachableComponents(left, top, right, bottom) {\n let ret = [];\n for (let y = top; y < bottom; y++) {\n for (let x = left; x < right; x++) {\n const component = this.componentAtPixel(x, y);\n if (component < 0)\n continue;\n if (ret.indexOf(component) >= 0)\n continue;\n if (!this.componentIsValid(component)) {\n console.log('found invalid component in subrect');\n return [];\n }\n mergeArray(ret, [component]);\n }\n }\n if (ret.length == 0) {\n console.log('no components found');\n return ret;\n }\n console.log('found ' + ret.length + ' components in box');\n // expand with reachable valid components\n let todo = Array.from(ret); // copy array\n let invalid = [];\n while (todo.length > 0) {\n console.log(todo);\n let found = []; // IDs found this iteration\n for (let i = 0; i < todo.length; i++) {\n let reachable = this.findNearbyQuick(todo[i]);\n for (let j = 0; j < reachable.length; j++) {\n const nearcomp = reachable[j];\n if (invalid.indexOf(nearcomp) >= 0)\n continue;\n if (ret.indexOf(nearcomp) < 0 &&\n found.indexOf(nearcomp) < 0) {\n if (!this.componentIsValid(nearcomp)) {\n invalid.push(nearcomp);\n continue;\n }\n found.push(nearcomp);\n }\n }\n }\n ret = ret.concat(found);\n todo = found;\n }\n return ret;\n }", "function addShiploadToOp(event) {\n if (event.target.id == \"\") return;\n \n var shipIdParts = event.target.id.split(\"-\"),\n source = getAircraftSourceById(shipIdParts[1], shipIdParts[0] == \"BAS\"),\n opSource = getAirOpSourceById(shipIdParts[1], shipIdParts[0] == \"BAS\"),\n offset = $(event.target).offset(),\n adding = ((event.clientY - offset.top) < (event.target.offsetHeight / 2)),\n availSquads,\n squadsToAdd;\n\n //Add/remove all ship's aircraft\n for (var i = 0; i < 3; i++) {\n if ($(\"#airopmission\").val() == \"CAP\" && planeTypes[i] != \"F\") continue;\n\n var numDivSelector = \"#\" + source.ElementId + \"-\" + planeTypes[i] + \"-num\",\n numTdSelector = \"#mission\" + planeTypes[i];\n\n if (adding) {\n if (planeTypes[i] == \"T\") {\n squadsToAdd = source.TSquadrons;\n opSource.TSquadrons += source.TSquadrons;\n availSquads = source.TSquadrons = 0;\n } else if (planeTypes[i] == \"F\") {\n squadsToAdd = source.FSquadrons;\n opSource.FSquadrons += source.FSquadrons;\n availSquads = source.FSquadrons = 0;\n } else {\n squadsToAdd = source.DSquadrons;\n opSource.DSquadrons += source.DSquadrons;\n availSquads = source.DSquadrons = 0;\n }\n } else {\n if (planeTypes[i] == \"T\") {\n squadsToAdd = -opSource.TSquadrons;\n source.TSquadrons += opSource.TSquadrons;\n availSquads = source.TSquadrons;\n opSource.TSquadrons = 0;\n } else if (planeTypes[i] == \"F\") {\n squadsToAdd = -opSource.FSquadrons;\n source.FSquadrons += opSource.FSquadrons;\n availSquads = source.FSquadrons;\n opSource.FSquadrons = 0;\n } else {\n squadsToAdd = -opSource.DSquadrons;\n source.DSquadrons += opSource.DSquadrons;\n availSquads = source.DSquadrons;\n opSource.DSquadrons = 0;\n }\n }\n $(numDivSelector).text(availSquads.toString());\n $(numTdSelector).text(textAdd($(numTdSelector).text(), squadsToAdd));\n }\n}", "function check_overlap(x,y)\n{\n var detect=0;\n \n for (var i=0;i<no_of_elements;i++)\n {\n if (cli===i)\n break;\n \n if((Math.abs(x-elems[i].start)<elems[cli].width) &&(Math.abs(y-elems[i].end)<elems[cli].height))\n detect=1;\n \n }\n writeMessage(canvas,detect);\n \n return detect;\n \n }", "function processImages(collection) {\n if (only.length && only.indexOf(collection.name) === -1) {\n return;\n }\n\n if (skip.indexOf(collection.name) != -1) {\n return\n }\n\n // print number of images at AOI\n let images = ee.ImageCollection(collection.asset)\n .filterBounds(aoi)\n .select(collection.bands.native, collection.bands.readable)\n .map(function (i) {\n return i.set('bounds', aoi)\n });\n\n if (collection.filter) {\n images = images.filter(collection.filter)\n }\n\n if (start && stop) {\n images = images.filterDate(start, stop)\n }\n\n // BUT: EE does image footprints are not alway correct, make sure we have images with values\n images = images.map(function (image) {\n let value = ee.Dictionary(image.select(collection.visual.bands[0]).reduceRegion(ee.Reducer.firstNonNull(), aoi, 100)).values().get(0);\n return image.set('aoi_value', value);\n //.updateMask(focusNearWater)\n\n }).filter(ee.Filter.neq('aoi_value', null));\n\n // apply addition transform if needed\n if (collection.transform) {\n images = images.map(collection.transform)\n }\n\n renderedImagesAll = renderedImagesAll.merge(images.map(function (i) {\n let rendered = i.visualize(collection.visual)\n .set('collection', collection)\n .set('system:time_start', i.get('system:time_start'))\n .set('system:id', i.get('system:id'));\n\n if (renderWater && !debug) {\n // add water edge on top\n let waterVector = ee.FeatureCollection(collection.algorithms.detectWater(i, collection));\n\n let waterImage = ee.Image(0).byte().paint(waterVector, 1, 1);\n\n rendered = ee.ImageCollection([\n rendered,\n waterImage.mask(waterImage).visualize({palette: 'ffffff', forceRgbOutput: true})\n ]).mosaic();\n\n return rendered\n .copyProperties(waterVector)\n .set('collection', collection)\n .set('system:time_start', i.get('system:time_start'))\n .set('system:id', i.get('system:id'))\n .set('water_area', waterVector.geometry().area(ee.ErrorMargin(errorMargin)))\n\n } else {\n return rendered\n .copyProperties(i)\n .set('collection', collection)\n .set('system:time_start', i.get('system:time_start'))\n .set('system:id', i.get('system:id'))\n }\n }));\n\n if (cloudFreeOnly) {\n renderedImagesAll = renderedImagesAll\n .filter(ee.Filter.and(\n ee.Filter.lt('cloud_pixels', 10),\n ee.Filter.gt('water_area', 100),\n ee.Filter.lt('snow_pixels', 10),\n ee.Filter.eq('nodata_pixels', 0)\n ));\n }\n\n // add to map (client, async)\n function processOnCount(count, error) {\n print(collection.name + ': ', count);\n\n if (count === 'undefined') {\n onProcessed(collection);\n return;\n }\n\n totalImageCount += count;\n\n // add a few layers\n let layerCount = Math.min(mapLayerCountToAddProcessed, count);\n let list = images.toList(layerCount, 0);\n for (let i = 0; i < layerCount; i++) {\n let image = ee.Image(list.get(i));\n Map.addLayer(image, collection.visual, collection.name + ' ' + i, i === 0);\n\n pushLayer(image, collection.name);\n\n if (collection.algorithms.onLayerAdd && debug) {\n collection.algorithms.onLayerAdd(image, collection)\n }\n }\n\n onProcessed(collection);\n }\n\n let count = images.select(0).aggregate_count('system:id');\n count.getInfo(processOnCount)\n }", "broadDetection(posx1, posy1) {\n potentialCollidingDaves = []\n\n //method to create a list of Daves in the environment\n\n potentialCollidingDaves.forEach(secondDave => {\n narrowDetection(posx1, posy1, secondDave.posx2, secondDave.posy2)\n });\n\n }", "checkParticleBoundaries(){\n const particlesToRemove = [];\n Object.keys(this.particles).forEach( (id) => {\n const particle = this.particles[id];\n // if particle is out of bounds, add to particles to remove array\n if ( particle.posX > this.canvasWidth\n || particle.posX < 0\n || particle.posY > this.canvasHeight\n || particle.posY < 0\n ) {\n particlesToRemove.push(id);\n }\n });\n\n if (particlesToRemove.length > 0){\n\n particlesToRemove.forEach((id) => {\n // We're checking if the total particles exceed the max particles.\n // If the total particles exeeds max particles, we delete the particle\n // entry in the object. Otherwise, we just create a new particle\n // and insert it into the old particle's object id. This saves us\n // a little time above with generating a new UUID or running the delete command\n if (Object.keys(this.particles).length > this.maxParticles){\n delete this.particles[id];\n } else {\n this.particles[id] = this.makeRandomParticle();\n }\n });\n }\n }", "mergeBelow(layer) {\n EventBus.$emit(\"try-merging-layer-below\", layer.name);\n }", "function overlap(b1, b2){\r\n if (dist(b1, b2) < b1.r + b2.r){\r\n return true;\r\n }\r\n return false;\r\n}", "function OverlayFit() { }", "collidesWith(player) {\n //this function returns true if the the rectangles overlap\n // console.log('this.collidesWith')\n const _overlap = (platform, object) => {\n // console.log('_overlap')\n // check that they don't overlap in the x axis\n const objLeftOnPlat = object.left <= platform.right && object.left >= platform.left;\n const objRightOnPlat = object.right <= platform.right && object.right >= platform.left;\n const objBotOnPlatTop = Math.abs(platform.top - object.bottom) === 0;\n \n // console.log(\"OBJECT BOTTOM: \", object.bottom/);\n // console.log(\"PLATFORM TOP: \", platform.top);\n // console.log('objectBotOnPlat: ', !objBotOnPlatTop)\n // console.log('OBJECT RIGHT: ', object.right)\n // console.log('PLATFORM RIGHT: ', platform.right)\n // console.log(\"OBJECT LEFT: \", object.left);\n // console.log(\"PLATFORM LEFT: \", platform.left);\n // console.log('objectLeftOnPlat', !objLeftOnPlat);\n // console.log('objRightOnPlat', !objRightOnPlat);\n\n if (!objLeftOnPlat && !objRightOnPlat) {\n // if (player.y < 400) { \n // debugger\n // }\n return false;\n // if (objBotOnPlatTop) return true;\n // return false;\n }\n \n if (objLeftOnPlat || objRightOnPlat) {\n // debugger\n // console.log('PLATFORM:::::', platform.top)\n // console.log('PLAYER:::::::', object.bottom)\n // console.log('objBotOnPlat:::::::::', objBotOnPlatTop)\n\n if (objBotOnPlatTop) {\n debugger\n }\n }\n //check that they don't overlap in the y axis\n const objTopAbovePlatBot = object.top > platform.bottom;\n if (!objBotOnPlatTop) {\n // console.log()\n // if (player.y < 400) { \n // debugger\n // }\n return false;\n }\n\n return true;\n };\n\n let collision = false;\n this.eachPlatform(platform => {\n //check if the bird is overlapping (colliding) with either platform\n if (_overlap(platform, player.bounds())) {\n // console.log('WE ARE HERE IN THE OVERLAP')\n // console.log(platform)\n collision = true;\n // debugger\n // console.log(player)\n player.y = platform.top;\n // console.log('PLATFORM: ', platform)\n // console.log(collision)\n // player.movePlayer(\"up\")\n }\n // _overlap(platform.bottomPlatform, player)\n });\n\n // console.log('collision:')\n // console.log(collision)\n return collision;\n }", "function checkOverlap(spriteA, spriteB) {\n\n var overlapping = 0;\n try {\n\n for (var i = 0; i < spriteB.children.entries.length; i++) {\n var boundsA = spriteA.getBounds();\n var boundsB = spriteB.children.entries[i].getBounds();\n\n if (Phaser.Geom.Rectangle.Intersection(boundsA, boundsB).width > 0) {\n overlapping = 1;\n break;\n }\n }\n\n return overlapping;\n }\n catch (e) {\n console.log(e);\n return false;\n }\n\n}", "function addClipping()\r\n\t{\r\n\tnewClipping = this.id.substring(3,this.id.length)\r\n\tduplicate = false;\r\n\tfor (i=0; i < allClippings.length; i++) //find the position the allClippings array of the selected clipping\r\n\t\t{\r\n\t\tif (newClipping == allClippings[i].id) {pos = i; i = allClippings.length}\r\n\t\t}\r\n\t\t\r\n\tif (activeClippings.length > 0)\tcheckForDuplicates() //make sure clipping is not already seletected\r\n\t\r\n\tif (!duplicate)\r\n\t{\t\r\n\t\teventCheckForCookies();\r\n\t\tif (cookiesOn == true)\r\n\t\t\t{\r\n\t\t\tactiveClippings[activeClippings.length] = new Clipping(allClippings[pos].id,allClippings[pos].headline,allClippings[pos].URL);\r\n\t\t\t\r\n\t\t\t//find all instances of the clipping in article and hides it\r\n\t \t\tclippingInstanceVisibility(this.id,'hidden') \r\n\t \t\t\r\n\t \t\tdrawClippings();\t\r\n\t \t\tevent.cancleBubble = true;\r\n\t \t\tupdateClippingCounter();\r\n\t\t\tsaveClippings();\r\n\t\t \t}\r\n\t \t}\r\n\t}", "function check_collision( objects_to_check )\n\t{\n\t\treturn false;\n\t}", "function overlapTest(a, b) {\n return a.x < b.x + b.w && a.x + a.w > b.x &&\n\t\t a.y < b.y + b.h && a.y + a.h > b.y\n}", "function randOvalCoordinate(i){\r\n // overlapping = 0;\r\n var r = screenScale.height/2 - CurPos.scale,\r\n R = screenScale.width/2 - CurPos.scale;\r\n var _r = Math.sqrt(Math.random()*(R*R-r*r)+r*r);\r\n var theta = Math.random()*2*Math.PI;\r\n // var theta = Math.random()*2*Math.PI;\r\n passerbyPos[i] = {x:Math.abs(_r*Math.cos(theta)+(screenScale.width/2- CurPos.scale*2)),y:Math.abs(_r*Math.sin(theta)/4+(screenScale.height/2- CurPos.scale*2))};\r\n // plot(_r*Math.cos(theta),_r*Math.sin(theta)/4);\r\n imgOverlapping(i);\r\n}", "function setUpPinhole(scene)\n{\n //clear scene except for grid\n var obj;\n for( var i = scene.children.length - 1; i >= 0; i--) {\n if(scene.children[i].name != \"grid\")\n {\n obj = scene.children[i];\n scene.remove(obj);\n }\n }\n\n markers = [];\n for(var i = 0; i < numSamples; i++)\n {\n var y = 1.0*Math.floor(i / sqrtVal);\n var x = 1.0*(i % sqrtVal);\n if(!obstacle || ((x - 10 < obstacleGapWidth/2.0 && x - 10 >= -obstacleGapWidth/2.0) ||\n (y - 10 < obstacleYCoord - searchRadius || y - 10 >= obstacleYCoord + searchRadius)))\n {\n createMarkers(x, y, scene);\n }\n }\n\n if(obstacle)\n {\n var dim = (20 - obstacleGapWidth)/2.0;\n var obGeo = new THREE.BoxGeometry(dim, 1, searchRadius*2);\n var obMat = new THREE.MeshBasicMaterial( {color: 0x8b8b8b, side: THREE.DoubleSide} );\n var halfWidth = obstacleGapWidth/2.0;\n var ob1 = new THREE.Mesh(obGeo, obMat);\n ob1.position.set(halfWidth + (10-halfWidth)/2.0, 0.5, obstacleYCoord);\n scene.add(ob1);\n var ob2 = new THREE.Mesh(obGeo, obMat);\n ob2.position.set(-halfWidth - (10-halfWidth)/2.0, 0.5, obstacleYCoord);\n scene.add(ob2);\n }\n\n var col1 = 0xff0000;\n var col2 = 0x0000ff;\n\n agents = [];\n for(var i = 0; i < 10; i++)\n {\n var thisPos = new THREE.Vector2(2*i-10+1, 10);\n var thisGoal = new THREE.Vector2(10-2*i-1, -10);\n var thisAgent = new Agent(thisPos, thisGoal, col1);\n agents.push(thisAgent);\n }\n for(var i = 0; i < 10; i++)\n {\n var thisPos = new THREE.Vector2(2*i-10+1, -10);\n var thisGoal = new THREE.Vector2(10-2*i-1, 10);\n var thisAgent = new Agent(thisPos, thisGoal, col2);\n agents.push(thisAgent);\n }\n\n for(var i = 0; i < agents.length; i++)\n {\n var agGeo = new THREE.CylinderGeometry(0.25, 0.25, 1.0);\n var col = new THREE.Color(agents[i].col);\n var agMat = new THREE.MeshBasicMaterial( {color: col, side: THREE.DoubleSide} );\n var ag = new THREE.Mesh(agGeo, agMat);\n ag.name = \"agent\" + i; //used in onUpdate\n ag.position.set(agents[i].position.x, 0.5, agents[i].position.y);\n scene.add(ag);\n }\n}", "_setHitArea() {\n // todo [optimize] Update hit area only when dragging of element was done - no need to recalculate ti\n // To make sure our hit area box is nice and surrounds the connection curve we create\n // two parallel approximated curves besides the main one by introducing shifts for X and Y\n // coordinates.\n\n // We're adding Y shift pretty easily, But then there are several possible\n // cases for calculating X. So we calculate shifts for the case when source is to the\n // right and above the target. And in other cases simply switch \"polarity\"\n const curve1 = [], curve2 = [];\n\n // Create parallel approximated curves\n let fraction = 0;\n while (fraction <= 1) {\n fraction = (fraction > 1) ? 1 : fraction;\n const point = ConnectionHelper.GetBezierPoint(\n this.pointA, this.controlPointA, this.controlPointB, this.pointB,\n fraction,\n );\n\n let xShift = DEFAULT_HIT_AREA_SHIFT;\n // In case our source point is to the left of the end point we need to reduce the\n // X coordinate of the hitArea curve that have bigger Y (having a bigger Y means that\n // it is lower one) in order to have a nice hitArea box\n if (this.iconA.x < this.iconB.x) {\n xShift = -xShift;\n }\n\n // In case our source is lower that the target.\n // Important! Do not unite this condition with the previous one - there are\n // cases when both should work at the same time\n if (this.iconA.y > this.iconB.y) {\n xShift = -xShift;\n }\n curve1.push(point.x + xShift);\n curve1.push(point.y + DEFAULT_HIT_AREA_SHIFT);\n curve2.push(point.x - xShift);\n curve2.push(point.y - DEFAULT_HIT_AREA_SHIFT);\n fraction += DEFAULT_HIT_AREA_STEP;\n }\n\n // Create a polygon from two curves. To do it\n // we add the second curve in reverse order to the first\n for (let i = (curve2.length - 1); i >= 0; i -= 2) {\n curve1.push(curve2[i - 1]); curve1.push(curve2[i]);\n }\n\n // console.log('curve merged ');\n // for (let i = 0; i < curve1.length; i += 2) {\n // console.log(curve1[i], curve1[i+1]);\n // }\n\n // DEBUG functionality: Draw hit area box\n // this.graphics.moveTo(curve1[0], curve1[1]);\n // for (let i = 2; i < curve1.length; i += 2) {\n // this.graphics.lineTo(curve1[i], curve1[i+1]);\n // }\n // this.graphics.lineTo(curve1[0], curve1[1]);\n\n this.graphics.hitArea = new PIXI.Polygon(curve1);\n }", "async removeObsoleteArtifacts() {\n const validArtifactsPaths = new Set();\n for (const { sourceName, artifacts } of this._validArtifacts) {\n for (const artifactName of artifacts) {\n validArtifactsPaths.add(this._getArtifactPathSync((0, contract_names_1.getFullyQualifiedName)(sourceName, artifactName)));\n }\n }\n const existingArtifactsPaths = await this.getArtifactPaths();\n for (const artifactPath of existingArtifactsPaths) {\n if (!validArtifactsPaths.has(artifactPath)) {\n await this._removeArtifactFiles(artifactPath);\n }\n }\n await this._removeObsoleteBuildInfos();\n }", "function elementsOverlap(pos) {\n if (snake.x == pos.x && snake.y == pos.y)\n return true;\n if(food){\n if(food.x == pos.x && food.y == pos.y)\n return true;\n }\n if(barriers && barriers.length>0 && food){\n for(var i = 0; i < barriers.length; i++){\n for(var j = 0; j < barriers[i].positions.length; j++){\n if(barriers[i].positions[j].pos.x == pos.x && barriers[i].positions[j].pos.y == pos.y){\n return true;\n }\n if(barriers[i].positions[j].pos.x == food.x && barriers[i].positions[j].pos.y == food.y){\n return true;\n }\n }\n }\n }\n for (var i = 0; i < snake.tail.length; i++) {\n if (snake.tail[i].x == pos.x && snake.tail[i].y == pos.y)\n return true;\n }\n return false;\n}", "function greedyLayout(areas, params) {\n var loss = params && params.lossFunction ? params.lossFunction : lossFunction; // define a circle for each set\n\n var circles = {},\n setOverlaps = {},\n set;\n\n for (var i = 0; i < areas.length; ++i) {\n var area = areas[i];\n\n if (area.sets.length == 1) {\n set = area.sets[0];\n circles[set] = {\n x: 1e10,\n y: 1e10,\n rowid: circles.length,\n size: area.size,\n radius: Math.sqrt(area.size / Math.PI)\n };\n setOverlaps[set] = [];\n }\n }\n\n areas = areas.filter(function (a) {\n return a.sets.length == 2;\n }); // map each set to a list of all the other sets that overlap it\n\n for (i = 0; i < areas.length; ++i) {\n var current = areas[i];\n var weight = current.hasOwnProperty('weight') ? current.weight : 1.0;\n var left = current.sets[0],\n right = current.sets[1]; // completely overlapped circles shouldn't be positioned early here\n\n if (current.size + SMALL$1 >= Math.min(circles[left].size, circles[right].size)) {\n weight = 0;\n }\n\n setOverlaps[left].push({\n set: right,\n size: current.size,\n weight: weight\n });\n setOverlaps[right].push({\n set: left,\n size: current.size,\n weight: weight\n });\n } // get list of most overlapped sets\n\n\n var mostOverlapped = [];\n\n for (set in setOverlaps) {\n if (setOverlaps.hasOwnProperty(set)) {\n var size = 0;\n\n for (i = 0; i < setOverlaps[set].length; ++i) {\n size += setOverlaps[set][i].size * setOverlaps[set][i].weight;\n }\n\n mostOverlapped.push({\n set: set,\n size: size\n });\n }\n } // sort by size desc\n\n\n function sortOrder(a, b) {\n return b.size - a.size;\n }\n\n mostOverlapped.sort(sortOrder); // keep track of what sets have been laid out\n\n var positioned = {};\n\n function isPositioned(element) {\n return element.set in positioned;\n } // adds a point to the output\n\n\n function positionSet(point, index) {\n circles[index].x = point.x;\n circles[index].y = point.y;\n positioned[index] = true;\n } // add most overlapped set at (0,0)\n\n\n positionSet({\n x: 0,\n y: 0\n }, mostOverlapped[0].set); // get distances between all points. TODO, necessary?\n // answer: probably not\n // var distances = venn.getDistanceMatrices(circles, areas).distances;\n\n for (i = 1; i < mostOverlapped.length; ++i) {\n var setIndex = mostOverlapped[i].set,\n overlap = setOverlaps[setIndex].filter(isPositioned);\n set = circles[setIndex];\n overlap.sort(sortOrder);\n\n if (overlap.length === 0) {\n // this shouldn't happen anymore with addMissingAreas\n throw \"ERROR: missing pairwise overlap information\";\n }\n\n var points = [];\n\n for (var j = 0; j < overlap.length; ++j) {\n // get appropriate distance from most overlapped already added set\n var p1 = circles[overlap[j].set],\n d1 = distanceFromIntersectArea(set.radius, p1.radius, overlap[j].size); // sample positions at 90 degrees for maximum aesthetics\n\n points.push({\n x: p1.x + d1,\n y: p1.y\n });\n points.push({\n x: p1.x - d1,\n y: p1.y\n });\n points.push({\n y: p1.y + d1,\n x: p1.x\n });\n points.push({\n y: p1.y - d1,\n x: p1.x\n }); // if we have at least 2 overlaps, then figure out where the\n // set should be positioned analytically and try those too\n\n for (var k = j + 1; k < overlap.length; ++k) {\n var p2 = circles[overlap[k].set],\n d2 = distanceFromIntersectArea(set.radius, p2.radius, overlap[k].size);\n var extraPoints = circleCircleIntersection({\n x: p1.x,\n y: p1.y,\n radius: d1\n }, {\n x: p2.x,\n y: p2.y,\n radius: d2\n });\n\n for (var l = 0; l < extraPoints.length; ++l) {\n points.push(extraPoints[l]);\n }\n }\n } // we have some candidate positions for the set, examine loss\n // at each position to figure out where to put it at\n\n\n var bestLoss = 1e50,\n bestPoint = points[0];\n\n for (j = 0; j < points.length; ++j) {\n circles[setIndex].x = points[j].x;\n circles[setIndex].y = points[j].y;\n var localLoss = loss(circles, areas);\n\n if (localLoss < bestLoss) {\n bestLoss = localLoss;\n bestPoint = points[j];\n }\n }\n\n positionSet(bestPoint, setIndex);\n }\n\n return circles;\n }", "isConflict(id,xPos,yPos,width,height){\n let result = 0;\n //check borders first\n if (xPos <0)\n result = -1; //off to the left\n else if (xPos+ width > this.boardWidth)\n result = -2; //off the screen to the right\n else if (yPos < 0)\n result = -3; //off the top of the screen\n else if (yPos +height > this.boardHeight)\n result = -4; //off the bottom of the screen\n //console.log(\"start\")\n for (let i=xPos;i<xPos+width && i<this.boardWidth && result ==0;i++){\n for (let j=yPos;j < yPos + height && j < this.boardHeight&& result==0;j++){\n //only return conflict when it doesn't equal itself\n if (this.board[i][j] != id)\n result = this.board[i][j];\n //console.log(i + \" \" + j + \" set to \" + this.board[i][j]);\n }\n }\n return result;\n }", "hitCheck(a, b){ // colision\n var ab = a._boundsRect;\n var bb = b._boundsRect;\n return ab.x + ab.width > bb.x && ab.x < bb.x + bb.width && ab.y + ab.height > bb.y && ab.y < bb.y + bb.height;\n }", "function checkCollision(a, b) {\n if (a !== undefined && b !== undefined) {\n var aRad = (a.a + a.b + a.c) / 3;\n var bRad = (b.a + b.b + b.c) / 3;\n var aPos = vec3.create();\n\n vec3.add(aPos, a.center, a.translation);\n var bPos = vec3.create();\n vec3.add(bPos, b.center, b.translation);\n var dist = vec3.distance(aPos, bPos);\n\n if (dist < aRad + bRad) {\n //spawn explosion and destroy asteroid, doesn't matter what asteroid collided with, always explodes\n generateExplosion(vec3.add(vec3.create(), vec3.fromValues(a.x, a.y, a.z),\n vec3.fromValues(a.translation[0], a.translation[1], a.translation[2])), false);\n deleteModel(a);\n //handle collision\n if (b.tag == 'shot') {\n // destroy asteroid and shot, give player points\n //test *******apocalypse = true;\n //test *******gameOver(b);\n deleteModel(b);\n score += 10;\n document.getElementById(\"score\").innerHTML = \"Score: \" + score;\n } else if (b.tag == 'station') {\n // destroy asteroid, damage station and destroy if life < 0 then weaken shield\n // if last station destroyed, destroy shield as wells\n b.health -= 5;\n if (b.css == 'station1') {\n document.getElementById(\"station1\").innerHTML = \"Station Alpha: \" + b.health;\n } else if (b.css == 'station2') {\n document.getElementById(\"station2\").innerHTML = \"Station Bravo: \" + b.health;\n } else {\n document.getElementById(\"station3\").innerHTML = \"Station Charlie: \" + b.health;\n }\n if (b.health == 0) {\n var change = false;\n base_limit--;\n // reduce shield alpha by one to signify weakening\n for (var o in inputEllipsoids) {\n if (inputEllipsoids[o].tag == 'shield') {\n inputEllipsoids[o].alpha -= 0.2;\n }\n }\n // if the destroyed center is highlighted, switch to next\n if (b.id == current_center) {\n for (var s in stations) {\n if (stations[s].id > b.id) {\n stations[s].id--;\n }\n }\n change = true;\n }\n // remove the destroyed station\n station_centers.splice(b.id, 1);\n deleteModel(b);\n // has to be after splice/delete or else will access out of date station_centers\n if (change) {\n current_center++;\n changeStation();\n }\n shield_level--;\n document.getElementById(\"shield\").innerHTML = \"Shield: \" + shield_level;\n // destroy shield if no more stations\n if (shield_level == 0) {\n for (var o in inputEllipsoids) {\n if (inputEllipsoids[o].tag == 'shield') {\n deleteModel(inputEllipsoids[o]);\n break;\n }\n }\n deleteModel(highlight);\n }\n if (b.css == 'station1') {\n document.getElementById(\"station1charge\").innerHTML = \"Destroyed!\";\n document.getElementById(\"station1\").innerHTML = \"Station Alpha:\"\n } else if (b.css == 'station2') {\n document.getElementById(\"station2charge\").innerHTML = \"Destroyed!\";\n document.getElementById(\"station2\").innerHTML = \"Station Bravo:\"\n } else {\n document.getElementById(\"station3charge\").innerHTML = \"Destroyed!\";\n document.getElementById(\"station3\").innerHTML = \"Station Charlie:\"\n }\n }\n } else if (b.tag == 'shield') {\n // destroy asteroid, damage earth based on shield strength\n earth_health -= 15 / shield_level;\n document.getElementById(\"earth\").innerHTML = \"Earth: \" + earth_health;\n if (earth_health <= 0) {\n for (var o in inputEllipsoids) {\n if (inputEllipsoids[o].tag == 'earth') {\n // handle game over\n gameOver(inputEllipsoids[o]);\n break;\n }\n }\n }\n } else if (b.tag == 'earth') {\n // destroy asteroid, damage earth and destroy if life < 0\n earth_health -= 15;\n document.getElementById(\"earth\").innerHTML = \"Earth: \" + earth_health;\n if (earth_health <= 0) {\n // handle game over\n gameOver(b);\n }\n } else if (b.tag == 'moon') {\n b.health -= 5;\n if (b.health <= 0) {\n generateExplosion(vec3.add(vec3.create(), vec3.fromValues(b.x, b.y, b.z),\n vec3.fromValues(b.translation[0], b.translation[1], b.translation[2])), true);\n deleteModel(b);\n }\n }\n }\n }\n}", "function newAliens(arrayOfColorPairs, id) {\n \n var bubblePicture = \"bubble.png\"; // The picture used for the bubble\n \n var bigAlien = {left: 0, top: 80, width: 80, height:80}, // The relative position and size of each bigAlien\n bubble = {left: 10, top: 0, width: 70, height: 79}, // The relative position and size of each bubble\n miniAlien = {left: 20, top: 5, width: 50, height: 50}; // The relative position and size of each miniAlien\n \n var xoffset = 0; // The number of pixels separating each bigAlien\n \n if (typeof id != \"string\") id = \"alien\"; // Giving an ID to the picture\n \n // patches is the array of objects representing the different DIV in the click2uncover element\n var patches = [];\n for (pair in arrayOfColorPairs) {\n\n // patchBigAlien, patchBubble and patchMiniAlien are the objects corresponding to the DIVs currently processed\n var patchBigAlien, patchBubble, patchMiniAlien;\n \n patchBigAlien = $().extend({id: id+\"bigAlien\"+pair, background: getUrlPic(arrayOfColorPairs[pair][0])}, bigAlien);\n patchBubble = $().extend({id: id+\"bubble\"+pair, background: getUrlPic(bubblePicture)}, bubble);\n patchMiniAlien = $().extend({id: id+\"miniAlien\"+pair, background: getUrlPic(arrayOfColorPairs[pair][1])}, miniAlien);\n \n // Adding an offset if several aliens\n patchBigAlien.left += (bigAlien.width + xoffset) * pair;\n patchBubble.left += (bigAlien.width + xoffset) * pair;\n patchMiniAlien.left += (bigAlien.width + xoffset) * pair;\n \n // Adjusting the size of the background picture to its frame\n patchBigAlien[\"background-size\"] = \"cover\";\n patchBubble[\"background-size\"] = \"cover\";\n patchMiniAlien[\"background-size\"] = \"cover\";\n \n // Adding each image to the c2p\n patches.push(patchBigAlien);\n patches.push(patchBubble);\n patches.push(patchMiniAlien);\n }\n\n // Returns the click2uncover element, containing the patches, and whose size is determined by bigAlien\n return c2u.newPicture(\"\", patches, {width: (bigAlien.width + xoffset) * arrayOfColorPairs.length, height: bigAlien.height + bigAlien.top});\n}", "addToChangeLayers(){\n let _to = this.props.toVersion.key;\n //attribute change in protected areas layers\n this.addLayer({id: window.LYR_TO_CHANGED_ATTRIBUTE, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"fill-color\": \"rgba(99,148,69,0.4)\", \"fill-outline-color\": \"rgba(99,148,69,0.8)\"}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n //geometry change in protected areas layers - to\n this.addLayer({id: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON_LINE, sourceId: window.SRC_TO_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY_LINE, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_POINT_COUNT_CHANGED_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_POINT_COUNT_CHANGED_POLYGON_LINE, sourceId: window.SRC_TO_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY_LINE, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_SHIFTED_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_SHIFTED_POLYGON_LINE, sourceId: window.SRC_TO_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY_LINE, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n //added protected areas layers\n this.addLayer({id: window.LYR_TO_NEW_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"fill-color\": \"rgba(63,127,191,0.2)\", \"fill-outline-color\": \"rgba(63,127,191,0.6)\"}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_NEW_POINT, sourceId: window.SRC_TO_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _to + \"_points\", layout: {visibility: \"visible\"}, paint: {\"circle-radius\": CIRCLE_RADIUS_STOPS, \"circle-color\": \"rgb(63,127,191)\", \"circle-opacity\": 0.6}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n \n }", "function overlap(obj1, obj2) {\n var right1 = obj1.x + obj1.width;\n var right2 = obj2.x + obj2.width;\n var left1 = obj1.x;\n var left2 = obj2.x;\n var top1 = obj1.y;\n var top2 = obj2.y;\n var bottom1 = obj1.y + obj1.height;\n var bottom2 = obj2.y + obj2.height;\n\n if (left1 < right2 && left2 < right1 && top1 < bottom2 && top2 < bottom1) {\n return true;\n }\n return false;\n }", "function addIntersectPoints() {\n app.executeMenuCommand('group');\n app.executeMenuCommand('Make Planet X');\n selection[0].translate(0, 0); // Update view\n app.executeMenuCommand('Expand Planet X');\n try {\n app.executeMenuCommand('ungroup');\n app.executeMenuCommand('ungroup');\n } catch (err) {}\n}", "function addIntersectPoints() {\n app.executeMenuCommand('group');\n app.executeMenuCommand('Make Planet X');\n selection[0].translate(0, 0); // Update view\n app.executeMenuCommand('Expand Planet X');\n try {\n app.executeMenuCommand('ungroup');\n app.executeMenuCommand('ungroup');\n } catch (err) {}\n}", "function checkObjectOverlap(object) {\n //Check to see if object with object is overlapping any other object that it can be grouped with.\n var manipulationObjects = document.getElementsByClassName('manipulationObject');\n var overlapArray = new Array();\n \n for(var i = 0; i < manipulationObjects.length; i++) { //go through all manipulationObjects, checking for overlap.\n if(object.id != manipulationObjects[i].id) { //Don't check the object you're moving against itself.\n //check to see if objects overlap. If they do, add the object to the array.\n if((object.offsetLeft + object.offsetWidth > manipulationObjects[i].offsetLeft) && (object.offsetLeft < manipulationObjects[i].offsetLeft + manipulationObjects[i].offsetWidth) && (object.offsetTop + object.offsetHeight > manipulationObjects[i].offsetTop) && (object.offsetTop < manipulationObjects[i].offsetTop + manipulationObjects[i].offsetHeight)) {\n \n //check to see if the 2 are already grouped together\n var areGrouped = areObjectsGrouped(object, manipulationObjects[i]);\n \n //This check may need to be moved over to the checkObjectOverlap function.\n //if they're not grouped, group them.\n if(areGrouped == -1) {\n var overlappedObjs = new Array();\n overlappedObjs[0] = object;\n overlappedObjs[1] = manipulationObjects[i];\n overlapArray[overlapArray.length] = overlappedObjs;\n }\n }\n }\n }\n \n return overlapArray;\n}", "allowPickUp () {\n BOX.Engine.noa.entities.addComponent(this.noaEntityId, BOX.Engine.noa.entities.names.collideEntities, {\n cylinder: true,\n callback: otherEntsId => { \n \n let player = BOX.Engine.getEntityByNoaID(otherEntsId); //TEMPORARY - need to find unit by noaId\n if (player.data.ownerPlayer) {\n console.log('item collide unit', this.noaEntityId, otherEntsId, player) \n player.equipItem(this);\n //disable pick up after collision with unit\n BOX.Engine.noa.entities.removeComponent(this.noaEntityId, BOX.Engine.noa.entities.names.collideEntities);\n }\n \n }\n });\n }", "function runOver (){\n\n\tvar carsX = [carX1, carX2, carX3, carX4, carX5, carX6, carX7, carX8];\n\tvar carsY = [carY1, carY2, carY3, carY4, carY5, carY6, carY7, carY8];\n //for loop that will check for x and y values\n\tfor (i = 0; i < carsX.length; i++){\n\t\tif (carsX[i] <= x + width &&\n\t\tcarsX[i] + carWidth >= x &&\n\t\tcarsY[i] + carHeight >= y &&\n\t\tcarsY[i] <= y + height) {\n\t\t\ty= 444;\n\t\t\tlives = lives - 1;\n\t\t}\n\t}\n}", "function overlap (lines, event, maxParallelEvents, toRemove, doublecheck) {\n var range = event.pre > 0\n ? moment.range(moment(event.start).subtract(event.pre, 'minutes'), moment(event.end))\n : event.range\n for (var i = 0; i < lines.length; i++) {\n if (event.depth > maxParallelEvents) {\n var overlap = false\n _.each(lines[maxParallelEvents], function (elt) {\n\n var eltRange = elt.pre > 0\n ? moment.range(moment(elt.start).subtract(elt.pre, 'minutes'), moment(elt.end))\n : elt.range\n\n overlap = range.overlaps(eltRange)\n if (!overlap && doublecheck) {\n overlap = (event.start.day() === elt.start.day() || event.start.day() === elt.end.day() || event.end.day() === elt.start.day() || event.end.day() === elt.end.day())\n }\n if (overlap) {\n elt.start = moment.min(event.start, elt.start) // set start to minimum of 2 overlapping event\n elt.end = moment.max(event.end, elt.end) // set end to maximum of 2 overlapping event\n elt.range = moment.range(elt.start, elt.end) // Update range\n elt.line = maxParallelEvents\n elt.eventList.push(event)\n if (elt.technician !== event.technician) { // Technician isn't the same, hide it\n elt.technician = ''\n event.technician = ''\n }\n }\n })\n if (overlap) {\n toRemove.push(event)\n break\n }\n event.depth = maxParallelEvents\n event.line = maxParallelEvents\n if (!event.eventList) {\n var eventClone = _.cloneDeep(event)\n event.eventList = [eventClone]\n }\n lines[maxParallelEvents].push(event)\n break\n }\n if (!lines[i].length) {\n lines[i].push(event)\n event.line = i\n break\n }\n if (_.filter(lines[i], function (elt) { // if any event in lines[i] overlap\n var eltRange = elt.pre > 0\n ? moment.range(moment(elt.start).subtract(elt.pre, 'minutes'), moment(elt.end))\n : elt.range\n overlap = range.overlaps(eltRange)\n if (!overlap && doublecheck) {\n overlap = (event.start.day() === elt.start.day() || event.start.day() === elt.end.day() || event.end.day() === elt.start.day() || event.end.day() === elt.end.day())\n }\n if (overlap) {\n elt.depth += 1\n return true\n } }).length) {\n event.depth += 1\n if (!lines[i + 1]) { // if next line is doesn't exist, add one\n lines[i + 1] = []\n }\n } else {\n lines[i].push(event)\n event.line = i\n break\n }\n }\n }", "function pipeCollisions(){\n\tfor(let i = 0; i < pipe.count; i++){\n\t\tif( (DOM_pipes_top[i].temp_x <= bird.width-10) && (DOM_pipes_top[i].temp_x >= -pipe.width+10) ){\n\t\t\tif(bird.y < (DOM_pipes_top[i].temp_y - pipe.gap/2 + bird.height/2)){\n\t\t\t\tif(!bird.immortal){\n\t\t\t\t\tendGame();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bird.y > (DOM_pipes_top[i].temp_y + pipe.gap/2 - bird.height/2)){\n\t\t\t\tif(!bird.immortal){\n\t\t\t\t\tendGame();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function checkCoordinates (startCoordinate, direction, length) {\n let noOverlap = true\n for (let i = 0; i < length; i++) {\n let newCoordinate = [startCoordinate[0] + i * direction[0], startCoordinate[1] + i * direction[1]]\n this.reservedCoordinates.forEach(coordinate => {\n let reservedX = coordinate[0]\n let reservedY = coordinate[1]\n let newX = newCoordinate[0]\n let newY = newCoordinate[1]\n if (reservedX === newX && reservedY === newY) {\n noOverlap = false\n } \n })\n }\n return noOverlap\n}", "function makeSpaceShip(spec) {\n let that = {};\n\n that.image = new Image();\n that.ready = false;\n\n that.image.onload = function() {\n if (that.image.width >= that.image.height) {\n let aspectRatio = that.image.width / that.image.height;\n that.width = spec.width * aspectRatio;\n that.height = spec.height;\n }\n else {\n let aspectRatio = that.image.height / that.image.width;\n that.width = spec.width;\n that.height = spec.height * aspectRatio;\n }\n\n that.exhaust = {x: 0, y:0};\n that.exhaust.x = spec.center.x;\n that.radius = that.height/2;\n that.exhaust.y = spec.center.y + that.radius;\n\n that.hitBox = {\n center: {x: spec.center.x, y: spec.center.y},\n radius: that.height/2\n };\n\n that.ready = true;\n };\n\n that.image.src = spec.imageSrc;\n that.center = spec.center;\n that.rotation = Math.PI / 2;\n that.speed = spec.speed;\n that.level = -that.rotation * 180 / Math.PI;\n that.fuel = spec.startingFuel;\n that.accelerationRate = 0;\n that.nose = {x: 0, y:0};\n that.tail = {x: 0, y:0};\n\n that.useJets = (elapsedTime) => {\n if (that.fuel > 0) {\n thrustSound1.play();\n thrustSound2.play();\n that.fuel -= (elapsedTime * spec.fuelConsumptionRate);\n if (that.accelerationRate > 0) {\n that.accelerationRate = 0;\n }\n that.center.x += that.level * 0.005 * that.accelerationRate;\n that.accelerationRate -= (elapsedTime**0.001);\n exhaustSystem.isCreateNewParticles = true;\n }\n };\n\n that.rotateLeft = (elapsedTime) => {\n if (that.rotation > -1 * Math.PI / 2 + 0.5) {\n that.rotation -= (elapsedTime * spec.rotateRate);\n that.level = -that.rotation * 180 / Math.PI;\n }\n };\n\n that.rotateRight = (elapsedTime) => {\n if (that.rotation < Math.PI / 2 - 0.5) {\n that.rotation += (elapsedTime * spec.rotateRate);\n that.level = -that.rotation * 180 / Math.PI;\n }\n };\n\n return that;\n}", "function onIrrelevantElement(e, api, targetCoordSysModel) {\n\t var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.\n\t\n\t var coordSys = model && model.coordinateSystem;\n\t return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;\n\t }", "function overlapTest(a, b) {\n return a.x < b.x + b.w && a.x + a.w > b.x &&\n a.y < b.y + b.h && a.y + a.h > b.y\n}", "function overlapTest(a, b) {\n return a.x < b.x + b.w && a.x + a.w > b.x &&\n a.y < b.y + b.h && a.y + a.h > b.y\n}", "function camSetArtifacts(artifacts)\n{\n\t__camArtifacts = artifacts;\n\tfor (var alabel in __camArtifacts)\n\t{\n\t\tvar ai = __camArtifacts[alabel];\n\t\tvar pos = camMakePos(alabel);\n\t\tif (camDef(pos.id))\n\t\t{\n\t\t\t// will place when object with this id is destroyed\n\t\t\tai.id = \"\" + pos.id;\n\t\t\tai.placed = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// received position or area, place immediately\n\t\t\tvar acrate = addFeature(\"Crate\", pos.x, pos.y);\n\t\t\taddLabel(acrate, __camGetArtifactLabel(alabel));\n\t\t\tai.placed = true;\n\t\t}\n\t}\n}", "function collideWithButton(newImage) { //DONT TOUCH - Jacob\n let buttonHeight = button.clientHeight;\n let buttonWidth = button.clientWidth;\n let screenWidth = buttonHolder.clientWidth;\n let screenHeight = buttonHolder.clientHeight;\n let imageTop = newImage.style.top;\n let imageLeft = newImage.style.left;\n let imageHeight = newImage.style.height;\n let imageWidth = imageHeight;\n imageTop = Number(imageTop.substring(0, imageTop.length - 2));\n imageLeft = Number(imageLeft.substring(0, imageLeft.length - 2));\n imageWidth = Number(imageWidth.substring(0, imageWidth.length - 2));\n imageHeight = Number(imageHeight.substring(0, imageHeight.length - 2));\n\n\n\n let imageBottom = imageTop + imageHeight;\n let imageRight = imageLeft + imageWidth;\n let midWidth = imageLeft + imageWidth / 2;\n let midHeight = imageTop + imageHeight / 2;\n\n //if this happens we know that it's in the right y position\n if (screenHeight / 2 - buttonHeight / 2 <= imageTop && screenHeight / 2 + buttonHeight / 2 >= imageTop) { //checking top left corner of image\n //testing if it's inside the button.\n if (screenWidth / 2 - buttonWidth / 2 <= imageLeft && screenWidth / 2 + buttonWidth / 2 >= imageLeft) {\n return false;\n }\n }\n if (screenHeight / 2 - buttonHeight / 2 <= imageBottom && screenHeight / 2 + buttonHeight / 2 >= imageBottom) { //bottom left\n //testing if it's inside the button.\n if (screenWidth / 2 - buttonWidth / 2 <= imageLeft && screenWidth / 2 + buttonWidth / 2 >= imageLeft) {\n return false;\n }\n }\n if (screenHeight / 2 - buttonHeight / 2 <= imageBottom && screenHeight / 2 + buttonHeight / 2 >= imageBottom) { //bottom right\n //testing if it's inside the button.\n if (screenWidth / 2 - buttonWidth / 2 <= imageRight && screenWidth / 2 + buttonWidth / 2 >= imageRight) {\n return false;\n }\n }\n if (screenHeight / 2 - buttonHeight / 2 <= imageTop && screenHeight / 2 + buttonHeight / 2 >= imageTop) { //top right\n //testing if it's inside the button.\n if (screenWidth / 2 - buttonWidth / 2 <= imageRight && screenWidth / 2 + buttonWidth / 2 >= imageRight) {\n return false;\n }\n }\n\n //Checking midpoints of edges\n if (screenHeight / 2 - buttonHeight / 2 <= midHeight && screenHeight / 2 + buttonHeight / 2 >= midHeight) { //leftMid\n //testing if it's inside the button.\n if (screenWidth / 2 - buttonWidth / 2 <= imageLeft && screenWidth / 2 + buttonWidth / 2 >= imageLeft) {\n return false;\n }\n }\n if (screenHeight / 2 - buttonHeight / 2 <= midHeight && screenHeight / 2 + buttonHeight / 2 >= midHeight) { //rightMid\n //testing if it's inside the button.\n if (screenWidth / 2 - buttonWidth / 2 <= imageRight && screenWidth / 2 + buttonWidth / 2 >= imageRight) {\n return false;\n }\n }\n if (screenHeight / 2 - buttonHeight / 2 <= imageBottom && screenHeight / 2 + buttonHeight / 2 >= imageBottom) { //bottomMid\n //testing if it's inside the button.\n if (screenWidth / 2 - buttonWidth / 2 <= midWidth && screenWidth / 2 + buttonWidth / 2 >= midWidth) {\n return false;\n }\n }\n if (screenHeight / 2 - buttonHeight / 2 <= imageTop && screenHeight / 2 + buttonHeight / 2 >= imageTop) { //topMid\n //testing if it's inside the button.\n if (screenWidth / 2 - buttonWidth / 2 <= midWidth && screenWidth / 2 + buttonWidth / 2 >= midWidth) {\n return false;\n }\n }\n return true;\n\n\n}", "function nullsForPins(){ //start script\n app.beginUndoGroup(\"Create Nulls for Pins\");\n\n //if(parseFloat(app.version) >= 10.5){\n var theComp = app.project.activeItem; //only selected\n\n // check if comp is selected\n if (theComp == null || !(theComp instanceof CompItem)){\n // if no comp selected, display an alert\n alert(\"Please establish a comp as the active item and run the script again.\");\n } else { \n var theLayers = theComp.selectedLayers;\n if(theLayers.length==0){\n alert(\"Please select some layers and run the script again.\");\n }else{\n // otherwise, loop through each selected layer in the selected comp\n for (var i = 0; i < theLayers.length; i++){\n // define the layer in the loop we're currently looking at\n var curLayer = theLayers[i];\n // condition 1: must be a footage layer\n if (curLayer.matchName == \"ADBE AV Layer\"){\n //condition 2: must be a 2D layer\n if(!curLayer.threeDLayer){\n //condition 3: must have puppet pins applied\n if(curLayer.effect.puppet != null){\n var wherePins = curLayer.property(\"Effects\").property(\"Puppet\").property(\"arap\").property(\"Mesh\").property(\"Mesh 1\").property(\"Deform\");\n var pinCount = wherePins.numProperties;\n for (var n = 1; n <= pinCount; n++){\n // Get position of puppet pin\n try{ \n var pin = curLayer.effect(\"Puppet\").arap.mesh(\"Mesh 1\").deform(n);\n //var solid = theComp.layers.addSolid([1.0, 1.0, 0], nullName, 50, 50, 1);\n var solid = theComp.layers.addNull();\n solid.name = pin.name + \"_ctl\";\n //~~~~~\n //scaled from layer coords to world coords\n var p = pin.position.value;\n var posCalc = solid.property(\"Effects\").addProperty(\"Point Control\")(\"Point\");\n posCalcExpr = \"var p = [\"+p[0]+\",\"+p[1]+\"];\" + \"\\r\" +\n //close, but not exact\n //\"var x = \" + (p[0]/curLayer.width)*theComp.width+ \";\" + \"\\r\" +\n //\"var y = \" + (p[1]/curLayer.height)*theComp.height + \";\" + \"\\r\" +\n //\"[x,y];\";\n \"var target = thisComp.layer(\\\"\" + curLayer.name + \"\\\");\" + \"\\r\" +\n \"target.toComp(p);\"\n \n posCalc.expression= posCalcExpr;\n //alert(posCalc.value);\n solid.property(\"position\").setValue(posCalc.value);\n solid.property(\"Effects\")(\"Point Control\").remove();\n //~~~~~~\n var pinExpr = \"fromComp(thisComp.layer(\\\"\"+solid.name+\"\\\").toComp(thisComp.layer(\\\"\"+solid.name+\"\\\").anchorPoint));\";\n pin.position.expression = pinExpr;\n }catch(e){}\n }\n curLayer.property(\"Effects\").property(\"Puppet\").property(\"On Transparent\").setValue(1); \n curLayer.locked = true;\n }else{\n alert(\"This only works on layers with puppet pins.\");\n }\n }else{\n alert(\"This only works properly on 2D layers.\");\n }\n }else{\n alert(\"This only works on footage layers.\");\n }\n }\n }\n }\n \n app.endUndoGroup();\n} //end script", "function projectShadows(cloudMask,image,irSumThresh,contractPixels,dilatePixels,cloudHeights,yMult){\r\n if(yMult === undefined || yMult === null){\r\n yMult = ee.Algorithms.If(ee.Algorithms.IsEqual(image.select([3]).projection(), ee.Projection(\"EPSG:4326\")),1,-1);\r\n }\r\n var meanAzimuth = image.get('MEAN_SOLAR_AZIMUTH_ANGLE');\r\n var meanZenith = image.get('MEAN_SOLAR_ZENITH_ANGLE');\r\n ///////////////////////////////////////////////////////\r\n // print('a',meanAzimuth);\r\n // print('z',meanZenith)\r\n \r\n //Find dark pixels\r\n var darkPixels = image.select(['nir','swir1','swir2']).reduce(ee.Reducer.sum()).lt(irSumThresh)\r\n .focal_min(contractPixels).focal_max(dilatePixels)\r\n ;//.gte(1);\r\n \r\n \r\n //Get scale of image\r\n var nominalScale = cloudMask.projection().nominalScale();\r\n //Find where cloud shadows should be based on solar geometry\r\n //Convert to radians\r\n var azR =ee.Number(meanAzimuth).add(180).multiply(Math.PI).divide(180.0);\r\n var zenR =ee.Number(meanZenith).multiply(Math.PI).divide(180.0);\r\n \r\n \r\n \r\n //Find the shadows\r\n var shadows = cloudHeights.map(function(cloudHeight){\r\n cloudHeight = ee.Number(cloudHeight);\r\n \r\n var shadowCastedDistance = zenR.tan().multiply(cloudHeight);//Distance shadow is cast\r\n var x = azR.sin().multiply(shadowCastedDistance).divide(nominalScale);//X distance of shadow\r\n var y = azR.cos().multiply(shadowCastedDistance).divide(nominalScale).multiply(yMult);//Y distance of shadow\r\n // print(x,y)\r\n \r\n return cloudMask.changeProj(cloudMask.projection(), cloudMask.projection().translate(x, y));\r\n \r\n \r\n });\r\n \r\n \r\n var shadowMask = ee.ImageCollection.fromImages(shadows).max();\r\n \r\n //Create shadow mask\r\n shadowMask = shadowMask.and(cloudMask.not());\r\n shadowMask = shadowMask.and(darkPixels).focal_min(contractPixels).focal_max(dilatePixels);\r\n // Map.addLayer(cloudMask.updateMask(cloudMask),{'min':1,'max':1,'palette':'88F'},'Cloud mask');\r\n // Map.addLayer(shadowMask.updateMask(shadowMask),{'min':1,'max':1,'palette':'880'},'Shadow mask');\r\n \r\n var cloudShadowMask = shadowMask.or(cloudMask);\r\n \r\n image = image.updateMask(cloudShadowMask.not()).addBands(shadowMask.rename(['cloudShadowMask']));\r\n return image;\r\n}" ]
[ "0.6045579", "0.5611285", "0.54688466", "0.5418428", "0.54057753", "0.5262794", "0.5208748", "0.52067304", "0.51245314", "0.51079255", "0.51079255", "0.51061606", "0.5095474", "0.5088224", "0.5078736", "0.5055305", "0.50309116", "0.5027557", "0.5023838", "0.49943924", "0.49928826", "0.49835142", "0.49715582", "0.49601167", "0.4957818", "0.4945149", "0.49313992", "0.49248192", "0.49202052", "0.49197614", "0.4913021", "0.49101266", "0.4902876", "0.48910528", "0.486345", "0.4849826", "0.48371443", "0.48348743", "0.48345584", "0.48252672", "0.4822732", "0.4819888", "0.48158473", "0.4807928", "0.4805903", "0.48042193", "0.47970235", "0.47956425", "0.47876614", "0.47869968", "0.47833586", "0.4779687", "0.47713894", "0.4765476", "0.475608", "0.4748551", "0.47422394", "0.47380957", "0.47375908", "0.47329426", "0.47192082", "0.47112137", "0.47096258", "0.4703895", "0.47011378", "0.4696151", "0.46875158", "0.46784335", "0.4678087", "0.4677299", "0.4672074", "0.4668358", "0.4662807", "0.46611404", "0.46588197", "0.46579176", "0.46564305", "0.46539643", "0.46528947", "0.46507767", "0.4650603", "0.46502966", "0.46497223", "0.464613", "0.46419796", "0.46417037", "0.46417037", "0.46379602", "0.463699", "0.46347183", "0.4630653", "0.46265176", "0.4625106", "0.46232292", "0.4620072", "0.46182784", "0.46182784", "0.46155187", "0.4614092", "0.46129623", "0.46106753" ]
0.0
-1
Exponential Moving Average filter. Needs last sample of the previous synth buffer
ema (inBuffer, outBuffer){ for (let i = 0; i < inBuffer.length; i++){ // Smooth, EMA if (i == 0){// Skip first sample (Or take it from previous buffer?) outBuffer[i] = inBuffer[i]; } else { outBuffer[i] = inBuffer[i]*0.01 + outBuffer[i-1]*0.99; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function calculateExponentialMovingAverage(currentObservation,\n previousExponentialMovingAverage) {\n\n //hacker diet suggests 0.9\n //TODO: make this configurable\n var smoothingFactor = 0.8;\n\n //inspired by hacker diet: \n //https://www.fourmilab.ch/hackdiet/www/subsubsection1_4_1_0_8_3.html\n var result = previousExponentialMovingAverage +\n (\n (1 - smoothingFactor) *\n (currentObservation - previousExponentialMovingAverage)\n );\n\n //get two decimal places, toFixed returns string\n //TODO: this should really be just in c3 or d3 code\n result = Math.round(result * 100)/100;\n return result;\n }", "function processAudio(e) {\n let buffer = e.inputBuffer.getChannelData(0);\n let out = e.outputBuffer.getChannelData(0);\n let amp = 0;\n\n // Iterate through buffer to get the max amplitude for this frame\n for (let i = 0; i < buffer.length; i++) {\n let loud = Math.abs(buffer[i]);\n if (loud > amp) {\n amp = loud;\n }\n // Write input samples to output unchanged\n out[i] = buffer[i];\n }\n\n // Calc the amp : x,y blur effect and apply it\n amp = amp * 2 + ',0';\n blurFilter.setAttribute(\"stdDeviation\", amp);\n}", "function EWMA(halfLife){// Larger values of alpha expire historical data more slowly.\nthis.alpha_=halfLife?Math.exp(Math.log(0.5)/halfLife):0;this.estimate_=0;this.totalWeight_=0;}", "function moving_average(data, n) {\n\tlet avg=[data[0]]\t\n\tfor(var i = 2; i <= data.length; i++) {\n\t\tif(i < n) {\n\t\t\tavg.push(simple_average(data.slice(0, i)))\n\t\t} else {\n\t\t\tavg.push(simple_average(data.slice(i-n, i)))\n\t\t}\n\t}\n\treturn avg\n}", "get mean(): number {\n if(this.alpha > 1) {\n return this.alpha * this.xm / (this.alpha - 1);\n }\n return Infinity;\n }", "average() {\n return this.buffer.reduce((accum, current) => accum + current) / this.size;\n }", "function getAverageVolume(array) {\n var values = 0;\n var average;\n var length = array.length;\n\n // get all the frequency amplitudes\n for (var i = 0; i < length; i++) {\n values += array[i];\n }\n average = values / length;\n return average;\n }", "function AMAauto(empresa,time,rendimiento){\n Exitosas = 0;\n indicador = 'Adaptative Moving Average'+'| periodo:'+time;\n\n\n\n listadoPrecios = empresa['precios'];\n listadoPrecios.reverse();\n\n contadorDias = 0;\n enOperacion = false;\n primerPrecio = 0;\n precioObjetivo=0;\n listadoPrecios.forEach(function (value,index)\n {\n contadorDias++;\n if(contadorDias > time){contadorDias = 1;enOperacion= false}\n if(contadorDias == 1){\n if(listadoPrecios[index+(time-1)] !== undefined){\n if(listadoPrecios[(index-1)-(time+time)] !== undefined){\n ama = AMA(index-1, time);\n if(ama > AMA((index-1)-time, time) && ((value['open']>ama && value['close']<ama) || (value['open']<ama && value['close']>ama) || (value['open']>ama && value['close']>ama && value['lower']<ama) || (value['open']>ama && value['close']>ama && value['lower']>ama)) ){\n enOperacion = true;\n primerPrecio = value['open'];\n precioObjetivo = primerPrecio * (1 + (rendimiento/100));\n\n }\n\n }\n\n }\n }\n if(enOperacion && value['higher'] >= precioObjetivo){\n\n Exitosas++;\n enOperacion= false;\n\n }\n function AMA(amaIndex, periodo){\n // calcula ER efitience ratio\n\n let cambio = Math.abs(listadoPrecios[amaIndex]['close'] - listadoPrecios[amaIndex-periodo]['close']);\n let volatilidad = 0;\n for(let i = amaIndex; i > amaIndex-periodo; i--){\n volatilidad = volatilidad + Math.abs(listadoPrecios[i]['close'] - listadoPrecios[i-1]['close']);\n }\n let ER = cambio/volatilidad;\n\n // calcula SC constante de suavizado\n let SC = Math.pow(ER * (2/(2+1) - 2/(30+1)) + 2/(30+1),2);\n\n // calcula AMA adaptative moving average\n let insideAMA=0;\n //index-1\n if(amaIndex == (index-1)-periodo){\n sma = SMA(amaIndex,periodo);\n insideAMA = sma + SC * (listadoPrecios[amaIndex]['close'] - sma);\n }\n else{\n backAma = AMA(amaIndex-1, periodo)\n insideAMA = backAma + SC * (listadoPrecios[amaIndex]['close'] - backAma);\n }\n\n return insideAMA;\n }\n\n function SMA(smaIndex, periodo){\n var insideSMA = 0;\n\n for (let i = smaIndex-(periodo-1); i <= smaIndex ; i++){\n insideSMA = insideSMA + listadoPrecios[i]['close'];\n }\n insideSMA = insideSMA/periodo;\n\n return insideSMA;\n }\n });\n\n\n\n\n\n\n return {predicExitosas: Exitosas, indicador: indicador, parametros: [time]};\n}", "function MovingAverage(maxSize) {\n\tlet array = []\n\n\tthis.push = function(element) {\n\t\tif (array.length >= maxSize) {\n\t\t\tarray.shift()\n\t\t}\n\t\tarray.push(element)\n\t}\n\n\tthis.average = function() {\n\t\treturn Util.average(array)\n\t}\n\n\tthis.mode = function() {\n\t\treturn Util.mode(array)\n\t}\t\n}", "mean() {\n return Utils.mean(this.series)\n }", "function movingAverage(array, period) {\n\n if (period % 2 === 0) throw Error('Moving average period should be odd');\n\n const shift = (period - 1) / 2;\n const movingAverage = array.map( (p, i, arr) => {\n const low = Math.max(i - shift, 0);\n const upp = Math.min(i + shift + 1, array.length);\n return arr.slice(low, upp).reduce((a,b) => a + b, 0) / (upp - low);\n })\n\n return movingAverage;\n\n}", "get noiseSpread() {}", "function getAverageVolume(array) {\n var values = 0;\n var average;\n\n var length = array.length;\n\n // get all the frequency amplitudes\n for (var i = 0; i < length; i++) {\n values += array[i];\n }\n\n average = values / length;\n return average;\n}", "function avgAmp(dataIndex, rangeL, rangeR, n) {\n var sum = 0.0;\n for (var i=rangeL; i<=rangeR; i++)\n sum += Math.abs(data[dataIndex + i]);\n return sum/n;\n }", "applyPreEmph(curSample, prevSample) {\n\t\treturn curSample - this.preEmphasisFilterFactor * prevSample;\n\t}", "avg() {\n\t\tlet argArr = this.args;\n\t\tfunction avgSet(s,c,f) {\n\t\t\taverage: s;\n\t\t\tceiling: c;\n\t\t\tfloor: f;\n\t\t}\n\t\tlet evaluate = function() {\n\t\t\tlet sum = 0;\n\t\t\tfor(let c=0;c<argArr.length;c++) {\n\t\t\t\tsum += argArr[c];\n\t\t\t}\n\t\t\tsum /= argArr.length\n\t\t\tlet ceil = Math.ceil(sum)\n\t\t\tlet floor = Math.floor(sum)\n\n\t\t\tlet avg = avgSet(sum,ceil,floor); //{average:sum,ceiling:ceil,floor:floor}\n\t\t\treturn avg;\n\t\t};\n\t\t// console.log(evaluate())\n\t\tthis.record(`Evaluated avg: ${evaluate().average} | fxnCount: ${this.fxnCount} | avgCount: ${this.avgCount}`,evaluate());\n\t}", "avgByElement(measure, number) {\n var avg;\n var subscription = this.extract(measure)\n .bufferCount(number)\n .subscribe(function (x) {\n avg = x.reduce(function (tot, elem) {\n return tot + elem;\n }) / number;\n console.log(avg);\n });\n return avg;\n }", "function ampwave(wave,a){\r\n\tvar wl = wave[0].length, starttime = Date.now();\r\n\tfor(var i=0; i<wl; i++){ wave[0][i] *= a; wave[1][i] *= a; }\r\n\tlog('ampwave() took '+(Date.now()-starttime)+' ms.');\r\n\treturn wave;\r\n}// End of ampwave()", "function xa(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=void 0!==i?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n}", "function EWMA(halfLife) {\n ewma__classCallCheck(this, EWMA);\n\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = 0;\n this.totalWeight_ = 0;\n }", "function EWMA(halfLife) {\n ewma__classCallCheck(this, EWMA);\n\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = 0;\n this.totalWeight_ = 0;\n }", "function Effect(){\n\n\tthis.input = audioCtx.createGain();\n\tthis.filterFade = new FilterFade(0);\n\tthis.output = audioCtx.createGain();\n\tthis.startArray = [];\n\n\tthis.input.connect(this.filterFade.input);\n\n}", "function MovingAverage(lookback) {\n var __arguments = new Array(arguments.length);\n for (var __argumentIndex = 0; __argumentIndex < __arguments.length; ++__argumentIndex) {\n __arguments[__argumentIndex] = arguments[__argumentIndex];\n }\n if (__arguments.length == 1) {\n var lookback_1 = __arguments[0];\n //super();\n this.fmliveswitchMovingAverageInit();\n if ((lookback_1 < 1)) {\n throw new fm.liveswitch.Exception(\"Lookback must be a positive integer.\");\n }\n this.setAverage(-1);\n this.__valuesLookback = lookback_1;\n this.__values = new Array(lookback_1);\n for (var i = 0; (i < this.__values.length); i++) {\n this.__values[i] = 0;\n }\n }\n else {\n throw new fm.liveswitch.Exception('Constructor overload does not exist with specified parameter count/type combination.');\n }\n }", "function createEMA(days) {\n EMA = 0;\n EMAarray = [];\n let multiplier;\n let start = stressArray.length - 366;\n console.log(start);\n for (let i = start; i < stressArray.length - 1; i++) {\n if (i === 0) {\n multiplier = 1;\n }\n else {\n multiplier = (1 / 4);\n }\n EMA += (stressArray[i] - EMA) * multiplier;\n EMAarray.push(EMA);\n }\n let index = 366 - days;\n chartEMA = EMAarray.slice(index);\n console.log(chartEMA.length, chartEMA);\n }", "get mean(): number {\n if(this.beta > 1) {\n return this.alpha / (this.beta - 1);\n }\n return Infinity;\n }", "computeAverageSample() {\n const self = this;\n\n if (self._binBounds !== null) {\n const averageSample = [computeAverage(self._timestamps)];\n\n // compute the average of all the values within each channel\n for (let i = 0; i < self._channelValues.length; i++) {\n averageSample[i + 1] = computeAverage(self._channelValues[i]);\n }\n\n return averageSample;\n }\n\n return null;\n }", "function elastic(amplitude, period) {\n if ( amplitude === void 0 ) amplitude = 1;\n if ( period === void 0 ) period = .5;\n\n var a = minMax(amplitude, 1, 10);\n var p = minMax(period, .1, 2);\n return function (t) {\n return (t === 0 || t === 1) ? t : \n -a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p);\n }\n}", "function EstimateAmplitude(noiseStddev)\n {\n var distanceEstimatorX = new MaximumDistanceEstimator();\n var distanceEstimatorY = new MaximumDistanceEstimator();\n var noiseStddev = noiseStddev;\n\n /**\n * Feed each sampling into this update function.\n */\n this.update = function(\n posX,\n posY)\n {\n distanceEstimatorX.update(posX, noiseStddev);\n distanceEstimatorY.update(posY, noiseStddev);\n }\n\n /**\n * Get most recent maximum amplitude estimate.\n */\n this.amplitude = function()\n {\n return Math.max(\n distanceEstimatorX.velocity(),\n distanceEstimatorY.velocity());\n }\n }", "function elastic(amplitude, period) {\n if ( amplitude === void 0 ) amplitude = 1;\n if ( period === void 0 ) period = .5;\n\n var a = minMax(amplitude, 1, 10);\n var p = minMax(period, .1, 2);\n return function (t) {\n return (t === 0 || t === 1) ? t :\n -a * Math.pow(2, 10 * (t - 1)) * Math.sin((((t - 1) - (p / (Math.PI * 2) * Math.asin(1 / a))) * (Math.PI * 2)) / p);\n }\n}", "readBufferProcessEvent(e) {\n\t\tlet l = e.outputBuffer.getChannelData(0)\n\t\tlet r = e.outputBuffer.getChannelData(1)\n\t\tconst len = e.inputBuffer.length\n\t\tconst half = this._bufferSize >> 1\n\t\tconst sources = this.targets.lightness\n\t\tconst averages = this.buffers.lightness\n\n\t\tfor (let idx = 0; idx < len; idx++) {\n\t\t\tconst t = this._sample / 44100\n\t\t\t\n\t\t\t// Zero before summing\n\t\t\tl[idx] = 0\n\t\t\tr[idx] = 0\n\n\t\t\t// Iterate through all possible tones, summing\n\t\t\tfor (let tone_idx = 0; tone_idx < half; tone_idx++) {\n\t\t\t\tconst tone = Math.sin(t * this._frequencies[tone_idx])\n\t\t\t\t// Smooth (moving average)\n\t\t\t\taverages[tone_idx] = (sources[this._hilbert[tone_idx]] + averages[tone_idx]) / 2\n\t\t\t\taverages[half+tone_idx] = (sources[this._hilbert[half+tone_idx]] + averages[tone_idx]) / 2\n\n\t\t\t\t// TODO: compression\n\t\t\t\tl[idx] += (tone * averages[tone_idx] )/half\n\t\t\t\tr[idx] += (tone * averages[half + tone_idx] )/half\n\t\t\t}\n\n\t\t\t// Decrease dynamic range\n\t\t\t// Technically we should use abs values here because the output range is [-1 1] but\n\t\t\t// this loop is probably expensive enough already and it will function approximately\n\t\t\t// the same\n\t\t\tif (l[idx] > this.maxLoudness || r[idx] > this.maxLoudness)\n\t\t\t\tthis.maxLoudness += 1e-5\n\n\t\t\tif (this.maxLoudness > 0 && this.compression > 0) {\n\t\t\t\tl[idx] = l[idx] / (this.maxLoudness + (1-this.maxLoudness)*(1-this.compression))\n\t\t\t\tr[idx] = r[idx] / (this.maxLoudness + (1-this.maxLoudness)*(1-this.compression))\n\t\t\t}\n\n\t\t\t// Reduce to effect maximum compression\n\t\t\tthis.maxLoudness -= 1e-6 // will reset back to zero after 10 seconds\n\n\t\t\tthis._sample++\n\t\t}\n\n\t\tconst hues = this.targets.hue\n\t\tconst saturations = this.targets.saturation\n\n\t\tlet average_hueL = 0,\n\t\t average_hueR = 0,\n\t\t count_hueL = 0,\n\t\t\tcount_hueR = 0,\n\t\t\taverage_satL = 0,\n\t\t\taverage_satR = 0\n\t\t// Only look at the central quarter of the image for colour detection\n\t\tfor (let idx = 0; idx < half/4; idx++) {\n\t\t\taverage_satL += saturations[ idx+half/4+half/8]\n\t\t\taverage_satR += saturations[half + idx+half/4+half/8]\n\t\t\tif (!Number.isNaN(hues[idx+half/4+half/8])) {\n\t\t\t\taverage_hueL += hues[idx+half/4+half/8]\n\t\t\t\tcount_hueL++\n\t\t\t}\n\t\t\tif (!Number.isNaN(hues[half+idx+half/4+half/8])) {\n\t\t\t\taverage_hueR += hues[half+idx+half/4+half/8]\n\t\t\t\tcount_hueR++\n\t\t\t}\n\t\t}\n\n\t\t// Modulate frequency for hue\n\t\tif (count_hueL > 0) { \n\t\t\taverage_hueL = average_hueL/count_hueL\n\t\t\tthis.sawtoothNodeL.frequency.value = average_hueL * 1320 + 440\n\t\t}\n\n\t\tif (count_hueR > 0) { \n\t\t\taverage_hueR = average_hueR/count_hueR\n\t\t\tthis.sawtoothNodeR.frequency.value = average_hueR * 1320 + 440\n\t\t}\n\n\t\t// And distortion and amplitude for saturation\n\t\tthis.distortionL.distortion = this.scaleL.max = (average_satL/(half/4)) * this.fmVolume\n\t\tthis.distortionR.distortion = this.scaleR.max = (average_satR/(half/4)) * this.fmVolume\n\t}", "function normalizeEm (z) {return z / (keyFrame - 1) / n;}", "avg() {}", "function nextGaussian(mean, stdDev) {\n var x1 = 0;\n var x2 = 0;\n var y1 = 0;\n var z = 0;\n if (usePrevious) {\n usePrevious = false;\n return mean + y2 * stdDev;\n }\n usePrevious = true;\n do {\n x1 = 2 * Math.random() - 1;\n x2 = 2 * Math.random() - 1;\n z = (x1 * x1) + (x2 * x2);\n } while (z >= 1);\n z = Math.sqrt((-2 * Math.log(z)) / z);\n y1 = x1 * z;\n y2 = x2 * z;\n return mean + y1 * stdDev;\n }", "function computeSimpleMovingAverage(dataPoints) {\n\tif (dataPoints.length == 0) {\n\t\treturn 0;\n\t}\n\telse {\n\t\t// Computes the SMA for the current data points\n\t\tvar sum = 0;\n\t\t// faster implementation than doing a for loop\n\t\tvar i = dataPoints.length;\n\t\twhile (i--) {\n\t\t\tsum += dataPoints[i];\n\t\t}\n\t\treturn sum / dataPoints.length;\n\t}\n}", "average() {\n\n }", "function refreshEMA(reset) {\n\tif (reset) {\n\t\tlog(\"Reset EMA data (EMA/Thresholds/Interval has changed)...\");\n\t\tindicators = [];\n\t}\n\n\tif (priceArray.length == 0) {\n\t\tlog(\"Error: priceArray not loaded!\");\n\t} else if (priceArray.length > MaxSamplesToKeep) {\n\t\t\n\t\t// We have more ticker points than we intended to keep, so remove the oldest ones we don't need.\n\t\tvar skip = priceArray.length - MaxSamplesToKeep;\n\t\tpriceArray = priceArray.slice(skip);\n\t\ttimeInMinutes = timeInMinutes.slice(skip);\n\t\tindicators = indicators.slice(skip);\n\t}\n\n\t// Update the EMAs given the new price data.\n\tupdateEMAs(indicators);\n\t\n\tvar price = priceArray[priceArray.length-1];\n\n\t// The difference between EMA differences between ticks.\n\tvar emaDiff = indicators[indicators.length - 1].emaDiff;\n\tvar previousEmaDiff = (indicators.length <= numberOfEMAs) ? 0 : indicators[indicators.length - (1 + numberOfEMAs)].emaDiff;\n\n\t// The difference between PPO differences between ticks.\n\tvar ppoDiff = indicators[indicators.length - 1].ppoDiff;\n\tvar previousPpoDiff = (indicators.length <= numberOfEMAs) ? 0 : indicators[indicators.length - (1 + numberOfEMAs)].ppoDiff;\n\n\t// Amount the PPO line has moved vertically between ticks (we call it \"speed\").\n\tvar ppo = indicators[indicators.length - 1].ppo;\n\tvar previousPpo = (indicators.length <= numberOfEMAs) ? 0 : indicators[indicators.length - (1 + numberOfEMAs)].ppo;\n\tvar ppoSpeed = Math.abs(previousPpo - ppo);\n\t\n\t// Last minute recorded vs. the current time.\n\tvar lastMinuteFetch = timeInMinutes[timeInMinutes.length - 1];\n\tvar minuteNow = parseInt((new Date()).getTime()/60000);\n\n\t// If we're not yet in the present, disable trading!\n\tif (lastMinuteFetch < minuteNow - adjustedTradingIntervalMinutes) {\n\t\ttradingEnabled = 0;\n\t} else {\n\t\tchrome.browserAction.setBadgeText( { text: Math.abs(emaDiff).toFixed(2), } );\n\t}\n\t\n\t// Calculate the number of time-shifted EMAs that have crossed positively (BuyConf) or negatively (SellConf).\n\tif(indicators.length <= numberOfEMAs && MinSellThreshold >= 0) emaSellConfirmations++;\n\tif(indicators.length <= numberOfEMAs && MinBuyThreshold < 0) emaBuyConfirmations++;\n\t\n\tif(emaDiff > MinBuyThreshold && previousEmaDiff <= MinBuyThreshold) {\n\t\temaBuyConfirmations++;\n\t\tif(emaBuyConfirmations >= numberOfEMAs) ppoBought = false;\n\t} else if(emaDiff <= MinBuyThreshold && previousEmaDiff > MinBuyThreshold) {\n\t\temaBuyConfirmations--;\n\t}\n\n\tif(emaDiff < MinSellThreshold && previousEmaDiff >= MinSellThreshold) {\n\t\temaSellConfirmations++;\n\t\tif(emaSellConfirmations >= numberOfEMAs) ppoSold = false;\n\t} else if(emaDiff >= MinSellThreshold && previousEmaDiff < MinSellThreshold) {\n\t\temaSellConfirmations--;\n\t}\n\t\n\t// Get the date for logging purposes.\n\tvar d = new Date(lastMinuteFetch*60*1000);\n\tvar date = d.getFullYear() + \" \" + d.getDate() + \"/\" + (d.getMonth() + 1) + \" \" + padIt(d.getHours()) + \":\"+padIt(d.getMinutes());\n\t\n\t// If we're waiting until we can buy again after a SELL case 3...\n\tif(sellWatching) {\n\t\tif(ppo < previousPpo && (ppoSpeed > MinBuyReboundSpeed && previousPpo != 0.0) && !noEMABuy && state.indexOf(\"BUY\") == -1)\n\t\t\ttradeBlockCounter = -1;\n\t\t\n\t\tif(tradeBlockCounter <= 0)\n\t\t\tsellWatching = false;\n\t}\n\n\t//If we're waiting until we can sell again after a BUY case 3...\n\tif(tradeBlockCounter == 0 && buyWatching) {\n\n\t\tif(price <= tradeBlockBuyPrice) {\n\t\t\tlog(date + \": Price $\" + round(price, 2) + \" lower than buy-in price $\" + round(tradeBlockBuyPrice, 2) + \". Sell now (unless another buy triggers).\");\n\t\t\ttradeBlockBuyPrice = 0.0;\n\t\t} else if(price > tradeBlockBuyPrice) {\n\t\t\tlog(date + \": Price $\" + round(price, 2) + \" higher than buy-in price $\" + round(tradeBlockBuyPrice, 2) + \". Sell in 1 sample interval (unless another buy triggers).\");\n\t\t\t\n\t\t\ttradeBlockCounter = numberOfEMAs;\n\t\t\ttradeBlockBuyPrice = 0.0;\n\t\t}\n\t\t\n\t\tbuyWatching = false;\n\t}\n\t\n\t// Reset the trade block counter if we're still in the same rapid fall or rise situation.\n\t// This means that apparently the rebound took a little longer than expected to materialize,\n\t// and we should wait some more. \n\tif(tradeBlockCounter > 0 && (\n\t\t\t(ppo < previousPpo && (ppoSpeed > MinBuyReboundSpeed && previousPpo != 0.0) && !noEMABuy) || \n\t\t\t(ppo > previousPpo && (ppoSpeed > MinSellReboundSpeed && previousPpo != 0.0) && !noEMASell))) {\n\t\ttradeBlockCounter = numberOfEMAs;\n\t}\n\t\n\t// If we're not blocked after a dip/peak buy/sell...\n\tif(tradeBlockCounter <= 0) {\n\n\t\t// If EMAs have crossed, reset the buy/sell blocks that may have resulted from a case 2 or 2.2 BUY or SELL.\n\t\tif(previousEmaDiff < 0 && emaDiff >= 0) {\n\t\t\tnoEMASell = false;\n\t\t} else if(previousEmaDiff >= 0 && emaDiff < 0) {\n\t\t\tnoEMABuy = false;\n\t\t}\n\t\t\n\t\t\n\t\t/*************************\n\t\t * TRADING DECISION LOGIC\n\t\t *************************/\n\t\t\n\t\t// BUY case 3: Buy on unsustainable (PPO) fall, as a rebound is expected.\n\t\tif(ppo < previousPpo && (ppoSpeed > MinBuyReboundSpeed && previousPpo != 0.0) && !noEMABuy) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[0, 128, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>BUY signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. Unsustainable PPO fall (\" + round(ppoSpeed, 3) + \"). Rebound expected.\");\n\t\t\tppoSold = false;\n\t\t\tnoEMASell = false;\n\t\t\t\n\t\t\tbuyBTC(price);\n\t\t\t\n\t\t\t// Keep track of buy-in price.\n\t\t\ttradeBlockBuyPrice = price;\n\t\t\tbuyWatching = true;\n\n\t\t\ttradeBlockCounter = numberOfEMAs;\n\t\t\tstate = \"BUY3\";\n\t\t}\n\n\t\t// SELL case 3: Sell on unsustainable (PPO) rise, as a rebound is expected.\n\t\telse if(ppo > previousPpo && (ppoSpeed > MinSellReboundSpeed && previousPpo != 0.0) && !noEMASell) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[128, 0, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>SELL signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. Unsustainable PPO rise (\" + round(ppoSpeed, 3) + \"). Rebound expected.\");\n\t\t\tppoBought = false;\n\t\t\tnoEMABuy = false;\n\t\t\t\n\t\t\tsellBTC(price);\n\t\t\t\n\t\t\tsellWatching = true;\n\t\t\t\n\t\t\ttradeBlockCounter = numberOfEMAs;\n\t\t\tstate = \"SELL3\";\n\t\t}\n\n\t\t// BUY case 1: Standard EMA cross past buy threshold, provided this buy is currently allowed (i.e. if sold due to PPO cross, prevent this buy from executing immediately after).\n\t\telse if (emaDiff >= MinBuyThreshold && !noEMABuy && emaBuyConfirmations >= minEMAConfirmations && state.indexOf(\"BUY\") == -1) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[0, 128, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>BUY signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. EMA difference (\" + round(emaDiff, 3) + \") exceeded EMA difference threshold (\" + MinBuyThreshold + \").\");\n\t\t\tppoSold = false;\n\n\t\t\tbuyBTC(price);\n\n\t\t\tstate = \"BUY1\";\n\t\t}\n\n\t\t// SELL case 1: Standard EMA cross past sell threshold, provided this sell is currently allowed (i.e. if bought due to PPO cross, prevent this sell from executing immediately after).\n\t\telse if (emaDiff <= MinSellThreshold && !noEMASell && emaSellConfirmations >= minEMAConfirmations && state.indexOf(\"SELL\") == -1) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[128, 0, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>SELL signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. EMA difference (\" + round(emaDiff, 3) + \") exceeded EMA difference threshold (\" + MinSellThreshold + \").\");\n\t\t\tppoBought = false;\n\t\t\t\n\t\t\tsellBTC(price);\n\n\t\t\tstate = \"SELL1\";\n\t\t}\n\n\t\t// BUY case 2: A positive PPO cross faster than the minimum crossing speed.\n\t\telse if (previousPpoDiff != ppoDiff && (previousPpoDiff <= 0 && ppoDiff > 0) && ppoSpeed > MinBuyCrossSpeed && state.indexOf(\"BUY\") == -1) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[0, 128, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>BUY signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. PPO crossed at speed \" + round(ppoSpeed, 3) + \", which is greater than PPO cross speed threshold \" + MinBuyCrossSpeed + \".\");\n\t\t\t\n\t\t\tif(emaDiff <= 0) noEMASell = true; // Prevent selling the very next tick (EMA might still be in sell position)\n\t\t\tppoBought = true;\t// Flag for potential SELL case 2.5 trigger\n\t\t\tppoSold = false;\n\t\t\t\n\t\t\tbuyBTC(price);\n\n\t\t\tstate = \"BUY2\";\n\t\t}\n\t\t\n\t\t// BUY case 2.2: A PPO rise faster than the minimum rising speed (i.e. exceeding MinBuySpeed). Only triggers if a positive cross has already occurred.\n\t\telse if(previousPpoDiff != ppoDiff && previousPpo < ppo && (previousPpoDiff > 0 && ppoDiff > 0) && ppoSpeed > MinBuySpeed && state.indexOf(\"BUY\") == -1) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[0, 128, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>BUY signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. PPO rose at speed \" + round(ppoSpeed, 3) + \", which is greater than non-cross speed threshold \" + MinBuySpeed + \".\");\n\t\t\t\n\t\t\tif(emaDiff <= 0) noEMASell = true;\t// Prevent selling the very next tick (EMA might still be in sell position)\n\t\t\tppoBought = true;\t// Flag for potential SELL case 2.5 trigger\n\t\t\tppoSold = false;\n\t\t\t\n\t\t\tbuyBTC(price);\n\n\t\t\tstate = \"BUY2.2\";\n\t\t}\n\n\t\t// SELL case 2.5: A negative PPO cross after a positive PPO cross fast enough to trigger a buy, while EMA is still below its buy threshold. This suggests a misprediction of an uptrend, so sell to cut losses.\n\t\telse if (previousPpoDiff != ppoDiff && (previousPpoDiff > 0 && ppoDiff <= 0) && ppoBought && emaDiff < MinBuyThreshold && state.indexOf(\"SELL\") == -1) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[128, 0, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>SELL signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. Negative PPO cross after a PPO-based buy while EMA difference (\" + round(emaDiff, 3) + \") is still below its buy threshold of \" + MinBuyThreshold + \".\");\n\t\t\t\n\t\t\tppoBought = false;\n\n\t\t\tsellBTC(price);\n\n\t\t\tstate = \"SELL2.5\";\n\t\t}\n\n\t\t// SELL case 2: A negative PPO cross faster than the minimum crossing speed.\n\t\telse if (previousPpoDiff != ppoDiff && (previousPpoDiff > 0 && ppoDiff <= 0) && ppoSpeed > MinSellCrossSpeed && state.indexOf(\"SELL\") == -1) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[128, 0, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>SELL signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. PPO crossed at speed \" + round(ppoSpeed, 3) + \", which is greater than PPO cross speed threshold \" + MinSellCrossSpeed + \".\");\n\t\t\t\n\t\t\tif(emaDiff >= 0) noEMABuy = true;\n\t\t\tppoSold = true;\n\t\t\tppoBought = false;\n\n\t\t\tsellBTC(price);\n\n\t\t\tstate = \"SELL2\";\n\t\t}\n\t\t\n\t\t// SELL case 2.2: A PPO fall faster than the minimum falling speed (i.e. exceeding MinSellSpeed). Only triggers if a positive cross has already occurred.\n\t\telse if(previousPpoDiff != ppoDiff && ppo < previousPpo && (previousPpoDiff <= 0 && ppoDiff <= 0) && ppoSpeed > MinSellSpeed && state.indexOf(\"SELL\") == -1) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[128, 0, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>SELL signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. PPO fell at speed \" + round(ppoSpeed, 3) + \", which is greater than non-cross speed threshold \" + MinSellSpeed + \".\");\n\t\t\t\n\t\t\tif(emaDiff >= 0) noEMABuy = true;\n\t\t\tppoSold = true;\n\t\t\tppoBought = false;\n\t\t\t\n\t\t\tsellBTC(price);\n\n\t\t\tstate = \"SELL2.2\";\n\t\t}\n\n\t\t// BUY case 2.5: A positive PPO cross after a negative PPO cross fast enough to trigger a sell, while EMA is still above its sell threshold. This suggests a misprediction of a downtrend, so buy back in.\n\t\telse if (previousPpoDiff != ppoDiff && (previousPpoDiff <= 0 && ppoDiff > 0) && ppoSold && emaDiff > MinSellThreshold && state.indexOf(\"BUY\") == -1) {\n\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[0, 128, 0, 200]});\n\t\t\tlog(\"<span style='color: #000000;'>BUY signal triggered on \" + date + \" at $\" + round(price, 2) + \"</span>. Positive PPO cross after a PPO-based sell while EMA difference (\" + round(emaDiff, 3) + \") is still above its sell threshold of \" + MinSellThreshold + \".\");\n\t\t\t\n\t\t\tppoSold = false;\n\n\t\t\tbuyBTC(price);\n\n\t\t\tstate = \"BUY2.5\";\n\t\t}\n\n\t\telse {\n\t\t\t// If some but not all time-shifted EMAs have crossed...\n\t\t\tif (emaDiff > 0) \tchrome.browserAction.setBadgeBackgroundColor({color:[10, 100, 10, 100]});\n\t\t\telse \t\t\t\tchrome.browserAction.setBadgeBackgroundColor({color:[100, 10, 10, 100]});\n\t\t}\n\t}\n\t\n\ttradeBlockCounter--;\n}", "function stream_waves(n, m) {\n\t\t\t return d3.range(n).map(function(i) {\n\t\t\t\treturn d3.range(m).map(function(j) {\n\t\t\t\t\tvar x = 20 * j / m - i / 3;\n\t\t\t\t\treturn 2 * x * Math.exp(-.5 * x);\n\t\t\t\t }).map(stream_index);\n\t\t\t\t});\n\t\t\t}", "recordMSE() {\n const mse = this.features.matMul(this.weights)\n .sub(this.labels)\n .pow(2)\n .sum()\n .div(this.features.shape[0])\n .dataSync() // only single value not tensor\n // console.log('mse : ', mse[0]);\n this.mseHistory.unshift(mse[0]); // latest entry on to top\n }", "set noiseSpread(value) {}", "calculateLoudness(buffer) {\n\n // first call or after resetMemory\n if (this.copybuffer == undefined) {\n // how long should the copybuffer be at least? \n // --> at least maxT should fit in and length shall be an integer fraction of buffer length\n let length = Math.floor(this.sampleRate * this.loudnessprops.maxT / buffer.length + 1) * buffer.length;\n this.copybuffer = new CircularAudioBuffer(context, this.nChannels, length, this.sampleRate);\n }\n\n //accumulate buffer to previous call\n this.copybuffer.concat(buffer);\n\n // must be gt nSamplesPerInterval\n // or: wait at least one interval time T to be able to calculate loudness\n if (this.copybuffer.getLength() < this.nSamplesPerInterval) {\n console.log('buffer too small ... have to eat more data');\n return NaN;\n }\n\n // get array of meansquares from buffer of overlapping intervals\n let meanSquares = this.getBufferMeanSquares(this.copybuffer, this.nSamplesPerInterval, this.nStepsize);\n\n // first stage filter\n this.filterBlocks(meanSquares, this.gamma_a);\n\n // second stage filter\n let gamma_r = 0.;\n for (let chIdx = 0; chIdx < this.nChannels; chIdx++) {\n let mean = 0.;\n for (let idx = 0; idx < meanSquares[chIdx].length; idx++) {\n mean += meanSquares[chIdx][idx];\n }\n mean /= meanSquares[chIdx].length;\n gamma_r += (this.channelWeight[chIdx] * mean);\n }\n gamma_r = -0.691 + 10.0 * Math.log10(gamma_r) - 10.;\n\n this.filterBlocks(meanSquares, gamma_r);\n\n // gated loudness from filtered blocks\n let gatedLoudness = 0.;\n for (let chIdx = 0; chIdx < this.nChannels; chIdx++) {\n let mean = 0.;\n for (let idx = 0; idx < meanSquares[chIdx].length; idx++) {\n mean += meanSquares[chIdx][idx];\n }\n mean /= meanSquares[chIdx].length;\n\n gatedLoudness += (this.channelWeight[chIdx] * mean);\n }\n gatedLoudness = -0.691 + 10.0 * Math.log10(gatedLoudness);\n\n //console.log(this.id, '- gatedLoudness:', gatedLoudness);\n\n return gatedLoudness;\n }", "averaging(val) {\n this._averaging = val;\n return this;\n }", "receive(isample) {\n let lastr = this._lastr;\n let lasti = this._lasti;\n\n let space = this._sf.updatex(isample);\n let mark = this._mf.updatex(isample);\n let r = space.r + mark.r;\n let i = space.i + mark.i;\n let x = r * lastr - i * lasti;\n let y = r * lasti + i * lastr;\n this._lastr = r; // save the conjugate\n this._lasti = -i;\n let angle = Math.atan2(y, x); // arg\n let comp = (angle > 0) ? -10.0 : 10.0;\n let sig = this._dataFilter.update(comp);\n // console.log('sig:' + sig + ' comp:' + comp)\n\n this.scopeOut(sig);\n\n let bit = this._bit;\n\n // trace('sig:' + sig)\n if (sig > this._hiHys) {\n bit = false;\n } else if (sig < this._loHys) {\n bit = true;\n }\n\n bit = bit !== this._inverted; // user-settable\n\n this.processBit(bit);\n this._bit = bit;\n }", "function applyFilters(params, samples) {\n var fltp = 0.0;\n var fltdp = 0.0;\n var fltw = Math.pow(params.lpf_freq, 3.0) * 0.1;\n var fltw_d = 1.0 + params.lpf_ramp * 0.0001;\n var fltdmp =\n 5.0 / (1.0 + Math.pow(params.lpf_resonance, 2.0) * 20.0) * (0.01 + fltw);\n if (fltdmp > 0.8) fltdmp = 0.8;\n var flthp = Math.pow(params.hpf_freq, 2.0) * 0.1; // function of i and flthd\n var flthd = Math.pow(1.0 + params.hpf_ramp * 0.0003, 1 / SUPERSAMPLES); // constant\n\n var len = samples.length;\n var out = new Float64Array(len);\n var y_out = 0.0;\n for (var i = 0; i < len; i++) {\n var y = samples[i];\n\n // Low-pass filter\n var pp = fltp;\n fltw *= fltw_d;\n if (fltw < 0.0) fltw = 0.0;\n if (fltw > 0.1) fltw = 0.1;\n if (params.lpf_freq != 1.0) {\n fltdp += (y - fltp) * fltw;\n fltdp -= fltdp * fltdmp;\n } else {\n fltp = y;\n fltdp = 0.0;\n }\n fltp += fltdp;\n\n // High-pass filter\n if (flthd !== 1.0) {\n flthp *= flthd;\n if (flthp < 0.00001) flthp = 0.00001;\n if (flthp > 0.1) flthp = 0.1;\n }\n y_out += fltp - pp;\n y_out -= y_out * flthp;\n\n out[i] = y_out;\n }\n return out;\n}", "function _calcAvgAmps() {\n\n // compute amplitude by averaging over n values in the range [rangeL, rangeR]\n function avgAmp(dataIndex, rangeL, rangeR, n) {\n var sum = 0.0;\n for (var i=rangeL; i<=rangeR; i++)\n sum += Math.abs(data[dataIndex + i]);\n return sum/n;\n }\n\n var totalWidth = this.waveContainer.clientWidth,\n data = this._params.data,\n ratio = totalWidth !== data.length ? data.length/totalWidth : 1,\n totalBarWidth = this._params.barWidth + this._params.barGap,\n rangeR = (totalBarWidth - 1)/2,\n rangeL = -~~rangeR,\n incr = totalBarWidth*ratio,\n bd = { amps: [], x: [] };\n rangeR = Math.round(rangeR);\n this._totalBarWidth = totalBarWidth;\n\n bd.amps.push(avgAmp(0, 0, rangeR, totalBarWidth));\n bd.x.push(0);\n var i, j;\n for (i=totalBarWidth, j=incr; j+rangeR<data.length; i+=totalBarWidth, j+=incr) {\n bd.amps.push(avgAmp(~~j, rangeL, rangeR, totalBarWidth));\n bd.x.push(i);\n }\n // see if we can squeeze in one more bar\n j = ~~j;\n rangeR = -(j - data.length + 1);\n if (i <= totalWidth - totalBarWidth && rangeR > rangeL) {\n bd.amps.push(avgAmp(j, rangeL, rangeR, rangeR - rangeL));\n bd.x.push(i);\n }\n bd.norm = 1/Math.max.apply(Math, bd.amps);\n\n return bd;\n\n /* nrOfBars = ~~((data.length + this._params.barGap)/(totalBarWidth*ratio)) + 1 */\n }", "function getAudioValues(array) {\n var values = 0;\n var average;\n var length = array.length;\n\n for (var i = 0; i < length; i++) {\n values += array[i];\n }\n average = values / length;\n\n return average;\n}", "function avg() {\n\t var clean = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : filter.ignoreMissing;\n\t\n\t return function (values) {\n\t var cleanValues = clean(values);\n\t if (!cleanValues) return null;\n\t var sum = _underscore2.default.reduce(cleanValues, function (a, b) {\n\t return a + b;\n\t }, 0);\n\t return sum / cleanValues.length;\n\t };\n\t}", "function karaoke(evt) {\n let inputL = evt.inputBuffer.getChannelData(0),\n inputR = evt.inputBuffer.getChannelData(1),\n output = evt.outputBuffer.getChannelData(0),\n len = inputL.length,\n i = 0;\n for (; i < len; i++) {\n output[i] = inputL[i] - inputR[i];\n }\n}", "function applyArpeggio(params, periodSamples) {\n var len = periodSamples.length;\n var artime = Math.floor(Math.pow(1.0 - params.arp_speed, 2.0) * 20000 + 32);\n if (params.arp_mod === 0.0 || artime >= len) {\n // No arpeggio. The algorithm below will produce an exact copy\n // of the input. Don't bother.\n return periodSamples;\n }\n\n var arp_mod = (params.arp_mod >= 0.0)\n ? 1.0 - Math.pow(params.arp_mod, 2.0) * 0.9\n : 1.0 + Math.pow(params.arp_mod, 2.0) * 10.0;\n\n var out = new Float64Array(len);\n for (var i = 0; i < artime; i++) {\n out[i] = periodSamples[i];\n }\n for (; i < len; i++) {\n out[i] = periodSamples[i] * arp_mod;\n }\n return out;\n}", "function stream_waves(n, m) {\n return d3.range(n).map(function(i) {\n return d3.range(m).map(function(j) {\n var x = 20 * j / m - i / 3;\n return 2 * x * Math.exp(-.5 * x);\n }).map(stream_index);\n });\n }", "feedforward(inputs){\n let sum = 0;\n \n for (let i = 0; i < this.weights.length; i++) {\n sum += inputs[i] * this.weights[i];\n }\n \n return this.activate(sum);\n \n }", "function handleOrientation(event) { //[1]\r\n \r\n // Getting angle (beta value) from parameter object and store into beta variable\r\n var beta = event.beta;\r\n \r\n \r\n // Step 2: Smoothing sensor data\r\n \r\n // Storing beta values into array \r\n array[i]=beta;\r\n i++;\r\n \r\n // Perform smoothing (averaging) when array is filled\r\n if (i=== array.length)\r\n {\r\n // Resetting average and sum values before calculating average\r\n\t\t\t\tavg = 0;\r\n\t\t\t\tsum = 0;\r\n \r\n //averaging values\r\n for (var j = 0;j<array.length;j++)\r\n {\r\n sum+=array[j];\r\n }\r\n avg=sum/array.length;\r\n \r\n // Reset data array and index counter for next round\r\n i=0;\r\n array.fill(0);\r\n }\r\n \r\n \r\n // Output angle (beta values) and smoothed angle (average beta) to screen\r\n //output=\"beta: \" + beta.toFixed(1) + \"<br />\" + \"i: \" + i + \"<br />\" + \"beta avg: \" + avg.toFixed(1) + \"<br />\";\r\n output=\"beta: \" + beta.toFixed(1) + \"<br />\" + \"beta average: \" + avg.toFixed(0) + \"<br />\";\r\n cameraVideoPage.setHeadsUpDisplayHTML(output);\r\n\r\n }", "function onPeek(e){\n //check for number of samples taken\n if (counter<noOfTakenSamples){\n if (inNoiseMon === true){\n console.log('Taking Sample'); \n xAxisArray.push(e.accel.x);\n yAxisArray.push(e.accel.y);\n zAxisArray.push(e.accel.z);\n console.log('SampleTaken');\n var deadlock = false;\n if (deadlock === false){\n deadlock = true;\n counter++;\n console.log(counter);\n insertCounterElements(); \n deadlock = false;\n }\n else{\n } \n }\n else{\n console.log(\"Stopped Reading\");\n CountScreen.hide();\n Accel.config({\n subscribe: false\n }); \n }\n }\n else{\n //stop events\n Accel.config({\n subscribe: false\n }); \n xAxisArray.sort();\n yAxisArray.sort();\n zAxisArray.sort(); \n insertEndScreenElements();\n //Return to Screen \n } \n \n}", "function smoothInput(current) {\n if (handHistory.length === 0) {\n return current;\n }\n\n var x = 0, y = 0, z = 0;\n var periods = handHistory.length;\n\n for (var i = 0; i < periods; i++) {\n x += current[0] + handHistory[i][0];\n y += current[1] + handHistory[i][1];\n z += current[2] + handHistory[i][2];\n }\n\n periods += 1; // To incldue the current frame\n return {x: x/periods, y: y/periods, z: z/periods};\n}", "function hannWindow(data, counter){\n var dataCopy = new Float32Array(data.length);\n for(var i = 0; i < dataCopy.length; i++){\n var mult = 0.5*(1.0 - Math.cos(2.0*M_PI*i/data.length));\n dataCopy[i] = data[counter]*mult;\n counter++;\n if(counter >= dataCopy.length)\n counter = 0;\n }\n return dataCopy;\n}", "keskiarvo() {\n let sum = this.state.timer20.reduce((previous, current) => current += previous);\n let avg = sum / this.state.timer20.length;\n return avg\n }", "avgByElementOverlapped(measure, number, bufdim) {\n var avg;\n var subscription = this.extract(measure)\n .bufferCount(number, bufdim)\n .subscribe(function (x) {\n avg = x.reduce(function (tot, elem) {\n return tot + elem;\n }) / num;\n console.log(avg);\n });\n return subscription;\n }", "rate(T){\n return -Math.log(this.df(T))/T;\n }", "_AMDF(buf, sampleRate) {\n var SIZE = buf.length; // set SIZE variable equal to buffer length 4096 => half a second\n var MAX_SAMPLES = Math.floor(SIZE / 2); // set MAX_SAMPLES = 4096/2 = 2048\n var best_offset = -1; // initialise best_offset to -1\n var best_correlation = 0; // initialise best_correlation to 0\n var rms = 0; // initialise rms to 0 (rms => root-mean-square)\n var foundGoodCorrelation = false; // initialise foundGoodCorrelation flag to false\n var correlations = new Array(MAX_SAMPLES); // create an array variable called correlations of size MAX_SAMPLES (2048)\n\n for (var i = 0; i < SIZE; i++) {\n var val = buf[i]; // val is equal to the (i)th value in the array\n rms += val * val; // rms is the summation of each value squared\n }\n rms = Math.sqrt(rms / SIZE); // set rms equal to the square root of rms/SIZE (square root of the average)\n if (rms < 0.01) // not enough signal\n return -1;\n\n var lastCorrelation = 1; // initialise lastCorrelation to 1 so that the first check won't be the best correlation\n for (var offset = 52; offset < 160; offset++) { // offset initialised to 52, goes through a for loop from 52 to 160, which will cover the notes that Singphony can render\n var correlation = 0; // re-set correlation to 0 at each offset value\n\n for (var i = 0; i < MAX_SAMPLES; i++) { // cycle through from 0 to 2048\n correlation += Math.abs((buf[i]) - (buf[i + offset])); // step through at each value and subtract the value at the offset from the value in the original buffer and keep adding that to the correlation value\n } // correlation will be a large enough positive float\n\n correlation = 1 - (correlation / MAX_SAMPLES); // set correlation to 1 - correlation/512\n correlations[offset] = correlation; // store it, for the tweaking we need to do below.\n if ((correlation > this.GOOD_ENOUGH_CORRELATION) && (correlation > lastCorrelation)) { // if the correlation value is higher than 0.9 and the previous correlation value\n foundGoodCorrelation = true; // set foundGoodCorrelation flag to true\n if (correlation > best_correlation) { //\n best_correlation = correlation; // update the best_correlation value to the latest correlation value\n best_offset = offset; // update best_offset to the latest offset value\n }\n } else if (foundGoodCorrelation) {\n // short-circuit - we found a good correlation, then a bad one, so we'd just be seeing copies from here.\n return sampleRate / best_offset;\n }\n lastCorrelation = correlation; // set lastCorrelation to latest correlation\n }\n return -1;\n }", "feedforward(inputs) {\n // Sum all values\n let sum = 0;\n for (let i = 0; i < this.weights.length; i++) {\n sum += inputs[i] * this.weights[i];\n }\n // Result is sign of the sum, -1 or 1\n return this.activate(sum);\n }", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}", "function average() { \n\treturn a;\n}", "function setAnalyser () {\n analyser.minDecibels = -90\n analyser.maxDecibels = -10\n analyser.smoothingTimeConstant = 0.85\n }", "onProcess(audioProcessingEvent) {\n\n this.blocked = true;\n this.nCall++;\n\n let inputBuffer = audioProcessingEvent.inputBuffer;\n let outputBuffer = audioProcessingEvent.outputBuffer;\n\n for (let chIdx = 0; chIdx < outputBuffer.numberOfChannels; chIdx++) {\n let inputData = inputBuffer.getChannelData(chIdx);\n let outputData = outputBuffer.getChannelData(chIdx);\n\n if (!this.bypass) {\n this.PreStageFilter[chIdx].process(inputData, outputData);\n } else {\n // just copy\n for (let sample = 0; sample < inputBuffer.length; sample++) {\n outputData[sample] = inputData[sample];\n }\n }\n } // next channel\n\n let time = this.nCall * inputBuffer.length / this.sampleRate;\n let gl = this.calculateLoudness(outputBuffer);\n this.callback(time, gl);\n\n this.blocked = false;\n }", "function ratesAverage(oldarr) {\r\n let mitja = oldarr.reduce((t, e, i, a) => { return t + e.rate / a.length }, 0);\r\n return (Math.round(mitja * 100) / 100);\r\n}", "function amplitude_set_new_volume(e){\n if(document.getElementById('amplitude-volume-meter')){\n var amplitude_volume_slider_width = document.getElementById('amplitude-volume-meter').offsetWidth;\n var amplitude_volume_slider_rect = document.getElementById('amplitude-volume-meter').getBoundingClientRect();\n var amplitude_evt_obj = window.event ? event: e;\n var amplitude_percentage = ((amplitude_evt_obj.layerX - amplitude_volume_slider_rect.left) /amplitude_volume_slider_width);\n\n if(amplitude_percentage > 1){\n amplitude_percentage = 1;\n }\n amplitude_set_volume(amplitude_percentage);\n }\n}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function interpolateArray(data, newSampleRate, oldSampleRate) {\n var fitCount = Math.round(data.length * (newSampleRate / oldSampleRate));\n //var newData = new Array();\n var newData = [];\n //var springFactor = new Number((data.length - 1) / (fitCount - 1));\n var springFactor = Number((data.length - 1) / (fitCount - 1));\n newData[0] = data[0]; // for new allocation\n for (var i = 1; i < fitCount - 1; i++) {\n var tmp = i * springFactor;\n //var before = new Number(Math.floor(tmp)).toFixed();\n //var after = new Number(Math.ceil(tmp)).toFixed();\n var before = Number(Math.floor(tmp)).toFixed();\n var after = Number(Math.ceil(tmp)).toFixed();\n var atPoint = tmp - before;\n newData[i] = linearInterpolate(data[before], data[after], atPoint);\n }\n newData[fitCount - 1] = data[data.length - 1]; // for new allocation\n return newData;\n }", "function calcExponent(mouse) {\n const starting = parseInt((mouse) / gridDimensions.y)\n const extra = 0.1 * (1.6 ** starting)\n return extra\n\n }", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(; /* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(; /* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(; /* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}", "addXfadeInput() {\n const { scenes } = this.creator;\n const filters = [];\n let offset = 0;\n let cid;\n\n forEach(scenes, (scene, index) => {\n const file = scene.getFile();\n this.command.addInput(file);\n\n if (index >= scenes.length - 1) return;\n offset += scene.getNormalDuration();\n const filter = scene.toTransFilter(offset);\n\n cid = cid || `${index}:v`;\n const nid = `${index + 1}:v`;\n filter.inputs = [cid, nid];\n cid = `scene-${index}`;\n filter.outputs = [cid];\n filters.push(filter);\n });\n\n this.command.complexFilter(filters, cid);\n }", "function x1(t) {\r\n return sin(t / frequency) * amplitude + sin(t / frequency) * amplitude;\r\n}", "function doSample(event) {\n var now = Date.now();\n if (lastSampleTimestamp <= 0){\n lastSampleTimestamp = now;\n return; \n }\n var deltaSec = (now - lastSampleTimestamp)/1000;\n\n\n if (sampleRateSamples > 0){\n //Use the first several samples to calculate the device's sample rate\n if (rawSampleRate == null) {\n rawSampleRate = 1 / deltaSec;\n } else {\n rawSampleRate = (rawSampleRate + (1 / deltaSec))/2; //Hz \n }\n sampleRateSamples--;\n\n } else if (sampleRateSamples == 0){\n //We got all our device sample-rate related readings, \n //now calculate the sample-rate related parameters\n sampleIntervalMS = 1000 / rawSampleRate;\n\n var destSampleRate = 2*options.max_stride_freq;\n samplesToSkip = Math.floor(rawSampleRate / destSampleRate) - 1;\n sampleIntervalMS *= (samplesToSkip+1);\n actualSampleRate = 1000/sampleIntervalMS; //Hz\n amplitudeCheckSamples = Math.ceil(actualSampleRate); //look a second back\n\n //store first sample\n var datum = event.accelerationIncludingGravity[options.axis] || 0.5;\n shift(samples, datum);\n\n sampleRateSamples--;\n\n } else {\n //normal measurments\n if (samplesSkipped < samplesToSkip) {\n samplesSkipped++;\n return;\n }\n samplesSkipped = 0;\n\n var datum = event.accelerationIncludingGravity[options.axis] || 0.5;\n\n if (samples[samples.length-1] != 0){ //TODO\n //integrate to get a velocity sample\n var velocity = vSamples[vSamples.length-1] + (datum - samples[samples.length-1])*sampleIntervalMS/1000;\n shift(vSamples, velocity);\n }\n\n var smoothed = datum;//smooth(samples[samples.length-1], datum, options.smooth_alpha);\n shift(samples, smoothed);\n\n var freq = -1;\n switch (options.algorithm) {\n case 'fft':\n freq = getFreqFft(samples);\n break;\n case 'zero-cross':\n freq = getFreqCross(samples);\n break;\n case 'zero-cross-v':\n freq = getFreqCross(vSamples);\n break;\n }\n\n var spm = Math.round(freq*60);\n if (spm > lastSpm) {\n //rising (usually slower than falling)\n spm = Math.round(smooth(lastSpm, spm, options.smooth_alpha_rising));\n } else {\n //falling (it's possible to stop very quickly)\n spm = Math.round(smooth(lastSpm, spm, options.smooth_alpha_falling));\n }\n lastSpm = spm;\n }\n \n lastSampleTimestamp = now;\n }", "function avg(iterArray) {\n var runningSum = 0;\n for (var i = 0; i < iterArray.length; i++) {\n runningSum += iterArray[i];\n }\n\n return runningSum / iterArray.length;\n}", "function stream_waves(n, m) {\n return d3.range(n).map(function (i) {\n return d3.range(m).map(function (j) {\n var x = 20 * j / m - i / 3;\n return 2 * x * Math.exp(-.5 * x);\n }).map(stream_index);\n });\n }", "function __WEBPACK_DEFAULT_EXPORT__(array, step, smooth, f) {\n f = f || (_ => _);\n\n let i = 0, j = 1,\n n = array.length,\n v = new Float64Array(n),\n a = f(array[0]),\n b = a,\n w = a + step,\n x;\n\n for (; j<n; ++j) {\n x = f(array[j]);\n if (x >= w) {\n b = (a + b) / 2;\n for (; i<j; ++i) v[i] = b;\n w = x + step;\n a = x;\n }\n b = x;\n }\n\n b = (a + b) / 2;\n for (; i<j; ++i) v[i] = b;\n\n return smooth ? smoothing(v, step + step / 4) : v;\n}", "function _dampedOscillator(t, params) {\n if (!params._isPrepared) {\n params._isPrepared = true;\n params._curFrequency = params.frequency || 0.1;\n params._curAmplitude = 1;\n params._scale = 1 - (params.friction || 0.1);\n params._shift = 0;\n params._negativeHandler = _parseNegativeHandler(params.negativeHander);\n }\n var t1 = t - params._shift;\n if (t1 >= params._curFrequency) {\n params._shift = t;\n params._curFrequency = params._curFrequency * params._scale;\n params._curAmplitude = params._curAmplitude * params._scale;\n t1 = t - params._shift;\n }\n // @TODO: Improve the damped function\n var v = Math.sin(Math.PI * 2 * (t1 / params._curFrequency)) * params._curAmplitude;\n return params._negativeHandler ? params._negativeHandler(v) : v;\n }", "function moving_average(data, neighbors) {\n return data.map((val, idx, arr) => {\n let start = Math.max(0, idx - neighbors),\n end = idx + neighbors\n let subset = arr.slice(start, end + 1)\n let sum = subset.reduce((a,b) => a + b)\n return sum / subset.length\n })\n}", "function Ea(e,t,n,i){xa.call(this,e,t,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0}", "function updateWaveform() {\n requestAnimationFrame(updateWaveform);\n analyser.getFloatTimeDomainData(waveform)\n }", "function rollingAverage(arr, windowPeriod = 12) {\n rollingAverageValues = [];\n for (var i = windowPeriod - 1; i < arr.length; i++) {\n let ctr = 0;\n let newVal = arr[i];\n if (arr[i] == null) {\n ctr += 1;\n };\n for (var j = 1; j < windowPeriod; j++) {\n newVal += arr[i-j];\n if (arr[i-j] == null) {\n ctr += 1;\n };\n };\n rollingAverageValues.push(newVal / (windowPeriod - ctr));\n }\n return rollingAverageValues;\n}", "setFilterFrequency(y) {\n // min 40Hz\n let min = 40;\n // max half of the sampling rate\n let max = this.myAudioContext.sampleRate / 2;\n // Logarithm (base 2) to compute how many octaves fall in the range.\n let numberOfOctaves = Math.log(max / min) / Math.LN2;\n // Compute a multiplier from 0 to 1 based on an exponential scale.\n // let multiplier = Math.pow(2, numberOfOctaves * (((2 / this.surface.clientHeight) * (this.surface.clientHeight - y)) - 1.0));\n let multiplier = Math.pow(2, numberOfOctaves * (((2 / this.canvas.height/2) * (this.canvas.height - y)) - 1.0));\n // console.log(y,max*multiplier,multiplier);\n // Get back to the frequency value between min and max.\n return max * multiplier;\n }", "function stream_waves(n, m) {\n return d3.range(n).map(function(i) {\n return d3.range(m).map(function(j) {\n var x = 20 * j / m - i / 3;\n return 2 * x * Math.exp(-.5 * x);\n }).map(stream_index);\n });\n}", "function createGaussian(duration) {\n var length = Math.floor(WX.srate * duration);\n var noiseFloat32 = new Float32Array(length);\n for (var i = 0; i < length; i++) {\n var r1 = Math.log(Math.random()), r2 = Math.PI * Math.random();\n noiseFloat32[i] = Math.sqrt(-2.0 * r1) * Math.cos(2.0 * r2) * 0.5;\n }\n var noiseBuffer = WX.Buffer(2, length, WX.srate);\n noiseBuffer.getChannelData(0).set(noiseFloat32, 0);\n noiseBuffer.getChannelData(1).set(noiseFloat32, 0);\n return noiseBuffer;\n }", "function analyzeData() {\n let tdMaxsTotal = tdMinsTotal = tdAvgsTotal = tdTotalRanges = 0;\n let frTotalMaxs = frTotalMins = frTotalAvgs = frTotalRanges = 0;\n\n frAnalyserNode.getFloatFrequencyData(soundData.frBuffer);\n soundData.frBufferHistory.push(soundData.frBuffer.slice(0));\n if (soundData.frBufferHistory.length > frBufferLength) soundData.frBufferHistory.shift();\n\n tdAnalyserNode.getFloatTimeDomainData(soundData.tdBuffer);\n soundData.tdBufferHistory.push(soundData.tdBuffer.slice(0));\n if (soundData.tdBufferHistory.length > tdBufferLength) soundData.tdBufferHistory.shift();\n\n // Calculate sound wave time data min and max and get total for averaging\n // td {-1, 1}\n soundData.tdMax = {\n index: 0,\n value: -500\n };\n soundData.tdMin = {\n index: 0,\n value: 500\n };\n soundData.tdTot = 0;\n\n for (let i = 0; i < tdBufferLength; i++) {\n if (soundData.tdBuffer[i] > soundData.tdMax.value) soundData.tdMax = {\n index: i,\n value: soundData.tdBuffer[i]\n };\n if (soundData.tdBuffer[i] < soundData.tdMin.value) soundData.tdMin = {\n index: i,\n value: soundData.tdBuffer[i]\n };\n soundData.tdTot += soundData.tdBuffer[i];\n\n if (soundData.tdBuffer[i] > soundData.tdMaxAllTime) soundData.tdMaxAllTime = soundData.tdBuffer[i];\n if (soundData.tdBuffer[i] < soundData.tdMinAllTime) soundData.tdMinAllTime = soundData.tdBuffer[i];\n\n }\n\n soundData.tdMaxs.push(soundData.tdMax);\n if (soundData.tdMaxs.length > arraySize) soundData.tdMaxs.shift();\n\n soundData.tdMins.push(soundData.tdMin);\n if (soundData.tdMins.length > arraySize) soundData.tdMins.shift();\n\n // Calculate average\n soundData.tdAvg = soundData.tdTot / tdBufferLength;\n soundData.tdAvgs.push(soundData.tdAvg);\n if (soundData.tdAvgs.length > arraySize) soundData.tdAvgs.shift();\n\n // Calculate range\n soundData.tdRange = soundData.tdMax.value - soundData.tdMin.value;\n soundData.tdRanges.push(soundData.tdRange);\n if (soundData.tdRanges.length > arraySize) soundData.tdRanges.shift();\n\n\n\n // Calculate frequency min and max and get total for averaging\n // fr {-180, -12 }\n soundData.frMax = {\n index: 0,\n value: -500\n };\n soundData.frMin = {\n index: 0,\n value: 500\n };\n soundData.frTot = 0;\n\n for (let i = 0; i < frBufferLength; i++) {\n if (soundData.frBuffer[i] > soundData.frMax.value) soundData.frMax = {\n index: i,\n value: soundData.frBuffer[i]\n };\n if (soundData.frBuffer[i] < soundData.frMin.value) soundData.frMin = {\n index: i,\n value: soundData.frBuffer[i]\n };\n soundData.frTot += soundData.frBuffer[i];\n\n if (soundData.frBuffer[i] > soundData.frMaxAllTime) soundData.frMaxAllTime = soundData.frBuffer[i];\n if (soundData.frBuffer[i] < soundData.frMinAllTime && soundData.frBuffer[i] > -100000) soundData.frMinAllTime = soundData.frBuffer[i];\n }\n\n soundData.frMaxs.push(soundData.frMax);\n if (soundData.frMaxs.length > arraySize) soundData.frMaxs.shift();\n\n soundData.frMins.push(soundData.frMin);\n if (soundData.frMins.length > arraySize) soundData.frMins.shift();\n\n // Calculate average \n soundData.frAvg = soundData.frTot / frBufferLength;\n soundData.frAvgs.push(soundData.frAvg);\n if (soundData.frAvgs.length > arraySize) soundData.frAvgs.shift();\n\n // Calculate range\n soundData.frRange = soundData.frMax.value - soundData.frMin.value;\n soundData.frRanges.push(soundData.frRange);\n if (soundData.frRanges.length > arraySize) soundData.frRanges.shift();\n\n\n // \n\n for (let index = 0; index < arraySize; index++) {\n tdMaxsTotal += soundData.tdMaxs[index].value;\n tdMinsTotal += soundData.tdMins[index].value;\n tdAvgsTotal += soundData.tdAvgs[index];\n tdTotalRanges += soundData.tdRanges[index];\n\n frTotalMaxs += soundData.frMaxs[index].value;\n frTotalMins += soundData.frMins[index].value;\n frTotalAvgs += soundData.frAvgs[index];\n frTotalRanges += soundData.frRanges[index];\n\n };\n\n soundData.tdAvgTotalMaxs = tdMaxsTotal / arraySize;\n soundData.tdAvgTotalMins = tdMinsTotal / arraySize;\n soundData.tdAvgTotalAvgs = tdAvgsTotal / arraySize;\n soundData.tdAvgTotalRanges = tdTotalRanges / arraySize;\n\n soundData.frAvgTotalMaxs = frTotalMaxs / arraySize;\n soundData.frAvgTotalMins = frTotalMins / arraySize;\n soundData.frAvgTotalAvgs = frTotalAvgs / arraySize;\n soundData.frAvgTotalRanges = frTotalRanges / arraySize;\n }", "incrementRepeating(event) {\n event.count++;\n // the web audio spec doesn't allow buffer source nodes to be reused\n const dummySource = this.audioCtx.createBufferSource();\n dummySource.buffer = event.source.buffer;\n dummySource.connect(this.audioCtx.destination);\n dummySource.onended = () => {\n event.callback();\n // add the next occurence\n this.incrementRepeating(event);\n };\n dummySource.start(\n event.time + event.count * event.frequency - dummySource.buffer.duration\n );\n event.source = dummySource;\n }", "#calcFilter() {\n const w0 = 2 * Math.PI * this.#f0 / sampleRate;\n const alpha = Math.sin(w0) / (this.#q * 2);\n const cosW0 = Math.cos(w0);\n let b0, b1, b2, a0, a1, a2;\n\n switch (this.#filterType) {\n case 'low-pass': {\n b0 = (1 - cosW0) / 2;\n b1 = 1 - cosW0;\n b2 = (1 - cosW0) / 2;\n a0 = 1 + alpha;\n a1 = -2 * cosW0;\n a2 = 1 - alpha;\n break;\n }\n case 'high-pass': {\n b0 = (1 + cosW0) / 2;\n b1 = -(1 + cosW0);\n b2 = (1 + cosW0) / 2;\n a0 = 1 + alpha;\n a1 = -2 * cosW0;\n a2 = 1 - alpha;\n break;\n }\n case 'band-pass': {\n // This is the \"peak gain = Q\" BPF variant from the Audio EQ\n // Cookbook.\n b0 = this.#q * alpha;\n b1 = 0;\n b2 = -this.#q * alpha;\n a0 = 1 + alpha;\n a1 = -2 * cosW0;\n a2 = 1 - alpha;\n break;\n }\n case 'notch': {\n b0 = 1;\n b1 = -2 * cosW0;\n b2 = 1;\n a0 = 1 + alpha;\n a1 = -2 * cosW0;\n a2 = 1 - alpha;\n break;\n }\n default: {\n // Unknown filter type.\n b0 = b1 = b2 = a0 = a1 = a2 = 0;\n break;\n }\n }\n\n this.#x0Co = b0 / a0;\n this.#x1Co = b1 / a0;\n this.#x2Co = b2 / a0;\n this.#y1Co = -a1 / a0;\n this.#y2Co = -a2 / a0;\n }", "function avg(){\n var a = calc.input.value.toString();\n a=a.split(\"+\");\n calc.input.value=eval(calc.input.value)/a.length;\n end=false;\n \n}", "function SMA(period) {\n var nums = [];\n return function(num) {\n nums.push(num);\n if (nums.length > period)\n nums.splice(0,1); // remove the first element of the array\n var sum = 0;\n for (var i in nums)\n sum += nums[i];\n var n = period;\n if (nums.length < period)\n n = nums.length;\n return(sum/n);\n }\n}", "function newAvg(arr, newavg) {\n if(!arr.length){return newavg};\n if(newavg * (arr.length + 1) - arr.reduce((prev, curr) => prev + curr) < 0){throw Error();}\n \n return Math.ceil(newavg * (arr.length + 1) - arr.reduce((prev, curr) => prev + curr));\n}", "function get4Rmean() {\n var total = 0;\n for (var i = 0; i < R_buffer.length; i++) {\n total += R_buffer[i];\n }\n var avg = total / R_buffer.length;\n return avg;\n }", "function addEqualiser() {\n\n var gainDb = -40.0; // atenuation When it takes a positive value it is a real gain, when negative it is an attenuation. It is expressed in dB, has a default value of 0 and can take a value in a nominal range of -40 to 40.\n var bandSplit = [360, 3600];\n context_player = new AudioContext();\n\n for (var i = 0; i < 2; i++) {\n\n mediaElement_player.push(null);\n sourceNode_player.push(null);\n source_player.push(null);\n lGain_player.push(null);\n mGain_player.push(null);\n hGain_player.push(null);\n sum_player.push(null);\n volumeNodes.push(null);\n\n\n mediaElement_player[i] = document.getElementById('jp_audio_' + i);\n source_player[i] = context_player.createMediaElementSource(mediaElement_player[i]);\n\n initFrequencyQuality(i);\n\n // affects the ammount of treble in a sound - treble knob - atenuates the sounds below the 3600 frequencies\n var lBand_player = context_player.createBiquadFilter();\n lBand_player.type = \"lowshelf\";\n lBand_player.frequency.value = bandSplit[1];\n lBand_player.gain.value = gainDb;\n\n // affects the ammount of bass in a sound - bass knob - atenuates the sounds higher than 360 frequencies\n var hBand_player = context_player.createBiquadFilter();\n hBand_player.type = \"highshelf\";\n hBand_player.frequency.value = bandSplit[0];\n hBand_player.gain.value = gainDb;\n\n var hInvert_player = context_player.createGain();\n hInvert_player.gain.value = -1.0;\n\n //Subtract low and high frequencies (add invert) from the source for the mid frequencies\n var mBand_player = context_player.createGain();\n\n //or use picking\n //mBand_player = context_player.createBiquadFilter();\n //mBand_player.type = \"peaking\";\n //mBand_player.frequency.value = bandSplit[0];\n //mBand_player.gain.value = gainDb;\n\n var lInvert_player = context_player.createGain();\n lInvert_player.gain.value = -1.0;\n\n sourceNode_player[i].connect(lBand_player);\n sourceNode_player[i].connect(mBand_player);\n sourceNode_player[i].connect(hBand_player);\n\n hBand_player.connect(hInvert_player);\n lBand_player.connect(lInvert_player);\n\n hInvert_player.connect(mBand_player);\n lInvert_player.connect(mBand_player);\n\n\n lGain_player[i] = context_player.createGain();\n mGain_player[i] = context_player.createGain();\n hGain_player[i] = context_player.createGain();\n\n lBand_player.connect(lGain_player[i]);\n mBand_player.connect(mGain_player[i]);\n hBand_player.connect(hGain_player[i]);\n\n sum_player[i] = context_player.createGain();\n lGain_player[i].connect(sum_player[i]);\n mGain_player[i].connect(sum_player[i]);\n hGain_player[i].connect(sum_player[i]);\n\n lGain_player[i].gain.value = 1;\n mGain_player[i].gain.value = 1;\n hGain_player[i].gain.value = 1;\n\n volumeNodes[i] = context_player.createGain();\n sum_player[i].connect(volumeNodes[i]);\n volumeNodes[i].connect(context_player.destination);\n }\n\n //set volume\n var x = 50 / 100;\n // Use an equal-power crossfading curve:\n var gain1 = Math.cos(x * 0.5 * Math.PI);\n var gain2 = Math.cos((1.0 - x) * 0.5 * Math.PI);\n volumeNodes[0].gain.value = gain1;\n volumeNodes[1].gain.value = gain2;\n\n //create audio Recording node\n audioRecordNode = context_player.createGain();\n volumeNodes[0].connect(audioRecordNode);\n volumeNodes[1].connect(audioRecordNode);\n audioRecorder = new Recorder(audioRecordNode);\n}", "function logAverageFrame(times) { // times is the array of User Timing measurements from updatePositions()\n var numberOfEntries = times.length;\n var sum = 0;\n for (var i = numberOfEntries - 1; i > numberOfEntries - 11; i--) {\n sum = sum + times[i].duration;\n }\n console.log('Average time to generate last 10 frames: ' + sum / 10 + 'ms');\n}", "function adapt(delta, numPoints, firstTime) {\n \t\t\t\tvar k = 0;\n \t\t\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n \t\t\t\tdelta += floor(delta / numPoints);\n \t\t\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n \t\t\t\t\tdelta = floor(delta / baseMinusTMin);\n \t\t\t\t}\n \t\t\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n \t\t\t}", "getMean() {\n // console.log(this.temperatures, this.sum, this.entries)\n return this.sum / this.entries;\n }" ]
[ "0.6945081", "0.57183474", "0.5713561", "0.55339795", "0.5522362", "0.54916936", "0.5223794", "0.51811856", "0.5147332", "0.51190215", "0.51054066", "0.50999105", "0.50976515", "0.5086508", "0.5082541", "0.50785434", "0.5076225", "0.5072351", "0.5057199", "0.50501716", "0.50501716", "0.50204843", "0.49834636", "0.49629873", "0.49554068", "0.49129158", "0.48855665", "0.4876703", "0.48735812", "0.48226374", "0.48177427", "0.47996116", "0.47943392", "0.47797516", "0.4767841", "0.4766873", "0.47516906", "0.474513", "0.47318965", "0.47116494", "0.47083953", "0.47077718", "0.4706258", "0.47001046", "0.4697047", "0.46962756", "0.46952847", "0.46908256", "0.4682504", "0.46815485", "0.46785933", "0.4673334", "0.46639743", "0.46517298", "0.46459836", "0.46405473", "0.4629564", "0.46289304", "0.46287018", "0.46270448", "0.46266776", "0.46227905", "0.4619863", "0.4595751", "0.45832857", "0.45816353", "0.45816353", "0.45816353", "0.45816353", "0.45816353", "0.45811072", "0.4579365", "0.45782256", "0.45782256", "0.45782256", "0.4576433", "0.4576318", "0.45723265", "0.45702085", "0.45663065", "0.45598626", "0.45553365", "0.45517007", "0.4549415", "0.4533384", "0.45299563", "0.4516782", "0.45126522", "0.4508287", "0.44967747", "0.4495938", "0.44885942", "0.44881925", "0.44834706", "0.4479107", "0.44715795", "0.4469697", "0.4459731", "0.44533032", "0.44506112" ]
0.74534476
0
Windowing and mixing odd and pair buffers
synthesizeOutputBlock(outBlock) { // Get block index for pair and odd buffers /* We want to get X: the current block to mix 0 0 0 X 0 --> Pair block X O O O O --> Odd block o o o x ... --> Synthesized block (outBlock) */ let indBlockPair = this._countBlock % this._modIndexBuffer; let indBlockOdd = (indBlockPair + this._modIndexBuffer/2) % this._modIndexBuffer; // TODO: Right now this only works for 50% overlap and an even number of blocks per frame. // More modifications would be necessary to include less than 50% overlap and an odd number of blocks per frame. Right now an amplitude modulation would appear for an odd number of blocks per frame (to be tested - AM from 1 to 0.5). // Iterate over the corresponding block of the synthesized buffers for (let i = 0; i<outBlock.length; i++){ let indPair = i + 128*indBlockPair; let indOdd = i + 128*indBlockOdd; // Hanning window // Use hanning window sin^2(pi*n/N) let hannPairBValue = Math.pow(Math.sin(Math.PI*indPair/this._frameSize), 2); let hannOddBValue = Math.pow(Math.sin(Math.PI*indOdd/this._frameSize), 2); //let hannPairBValue = 0.54 - 0.46 * Math.cos(2*Math.PI*indPair/(this._frameSize-1)); //let hannOddBValue = 0.54 - 0.46 * Math.cos(2*Math.PI*indOdd/(this._frameSize-1)); // Hanning windowed frames addition outBlock[i] = hannPairBValue*this._pairSynthBuffer[indPair] + hannOddBValue*this._oddSynthBuffer[indOdd]; // Debugging //outBlock[i] = this._pairBuffer[i];//this._pairSynthBuffer[indPair];//0.5*this._pairSynthBuffer[indPair] + 0.5*this._oddSynthBuffer[indOdd]; this._block1[i] = this._pairSynthBuffer[indPair]; this._block2[i] = this._oddSynthBuffer[indOdd]; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updatewindow(strm,src,end,copy){var dist;var state=strm.state;/* if it hasn't been done already, allocate space for the window */if(state.window===null){state.wsize=1<<state.wbits;state.wnext=0;state.whave=0;state.window=new utils.Buf8(state.wsize);}/* copy state->wsize or less output bytes into the circular window */if(copy>=state.wsize){utils.arraySet(state.window,src,end-state.wsize,state.wsize,0);state.wnext=0;state.whave=state.wsize;}else {dist=state.wsize-state.wnext;if(dist>copy){dist=copy;}//zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src,end-copy,dist,state.wnext);copy-=dist;if(copy){//zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src,end-copy,copy,0);state.wnext=copy;state.whave=state.wsize;}else {state.wnext+=dist;if(state.wnext===state.wsize){state.wnext=0;}if(state.whave<state.wsize){state.whave+=dist;}}}return 0;}", "function mix_buffers(gran = 100) {\n ret_buf = [];\n wt.forEach((weight, index) => {\n for(var i = 0; i < Math.round(weight*gran)/100; i++) {\n ret_buf.push(...buffer_picker[index]); //jesus christ\n }\n });\n return ret_buf; //I hope you like arrays with 50k+ elements\n}", "function createDiffBuffer(messageEvent) {\n var i;\n messageData = messageEvent.data;\n buffer = messageData.buffer;\n data1 = messageData.data1;\n data2 = messageData.data2;\n width = messageData.width;\n height = messageData.height;\n sensitivity = messageData.sensitivity;\n data = new Uint32Array(buffer);\n for (var y = 0; y < height; ++y) {\n for (var x = 0; x < width; ++x) {\n i = y * width + x\n average1 = ((data1[i*4] + data1[i*4+1] + data1[i*4+2]) / 3) / sensitivity;\n average2 = ((data2[i*4] + data2[i*4+1] + data2[i*4+2]) / 3) / sensitivity;\n delta = polarize(\n abs(average1 - average2), 0x15\n );\n\n data[i] =\n (255 << 24) | // alpha\n (delta << 16) | // blue\n (delta << 8) | // green\n delta; // red\n }\n }\n\n this.postMessage(buffer);\n}", "function updatewindow(strm, src, end, copy) {\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new common$1.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n common$1.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n common$1.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n common$1.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function mix (bufferA, bufferB, weight, offset) {\n validate(bufferA);\n validate(bufferB);\n\n if (weight == null) weight = 0.5;\n var fn = weight instanceof Function ? weight : function (a, b) {\n return a * (1 - weight) + b * weight;\n };\n\n if (offset == null) offset = 0;\n else if (offset < 0) offset += bufferA.length;\n\n for (var channel = 0; channel < bufferA.numberOfChannels; channel++) {\n var aData = bufferA.getChannelData(channel);\n var bData = bufferB.getChannelData(channel);\n\n for (var i = offset, j = 0; i < bufferA.length && j < bufferB.length; i++, j++) {\n aData[i] = fn.call(bufferA, aData[i], bData[j], j, channel);\n }\n }\n\n return bufferA;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new common.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n common.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n common.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n common.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new common.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n common.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n common.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n common.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n /* if it hasn't been done already, allocate space for the window */\n\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n state.window = new utils.Buf8(state.wsize);\n }\n /* copy state->wsize or less output bytes into the circular window */\n\n\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n } else {\n dist = state.wsize - state.wnext;\n\n if (dist > copy) {\n dist = copy;\n } //zmemcpy(state->window + state->wnext, end - copy, dist);\n\n\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n } else {\n state.wnext += dist;\n\n if (state.wnext === state.wsize) {\n state.wnext = 0;\n }\n\n if (state.whave < state.wsize) {\n state.whave += dist;\n }\n }\n }\n\n return 0;\n}", "function updateBuffers3(){\n //everytime i+3 means change the y coordinate for the top butters, here i starts form 1!\n for(var i = 1; i < 16; i=i+3){\n if (i==13) {continue;};\n triangleVerticestop[i] = triangleVerticestop[i] - 0.03*Math.sin(2*Math.PI*((framecount)/ 20.0));\n }\n //the repeat vertex, should be the same pace with the bottom\n triangleVerticestop[13] = triangleVerticestop[13] + 0.03*Math.sin(2*Math.PI*((framecount)/ 20.0));\n \n \n for(var i = 16; i < triangleVerticestop.length; i=i+3){\n triangleVerticestop[i] = triangleVerticestop[i] - 0.03*Math.sin(2*Math.PI*((framecount)/ 20.0));\n }\n \n //everytime i+3 means change the y coordinate for the bommon butters, here i starts form 1!\n for(var i = 1; i < 16; i=i+3){\n if (i==13) {continue};\n triangleVerticesmid[i] = triangleVerticesmid[i] + 0.03*Math.sin(2*Math.PI*((framecount)/ 20.0));\n }\n\n //the repeat vertex, should be the same pace with the top fan \n triangleVerticesmid[13] = triangleVerticesmid[13] -0.03*Math.sin(2*Math.PI*((framecount)/ 20.0)); \n \n for(var i = 16; i < triangleVerticestop.length; i=i+3){\n triangleVerticesmid[i] = triangleVerticesmid[i] + 0.03*Math.sin(2*Math.PI*((framecount)/ 20.0));\n }\n //update the top buffers new positions\n gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffertop);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleVerticestop), gl.DYNAMIC_DRAW);\n vertexPositionBuffertop.itemSize = 3;\n vertexPositionBuffertop.numberOfItems = 8;\n //update the bottom buffers new positions \n gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffermid);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleVerticesmid), gl.DYNAMIC_DRAW);\n vertexPositionBuffermid.itemSize = 3;\n vertexPositionBuffermid.numberOfItems = 8;\n\n\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window,src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window,src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n } else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n } else {\n state.wnext += dist;\n if (state.wnext === state.wsize) {\n state.wnext = 0;\n }\n if (state.whave < state.wsize) {\n state.whave += dist;\n }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n\t var dist;\n\t var state = strm.state;\n\n\t /* if it hasn't been done already, allocate space for the window */\n\t if (state.window === null) {\n\t state.wsize = 1 << state.wbits;\n\t state.wnext = 0;\n\t state.whave = 0;\n\n\t state.window = new Buf8(state.wsize);\n\t }\n\n\t /* copy state->wsize or less output bytes into the circular window */\n\t if (copy >= state.wsize) {\n\t arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n\t state.wnext = 0;\n\t state.whave = state.wsize;\n\t } else {\n\t dist = state.wsize - state.wnext;\n\t if (dist > copy) {\n\t dist = copy;\n\t }\n\t //zmemcpy(state->window + state->wnext, end - copy, dist);\n\t arraySet(state.window, src, end - copy, dist, state.wnext);\n\t copy -= dist;\n\t if (copy) {\n\t //zmemcpy(state->window, end - copy, copy);\n\t arraySet(state.window, src, end - copy, copy, 0);\n\t state.wnext = copy;\n\t state.whave = state.wsize;\n\t } else {\n\t state.wnext += dist;\n\t if (state.wnext === state.wsize) {\n\t state.wnext = 0;\n\t }\n\t if (state.whave < state.wsize) {\n\t state.whave += dist;\n\t }\n\t }\n\t }\n\t return 0;\n\t}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}", "function updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n \n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n \n state.window = new utils.Buf8(state.wsize);\n }\n \n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n }", "function updatewindow(strm, src, end, copy) {\n\t var dist;\n\t var state = strm.state;\n\t\n\t /* if it hasn't been done already, allocate space for the window */\n\t if (state.window === null) {\n\t state.wsize = 1 << state.wbits;\n\t state.wnext = 0;\n\t state.whave = 0;\n\t\n\t state.window = Buf8(state.wsize);\n\t }\n\t\n\t /* copy state->wsize or less output bytes into the circular window */\n\t if (copy >= state.wsize) {\n\t arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n\t state.wnext = 0;\n\t state.whave = state.wsize;\n\t }\n\t else {\n\t dist = state.wsize - state.wnext;\n\t if (dist > copy) {\n\t dist = copy;\n\t }\n\t //zmemcpy(state->window + state->wnext, end - copy, dist);\n\t arraySet(state.window, src, end - copy, dist, state.wnext);\n\t copy -= dist;\n\t if (copy) {\n\t //zmemcpy(state->window, end - copy, copy);\n\t arraySet(state.window, src, end - copy, copy, 0);\n\t state.wnext = copy;\n\t state.whave = state.wsize;\n\t }\n\t else {\n\t state.wnext += dist;\n\t if (state.wnext === state.wsize) { state.wnext = 0; }\n\t if (state.whave < state.wsize) { state.whave += dist; }\n\t }\n\t }\n\t return 0;\n\t }", "function updateBuffers() {\n \n triangleVerticestop[0] = triangleVerticestop[0] + 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticestop[3] = triangleVerticestop[3] + 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticestop[6] = triangleVerticestop[6] + 0.03*Math.sin(2*Math.PI*((framecount+5)/20));\n triangleVerticestop[9] = triangleVerticestop[9] + 0.03*Math.sin(2*Math.PI*((framecount+5)/20));\n triangleVerticestop[12] = triangleVerticestop[12] -0.03*Math.sin(2*Math.PI*((framecount+5)/20)); //repeat vetex, should be the same pace with the bommon fan\n triangleVerticestop[15] = triangleVerticestop[15] + 0.03*Math.sin(2*Math.PI*((framecount+5)/20));\n triangleVerticestop[18] = triangleVerticestop[18] + 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticestop[21] = triangleVerticestop[21] +0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n\n \n \n triangleVerticesmid[0] = triangleVerticesmid[0] - 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticesmid[3] = triangleVerticesmid[3] - 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticesmid[6] = triangleVerticesmid[6] - 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticesmid[9] = triangleVerticesmid[9] - 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticesmid[15] = triangleVerticesmid[15] - 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticesmid[12] = triangleVerticesmid[12] + 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0)); //repeat vetex, should be the same pace with the top fan\n triangleVerticesmid[18] = triangleVerticesmid[18] - 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n triangleVerticesmid[21] = triangleVerticesmid[21] - 0.03*Math.sin(2*Math.PI*((framecount+5)/20.0));\n\n //update the top buffer new positions\n gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffertop);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleVerticestop), gl.DYNAMIC_DRAW);\n vertexPositionBuffertop.itemSize = 3;\n vertexPositionBuffertop.numberOfItems = 8;\n //update the bottom buffer new positions\n gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffermid);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleVerticesmid), gl.DYNAMIC_DRAW);\n vertexPositionBuffermid.itemSize = 3;\n vertexPositionBuffermid.numberOfItems = 8;\n}", "function buffer2(geometry) {\n return geometry.buffer(5000);\n}" ]
[ "0.59155285", "0.58480716", "0.5809806", "0.5803648", "0.5788865", "0.57761717", "0.5769033", "0.5769033", "0.57507116", "0.57495636", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.5729805", "0.57256716", "0.5723022", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.57198894", "0.5696083", "0.5676125", "0.56747574", "0.56566644" ]
0.6297847
0
NOTE: modified to blend 2 single pixels color conversions
function hex2rgba(h) {return [hexToR(h), hexToG(h),hexToB(h), 255]}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static blendDestOut(p1,id1,p2,id2){\n\t\tconst op1=p1[id1+3],op2=p2[id2+3];\n\t\tconst op=(op1*(0x10000-op2))>>>16;\n\t\t// blended op, shoud be (op1*(0xFFFF-op2))/0xFFFF\n\t\t// no change to color params, has nothing to do with the color of p2\n\t\t// op holds op>=0\n\t\tp1[id1+3]=op; // only change opacity\n\t}", "function blendColors(c0, c1, p) {\n var f=parseInt(c0.slice(1),16),\n t=parseInt(c1.slice(1),16),\n R1=f>>16,\n G1=f>>8&0x00FF,\n B1=f&0x0000FF,\n R2=t>>16,\n G2=t>>8&0x00FF,\n B2=t&0x0000FF;\n return \"#\"+(0x1000000+(Math.round((R2-R1)*p)+R1)*0x10000\n +(Math.round((G2-G1)*p)+G1)*0x100+(\n Math.round((B2-B1)*p)+B1)).toString(16).slice(1);\n}", "function blend(c, a) {\n return 255 + (c - 255) * a;\n}", "function blend(c, a) {\n return 255 + (c - 255) * a;\n}", "function blend(img1, img2, blendfunc) {\n var h = img1.h,\n w = img1.w;\n var dst = new RGBAImage(w, h);\n\n for (var y=0;y<h;y++)\n {\n for( var x=0;x<w;x++ )\n dst.setPixel(x, y, blendfunc(img1.getPixel(x, y), img2.getPixel(x, y)));\n }\n return dst;\n}", "static blendDestOutOpacityLocked(p1,id1,p2,id2){\n\t\tconst op1=p1[id1+3],op2=p2[id2+3];\n\t\tconst op=Math.min(op2+op1-((op2*op1)>>>16),0xFFFF);\n\t\tconst k=op2/op;\n\t\tp1[id1]+=k*(0xFFFF-p1[id1]);\n\t\tp1[id1+1]+=k*(0xFFFF-p1[id1+1]);\n\t\tp1[id1+2]+=k*(0xFFFF-p1[id1+2]);\n\t}", "function diff(img1, img2) {\n return blend(img1, img2, function(a, b){\n var c = new Color();\n c.r = Math.abs(a.r - b.r);\n c.g = Math.abs(a.g - b.g);\n c.b = Math.abs(a.b - b.b);\n c.a = 255;\n return c;\n });\n}", "blendPixel(scaler, rotDeg, ker, trgi, blendInfo, scalePixelColorEq, scalePixelColorDist, outputMatrix) {\n\n var b = ker._[Rot._[(1 << 2) + (rotDeg)]];\n var c = ker._[Rot._[(2 << 2) + (rotDeg)]];\n var d = ker._[Rot._[(3 << 2) + (rotDeg)]];\n var e = ker._[Rot._[(4 << 2) + (rotDeg)]];\n var f = ker._[Rot._[(5 << 2) + (rotDeg)]];\n var g = ker._[Rot._[(6 << 2) + (rotDeg)]];\n var h = ker._[Rot._[(7 << 2) + (rotDeg)]];\n var i = ker._[Rot._[(8 << 2) + (rotDeg)]];\n\n var blend = BlendInfo.Rotate(blendInfo, rotDeg);\n\n if ((BlendInfo.GetBottomR(blend)) >= BlendType.BlendNormal) {\n\n var eq = function (pix1, pix2) {\n\n return scalePixelColorEq._(pix1, pix2);\n }\n\n var dist = function (pix1, pix2) {\n\n return scalePixelColorDist._(pix1, pix2);\n }\n\n var doLineBlend = function () {\n\n if (BlendInfo.GetBottomR(blend) >= BlendType.BlendDominant)\n return true;\n\n //make sure there is no second blending in an adjacent rotation for this pixel: handles insular pixels, mario eyes\n if (BlendInfo.GetTopR(blend) != BlendType.BlendNone && !eq(e, g))\n return false;\n\n if (BlendInfo.GetBottomL(blend) != BlendType.BlendNone && !eq(e, c))\n return false;\n\n //no full blending for L-shapes; blend corner only (handles \"mario mushroom eyes\")\n if (!eq(e, i) && eq(g, h) && eq(h, i) && eq(i, f) && eq(f, c))\n return false;\n\n return true;\n }\n\n var px = dist(e, f) <= dist(e, h) ? f : h;\n\n var output = outputMatrix;\n\n output.Move(rotDeg, trgi);\n\n if (doLineBlend()) {\n\n var fg = dist(f, g); //test sample: 70% of values max(fg, hc) / min(fg, hc) are between 1.1 and 3.7 with median being 1.9\n var hc = dist(h, c); //\n\n var haveShallowLine = Constants.Configuration.steepDirectionThreshold * fg <= hc && e != g && d != g;\n var haveSteepLine = Constants.Configuration.steepDirectionThreshold * hc <= fg && e != c && b != c;\n\n if (haveShallowLine) {\n\n if (haveSteepLine) {\n\n scaler.BlendLineSteepAndShallow(px, output);\n\n } else {\n\n scaler.BlendLineShallow(px, output);\n }\n\n } else {\n\n if (haveSteepLine) {\n\n scaler.BlendLineSteep(px, output);\n\n } else {\n\n scaler.BlendLineDiagonal(px, output);\n }\n }\n\n } else {\n\n scaler.BlendCorner(px, output);\n }\n }\n }", "function blendColors (args) {\n let base = [0, 0, 0, 0]\n let mix\n let added\n while (added = args.shift()) {\n if (typeof added[3] === 'undefined') {\n added[3] = 1\n }\n // check if both alpha channels exist.\n if (base[3] && added[3]) {\n mix = [0, 0, 0, 0]\n // alpha\n mix[3] = 1 - (1 - added[3]) * (1 - base[3])\n // red\n mix[0] = Math.round((added[0] * added[3] / mix[3]) + (base[0] * base[3] * (1 - added[3]) / mix[3]))\n // green\n mix[1] = Math.round((added[1] * added[3] / mix[3]) + (base[1] * base[3] * (1 - added[3]) / mix[3]))\n // blue\n mix[2] = Math.round((added[2] * added[3] / mix[3]) + (base[2] * base[3] * (1 - added[3]) / mix[3]))\n\n } else if (added) {\n mix = added\n } else {\n mix = base\n }\n base = mix\n }\n\n return mix\n}", "static blendNormalOpacityLocked(p1,id1,p2,id2){\n\t\tconst op1=p1[id1+3],op2=p2[id2+3];\n\t\tconst op=Math.min(op2+op1-((op2*op1)>>>16),0xFFFF);\n\t\tconst k=op2/op;\n\t\tp1[id1]+=k*(p2[id2]-p1[id1]);\n\t\tp1[id1+1]+=k*(p2[id2+1]-p1[id1+1]);\n\t\tp1[id1+2]+=k*(p2[id2+2]-p1[id1+2]);\n\t}", "function blendColors(colorA, colorB, amount) {\n\tconst [rA, gA, bA] = colorA.match(/\\w\\w/g).map((c) => parseInt(c, 16));\n\tconst [rB, gB, bB] = colorB.match(/\\w\\w/g).map((c) => parseInt(c, 16));\n\tconst r = Math.round(rA + (rB - rA) * amount).toString(16).padStart(2, '0');\n\tconst g = Math.round(gA + (gB - gA) * amount).toString(16).padStart(2, '0');\n\tconst b = Math.round(bA + (bB - bA) * amount).toString(16).padStart(2, '0');\n\treturn '#' + r + g + b;\n }", "function blendColors(colorA, colorB, amount) {\n let [rA, gA, bA] = colorA.match(/\\w\\w/g).map((c) => parseInt(c, 16));\n let [rB, gB, bB] = colorB.match(/\\w\\w/g).map((c) => parseInt(c, 16));\n let r = Math.round(rA + (rB - rA) * amount)\n .toString(16)\n .padStart(2, \"0\");\n let g = Math.round(gA + (gB - gA) * amount)\n .toString(16)\n .padStart(2, \"0\");\n let b = Math.round(bA + (bB - bA) * amount)\n .toString(16)\n .padStart(2, \"0\");\n return \"#\" + r + g + b;\n}", "blendBrushtip(src,tgt,param){\n\t\tprogram.setTargetTexture(tgt.data); // draw to temp data\n\t\tgl.viewport(0,0,w,h);\n\t\tgl.clearColor(0,0,0,0);\n\t\tgl.clear(gl.COLOR_BUFFER_BIT);\n\n\t\tprogram.setSourceTexture(\"u_image\",src.data);\n\t\tprogram.setUniform(\"u_aa_step\",[1/w,0]);\n\t\tprogram.setUniform(\"u_aa_cnt\",antiAliasRadius);\n\t\tgl.viewport(imgData.left,h-ih-imgData.top,iw,ih); // set viewport according to the image data\n\t\tgl.blendFunc(this.gl.ONE,this.gl.ZERO); // copy\n\t\tprogram.run();\n\t}", "function shadeBlend(p,c0,c1) {\n const n=p<0?p*-1:p,u=Math.round,w=parseInt;\n if(c0.length>7){\n const f=c0.split(\",\"),t=(c1?c1:p<0?\"rgb(0,0,0)\":\"rgb(255,255,255)\").split(\",\"),R=w(f[0].slice(4)),G=w(f[1]),B=w(f[2]);\n return \"rgb(\"+(u((w(t[0].slice(4))-R)*n)+R)+\",\"+(u((w(t[1])-G)*n)+G)+\",\"+(u((w(t[2])-B)*n)+B)+\")\"\n }else{\n const f=w(c0.slice(1),16),t=w((c1?c1:p<0?\"#000000\":\"#FFFFFF\").slice(1),16),R1=f>>16,G1=f>>8&0x00FF,B1=f&0x0000FF;\n return \"#\"+(0x1000000+(u(((t>>16)-R1)*n)+R1)*0x10000+(u(((t>>8&0x00FF)-G1)*n)+G1)*0x100+(u(((t&0x0000FF)-B1)*n)+B1)).toString(16).slice(1)\n }\n }", "function sub(img1, img2) {\n return blend(img1, img2, function(a, b){\n var c = a.sub(b);\n c.a = 255;\n c.clamp();\n return c;\n });\n}", "function blendColors(colorA, colorB, amount = 0.5)\n {\n const [rA, gA, bA] = colorA.match(/\\w\\w/g).map((c) => parseInt(c, 16));\n const [rB, gB, bB] = colorB.match(/\\w\\w/g).map((c) => parseInt(c, 16));\n\n const r = Math.round(rA + (rB - rA) * amount).toString(16).padStart(2, '0');\n const g = Math.round(gA + (gB - gA) * amount).toString(16).padStart(2, '0');\n const b = Math.round(bA + (bB - bA) * amount).toString(16).padStart(2, '0');\n\n return '#' + r + g + b;\n }", "function shadeBlendConvert(p, from, to) {\n if(typeof(p)!=\"number\"||p<-1||p>1||typeof(from)!=\"string\"||(from[0]!='r'&&from[0]!='#')||(typeof(to)!=\"string\"&&typeof(to)!=\"undefined\"))return null; //ErrorCheck\n if(!this.sbcRip)this.sbcRip=function(d){\n var l=d.length,RGB=new Object();\n if(l>9){\n d=d.split(\",\");\n if(d.length<3||d.length>4)return null;//ErrorCheck\n RGB[0]=i(d[0].slice(4)),RGB[1]=i(d[1]),RGB[2]=i(d[2]),RGB[3]=d[3]?parseFloat(d[3]):-1;\n }else{\n switch(l){case 8:case 6:case 3:case 2:case 1:return null;} //ErrorCheck\n if(l<6)d=\"#\"+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(l>4?d[4]+\"\"+d[4]:\"\"); //3 digit\n d=i(d.slice(1),16),RGB[0]=d>>16&255,RGB[1]=d>>8&255,RGB[2]=d&255,RGB[3]=l==9||l==5?r(((d>>24&255)/255)*10000)/10000:-1;\n }\n return RGB;}\n var i=parseInt,r=Math.round,h=from.length>9,h=typeof(to)==\"string\"?to.length>9?true:to==\"c\"?!h:false:h,b=p<0,p=b?p*-1:p,to=to&&to!=\"c\"?to:b?\"#000000\":\"#FFFFFF\",f=sbcRip(from),t=sbcRip(to);\n if(!f||!t)return null; //ErrorCheck\n if(h)return \"rgb(\"+r((t[0]-f[0])*p+f[0])+\",\"+r((t[1]-f[1])*p+f[1])+\",\"+r((t[2]-f[2])*p+f[2])+(f[3]<0&&t[3]<0?\")\":\",\"+(f[3]>-1&&t[3]>-1?r(((t[3]-f[3])*p+f[3])*10000)/10000:t[3]<0?f[3]:t[3])+\")\");\n else return \"#\"+(0x100000000+(f[3]>-1&&t[3]>-1?r(((t[3]-f[3])*p+f[3])*255):t[3]>-1?r(t[3]*255):f[3]>-1?r(f[3]*255):255)*0x1000000+r((t[0]-f[0])*p+f[0])*0x10000+r((t[1]-f[1])*p+f[1])*0x100+r((t[2]-f[2])*p+f[2])).toString(16).slice(f[3]>-1||t[3]>-1?1:3);\n}", "Blend() {}", "function bres(x1, y1, x2, y2) {\r\n\tloadPixels();\r\n\t\r\n\tvar dx = x2 - x1;\r\n\tvar dy = y2 - y1;\r\n\t\r\n\tvar d = dy - (dx/2);\r\n\tvar x = x1;\r\n\tvar y = y1;\r\n\t\r\n\twhile(x < x2) {\r\n\t\tx++;\r\n\t\tif(d<0) {\r\n\t\t\td = d + dy;\r\n\t\t} else {\r\n\t\t\td += (dy - dx);\r\n\t\t\ty++;\r\n\t\t}\r\n\t\tpixels[4 * (x + (y * 500))] = 255;\r\n\t}\r\n\t\r\n\tupdatePixels();\r\n}", "function blend (src, dst, amt) {\n return dst.map((c, i) => Math.round(amt * c + (1 - amt) * src[i]))\n}", "static blendNormal(p1,id1,p2,id2){\n\t\tconst op1=p1[id1+3],op2=p2[id2+3];\n\t\t// blended op, should be (op2*op1)/0xFFFF. The difference is negligible\n\t\t// @TODO: op==0?\n\t\tconst op=Math.min(op2+op1-((op2*op1)>>>16),0xFFFF);\n\t\tconst k=op2/op;\n\t\tp1[id1]+=k*(p2[id2]-p1[id1]);\n\t\tp1[id1+1]+=k*(p2[id2+1]-p1[id1+1]);\n\t\tp1[id1+2]+=k*(p2[id2+2]-p1[id1+2]);\n\t\tp1[id1+3]=op;\n\t}", "function blend(Cs, Cd, As, Ad) {\n return As * (1 - Ad) * Cs + As * Ad * filter(Cs, Cd) + (1 - As) * Ad * Cd;\n }", "static CombineImageData(data1, data2)\n {\n for(let i = 0; i < data1.length; i++)\n {\n for(let j = 0; j < data1[i].length; j++)\n {\n //if data1 pixel is black and data2 pixel is white\n //turn data1 pixel to white\n if(data1[i][j][0] == 0 && data2[i][j][0] == 255)\n {\n data1[i][j] = [255, 255, 255, 255];\n }\n }\n }\n }", "function mix(rgb1, rgb2, amount) {\n\t var p = amount / 100;\n\t var rgb = {\n\t r: (rgb2.r - rgb1.r) * p + rgb1.r,\n\t g: (rgb2.g - rgb1.g) * p + rgb1.g,\n\t b: (rgb2.b - rgb1.b) * p + rgb1.b\n\t };\n\t return rgb;\n\t}", "function shadeBlendConvert(p, from, to) {\n\t if(typeof(p)!=\"number\"||p<-1||p>1||typeof(from)!=\"string\"||(from[0]!='r'&&from[0]!='#')||(typeof(to)!=\"string\"&&typeof(to)!=\"undefined\"))return null; //ErrorCheck\n\t if(!this.sbcRip)this.sbcRip=function(d){\n\t var l=d.length,RGB=new Object();\n\t if(l>9){\n\t d=d.split(\",\");\n\t if(d.length<3||d.length>4)return null;//ErrorCheck\n\t RGB[0]=i(d[0].slice(4)),RGB[1]=i(d[1]),RGB[2]=i(d[2]),RGB[3]=d[3]?parseFloat(d[3]):-1;\n\t }else{\n\t switch(l){case 8:case 6:case 3:case 2:case 1:return null;} //ErrorCheck\n\t if(l<6)d=\"#\"+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(l>4?d[4]+\"\"+d[4]:\"\"); //3 digit\n\t d=i(d.slice(1),16),RGB[0]=d>>16&255,RGB[1]=d>>8&255,RGB[2]=d&255,RGB[3]=l==9||l==5?r(((d>>24&255)/255)*10000)/10000:-1;\n\t }\n\t return RGB;}\n\t var i=parseInt,r=Math.round,h=from.length>9,h=typeof(to)==\"string\"?to.length>9?true:to==\"c\"?!h:false:h,b=p<0,p=b?p*-1:p,to=to&&to!=\"c\"?to:b?\"#000000\":\"#FFFFFF\",f=sbcRip(from),t=sbcRip(to);\n\t if(!f||!t)return null; //ErrorCheck\n\t if(h)return \"rgb(\"+r((t[0]-f[0])*p+f[0])+\",\"+r((t[1]-f[1])*p+f[1])+\",\"+r((t[2]-f[2])*p+f[2])+(f[3]<0&&t[3]<0?\")\":\",\"+(f[3]>-1&&t[3]>-1?r(((t[3]-f[3])*p+f[3])*10000)/10000:t[3]<0?f[3]:t[3])+\")\");\n\t else return \"#\"+(0x100000000+(f[3]>-1&&t[3]>-1?r(((t[3]-f[3])*p+f[3])*255):t[3]>-1?r(t[3]*255):f[3]>-1?r(f[3]*255):255)*0x1000000+r((t[0]-f[0])*p+f[0])*0x10000+r((t[1]-f[1])*p+f[1])*0x100+r((t[2]-f[2])*p+f[2])).toString(16).slice(f[3]>-1||t[3]>-1?1:3);\n\t}", "function mix(rgb1, rgb2, amount) {\n var p = amount / 100;\n var rgb = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b\n };\n return rgb;\n}", "function mix(rgb1, rgb2, amount) {\n var p = amount / 100;\n var rgb = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b\n };\n return rgb;\n}", "function mix(rgb1, rgb2, amount) {\n var p = amount / 100;\n var rgb = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b\n };\n return rgb;\n}", "function mix(rgb1, rgb2, amount) {\n var p = amount / 100;\n var rgb = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b\n };\n return rgb;\n}", "function mix(rgb1, rgb2, amount) {\n var p = amount / 100;\n var rgb = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b\n };\n return rgb;\n}", "function mix(rgb1, rgb2, amount) {\n var p = amount / 100;\n var rgb = {\n r: (rgb2.r - rgb1.r) * p + rgb1.r,\n g: (rgb2.g - rgb1.g) * p + rgb1.g,\n b: (rgb2.b - rgb1.b) * p + rgb1.b\n };\n return rgb;\n}", "function lerpColor(col1, col2, s){\n return {r:Math.round(col1.r*(1-s) + col2.r*s),\n g:Math.round(col1.g*(1-s) + col2.g*s),\n b:Math.round(col1.b*(1-s) + col2.b*s)}\n}", "interpolateColors(color1, color2, mix) {\n const c1 = parseInt('0x' + color1.color.substr(1));\n const c1r = c1 >> 16;\n const c1g = c1 >> 8 & 0xff;\n const c1b = c1 & 0xff;\n const c2 = parseInt('0x' + color2.color.substr(1));\n const c2r = c2 >> 16;\n const c2g = c2 >> 8 & 0xff;\n const c2b = c2 & 0xff;\n\n const clampedMix = Math.min(1, Math.max(0, mix));\n const cr = c1r + clampedMix * (c2r - c1r);\n const cg = c1g + clampedMix * (c2g - c1g);\n const cb = c1b + clampedMix * (c2b - c1b);\n\n const colorInt = (cr << 16) + (cg << 8) + (cb | 0);\n let colorHex = '#';\n if (colorInt <= 0xff) {\n colorHex += '0000';\n } else if (colorInt <= 0xffff) {\n colorHex += '00';\n }\n\n return {\n color: `${colorHex}${colorInt.toString(16)}`,\n index: -1\n }\n }", "function interpolateColor(color1, color2, factor) {\n if (arguments.length < 3) { \n factor = 0.5; \n }\n var result = color1.slice();\n for (var i = 0; i < 3; i++) {\n result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));\n }\n return `rgb(${result[0]}, ${result[1]}, ${result[2]})`;\n}", "function antialiased(img, x1, y1, width, height, img2) {\n var x0 = Math.max(x1 - 1, 0),\n y0 = Math.max(y1 - 1, 0),\n x2 = Math.min(x1 + 1, width - 1),\n y2 = Math.min(y1 + 1, height - 1),\n pos = (y1 * width + x1) * 4,\n zeroes = 0,\n positives = 0,\n negatives = 0,\n min = 0,\n max = 0,\n minX, minY, maxX, maxY;\n\n // go through 8 adjacent pixels\n for (var x = x0; x <= x2; x++) {\n for (var y = y0; y <= y2; y++) {\n if (x === x1 && y === y1) continue;\n\n // brightness delta between the center pixel and adjacent one\n var delta = colorDelta(img, img, pos, (y * width + x) * 4, true);\n\n // count the number of equal, darker and brighter adjacent pixels\n if (delta === 0) zeroes++;\n else if (delta < 0) negatives++;\n else if (delta > 0) positives++;\n\n // if found more than 2 equal siblings, it's definitely not anti-aliasing\n if (zeroes > 2) return false;\n\n if (!img2) continue;\n\n // remember the darkest pixel\n if (delta < min) {\n min = delta;\n minX = x;\n minY = y;\n }\n // remember the brightest pixel\n if (delta > max) {\n max = delta;\n maxX = x;\n maxY = y;\n }\n }\n }\n\n if (!img2) return true;\n\n // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing\n if (negatives === 0 || positives === 0) return false;\n\n // if either the darkest or the brightest pixel has more than 2 equal siblings in both images\n // (definitely not anti-aliased), this pixel is anti-aliased\n return (!antialiased(img, minX, minY, width, height) && !antialiased(img2, minX, minY, width, height)) ||\n (!antialiased(img, maxX, maxY, width, height) && !antialiased(img2, maxX, maxY, width, height));\n}", "function interpolate(val, rgb1, rgb2) {\n if (val > 1) {\n val = 1;\n }\n val = Math.sqrt(val);\n var rgb = [0,0,0];\n var i;\n for (i = 0; i < 3; i++) {\n rgb[i] = Math.round(rgb1[i] * (1.0 - val) + rgb2[i] * val);\n }\n return rgb;\n}", "function colorDelta(img1, img2, k, m, yOnly) {\n var a1 = img1[k + 3] / 255,\n a2 = img2[m + 3] / 255,\n\n r1 = blend(img1[k + 0], a1),\n g1 = blend(img1[k + 1], a1),\n b1 = blend(img1[k + 2], a1),\n\n r2 = blend(img2[m + 0], a2),\n g2 = blend(img2[m + 1], a2),\n b2 = blend(img2[m + 2], a2),\n\n y = rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2);\n\n if (yOnly) return y; // brightness difference only\n\n var i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2),\n q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);\n\n return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;\n}", "function interpolateColor(color1, color2, factor) {\n if (arguments.length < 3) { \n factor = 0.5; \n }\n var result = color1.slice();\n for (var i = 0; i < 3; i++) {\n result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));\n }\n return result;\n}", "function colorStep(c1, c2, t) {\n if (t < 0) {\n t = 0;\n } else if (t > 1) {\n t = 1;\n }\n\n return {\n r: parseInt(c1['r'] + (c2['r'] - c1['r']) * t),\n g: parseInt(c1['g'] + (c2['g'] - c1['g']) * t),\n b: parseInt(c1['b'] + (c2['b'] - c1['b']) * t)\n };\n }", "function mix(color1, color2, weight) {\n var normalize = function normalize(n, index) {\n return (\n // 3rd index is alpha channel which is already normalized\n index === 3 ? n : n / 255\n );\n };\n var _parseToRgba$map = parseToRgba(color1).map(normalize),\n _parseToRgba$map2 = _slicedToArray(_parseToRgba$map, 4),\n r1 = _parseToRgba$map2[0],\n g1 = _parseToRgba$map2[1],\n b1 = _parseToRgba$map2[2],\n a1 = _parseToRgba$map2[3];\n var _parseToRgba$map3 = parseToRgba(color2).map(normalize),\n _parseToRgba$map4 = _slicedToArray(_parseToRgba$map3, 4),\n r2 = _parseToRgba$map4[0],\n g2 = _parseToRgba$map4[1],\n b2 = _parseToRgba$map4[2],\n a2 = _parseToRgba$map4[3];\n\n // The formula is copied from the original Sass implementation:\n // http://sass-lang.com/documentation/Sass/Script/Functions.html#mix-instance_method\n var alphaDelta = a2 - a1;\n var normalizedWeight = weight * 2 - 1;\n var combinedWeight = normalizedWeight * alphaDelta === -1 ? normalizedWeight : normalizedWeight + alphaDelta / (1 + normalizedWeight * alphaDelta);\n var weight2 = (combinedWeight + 1) / 2;\n var weight1 = 1 - weight2;\n var r = (r1 * weight1 + r2 * weight2) * 255;\n var g = (g1 * weight1 + g2 * weight2) * 255;\n var b = (b1 * weight1 + b2 * weight2) * 255;\n var a = a2 * weight + a1 * (1 - weight);\n return rgba(r, g, b, a);\n}", "static LerpColor(a, b, t) {\n return new b2.Color(Fracker.Lerp(a.r, b.r, t), Fracker.Lerp(a.g, b.g, t), Fracker.Lerp(a.b, b.b, t));\n }", "function applyBlending(src, dst, opacity, filter) {\n // calculate alpha blending of filter\n // Cs/Cd - source/destination color\n // As/Ad - source/destination alpha\n function blend(Cs, Cd, As, Ad) {\n return As * (1 - Ad) * Cs + As * Ad * filter(Cs, Cd) + (1 - As) * Ad * Cd;\n }\n\n for (var i = 0, n = dst.length; i < n; i += 4)\n {\n var srcA = (src[i+3] / 255) * opacity;\n if (srcA === 0) {\n continue;\n }\n\n var dstA = dst[i+3] / 255;\n\n var blendAlpha = srcA + dstA - dstA * srcA;\n\n dst[i ] = blend(src[i ] / 255, dst[i ] / 255, srcA, dstA) / blendAlpha * 255; // r\n dst[i+1] = blend(src[i+1] / 255, dst[i+1] / 255, srcA, dstA) / blendAlpha * 255; // g\n dst[i+2] = blend(src[i+2] / 255, dst[i+2] / 255, srcA, dstA) / blendAlpha * 255; // b\n dst[i+3] = blendAlpha * 255; // a\n }\n }", "function interpolateColor(color1, color2, factor) {\n if (arguments.length < 3) {\n factor = 0.5;\n }\n var result = color1.slice();\n for (var i = 0; i < 3; i++) {\n result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));\n }\n return result;\n }", "function bres(x1, y1, x2, y2) {\r\n\tloadPixels();\r\n\t\r\n\tvar m_new = 2 * (y2 - y1);\r\n\tvar slope_error_new = m_new - (x2 - x1);\r\n\t\r\n\tvar y = y1\r\n\tfor(var x = x1; x <= x2; x++) {\r\n\t\tpixel[4 * (x + (y * 500))] = 255;\r\n\t\t\r\n\t\tslope_error_new += m_new;\r\n\t\t\r\n\t\tif(slope_error_new >= 0) {\r\n\t\t\ty++;\r\n\t\t\tslope_error_new -= 2 * (x2 - x1);\r\n\t\t}\r\n\t}\r\n\t\r\n\tupdatePixels();\r\n}", "function interpolateColor(color1, color2, factor) {\n if (arguments.length < 3) {\n factor = 0.5;\n }\n var result = color1.slice();\n for (var i = 0; i < 3; i++) {\n result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));\n }\n return result;\n}", "function interpolate(color1, color2, factor) {\n\t if (factor === void 0) {\n\t factor = 0.5;\n\t }\n\n\t var result = color1.slice();\n\n\t for (var i = 0; i < 3; i++) {\n\t result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));\n\t }\n\n\t return result;\n\t }", "combineRGB(percent, rgbLow, rgbDiff) {\n\t\tlet color = 0x000000;\n\t\tcolor |= (percent * rgbDiff.r + rgbLow.r) << 16;\n\t\tcolor |= (percent * rgbDiff.g + rgbLow.g) << 8;\n\t\tcolor |= (percent * rgbDiff.b + rgbLow.b) << 0;\n\t\treturn color;\n\t}", "function add(img1, img2, weight) {\n return blend(img1, img2, function(a, b){return a.mul(weight).add(b.mul(1-weight));});\n}", "function blend(j, k) {\n return blend_beats(i, j, k)\n }", "function pixelMatches(img1, img2, k, m, maxDelta, yOnly) {\n\n if ((k + 3) >= img1.length) {\n throw new Error(`Cannot get positions ${k} through ${k + 3} from img array of length ${img1.length} (in target img)`);\n }\n if ((m + 3) >= img2.length) {\n throw new Error(`Cannot get positions ${m} through ${m + 3} from img array of length ${img2.length} (in sub img)`);\n }\n\n let r1 = img1[k + 0];\n let g1 = img1[k + 1];\n let b1 = img1[k + 2];\n let a1 = img1[k + 3];\n\n let r2 = img2[m + 0];\n let g2 = img2[m + 1];\n let b2 = img2[m + 2];\n let a2 = img2[m + 3];\n\n if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return true;\n\n if (a1 < 255) {\n a1 /= 255;\n r1 = blend(r1, a1);\n g1 = blend(g1, a1);\n b1 = blend(b1, a1);\n }\n\n if (a2 < 255) {\n a2 /= 255;\n r2 = blend(r2, a2);\n g2 = blend(g2, a2);\n b2 = blend(b2, a2);\n }\n\n const y = rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2);\n\n let delta;\n\n if (yOnly) { // brightness difference only\n delta = y;\n } else {\n const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2);\n const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);\n delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;\n }\n return delta <= maxDelta; \n}", "function imgDiff(a, b, walpha, bfactor) {\n\t\tbfactor = bfactor || 1;\n\t\tvar adata = a.data;\n\t\tvar bdata = b.data;\n\t\tvar i, wa, wb, d = 0;\n\t\tfor (i = 0; i < adata.length; i += 4) {\n\n\t\t\twa = wb = 1;\n\t\t\tif (walpha) {\n\t\t\t\twa = (adata[i + 3] / 255);\n\t\t\t\twb = (bdata[i + 3] / 255);\n\t\t\t}\n\t\t\td += (adata[i] + adata[i + 1] + adata[i + 2]) * wa / bfactor -\n\t\t\t\t(bdata[i] + bdata[i + 1] + bdata[i + 2]) * wb;\n\t\t}\n\t\treturn d;\n\t}", "resample_single() {\n const canvas = this.canvas;\n const width = 32;\n const height = 32;\n\n var width_source = canvas.width * 2;\n var height_source = canvas.height * 2;\n\n var ratio_w = width_source / width;\n var ratio_h = height_source / height;\n var ratio_w_half = Math.ceil(ratio_w / 2);\n var ratio_h_half = Math.ceil(ratio_h / 2);\n\n var img = this.ctx.getImageData(0, 0, width_source, height_source);\n var img2 = this.resultCtx.createImageData(width, height);\n var data = img.data;\n var data2 = img2.data;\n\n for(var j = 0; j < height; j++) {\n for(var i = 0; i < width; i++) {\n var x2 = (i + j * width) * 4;\n var weight = 0;\n var weights = 0;\n var weights_alpha = 0;\n var gx_r = 0;\n var gx_g = 0;\n var gx_b = 0;\n var gx_a = 0;\n var center_y = (j + 0.5) * ratio_h;\n var yy_start = Math.floor(j * ratio_h);\n var yy_stop = Math.ceil((j + 1) * ratio_h);\n for(var yy = yy_start; yy < yy_stop; yy++) {\n var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;\n var center_x = (i + 0.5) * ratio_w;\n var w0 = dy * dy; //pre-calc part of w\n var xx_start = Math.floor(i * ratio_w);\n var xx_stop = Math.ceil((i + 1) * ratio_w);\n for(var xx = xx_start; xx < xx_stop; xx++) {\n var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;\n var w = Math.sqrt(w0 + dx * dx);\n if(w >= 1) {\n //pixel too far\n continue;\n }\n //hermite filter\n weight = 2 * w * w * w - 3 * w * w + 1;\n var pos_x = 4 * (xx + yy * width_source);\n //alpha\n gx_a += weight * data[pos_x + 3];\n weights_alpha += weight;\n //colors\n if(data[pos_x + 3] < 255)\n weight = weight * data[pos_x + 3] / 250;\n gx_r += weight * data[pos_x];\n gx_g += weight * data[pos_x + 1];\n gx_b += weight * data[pos_x + 2];\n weights += weight;\n }\n }\n data2[x2] = gx_r / weights;\n data2[x2 + 1] = gx_g / weights;\n data2[x2 + 2] = gx_b / weights;\n data2[x2 + 3] = gx_a / weights_alpha;\n }\n }\n\n //draw\n this.resultCtx.putImageData(img2, 0, 0);\n }", "static get BlendNone() {\n\n return 0; //do not blend\n }", "function findColorDifference(dif, dest, src) {\n\t\treturn (dif * dest + (1 - dif) * src);\n\t}", "function colorDiff(reference, pixel) {\n var r = reference[0] - pixel[0]\n var g = reference[1] - pixel[1]\n var b = reference[2] - pixel[2]\n\n return Math.abs(r) + Math.abs(g) + Math.abs(b)\n}", "function drawPixel(x, y, r, g, b, a, blend_factor) {\n let index = (x + y * canvasWidth) * 4;\n canvasData.data[index + 0] = canvasData.data[index + 0]-(canvasData.data[index + 0]-r)/blend_factor;\n canvasData.data[index + 1] = canvasData.data[index + 1]-(canvasData.data[index + 1]-g)/blend_factor;\n canvasData.data[index + 2] = canvasData.data[index + 2]-(canvasData.data[index + 2]-b)/blend_factor;\n canvasData.data[index + 3] = a;\n}", "function mapCanvasBlendModesToPixi(array)\n{\n array = array || [];\n\n if (canUseNewCanvasBlendModes())\n {\n array[CONST.BLEND_MODES.NORMAL] = 'source-over';\n array[CONST.BLEND_MODES.ADD] = 'lighter'; //IS THIS OK???\n array[CONST.BLEND_MODES.MULTIPLY] = 'multiply';\n array[CONST.BLEND_MODES.SCREEN] = 'screen';\n array[CONST.BLEND_MODES.OVERLAY] = 'overlay';\n array[CONST.BLEND_MODES.DARKEN] = 'darken';\n array[CONST.BLEND_MODES.LIGHTEN] = 'lighten';\n array[CONST.BLEND_MODES.COLOR_DODGE] = 'color-dodge';\n array[CONST.BLEND_MODES.COLOR_BURN] = 'color-burn';\n array[CONST.BLEND_MODES.HARD_LIGHT] = 'hard-light';\n array[CONST.BLEND_MODES.SOFT_LIGHT] = 'soft-light';\n array[CONST.BLEND_MODES.DIFFERENCE] = 'difference';\n array[CONST.BLEND_MODES.EXCLUSION] = 'exclusion';\n array[CONST.BLEND_MODES.HUE] = 'hue';\n array[CONST.BLEND_MODES.SATURATION] = 'saturate';\n array[CONST.BLEND_MODES.COLOR] = 'color';\n array[CONST.BLEND_MODES.LUMINOSITY] = 'luminosity';\n }\n else\n {\n // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough'\n array[CONST.BLEND_MODES.NORMAL] = 'source-over';\n array[CONST.BLEND_MODES.ADD] = 'lighter'; //IS THIS OK???\n array[CONST.BLEND_MODES.MULTIPLY] = 'source-over';\n array[CONST.BLEND_MODES.SCREEN] = 'source-over';\n array[CONST.BLEND_MODES.OVERLAY] = 'source-over';\n array[CONST.BLEND_MODES.DARKEN] = 'source-over';\n array[CONST.BLEND_MODES.LIGHTEN] = 'source-over';\n array[CONST.BLEND_MODES.COLOR_DODGE] = 'source-over';\n array[CONST.BLEND_MODES.COLOR_BURN] = 'source-over';\n array[CONST.BLEND_MODES.HARD_LIGHT] = 'source-over';\n array[CONST.BLEND_MODES.SOFT_LIGHT] = 'source-over';\n array[CONST.BLEND_MODES.DIFFERENCE] = 'source-over';\n array[CONST.BLEND_MODES.EXCLUSION] = 'source-over';\n array[CONST.BLEND_MODES.HUE] = 'source-over';\n array[CONST.BLEND_MODES.SATURATION] = 'source-over';\n array[CONST.BLEND_MODES.COLOR] = 'source-over';\n array[CONST.BLEND_MODES.LUMINOSITY] = 'source-over';\n }\n\n return array;\n}", "function interleave2(x, y) {\n x &= 0xFFFF;\n x = (x | x << 8) & 0x00FF00FF;\n x = (x | x << 4) & 0x0F0F0F0F;\n x = (x | x << 2) & 0x33333333;\n x = (x | x << 1) & 0x55555555;\n y &= 0xFFFF;\n y = (y | y << 8) & 0x00FF00FF;\n y = (y | y << 4) & 0x0F0F0F0F;\n y = (y | y << 2) & 0x33333333;\n y = (y | y << 1) & 0x55555555;\n return x | y << 1;\n }", "function makeRed(){\n for (var pixel of img.values()){\n var avg=(pixel.getRed()+pixel.getGreen()+pixel.getBlue())/3;\n if (avg<128){\n pixel.setRed(2*avg);\n pixel.setGreen(0);\n pixel.setBlue(0);\n }else{\n pixel.setRed(255);\n pixel.setGreen(2*avg-255);\n pixel.setBlue(2*avg-255);\n } \n }\n var cc1=document.getElementById(\"c1\");\n img.drawTo(cc1);\n}", "function wuLine(x1, y1, x2, y2) {\n var canvas = document.getElementById(\"canvas3\");\n var context = canvas.getContext(\"2d\");\n var steep = Math.abs(y2 - y1) > Math.abs(x2 - x1);\n if (steep) {\n x1 = [y1, y1 = x1][0];\n x2 = [y2, y2 = x2][0];\n }\n if (x1 > x2) {\n x1 = [x2, x2 = x1][0];\n y1 = [y2, y2 = y1][0];\n }\n draw(context, colorFigure, steep ? y1 : x1, steep ? x1 : y1);\n draw(context, colorFigure, steep ? y2 : x2, steep ? x2 : y2);\n var dx = x2 - x1;\n var dy = y2 - y1;\n var gradient = dy / dx;\n var y = y1 + gradient;\n for (var x = x1 + 1; x < x2 - 1; x++) {\n colorFigure.a = (1 - (y - Math.floor(y))) * 10000;\n draw(context, colorFigure, x, Math.floor(y));\n colorFigure.a = (y - Math.floor(y)) * 10000;\n draw(context, colorFigure, x, Math.floor(y));\n y += gradient;\n }\n}", "function computeHalfTexCoord(tex1x, tex1y, tex2x, tex2y)\n{\n var newT = [];\n newT.push((tex1x + tex2x) * 0.5);\n newT.push((tex1y + tex2y) * 0.5);\n return newT;\n}", "function addColor(color1, color2){\n // Split string and parse to Integers.\n let rgb1Array = color1.split(\",\").map((value) => parseInt(value, 10) );\n let rgb2Array = color2.split(\",\").map((value) => parseInt(value, 10) );\n\n // Init array to store results\n let newColorArray = [];\n\n //Loop Through RGB, check if numbers are higher than 255, add together values r+r, g+g ,b+b\n for(let i = 0; i <= 2 ;i++ ){\n if(rgb1Array[i] <= 255 && rgb2Array <= 255 || (rgb1Array[i] + rgb2Array[i]) - 45 <= 255){\n // last number is value of dim light.\n newColorArray[i] = rgb1Array[i] + rgb2Array[i] - 45;\n }else{\n newColorArray[i] = 255;\n }\n }\n // Convert values back to String values.\n newColorArray = newColorArray.map((value) => value.toString());\n\n // Join array of Strings back to one String value.\n globalState.color = newColorArray.join();\n}", "function linear_blend_skin_2D( vertices, weights, transforms )\n{\n /// Add your code here.\n var result = []; \n for (var i = 0; i < vertices.length; i++) {\n result[i] = [];\n for (var j = 0; j < 2; j++) {\n result[i][j] = 0;\n }\n }\n for (var i = 0; i < vertices.length; i++) {\n var sum = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]; \n for (var j = 0; j < transforms.length; j++) {\n sum = numeric.add(sum, numeric.mul(weights[i][j], transforms[j]));\n }\n result[i] = numeric.dot(sum, [vertices[i][0], vertices[i][1], 1.0]);\n }\n return result;\n}", "updateColor() {\n if (this.colorToLerpTo == 0) {\n if (this.r != 255) {\n this.r++;\n if (this.g != 20) this.g--;\n if (this.b != 147) this.b--;\n this.color = makeColor(this.r, this.g, this.b);\n } else {\n this.g = 20;\n this.b = 147;\n this.colorToLerpTo = 1;\n this.color = makeColor(this.r, this.g, this.b);\n }\n } else if (this.colorToLerpTo == 1) {\n if (this.g != 255) {\n this.g++;\n if (this.b != 20) this.b--;\n if (this.r != 147) this.r--;\n this.color = makeColor(this.r, this.g, this.b);\n } else {\n this.r = 147;\n this.b = 20;\n this.colorToLerpTo = 2;\n this.color = makeColor(this.r, this.g, this.b);\n }\n } else if (this.colorToLerpTo == 2) {\n if (this.b != 255) {\n this.b++;\n if (this.r != 20) this.r--;\n if (this.g != 147) this.g--;\n this.color = makeColor(this.r, this.g, this.b);\n } else {\n this.g = 147;\n this.r = 20;\n this.colorToLerpTo = 0;\n this.color = makeColor(this.r, this.g, this.b);\n }\n }\n }", "function manipulatePixels(){\n //i) Get all of the rgba pixel data of the canvas by grabbing the image data\n var imageData=ctx.getImageData(0,0,canvas.width, canvas.height);\n\n //ii)imageData.data is an 8-bit typed array- values range from 0-255\n //imageData.data contains 4 values per pixel: 4 x canvas.width x\n //canvas.height = 10240000 values!\n //we are looping through this 60 fps-wow\n var data = imageData.data;\n var length = data.length;\n var width = imageData.width;\n\n //iii)Iteratethrougheachpixel\n //we step by 4 so that we can manipulate pixel per iteration\n //data[i]is the red value\n //data[i+1]is the green value\n //data[i+2]is the blue value\n //data[i+3]is the alpha value\n for(var i=0; i<length; i+=4){\n //increase green value only\n if(tintGreen){\n data[i+1]= data[i]+60; //just the green channel this time\n data[i+5]= data[i]+60; //just the green channel this time\n }\n if(invert){\n var red=data[i], green=data[i+1], blue=data[i+2];\n data[i]=255-red; //set red value\n data[i+1]=255-green; //set blue value\n data[i+2]=255-blue; //set green value\n\n }\n if(noise&&Math.random()<.10){\n //data[i]=data[i+1]=data[i+2]=128 //gray noise\n data[i+4]=data[i+5]=data[i+6]=255; //or white noise\n //data[i]=data[i+1]=data[i+2]=0; //or back noise\n data[i+3]=255; //alpha\n }\n if(lines){\n var row= Math.floor(i/4/width);\n if(row%50==0){\n //this row\n data[i]=data[i+1]= data[i+2]= data[i+3]=255;\n\n //next row\n data[i+(width*4)]=\n data[i+(width*4)+1]=\n data[i+(width*4)+2]=\n data[i+(width*4)+3]=255;\n }\n }\n\n //this sets the greyscale for each particle based on the scale\n //let c equal the value on the scale between 0----->1\n //we want to go from [r,g,b]----->[gr,gr,gr] //let gr equal the color grey\n // (1-c)*[r,g,b] + c*[gr,gr,gr] if c= 0, we get rgb, else if c=1 we get gr \n \n var average = (data[i]+ data[i+1]+ data[i+2])/3; //getting a grey valuev \"gr\"\n var saturated = greyScale*average; //depending on the scale value, change between grey to normal rgb values \"c*gr\"\n var oppositeVal= (1-greyScale); //if callGrey=0, we get rgb, else if callGrey=1, we get grey \"1-c\"\n\n // (1-c)*[r] + c[gr] \n data[i] = oppositeVal* data[i] + saturated;\n // (1-c)*[g] + c[gr] \n data[i+1] = oppositeVal* data[i+1] + saturated;\n // (1-c)*[b] + c[gr] \n data[i+2] = oppositeVal* data[i+2] + saturated; \n }\n\n //put the modified data back on the canvas\n ctx.putImageData(imageData,0,0);\n //console.log(\"was called\");\n }", "function simpleTint(image,r,g,b) {\r var canvas = document.createElement('canvas');\r canvas.width = image.width;\r canvas.height = image.height;\r var context = canvas.getContext(\"2d\");\r context.drawImage(image, 0, 0);\r var imageData = context.getImageData(0,0,canvas.width, canvas.height);\r var pos = 0;\r for (var i = 0; i<imageData.data.length; i+=4) {\r if (imageData.data[i+3]>0) {\r\r imageData.data[i] = Math.max(0,Math.min(255, r));\r imageData.data[i+1] = Math.max(0,Math.min(255, g));\r imageData.data[i+2] = Math.max(0,Math.min(255, b));\r }\r }\r context.putImageData(imageData,0,0);\r return canvas;\r\r}", "function colorMixer(rgbA, rgbB, amountToMix){\n var r = colorChannelMixer(rgbA[0],rgbB[0],amountToMix);\n var g = colorChannelMixer(rgbA[1],rgbB[1],amountToMix);\n var b = colorChannelMixer(rgbA[2],rgbB[2],amountToMix);\n return \"rgb(\"+r+\",\"+g+\",\"+b+\")\";\n}", "shiftRGB({ shift, blend=1, iterations=1, hold=false }) {\n const srcImg = this.img;\n let srcPixels = srcImg.pixels;\n const destPixels = new Uint8ClampedArray(srcImg.pixels);\n\n for (let i = 0; i < iterations; i++) {\n ImgUtil.forEachPixel(srcImg, rgba => rgba.forEach((i, idx) => {\n let j = i;\n if (idx < 3) j = (i + shift[idx]) % srcPixels.length;\n destPixels[i] = srcPixels[j];\n destPixels[i] = srcPixels[i] * (1 - blend) + srcPixels[j] * blend;\n }));\n srcPixels = new Uint8ClampedArray(destPixels);\n }\n\n if (hold) {\n this.holdShiftedImg = true;\n this.shiftedImg = destPixels;\n } else {\n this.holdShiftedImg = false;\n }\n\n ImgUtil.copyPixels(destPixels, this.img);\n return destPixels;\n }", "function colorGradient( color1, color2, ratio) {\n\n\tvar r = Math.ceil( parseInt(color1.substring(0,2), 16) * ratio + parseInt(color2.substring(0,2), 16) * (1-ratio));\n\tvar g = Math.ceil( parseInt(color1.substring(2,4), 16) * ratio + parseInt(color2.substring(2,4), 16) * (1-ratio));\n\tvar b = Math.ceil( parseInt(color1.substring(4,6), 16) * ratio + parseInt(color2.substring(4,6), 16) * (1-ratio));\n\n\t/*var r = Math.ceil( color1.r * ratio + color2.r * (1-ratio) );\n\tvar g = Math.ceil( color1.g * ratio + color2.g * (1-ratio) );\n\tvar b = Math.ceil( color1.b * ratio + color2.b * (1-ratio) );*/\n\t\n\treturn valToHex(r) + valToHex(g) + valToHex(b);\n\n\t//return rgb(r, g, b);\n\t}", "oppositeColors(x1,y1,x2,y2){\r\n if(this.getColor(x1,y1) !== 0 && this.getColor(x2,y2) !== 0 && this.getColor(x1,y1) !== this.getColor(x2,y2)){\r\n return true;\r\n }\r\n return false;\r\n }", "function manipulatePixels() {\r\n\t\r\n\t\tlet imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\r\n\t\t\r\n\t\tlet data = imageData.data;\r\n\t\tlet length = data.length;\t\r\n\t\tlet width = imageData.width;\r\n\t\t\r\n\t\tfor (let i = 0; i < length; i += 4) {\r\n\t\t\tif (tint) {\r\n\t\t\t\t\t// R G B A values are indexed through data[] in that order\r\n\t\t\t\tif(tintColor == \"red\")\r\n\t\t\t\t{\r\n\t\t\t\t\tdata[i] = data[i] + 100;\r\n\t\t\t\t}\r\n\t\t\t\tif(tintColor == \"blue\")\r\n\t\t\t\t{\r\n\t\t\t\t\tdata[i+2] = data[i+2] + 100;\r\n\t\t\t\t}\r\n\t\t\t\tif(tintColor == \"green\")\r\n\t\t\t\t{\r\n\t\t\t\t\tdata[i+1] = data[i+1] + 100;\r\n\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t}\r\n\t\t\tif (invert) {\r\n\t\t\t\tlet red = data[i], green = data[i+1], blue = data[i+2];\r\n\t\t\t\tdata[i] = 255 - red;\r\n\t\t\t\tdata[i+1] = 255 - green;\r\n\t\t\t\tdata[i+2] = 255 - blue;\r\n\t\t\t}\r\n\t\t\tif (noise && Math.random() < .10) {\r\n\t\t\t\tdata[i] = data[i+1] = data[i+2] = 128; // gray noise\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tctx.putImageData(imageData, 0, 0);\r\n\t}", "function filter(__src, f)\n{\n var h = __src.h,\n w = __src.w;\n var dst = new RGBAImage(w, h);\n var data = dst.data,\n data2 = __src.data;\n\n var wf = Math.floor(f.width / 2);\n var hf = Math.floor(f.height / 2);\n var bias = f.bias;\n var factor = f.factor;\n var p = f.p;\n\n if( p && p != 1.0 ) {\n for (var y=0;y<h;y++)\n {\n for (var x=0;x<w;x++)\n {\n var fidx = 0;\n var r, g, b;\n r = g = b = 0;\n var idx = (y*w+x)*4;\n for (var i=-hf, fi=0;i<=hf;i++,fi++)\n {\n var py = clamp(i+y,0,h-1);\n for (var j=-wf, fj=0;j<=wf;j++,fj++)\n {\n var px = clamp(j+x,0,w-1);\n\n var pidx = (py * w + px) * 4;\n\n var weight = f.value[fidx++];\n\n r += Math.pow(data2[pidx] * weight, p);\n g += Math.pow(data2[pidx+1] * weight, p);\n b += Math.pow(data2[pidx+2] * weight, p);\n }\n }\n\n r = clamp(Math.pow(r,1/p)/factor+bias, 0.0, 255.0);\n g = clamp(Math.pow(g,1/p)/factor+bias, 0.0, 255.0);\n b = clamp(Math.pow(b,1/p)/factor+bias, 0.0, 255.0);\n\n data[idx] = r;\n data[idx+1] = g;\n data[idx+2] = b;\n data[idx+3] = data2[idx+3];\n }\n }\n }\n else {\n // p is undefined or p is 1.0\n // no need to compute the power, which is time consuming\n for (var y=0;y<h;y++)\n {\n for (var x=0;x<w;x++)\n {\n var fidx = 0;\n var r, g, b;\n r = g = b = 0;\n var idx = (y*w+x)*4;\n for (var i=-hf, fi=0;i<=hf;i++,fi++)\n {\n var py = clamp(i+y,0,h-1);\n for (var j=-wf, fj=0;j<=wf;j++,fj++)\n {\n var px = clamp(j+x,0,w-1);\n\n var pidx = (py * w + px) * 4;\n\n var weight = f.value[fidx++];\n\n r += data2[pidx] * weight;\n g += data2[pidx+1] * weight;\n b += data2[pidx+2] * weight;\n }\n }\n\n r = clamp(r/factor+bias, 0.0, 255.0);\n g = clamp(g/factor+bias, 0.0, 255.0);\n b = clamp(b/factor+bias, 0.0, 255.0);\n\n data[idx] = r;\n data[idx+1] = g;\n data[idx+2] = b;\n data[idx+3] = data2[idx+3];\n }\n }\n }\n\n return dst;\n}", "function clipDesaturate(r, g, b) {\n l = (.299 * r) + (0.587 * g) + (0.114 * b);\n var ovr = false;\n var ratio = 1;\n if ((r > 1) || (g > 1) || (b > 1)) {\n ovr = true;\n var max = r;\n if (g > max) max = g;\n if (b > max) max = b;\n ratio = 1 / max;\n }\n if (ovr) {\n r -= l;\n g -= l;\n b -= l;\n r *= ratio;\n g *= ratio;\n b *= ratio;\n r += l;\n g += l;\n b += l;\n }\n if (r > 1) r = 1;\n else if (r < 0) r = 0;\n if (g > 1) g = 1;\n else if (g < 0) g = 0;\n if (b > 1) b = 1;\n else if (b < 0) b = 0;\n return {r: r, g: g, b: b, ovr: ovr};\n}", "function luminanace(r, g, b) {\n var a = [r, g, b].map(function (v) {\n v /= 255;\n return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);\n });\n return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;\n} //calculate contrast between two rgb colors", "function hexColorDelta(hex1, hex2) {\n // get red/green/blue int values of hex1\n var r1 = parseInt(hex1.substring(0, 2), 16);\n var g1 = parseInt(hex1.substring(2, 4), 16);\n var b1 = parseInt(hex1.substring(4, 6), 16);\n // get red/green/blue int values of hex2\n var r2 = parseInt(hex2.substring(0, 2), 16);\n var g2 = parseInt(hex2.substring(2, 4), 16);\n var b2 = parseInt(hex2.substring(4, 6), 16);\n // calculate differences between reds, greens and blues\n var r = 255 - Math.abs(r1 - r2);\n var g = 255 - Math.abs(g1 - g2);\n var b = 255 - Math.abs(b1 - b2);\n // limit differences between 0 and 1\n r /= 255;\n g /= 255;\n b /= 255;\n // 0 means opposit colors, 1 means same colors\n return (r + g + b) / 3;\n}", "async function bind(first_cat_image, second_cat_image, width, height) {\n\t\tif (first_cat_image !== null && second_cat_image !== null) {\n\t\t\t\n\t\t\tconst blankImage = await sharp({\n\t\t\t\tcreate: {\n\t\t\t\t\twidth: width * 2,\n\t\t\t\t\theight: height,\n\t\t\t\t\tchannels: 4,\n\t\t\t\t\tbackground: { r: 0, g: 0, b: 0, alpha: 0 }\n\t\t\t\t}\n\t\t\t}).toFormat('jpeg').toBuffer();\n\n\t\t\tconst firstBind = await sharp(blankImage)\n\t\t\t\t.composite([{ input: first_cat_image, gravity: 'southwest' }])\n\t\t\t\t.toFormat('jpeg').toBuffer();\n\n\t\t\tconst secondBind = await sharp(firstBind)\n\t\t\t\t.composite([{ input: second_cat_image, gravity: 'southeast' }])\n\t\t\t\t.toFormat('jpeg').toBuffer();\n\n\t\t\treturn secondBind;\n\t\t}\n\t}", "pack(v) {\n let bias = [1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0];\n\n let r = v;\n let g = this.fract(r * 255.0);\n let b = this.fract(g * 255.0);\n let a = this.fract(b * 255.0);\n let colour = [r, g, b, a];\n\n let dd = [colour[1]*bias[0],colour[2]*bias[1],colour[3]*bias[2],colour[3]*bias[3]];\n\n return [colour[0]-dd[0],colour[1]-dd[1],colour[2]-dd[2],colour[3]-dd[3] ];\n }", "function combineRGBComponents(r, g, b\n /* , a*/\n ) {\n return (\n /* a << 24 |*/\n r << 16 | g << 8 | b\n );\n }", "function interpolate(rgb1, rgb2, percent) {\n percent = _Math__WEBPACK_IMPORTED_MODULE_0__[\"fitToRange\"](percent, 0, 1);\n if (rgb1) {\n if (rgb2) {\n return {\n r: rgb1.r + Math.round((rgb2.r - rgb1.r) * percent),\n g: rgb1.g + Math.round((rgb2.g - rgb1.g) * percent),\n b: rgb1.b + Math.round((rgb2.b - rgb1.b) * percent),\n a: (rgb1.a || 1) + Math.round(((rgb2.a || 1) - (rgb1.a || 1)) * percent)\n };\n }\n else {\n return rgb1;\n }\n }\n else if (rgb2) {\n return rgb2;\n }\n else {\n return rgb1;\n }\n}", "function clipDarken(r, g, b) {\n var ovr = false;\n var ratio = 1;\n if ((r > 1) || (g > 1) || (b > 1)) {\n ovr = true;\n var max = r;\n if (g > max)\n max = g;\n if (b > max)\n max = b;\n ratio = 1 / max;\n }\n r *= ratio;\n g *= ratio;\n b *= ratio;\n if (r > 1) r = 1;\n else if (r < 0) r = 0;\n if (g > 1) g = 1;\n else if (g < 0) g = 0;\n if (b > 1) b = 1;\n else if (b < 0) b = 0;\n return {r: r, g: g, b: b, ovr: ovr};\n}", "bluer(){\n\t\tthis.multiplyColorValue(\"blue\", 1.2);\n\t}", "function colorimage(){\n\tvar colorimageobject = new Image(512, 512);\n \t//console.log(original_x);\n \t//console.log(original_y);\n \t//console.log(scale_ratio*512);\n \tcolorimageobject.onerror = function(){\n \t\talert(\"No color image to overlay! Setting to default colored image.\");\n \t\tcolorimageobject.src = \"transparent.png\";\n \t}\n\n \tcolorimageobject.onload = function(){\n \t\tvar filterImageData = image2imageData(colorimageobject);\n \t\tvar transparentImageData = white2transparentImageData(filterImageData);\n \t\tvar transparentDataURL = imageData2dataURL(transparentImageData);\n \t\t//console.log(transparentDataURL);\n \t\tvar transparentimageobject = new Image(512, 512);\n \t\ttransparentimageobject.onload = function(){\n \t\t\tvar defaultctx = document.getElementById(drawing_layer_ID).getContext(\"2d\");\n \t\t\tdefaultctx.clearRect(2, 2, document.getElementById(drawing_layer_ID).width-4, document.getElementById(drawing_layer_ID).height-4);\n \t\t\tdefaultctx.drawImage(transparentimageobject, original_x, original_y, Math.ceil(scale_ratio*512), Math.ceil(scale_ratio*512));\n \t\t}\n \t\ttransparentimageobject.src = transparentDataURL;\n \t\n \t\t//var defaultctx = document.getElementById(\"defaultCanvas0\").getContext(\"2d\");\n \t\t//defaultctx.drawImage(colorimageobject, original_x/2, original_y/2, Math.ceil(scale_ratio*512/2), Math.ceil(scale_ratio*512/2));\n \t}\n \tcolorimageobject.src = \"color2.png\";\n\t//colorimageobject.crossOrigin = \"anonymous\";\n}", "function compareColorsNormalized(r1,g1,b1,r2,g2,b2){\n var d = Math.sqrt((r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) * (b2 - b1));\n var p = d / Math.sqrt(3 * 255 * 255);\n return 100*p;\n}", "constructor(color1, color2) {\n\t// param color1: first color (factor = 0)\n\t// param color2: second color (factor = 1)\n\t\tthis.color1 = st_hex_to_rgb(color1);\n\t\tthis.color2 = st_hex_to_rgb(color2);\n\t}", "function setColors2(gl) {\n\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Uint8Array([\n // left column front\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n\n // top rung front\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n\n // middle rung front\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n 200, 70, 120,\n\n // left column back\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n\n // top rung back\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n\n // middle rung back\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n 80, 70, 200,\n\n // top\n 70, 200, 210,\n 70, 200, 210,\n 70, 200, 210,\n 70, 200, 210,\n 70, 200, 210,\n 70, 200, 210,\n\n // top rung right\n 200, 200, 70,\n 200, 200, 70,\n 200, 200, 70,\n 200, 200, 70,\n 200, 200, 70,\n 200, 200, 70,\n\n // under top rung\n 210, 100, 70,\n 210, 100, 70,\n 210, 100, 70,\n 210, 100, 70,\n 210, 100, 70,\n 210, 100, 70,\n\n // between top rung and middle\n 210, 160, 70,\n 210, 160, 70,\n 210, 160, 70,\n 210, 160, 70,\n 210, 160, 70,\n 210, 160, 70,\n\n // top of middle rung\n 70, 180, 210,\n 70, 180, 210,\n 70, 180, 210,\n 70, 180, 210,\n 70, 180, 210,\n 70, 180, 210,\n\n // right of middle rung\n 100, 70, 210,\n 100, 70, 210,\n 100, 70, 210,\n 100, 70, 210,\n 100, 70, 210,\n 100, 70, 210,\n\n // bottom of middle rung.\n 76, 210, 100,\n 76, 210, 100,\n 76, 210, 100,\n 76, 210, 100,\n 76, 210, 100,\n 76, 210, 100,\n\n // right of bottom\n 140, 210, 80,\n 140, 210, 80,\n 140, 210, 80,\n 140, 210, 80,\n 140, 210, 80,\n 140, 210, 80,\n\n // bottom\n 90, 130, 110,\n 90, 130, 110,\n 90, 130, 110,\n 90, 130, 110,\n 90, 130, 110,\n 90, 130, 110,\n\n // left side\n 160, 160, 220,\n 160, 160, 220,\n 160, 160, 220,\n 160, 160, 220,\n 160, 160, 220,\n 160, 160, 220]),\n gl.STATIC_DRAW);\n}", "function change() {\n noStroke();\n img.loadPixels();\n for (var x = 0; x < img.width; x++) {\n for (var y = 0; y < img.height; y++) {\n var currentPixel = img.get(x,y);\n //This is for the r,g,b, values and if they go over or under 0 or 255\n currentPixel[0] = currentPixel[0]+ input.value();\n currentPixel[1] = currentPixel[1]+ input.value();\n currentPixel[2] = currentPixel[2]+ input.value();\n \n if (currentPixel[0]>255){\n currentPixel[0] = currentPixel[1] - input.value();\n }\n if (currentPixel[0]<0){\n currentPixel[0] = currentPixel[1] + input.value();\n }\n if (currentPixel[1]>255){\n currentPixel[1] = currentPixel[1] - input.value();\n }\n if (currentPixel[1]<0){\n currentPixel[1] = currentPixel[1] + input.value();\n }\n if (currentPixel[2]>255){\n currentPixel[2] = currentPixel[1] - input.value();\n }\n if (currentPixel[2]<0){\n currentPixel[2] = currentPixel[1] + input.value();\n }\n \n \n\n \n fill(currentPixel[0],currentPixel[1],currentPixel[2])\n rect(x,y,1,1);\n }\n }\n updatePixels(); \n \n}", "function colorDistance(e1, e2) {\n //console.log(\"e1e2a: \", e1, e2);\n e1 = tinycolor(e1);\n e2 = tinycolor(e2);\n //console.log(\"e1e2b: \", e1, e2);\n var rmean = (e1._r + e2._r) / 2;\n var r = e1._r - e2._r;\n var g = e1._g - e2._g;\n var b = e1._b - e2._b;\n\n return Math.sqrt((((512 + rmean) * r * r) / 256) + 4 * g * g + (((767 - rmean) * b * b) / 256));\n }", "function DownSample4x (source : RenderTexture, dest : RenderTexture){\n off = 1.0f;\n Graphics.BlitMultiTap (source, dest, fogMaterial,\n new Vector2(-off, -off),\n new Vector2(-off, off),\n new Vector2( off, off),\n new Vector2( off, -off)\n );\n}", "function lumaDistance(r1, g1, b1, r2, g2, b2){\n const redDistance = r1 - r2;\n const greenDistance = g1 - g2;\n const blueDistance = b1 - b2;\n\n return redDistance * redDistance * 0.299 + greenDistance * greenDistance * 0.587 + blueDistance * blueDistance * 0.114;\n}", "static Renorm1(...args) {\n let [r, g, b, a] = args;\n if (a === undefined) {\n return [r / 255, g / 255, b / 255];\n } else {\n return [r / 255, g / 255, b / 255, a / 255];\n }\n }", "function makeGrey(){\n for (var pixel of img.values()){\n var avg=(pixel.getRed()+pixel.getGreen()+pixel.getBlue())/3;\n pixel.setRed(avg);\n pixel.setGreen(avg);\n pixel.setBlue(avg); \n }\n var cc1=document.getElementById(\"c1\");\n img.drawTo(cc1);\n}", "function pixelDiffPNGs(img1, img2) {\n return pixelmatch(img1.data, img2.data, null, img1.width, img1.height);\n}", "function brightCanvas( image ) {\n \tvar alpha, dirLuminance;\n \tvar ratio = 0.95; // set to 0.95\n \tif (ratio < 0.0) {\n \talpha = 1 + ratio;\n \tdirLuminance = 0; // blend with black\n \t} else {\n \talpha = 1 - ratio;\n \tdirLuminance = 1; // blend with white\n \t}\n\n \tfor (var x = 0; x < image.width; x++) {\n \tfor (var y = 0; y < image.height; y++) {\n \tvar pixel = getPixel(image, x, y);\n\n \tpixel[0] = (alpha * pixel[0]/255. + (1-alpha) * dirLuminance)*255;\n \tpixel[1] = (alpha * pixel[1]/255. + (1-alpha) * dirLuminance)*255;\n \tpixel[2] = (alpha * pixel[2]/255. + (1-alpha) * dirLuminance)*255;\n\n \tsetPixel(image, pixel, x, y);\n \t}\n \t}\n\n \treturn image;\n}", "function pickHex(weight, color1, color2) {\n let w1 = weight;\n let w2 = 1 - w1;\n let rgb = [Math.round(color1.red * w1 + color2.red * w2),\n Math.round(color1.green * w1 + color2.green * w2),\n Math.round(color1.blue * w1 + color2.blue * w2)];\n return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';\n }", "function colorMixer(rgbA, rgbB, amountToMix) {\r\n\t\tvar r = colorChannelMixer(rgbA[0], rgbB[0], amountToMix),\r\n\t\t\tg = colorChannelMixer(rgbA[1], rgbB[1], amountToMix),\r\n\t\t\tb = colorChannelMixer(rgbA[2], rgbB[2], amountToMix);\r\n\t\treturn 'rgb(' + r + ',' + g + ',' + b + ')';\r\n\t}", "function redEffect(pixels) {\n // looping through each and every pixel we have\n for(let i = 0; i < pixels.data.length; i += 4) {\n // the first one + 0 adding a 100 and so on for the others no definitive values but just random ones\n pixels.data[i + 0] = pixels.data[i + 0] + 200; // RED\n pixels.data[i + 1] = pixels.data[i + 1] - 50; // GREEN\n pixels.data[i + 2] = pixels.data[i + 2] * 0.5; // Blue\n }\n // now return it bitch\n return pixels;\n}", "function brighten(amt) {\r\n\tamt = (amt > 1) ? 1 : amt;\r\n\tamt = (amt < -1) ? -1 : amt;\r\n\tamt = ~~(255 * amt);\r\n\tloadPixels();\r\n\tfor (var y = 0; y < height; y++) {\r\n\t\tfor (var x = 0; x < width; x++) {\r\n\t\t\tvar i = (x + y * width) * 4;\r\n\t\t\tpixels[i] += amt;\r\n\t\t\tpixels[i+1] += amt;\r\n\t\t\tpixels[i+2] += amt;\r\n\t\t}\r\n\t}\r\n\tupdatePixels();\r\n}", "function multiply(color1) {\n\t var result = color1.slice();\n\n\t for (var _len4 = arguments.length, colors = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {\n\t colors[_key4 - 1] = arguments[_key4];\n\t }\n\n\t for (var i = 0; i < 3; i++) {\n\t for (var j = 0; j < colors.length; j++) {\n\t result[i] *= colors[j][i] / 255;\n\t }\n\n\t result[i] = Math.round(result[i]);\n\t }\n\n\t return result;\n\t }", "function gradientFillLayerMask( fromPoint, toPoint )\n{\n\tfunction pointDesc( pt )\n\t{\n\t\tvar desc = new ActionDescriptor();\n\t\tdesc.putUnitDouble( keyHorizontal, unitPixels, pt.fX );\n\t\tdesc.putUnitDouble( keyVertical, unitPixels, pt.fY );\n\t\treturn desc;\n\t}\n\t\n\tfunction stopDesc( location, midPoint )\n\t{\n\t\tvar desc = new ActionDescriptor();\n\t\tdesc.putInteger( keyLocation, location );\n\t\tdesc.putInteger( keyMidpoint, midPoint );\n\t\treturn desc;\n\t}\n\t\n\tfunction grayDesc( grayValue )\n\t{\n\t\tvar desc = new ActionDescriptor();\n\t\tdesc.putDouble( enumGray, grayValue );\n\t\treturn desc;\n\t}\n\n\tvar args = new ActionDescriptor();\n\targs.putObject( keyFrom, classPoint, pointDesc( fromPoint ) );\n\targs.putObject( keyTo, classPoint, pointDesc( toPoint ) );\n\targs.putEnumerated( keyMode, typeBlendMode, enumDarken );\n\targs.putEnumerated( keyType, typeGradientType, enumLinear );\n\targs.putBoolean( keyDither, true );\n\targs.putBoolean( keyUseMask, true );\n\targs.putBoolean( keyReverse, true );\n\t\n\tvar gradDesc = new ActionDescriptor();\n\tgradDesc.putString( keyName, \"White, Black\" );\n\tgradDesc.putEnumerated( typeGradientForm, typeGradientForm, enumCustomStops );\n\tgradDesc.putDouble( keyInterpolation, 4096.000000 );\n\t\n\tvar colorList = new ActionList();\n\tvar stop = stopDesc( 0, 50 );\n//\tstop.putEnumerated( keyType, typeColorStopType, enumForegroundColor );\n\tstop.putObject( classColor, classGrayscale, grayDesc( 100 ) );\n\tstop.putEnumerated( keyType, typeColorStopType, enumUserStop );\n\tcolorList.putObject( classColorStop, stop );\n\tstop = stopDesc( 4096, 50 );\n//\tstop.putEnumerated( keyType, typeColorStopType, enumBackgroundColor );\n\tstop.putObject( classColor, classGrayscale, grayDesc( 0 ) );\n\tstop.putEnumerated( keyType, typeColorStopType, enumUserStop );\n\tcolorList.putObject( classColorStop, stop );\n\tgradDesc.putList( typeColors, colorList );\n\t\n\tvar xferList = new ActionList();\n\tvar xfer = stopDesc( 0, 50 );\n\txfer.putUnitDouble( keyOpacity, unitPercent, 100.000000 );\n\txferList.putObject( keyTransferSpec, xfer );\n\txfer = stopDesc( 4096, 50 );\n\txfer.putUnitDouble( keyOpacity, unitPercent, 100.000000 );\n\txferList.putObject( keyTransferSpec, xfer );\n\t\n\tgradDesc.putList( keyTransparency, xferList );\n\targs.putObject( keyGradient, classGradient, gradDesc );\n\texecuteAction( eventGradient, args, DialogModes.NO );\n}", "function multiply_(color1) {\n\t for (var _len5 = arguments.length, colors = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {\n\t colors[_key5 - 1] = arguments[_key5];\n\t }\n\n\t for (var i = 0; i < 3; i++) {\n\t for (var j = 0; j < colors.length; j++) {\n\t color1[i] *= colors[j][i] / 255;\n\t }\n\n\t color1[i] = Math.round(color1[i]);\n\t }\n\n\t return color1;\n\t }", "function edge( __src ) {\n var gx = grayscale( filter(__src, new Filter.hsobel()) );\n var gy = grayscale( filter(__src, new Filter.vsobel()) );\n\n // sqrt(gx^2 + gy^2)\n var h = gx.h,\n w = gx.w;\n var g = new RGBAImage(w, h);\n var data = g.data,\n data1 = gx.data,\n data2 = gy.data;\n\n for (var idx=0;idx<w*h*4;idx++)\n {\n data[idx] = clamp(Math.sqrt(data1[idx] * data1[idx] + data2[idx] * data2[idx]), 0.0, 255.0);\n }\n\n var dst = new RGBAImage(w, h);\n var ddata = dst.data, sdata = __src.data;\n for (var y= 0, idx = 0;y<h;y++)\n {\n for (var x=0;x<w;x++, idx+=4)\n {\n ddata[idx+0] = sdata[idx+0] * data[idx] / 255.0;\n ddata[idx+1] = sdata[idx+1] * data[idx] / 255.0;\n ddata[idx+2] = sdata[idx+2] * data[idx] / 255.0;\n ddata[idx+3] = 255;\n }\n }\n return dst;\n}" ]
[ "0.77154845", "0.75974333", "0.72799206", "0.72799206", "0.72740066", "0.7221746", "0.7195399", "0.69225717", "0.6917332", "0.68476653", "0.68445396", "0.6819772", "0.67996424", "0.67159295", "0.6688296", "0.66803706", "0.66134334", "0.6602085", "0.65860164", "0.6539119", "0.6538469", "0.65060043", "0.6500331", "0.6378337", "0.63474715", "0.63169134", "0.63169134", "0.63169134", "0.63169134", "0.63169134", "0.63169134", "0.6129231", "0.61094993", "0.6076786", "0.6050404", "0.6033322", "0.60320735", "0.60234386", "0.60149497", "0.5991521", "0.59897727", "0.5952242", "0.59441197", "0.59407336", "0.5940675", "0.5913513", "0.589714", "0.58935225", "0.5859932", "0.5828297", "0.58269763", "0.5806286", "0.57891965", "0.5783639", "0.57776064", "0.57749265", "0.5771083", "0.57672864", "0.57334393", "0.570581", "0.5693092", "0.56925213", "0.5687183", "0.5654342", "0.56507987", "0.56405306", "0.56392395", "0.5628833", "0.5612335", "0.5591774", "0.55563134", "0.55544376", "0.555206", "0.5541492", "0.55406797", "0.5539709", "0.5528313", "0.5518915", "0.5511535", "0.54888266", "0.54865086", "0.5471073", "0.5469548", "0.545515", "0.54497737", "0.54444903", "0.54336727", "0.54262376", "0.5415935", "0.54085374", "0.54048395", "0.5399628", "0.5397546", "0.539595", "0.53937787", "0.5390433", "0.53832674", "0.53768", "0.5372652", "0.53725654", "0.53658277" ]
0.0
-1
var logElement = $(".overlaytext1");
function updateParallax2(e) { if (isFirefox) return; e = window.event ? window.event : e; var delta = e.wheelDelta ? e.wheelDelta : -e.detail; delta = Math.floor( delta * 0.1 ); // console.log("wheel delta " + delta); e.preventDefault(); document.body.scrollTop -= delta; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function appendToLogs(text) {\n $(\"#log\").append(\"<br>\" + $(\"<div/>\").text(text).html());\n}", "function log(text) {\t \n\t$(\"#datawindow\").append(\"<p>\" + text + \"</p>\");\n}", "function log(text){\n $('#consoleOutput').append('<p>'+text+'</p>');\n}", "function mylog(divTag, logTxt) {\n if (globalMyLog) {\n var element = document.getElementById(divTag);\n document.getElementById(divTag).innerText = element.innerText + logTxt + \" :-- \";\n }\n}", "function LOG(){\r\n\t\tvar content = document.getElementById(\"PSMWE_content2\");\r\n\t\tcontent.innerHTML = Log; \r\n}", "function showLogOverlay () {\n document.getElementById('js-accessory-overlay').style.display = \"block\";\n document.getElementById(\"js-message-log-area\").style.display = \"block\";\n}", "function createLogMessageElement(text) {\n var container = document.createElement('div');\n container.className = \"log-entry-container clearfix\";\n container.style = \"opacity: 1; text-align:center;\";\n \n var textElem = document.createElement('i');\n textElem.className = \"log-entry-message\";\n $(textElem).html(text);\n \n container.appendChild(textElem);\n \n return container;\n}", "function log(text) {\n\tvar l = document.getElementById('log');\n\tl.innerHTML += \"<p>\" + text + \"</p>\";\n}", "function getLogObj() {\r\n\r\n autoPlayLogId = Date();\r\n\r\n var newText = $(\"<span id='\" + autoPlayLogId + \"'>\" + ((autoPlay)?\"AutoPlay ON (Inicializando...)\":\"AutoPlay OFF\") + \"</span>\")[0]\r\n\r\n return newText;\r\n\r\n}", "get cardaddedmsg () { return $('//*[@id=\"top\"]/body//div[2]/ul//li/span') }", "function log(txt) {\n old = document.getElementById(\"test_log\").innerHTML;\n document.getElementById(\"test_log\").innerHTML = old + \"<br>\" + txt;\n}", "function displayOverlay(){\n var $overlay = $('<div id=\"overlay\" class=\"row\"></div>');\n var $msg1 = $('<div class=\"span12\"><h1 id=\"lightbox-text\" class=\"text-center\">you need to be logged in to vote!</h1></div>');\n var $msg2 = $('<div class=\"span12\"><p id=\"lightbox-text\" class=\"text-center\">Please login with Facebook or Google+</p></div>');\n var $socialIcons = $('<div class=\"span3 offset3\"><a href=\"/login/facebook/?next=/stats/\"><img class=\"lightbox-icon1\" src=\"/static/img/facebookicon.png\" alt=\"facebookicon\"></a><a href=\"/login/google-oauth2/?next=/stats/\"><img class=\"lightbox-icon2\" src=\"/static/img/googleicon.png\" alt=\"googleicon\"></a></div>');\n $overlay.append($msg1);\n $overlay.append($msg2);\n $overlay.append($socialIcons);\n $overlay.lightbox_me({\n centered: true\n });\n}", "function get_score_elem(overlay) {\n score = overlay.getElementsByClassName(\"match-score\");\n if (score.length > 0) {\n return score[0];\n }\n\n return null;\n}", "function pageLog(msg) {\n document.getElementById(\"log-div\").getElementsByTagName(\"p\")[0].innerHTML += msg + \"<br>\";\n}", "function scrollTextOverlays(){\n $(\".overlay-text\").each(function(){\n\n var parentBottom = $(this).parent()[0].getBoundingClientRect().bottom;\n var parentTop = $(this).parent()[0].getBoundingClientRect().top;\n\n if(parentTop <= 80 && parentBottom > 80){\n if($(this).hasClass(\"hidden\")){\n $(this).removeClass(\"hidden\");\n }\n } else {\n if (!$(this).hasClass(\"hidden\")) {\n $(this).addClass(\"hidden\");\n }\n }\n });\n}", "function log(text){\n var date = new Date();\n $('#log').prepend('<span class=\"time\">'+date.toLocaleString()+':</span>'+text+'<br>');\n}", "function log(message) {\n var pre = document.createElement(\"p\");\n pre.innerHTML = message;\n var status = document.getElementById(\"displayData2\");\n status.appendChild(pre);\n}", "function hideLogOverlay () {\n document.getElementById('js-accessory-overlay').style.display = \"none\";\n document.getElementById(\"js-overlay-text-chat\").style.display = \"none\";\n document.getElementById(\"js-overlay-color-change\").style.display = \"none\";\n document.getElementById(\"js-message-log-area\").style.display = \"none\";\n document.getElementById(\"js-chat-history-area\").style.display = \"none\";\n}", "function overlayOn() {\n console.log(\"overlay on\");\n //$(\"#overlay\").css(\"display\", \"block\");\n}", "function botMessageElement() {\n return $(\".bot_scenario textarea[name='\" + $('input.messages_focus').val() + \"']\");\n}", "function mylog(s) {\n var DEBUG_ELEMENT = document.getElementById(\"debugOutput\"); \n DEBUG_ELEMENT.innerHTML += s + \"<br />\"; \n}", "function element() {\n\n\t\t/* -------------------------------------------------- */\n\t\t/* FUNCTIONS\n\t\t/* -------------------------------------------------- */\n\n\t\t//removeIf(production)\n\t\tfunction log(eventName, element) {\n\n\t\t\tconsole.log(Date.now(), eventName, element.getAttribute('data-src'));\n\n\t\t}\n\t\t//endRemoveIf(production)\n\n\n\t\t/* -------------------------------------------------- */\n\t\t/* ANIMATIONS\n\t\t/* -------------------------------------------------- */\n\n\t\tfunction revealCopy(element) {\n\n\t\t\tif ( $(element).find('.section-container-text-block').find('h1').length ) {\n\n\t\t\t\tconsole.log('elements exist.');\n\n\t\t\t\tvar h1 = new SplitText($(element).find('h1'), {type: 'words, lines, chars', reduceWhiteSpace: true, position: null}), \n\t\t\t\t\t$h1 = h1.lines;\n\n\t\t\t\tvar tlH1 = new Timeline({paused: false, onComplete: function() { h1.revert(); } });\n\t\t\t\t\ttlH1.staggerFrom($h1, 1, {autoAlpha: 0, y: 25, ease: Expo.easeInOut}, 0.025);\n\n\t\t\t\t\ttlH1.delay(2).play(0);\n\n\t\t\t}\n\n\t\t\tif ( $(element).find('.section-container-text-block').find('p').length ) {\n\n\t\t\t\tconsole.log('elements exist.');\n\n\t\t\t\tvar p = new SplitText($(element).find('p'), {type: 'words, lines, chars', reduceWhiteSpace: true, position: null}), \n\t\t\t\t\t$p = p.lines;\n\n\t\t\t\tvar tlP = new Timeline({paused: false, onComplete: function() { p.revert(); } });\n\t\t\t\t\ttlP.staggerFrom($p, 1, {autoAlpha: 0, y: 25, ease: Expo.easeInOut}, 0.025);\n\n\t\t\t\t\ttlP.delay(2).play(0);\n\n\t\t\t}\n\n\t\t\tif ( $(element).find('.section-container-text-block').find('ul').length ) {\n\n\t\t\t\tconsole.log('elements exist.');\n\n\t\t\t\tvar list = new SplitText($(element).find('ul').children(), {type: 'words, lines, chars', reduceWhiteSpace: true, position: null}), \n\t\t\t\t\t$list = list.lines;\n\n\t\t\t\tvar tlList = new Timeline({paused: false, onComplete: function() { list.revert(); } });\n\t\t\t\t\ttlList.staggerFrom($list, 1, {autoAlpha: 0, y: 25, ease: Expo.easeInOut}, 0.025);\n\n\t\t\t\t\ttlList.delay(2).play(0);\n\n\t\t\t}\n\n\t\t}\t\t\n\n\n\t\t/* -------------------------------------------------- */\n\t\t/* OPTIONS\n\t\t/* -------------------------------------------------- */\n\n\t\tvar options = {\n\t\t\tcontainer: document,\n\t\t\telements_selector: '.section-container',\n\t\t\tthreshold: 0,\n\t\t\tthresholds: '0% 0% 0% 0%', // top, right, bottom, left\n\t\t\t//load_delay: 100,\n\t\t\tauto_unobserve: false,\n\t\t\tuse_native: false,\n\n\t\t\tcallback_enter: function(element) {\n\n\t\t\t\t//console.log('Entered the viewport', element);\n\t\t\t\t$(element).addClass('in-view');\n\t\t\t\t//revealCopy(element);\n\n\t\t\t},\n\n\t\t\tcallback_exit: function(element) {\n\n\t\t\t\t//console.log('Left the viewport', element);\n\t\t\t\t$(element).removeClass('in-view');\n\n\t\t\t}\n\n\t\t};\n\n\n\t\t/* -------------------------------------------------- */\n\t\t/* INIT\n\t\t/* -------------------------------------------------- */\n\n\t\tvar lazyLoad = new LazyLoad(options);\n\n\n\t\t/* -------------------------------------------------- */\n\t\t/* HELPERS\n\t\t/* -------------------------------------------------- */\n\n\t\t//lazyLoad.update();\n\t\t//lazyLoad.load(element, force);\n\t\t//lazyLoad.loadAll();\n\t\t//lazyLoad.destroy();\n\n\t}", "function createLogEntryElement(label, text, pt) {\n var container = document.createElement('div');\n container.className = \"log-entry-container clearfix\";\n \n var labelElem = document.createElement('b');\n labelElem.className = \"log-entry-label\";\n $(labelElem).html(label);\n \n var textElem = document.createElement('div');\n textElem.className = \"log-entry-text\";\n $(textElem).html(text);\n \n container.appendChild(labelElem);\n container.appendChild(textElem);\n \n container.onclick = function (ev) {\n if (!actualMainButtonState) {\n pt.load();\n $logModal.modal('hide');\n }\n }\n \n return container;\n}", "function gameLog (message) {\n\t$(\"#log\").prepend(\"<li>\" + message + \"</li>\");\n}", "function userMessageElement() {\n return $(\".user_scenario textarea[name='\" + $('input.messages_focus').val() + \"']\");\n}", "function getLogObj() {\r\n\r\n autoPlayLogId = Date();\r\n\r\n var newText = document.createElement('span');\r\n newText.id = autoPlayLogId;\r\n newText.innerHTML = (autoPlay)?\"AutoPlay ON (Inicializando...)\":\"AutoPlay OFF\";\r\n \r\n return newText;\r\n\r\n}", "function writeToLog(message){\n\t$(\"#log\").append(\"<li class='list-group-item'>\" + message + \"</li>\");\n}", "_geneToastEle(id, text) {\n let div = document.createElement('div');\n div.id = id.toString();\n div.className = 'toast toast-body my-toast'\n div.innerText = text\n document.body.appendChild(div)\n return div\n }", "function main() {\n var $skillset = $('.skillset'); \n alert($skillset);\n}", "function Overlay (main_element, options){\n}", "function log() {\n var logElem = document.querySelector(\".tracker\");\n\n var time = new Date();\n console.log(time);\n logElem.innerHTML += time;\n}", "function newScreenMsg(text){\r\n let newTextBox = document.createElement(\"div\");\r\n let newTextContent = document.createElement(\"p\"); \r\n $(newTextBox).addClass(\"bubble user\").append(newTextContent);\r\n $(newTextContent).append(text);\r\n\r\n let screenSpace = document.getElementById(\"screen\"); \r\n $(screenSpace).append(newTextBox);\r\n\r\n \r\n //add time\r\n let timeStamp = new Date().toLocaleTimeString();\r\n let timeSpace = document.createElement(\"p\");\r\n $(timeSpace).addClass(\"time\");\r\n $(newTextBox).append(timeSpace)\r\n $(timeSpace).append(timeStamp);\r\n console.log(timeStamp);\r\n}", "function setOverlayText(value) {\n browser.getElement('overlay-text').innerText = value;\n}", "function writeOverlay(to) {\n if (to != 'Empty') {\n for (let i = 0; i < texts.length; i++) {\n console.log(`Identifier: ${texts[i][0]}, Text: ${texts[i][1]}, Searching for: ${to}`);\n if (texts[i][0] == to) {\n $('#innerOverlayContainer').html(texts[i][1]);\n return;\n }\n }\n } else {\n $('#innerOverlayContainer').html('');\n }\n}", "function wtolog(msg) {\n var log = document.getElementById(\"log\");\n var m = document.createElement(\"p\");\n m.innerHTML = msg;\n log.appendChild(m);\n\n // Scroll to the latest log entry\n $(document).scrollTop($(m).position().top);\n}", "function alerts(alrtMsgs , time){\n const alrt = document.querySelector(\".alerts\");\n const alrtMsg = document.querySelector(\".alrtMsg\")\n console.log(alrt);\n alrt.style.opacity = \"1\";\n alrt.style.transform= \"translateY(300px)\"\n alrtMsg.textContent = alrtMsgs; \n setTimeout(function(){ alrt.style.opacity = \"0\"; }, time); \n}", "function alerts(alrtMsgs , time){\n const alrt = document.querySelector(\".alerts\");\n const alrtMsg = document.querySelector(\".alrtMsg\")\n console.log(alrt);\n alrt.style.opacity = \"1\";\n alrt.style.transform= \"translateY(300px)\"\n alrtMsg.textContent = alrtMsgs; \n setTimeout(function(){ alrt.style.opacity = \"0\"; }, time); \n}", "function showOverlayMessage(text) {\n $(\".overlay\").removeClass(\"black-bg\").addClass(\"white-bg\").fadeIn(\"slow\");\n if($(\".status-show\").hasClass(\"preloader\")){\n $(\".preloader\").html(text); \n } else {\n $(\".status-show\").css(\"display\", \"block\");\n $(\".status-show\").addClass(\"message\");\n toCenter($(\".message\"), 500, 200);\n $(\".message\").html(\"<div class='status-text'>\"+ text + \"<button type='button' class='orange-butt'> OK </button>\" + \"</div>\");\n }\n }", "function logMessage(msg, id){\n if (!id){\n id=\"output\";\n }\n document.getElementById(id).innerHTML += msg + \"<br>\";\n}", "function newScreenMsg(text){\r\n let newTextBox = document.createElement(\"div\");\r\n let newTextContent = document.createElement(\"p\"); \r\n $(newTextBox).addClass(\"bubble user\").append(newTextContent);\r\n $(newTextContent).append(text);\r\n\r\n let screenSpace = document.getElementById(\"screen\"); \r\n $(screenSpace).append(newTextBox);\r\n\r\n //add time\r\n let timeStamp = new Date().toLocaleTimeString();\r\n let timeSpace = document.createElement(\"p\");\r\n $(timeSpace).addClass(\"time\");\r\n $(newTextBox).append(timeSpace);\r\n $(timeSpace).append(addTimeFormat(timeStamp));\r\n}", "function logAlert(text,layOut,type,timeOut){\n \n noty({\"text\":text,\n \"layout\":layOut,\n \"type\":type,\n \"textAlign\":\"center\",\n \"easing\":\"swing\",\n \"animateOpen\":{\"height\":\"toggle\"},\n \"animateClose\":{\"height\":\"toggle\"},\n \"speed\":\"500\",\n \"timeout\":timeOut,\n \"closable\":false,\"closeOnSelfClick\":false});\n \n}", "function log(message) {\n var moveLog = document.getElementById('move-log');\n moveLog.innerHTML += message + \"</br>\";\n}", "function robotResponse1() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/gabby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> Indeed, some parts were horrible.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Gabby Mendoza on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function logMessage(msg, id) {\n if (!id) {\n id = \"output\";\n }\n document.getElementById(id).innerHTML += msg + \"<br>\";\n}", "function logMessage(msg, id) {\n if (!id) {\n id = \"output\";\n }\n document.getElementById(id).innerHTML += msg + \"<br>\";\n}", "function logMessage(msg, id) {\n if (!id) {\n id = \"output\";\n }\n document.getElementById(id).innerHTML += msg + \"<br>\";\n}", "function addLog(logText) {\n const logDiv = $('log-entries');\n if (!logDiv) {\n return;\n }\n logDiv.appendChild(document.createElement('hr'));\n const textDiv = document.createElement('div');\n textDiv.innerText = logText;\n logDiv.appendChild(textDiv);\n}", "function displayLogMessages(message)\n{\n\tvar msg = message.replace(/\\\\n/g, \"<br/>\");\n\tvar $elem = \"<p>\" + msg + \"</p>\";\n\n\t$(\"#stamsgs\").empty();\n\t$(\"#stamsgs\").append($elem);\n}", "function log(e) {\n var e = $(\"<p>\" + new Date().getHours() + \":\" + new Date().getMinutes() + \":\" + new Date().getSeconds() + \" -> \" + e + \"</p>\");\n $(\"#events_11\").prepend(e);\n // e.animate({\n // opacity: 1\n // }, 10000, 'linear', function() {\n // e.animate({\n // opacity: 0\n // }, 20000, 'linear', function() {\n // e.remove();\n // });\n // });\n }", "function log(data)\n{\n\t$('#chatEntries').append(data);\n}", "function showTip(element, message)\r\n{\r\n var tipMarkup = \"<div class=\\\"tip\\\"><div class=\\\"pointer\\\"></div>\" + message + \"</div>\";\r\n element.first().append(tipMarkup);\r\n}", "function cLogElement( elem ) {\n if ( allowLog ) {\n console.log( elem );\n }\n}", "function showText(e){\n $(e).html($(e).find('span').html());\n}", "function on() {\n $('.overlay').css('display', 'block');\n}", "function appendText(text) {\n let resultsLog = document.getElementById(\"round-result\");\n resultsLog.innerHTML += \"<br></br>\" + text;\n}", "constructor(overlay, seeMore, closeOverlay){\n this.overlay = document.querySelector(overlay);\n this.seeMore = document.querySelector(seeMore);\n this.closeOverlay = document.querySelector(closeOverlay);\n }", "function newBotMsg(text){\r\n let newTextBoxBot = document.createElement(\"div\");\r\n let newTextContentBot = document.createElement(\"p\");\r\n $(newTextBoxBot).addClass(\"bubble bot\").append(newTextContentBot);\r\n $(newTextContentBot).append(text);\r\n\r\n let screenSpace = document.getElementById(\"screen\"); \r\n $(screenSpace).append(newTextBoxBot);\r\n\r\n //add time\r\n let timeStamp = new Date().toLocaleTimeString();\r\n let timeSpace = document.createElement(\"p\");\r\n $(timeSpace).addClass(\"time\");\r\n $(newTextBoxBot).append(timeSpace);\r\n $(timeSpace).append(addTimeFormat(timeStamp));\r\n}", "function writeToEventLog(text) {\r\n $(\"#event-log\").prepend(`<p class=\"event-fragment\">${text}</p>`)\r\n}", "static get __attachedInstances(){return Array.from(document.body.children).filter(el=>el instanceof OverlayElement)}", "function entryMessage() {\n $EntryMessage = $(\"<h1>\");\n $EntryMessage.text(\"Welcome to the Weather Planner! Enter a city to get the current weather and the 5 day forecast...\");\n $(\".currentWeather\").append($EntryMessage);\n}", "function get_title(overlay) {\n title = overlay.getElementsByClassName(\"bob-title\");\n if (title.length > 0) {\n return title[0].innerHTML;\n }\n\n return null;\n}", "function log( text ) {\n\t\t$log = $('#log');\n\t\t//Add text to log\n\t\t$log.append(($log.val()?\"\\n\":'')+text);\n\t\t//Autoscroll\n\t\t$log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;\n}", "function logMessage(text, type) {\n type = type || \"info\";\n $(\".action-log .log-content\").prepend(createLogMessage(text, type));\n}", "logOutput (msg) {\n this.DOMNodes.runMessage.className = \"hidden\";\n let node = document.createElement(\"div\");\n node.innerHTML = msg;\n this.DOMNodes.log.appendChild(node);\n }", "function createToast(msg){\n var sec = '<section class=\"comToast\"><i><em class=\"rotate\"></em>'+msg+'</i></section>'\n $(\"body\").append(sec)\n}", "function robotResponse21() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/abby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> Sorry, I do not understand what you mean.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Abby Hume on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function createInstanceLogger(element)\r\n\t{\r\n\t\tvar elementName = element.attr('name');\r\n\r\n\t\treturn function(message)\r\n\t\t{\r\n\t\t console.log('Neo4jControls(' + (elementName === undefined ? \"\" : elementName) + '):' + message);\r\n\t\t};\r\n\t}", "function log(text,delta=\"classic\",animate=true){\n obj = document.getElementById(\"logger\");\n if(obj)\n obj.innerHTML += \"<p class='tester \"+delta+\"'>\"+text+\"</p>\";\n //obj.scrollTop = obj.scrollHeight-obj.offsetHeight -1;\n //setTimeout(removeAnimation,1000)\n if (animate) {\n elements = obj.getElementsByTagName(\"p\");\n for (i=0;i<elements.length-1;i++) {\n elements[i].className = elements[i].className.replace('tester',\"\");\n }\n\n last = elements[elements.length-1];\n last.addEventListener(\"webkitAnimationEnd\", myEndFunction);\n }\n //last.setAttribute(\"line\",idx)\n obj.scrollTop = obj.scrollHeight-obj.offsetHeight -1;\n return last\n }", "function log(message) {\n var childDiv = document.createElement(\"div\");\n var textNode = document.createTextNode(message);\n childDiv.appendChild(textNode);\n document.getElementById(\"log\").appendChild(childDiv);\n }", "function printAlert($alert,$id_name){\n\t$(\".alert-area\").append(\"<div class=\\\"alert alert-warning\\\" role=\\\"alert\\\">\"+$id_name+\" \"+$alert+\"</div>\");\n}", "function displayBoxContents (myElement)\t{\n\tvar boxToDisplay = myElement.target;\n\tconsole.log(boxToDisplay);\n\talert('the box id is: '+ boxToDisplay.id +'\\nthe box background color is: '+ boxToDisplay.style.backgroundColor +'\\nthe box top and left metrics are: '+ boxToDisplay.style.top + ' and ' + boxToDisplay.style.left);\n\t\t\n}", "function log(msg) {\n $('#console').append('<p>' + msg + '</p>');\n}", "function logText() {\n //Instantiating chat history inside chatLog\n let textToBeSent = document.getElementById(\"textBox\").value;\n\n let newDiv = document.createElement(\"div\");\n newDiv.setAttribute(\"id\", \"userMessage\");\n\n newDiv.textContent = textToBeSent;\n\n //appending message to the chat log\n chatLog.appendChild(newDiv);\n\n chatLog.appendChild(document.createElement(\"br\"));\n\n //logging message into the class chat history\n chatHistory.logUserMessage(textToBeSent);\n\n //Resetting textbox\n document.getElementById(\"textBox\").value = \"\";\n}", "function log(e, msg) {\n document.getElementById('log').innerHTML += \"\\n\" + e + \" \" + (msg || '');\n}", "function getTextElem(elem) {\n return getWrapper(elem).querySelector(\".svg-map-text\");\n }", "function LOG(stringToLog) {\n var pTag = document.createElement(\"p\");\n pTag.setAttribute(\"align\",\"left\");\n pTag.innerHTML = stringToLog;\n var logDiv = document.getElementById('logOutput');\n logDiv.appendChild(pTag);\n}", "function robotResponse6() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/gabby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> Hi Alison.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Gabby Mendoza on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function showLevel (){\n $msg = $('.level');\n $msg.show();\n}", "function log(txt) {\n console.log(txt);\n output.innerHTML += txt + '\\n';\n}", "get toastMessage () {\n return element(by.css(\"#toastMessage\"));\n }", "function robotResponse2() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/abby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> I really like this resource.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Abby Hume on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function log(message){\r\n \r\n console.log(message);\r\n/********************************************************** \r\n var logger = $($.mobile.activePage).find('textarea');\r\n var time = formateDate(new Date());\r\n var existings = logger.text();\r\n if(\" \" == existings){\r\n logger.text('[' + time + ']' + ' ' + message + '\\n');\r\n } else {\r\n existings += '[' + time + ']' + ' ' + message + '\\n';\r\n logger.text(existings);\r\n }\r\n logger.attr('rows', parseInt(logger.attr('rows')) + 3);\r\n**********************************************************/\r\n}", "function robotResponse3() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/gabby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> Yeah I definitely agree.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Gabby Mendoza on ' + newdate + '</p></div></div></div><hr>');\r\n }", "el() {\n return $('#metadata');\n }", "function logMove(message) {\r\n if (typeof message == 'string') {\r\n document.getElementById(\"log\").innerText += message + \"\\n\";\r\n }\r\n console.log(message) ;\r\n}", "function robotResponse9() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/abby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> I guess those are some pretty valid points.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Abby Hume on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function robotResponse7() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/abby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> I actually liked this one, any reasons why you thought it was bad?' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Abby Hume on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function writeText(elements = [],message){\n elements.forEach((el) => { Array.from(document.querySelectorAll(el)).forEach((e) => { e.innerText = message; }); });\n}", "function displayMessage(type,message)\n{\n messageEL.text(message);\n messageEL.attr(\"class\",type);\n\n}", "el() {\n return $('.automate-tags-container');\n }", "function robotResponse4() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/gabby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> Thanks for sharing this article.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Gabby Mendoza on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function displayMessage(type, message) {\n var msgDiv = $(\"#msgDiv\");\n msgDiv.text = message;\n msgDiv.attr(\"class\", type);\n}", "function Log(str)\r\n{\r\n\tvar currentDate = new Date()\r\n\r\n\tunsafeWindow.$('#Log_Div').append(\"<div>[\" + currentDate.getHours() + \":\" + currentDate.getMinutes() + \":\" + currentDate.getSeconds() + \"] \" + str + \"</div>\");\r\n\tScrollBottom(\"Log_Div\")\r\n}", "function getTrigger($layer) {\n return (0, _jquery2.default)('[aria-controls=\"' + $layer.attr('id') + '\"]');\n}", "function takeclass(){\r\n\tconsole.log(\"FUNCTION BEING RUN\");\r\n\tconsole.log($(\".take1class\"));\r\n\t$(\".take1class\").html(\"Intro to Business\");\r\n\t$(\".take2class\").html(\"Intro to Marketing\");\r\n\t$(\".take3class\").html(\"Intro to Finance\");\r\n}", "function UIgenerate() {\n var o = document.getElementById( 'overlay' );\n\n for ( var u = 0; u < ui.length; u++ ) {\n o.appendChild( ui[ u ].dom() );\n var s = document.createElement( 'span' );\n s.innerHTML = '&nbsp&nbsp'\n o.appendChild( s );\n }\n\n\n}", "function ftls(){\n\t\tif ($(\"#finger-tracing-learning-system-imitation-checkbox\").is(\":checked\")) {\n $('body > *').not('[role=\"dialog\"]').each(function (index) {\n var characters = $(this).html().split(\"\");\n \t\t\t\t\t\t\t\tvar proceed = true;\n\t\t\t\t\t\t\t\tvar string = '';\n $.each(characters, function (i, el) {\n \tif(el == \"<\"){proceed = false}\n \t\t\t\t\t\t\tif(proceed){\n \t\t\t\t\t\t\t\tstring += '<span>' + el + '</span>';\n \t\t\t\t\t\t\t} else {\n \t\t\t\t\t\t\t\tstring += el;\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t\tif(el == \">\"){proceed = true}\n });\n\t\t\t\t$(this).html(string);\n\t\t\t\t\t\t})\n\t\t\t$(\"span\").css(\"opacity\", 0.25).mouseenter(function() {\n\t\t\t\t$(this).fadeTo( \"fast\", 1 );\n\t\t\t});\n\t\t} else {\n\t\t $(\"span\").css(\"opacity\", 1);\n\t\t}\n\t}", "function getColorText(){\n // will return a string inside the color text span\n return $('#colorText').html();\n}", "function robotResponse10() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/abby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> Hmm, I am not sure I agree with those statements.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Abby Hume on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function message(msg) {\n $(\"#logger\").text(msg);\n }", "function newBotMsg(text){\r\n let newTextBox = document.createElement(\"div\");\r\n let newTextContent = document.createElement(\"p\"); \r\n $(newTextBox).addClass(\"bubble bot\").append(newTextContent);\r\n $(newTextContent).append(text);\r\n\r\n let screenSpace = document.getElementById(\"screen\"); \r\n $(screenSpace).append(newTextBox);\r\n\r\n addTime();\r\n\r\n function addTime() {\r\n\r\n //add time\r\n let timeStamp = new Date().toLocaleTimeString();\r\n let timeSpace = document.createElement(\"p\");\r\n $(timeSpace).addClass(\"time\");\r\n $(newTextBox).append(timeSpace)\r\n $(timeSpace).append(timeStamp);\r\n console.log(timeStamp);\r\n }\r\n //add time\r\n // let timeStamp = new Date().toLocaleTimeString();\r\n // let timeSpace = document.createElement(\"p\");\r\n // $(timeSpace).addClass(\"time\");\r\n // $(newTextBox).append(timeSpace)\r\n // $(timeSpace).append(timeStamp);\r\n // console.log(timeStamp);\r\n}" ]
[ "0.62317586", "0.6054275", "0.58416647", "0.5835165", "0.5753291", "0.57480377", "0.56529653", "0.5640447", "0.56026524", "0.5497163", "0.5435345", "0.539482", "0.53787166", "0.5368364", "0.5338706", "0.5325973", "0.5316682", "0.5311445", "0.53062785", "0.5278675", "0.52565265", "0.52364844", "0.52328247", "0.52277774", "0.5218017", "0.5192804", "0.5185527", "0.51571447", "0.51561314", "0.51442915", "0.513708", "0.513067", "0.51295334", "0.5118829", "0.5114397", "0.51097924", "0.51097924", "0.51093113", "0.51081604", "0.5103863", "0.51004905", "0.5093897", "0.50906104", "0.5089365", "0.5089365", "0.5089365", "0.50865185", "0.5083811", "0.50820535", "0.50758344", "0.5074038", "0.5063286", "0.5057878", "0.504847", "0.5047902", "0.50472254", "0.50393474", "0.502865", "0.5026685", "0.50171345", "0.50167125", "0.50110805", "0.5003299", "0.49922857", "0.49922287", "0.49860418", "0.49818072", "0.49781322", "0.49746987", "0.4967755", "0.49607292", "0.4960237", "0.4959717", "0.49458376", "0.49354482", "0.49348232", "0.4933038", "0.49283472", "0.49105984", "0.49085927", "0.48952", "0.4893494", "0.48919073", "0.48895788", "0.48860002", "0.48839647", "0.4882928", "0.48802623", "0.4877345", "0.48696783", "0.48662058", "0.4864183", "0.48623314", "0.48603252", "0.48557472", "0.48501152", "0.48492846", "0.4847688", "0.48385385", "0.48256814", "0.48246238" ]
0.0
-1
Access an unsigned byte at location index.
at(index) { return this.bytes[index] & 0xff; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getByte(idx) { return data.charCodeAt(idx); }", "getByte(index) {\n return this.track.floppyDisk.binary[this.track.offset + this.offset + index];\n }", "function getByte(bytes, offset) {\n return bytes.charCodeAt(offset) % 256;\n }", "getByte() {\n const r16 = this.registers.regs16;\n let pc = r16.get(r16.idx.PC);\n pc++;\n r16.set(r16.idx.PC, pc);\n return this.memory[pc - 1];\n }", "function getByte(dataView, offset) {\r\n\t return dataView.getUint8(offset);\r\n\t}", "function getByte(dataView, offset) {\n return dataView.getUint8(offset);\n }", "function getByte(dataView, offset) {\n return dataView.getUint8(offset);\n}", "readUInt8() {\n const buf = this.readBytes(1);\n return buf[0];\n }", "function readByte() {\n\t\t\treturn ram[pointerAddress];\n\t\t}", "get(index) {\n if (index < 0 || index >= this.length) {\n throw new Error(\"Index error\");\n }\n return memory.get(this.ptr + index);\n }", "setIndex(index) {\n index = index | 0;\n\n if (index < 0 || index > 63) {\n return false;\n }\n\n this.data.writeUInt8(index, 1);\n }", "at(index) {}", "get(index) {\n if(index < 0 || index >= this.length) {\n throw new Error('Index error')\n }\n return memory.get(this.ptr + index)\n }", "function getLetter(index) {\n return String.fromCharCode(64 + index);\n}", "readUint8 () {\n return this.uint8arr[this.pos++]\n }", "function get_bit(descreate_index) {\n index = descreate_index * bit_size;\n //offset = index - Math.round(index);\n \n c.fillStyle = \"rgb(255,0,0)\";\n c.fillRect(index_start+index ,y_debug,1,5);\n \n var count = 0;\n var total = 0;\n for (var i=index ; i<index+bit_size ; i++) {\n total += pixeldata[Math.round(i)];\n count++;\n }\n var r = Math.abs(Math.round(total / count)-1);\n //console.log('total:'+total+' count:'+count+' return:'+r);\n return r;\n }", "function _putBytesInternal($this, index, v) {\n var array = $this.array;\n for (var i = 0; i < v.length; i++) {\n array[i + index] = v[i] & 255;\n }\n }", "function _putBytesInternal($this, index, v) {\n var array = $this.array;\n for (var i = 0; i < v.length; i++) {\n array[i + index] = v[i] & 255;\n }\n }", "u8() {\n return this.buffer[this.at++];\n }", "function index(row, col) {\n return row * 8 + col;\n }", "function bnByteValue() {\n return this.t == 0 ? this.s : this[0] << 24 >> 24;\n}", "function bnByteValue()\n{\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24;\n}", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }", "function chr(x) {\n \t\treturn String.fromCharCode(0xFF & x);\n \t}", "function readUInt (buffer, bits, offset, isBigEndian) {\n offset = offset || 0;\n var endian = isBigEndian ? 'BE' : 'LE';\n var method = buffer['readUInt' + bits + endian];\n return method.call(buffer, offset);\n}", "getWord (addr) {\n // make sure that the address is within bounds\n addr = Memory.wrap(addr, this.SIZE);\n // publish a retrieve event\n this.events.retrieve.dispatch(addr, this.data[addr], 16 );\n return this.data[addr];\n }", "function at(position) {\n return value.charAt(position)\n }", "function at(position) {\n return value.charAt(position)\n }", "function at(position) {\n return value.charAt(position)\n }", "function at(position) {\n return value.charAt(position)\n }", "function readUInt (buffer, bits, offset, isBigEndian) {\n offset = offset || 0;\n var endian = !!isBigEndian ? 'BE' : 'LE';\n var method = buffer['readUInt' + bits + endian];\n return method.call(buffer, offset);\n}", "function ix(i, j){\n\t\treturn j * (width) + i; \n\t}", "function at(position) {\n return value.charAt(position);\n }", "function read8Bit(ba, o) {\n return ba[o];\n }", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24\n}", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24\n}", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24\n}", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24\n}", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24\n}", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24\n}", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24\n}", "getAt(idx) {\n if(idx >= this.length || idx < 0) {\n throw new Error(\"Invalid index.\");\n }\n return this._get(idx).val;\n }", "function bnByteValue() {\n return this.t == 0 ? this.s : this[0] << 24 >> 24;\n }", "function bnByteValue() {\n return this.t == 0 ? this.s : this[0] << 24 >> 24;\n }", "function bnByteValue() {\n return this.t == 0 ? this.s : this[0] << 24 >> 24;\n }", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24;\n}", "function bnByteValue() {\n return (this.t == 0) ? this.s : (this[0] << 24) >> 24;\n}", "function getBit(number, location) {\n return ((number >> location) & 1);\n}", "function popByte() {\n return( memory[regPC++] & 0xff );\n}", "getOffset(b) {\nreturn this.offsetVector[b];\n}", "function getUShort(dataView, offset) {\n return dataView.getUint16(offset, false);\n}", "function getUShort(dataView, offset) {\n return dataView.getUint16(offset, false);\n}", "function accessElementInArray(array,index){\n return array[index]\n}", "function getUShort(dataView, offset) {\n return dataView.getUint16(offset, false);\n }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }", "function getUShort(dataView, offset) {\r\n\t return dataView.getUint16(offset, false);\r\n\t}", "function accessElementInArray(array, index){\nreturn array[index];\n}", "function accessElementInArray(array, index){\n return array[index];\n}", "charAt(index) {return this.code[index];}" ]
[ "0.7577003", "0.66853446", "0.65939295", "0.61405", "0.61396", "0.61205125", "0.6051274", "0.60481846", "0.5847378", "0.5762398", "0.5715135", "0.56778294", "0.5675783", "0.56644213", "0.5624583", "0.5612432", "0.56009465", "0.56009465", "0.55862105", "0.5496427", "0.5490163", "0.547392", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5470581", "0.5462277", "0.54527307", "0.54333353", "0.54257286", "0.54257286", "0.54257286", "0.54257286", "0.5424558", "0.54185236", "0.54087263", "0.54049546", "0.5404461", "0.5404461", "0.5404461", "0.5404461", "0.5404461", "0.5404461", "0.5404461", "0.5401091", "0.5396625", "0.5396625", "0.5396625", "0.5385559", "0.5385559", "0.5375313", "0.53713965", "0.5369573", "0.5367733", "0.5367733", "0.53565997", "0.534294", "0.53406984", "0.53406984", "0.53406984", "0.53406984", "0.53406984", "0.53406984", "0.53406984", "0.53406984", "0.53406984", "0.53406984", "0.5334154", "0.532679", "0.53017396", "0.5297233" ]
0.77251947
0
Copy count bytes from array source starting at offset.
_set(source, offset, count) { if (source == null) { this.bytes[offset] = count; } else { this.bytes = new Array(count); this.Size = count; for (var x = 0; x < count; x++) { // Flex doesn't know bytes -> make it a byte if (source[offset + x] > 127) { this.bytes[x] = (256-source[offset + x])*-1; } else { this.bytes[x] = source[offset + x]; } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function arrayCopy(src, srcOffset, dest, destOffset, count) {\n if (count == 0) {\n return;\n } \n if (!src) {\n throw \"Undef src\";\n } else if (!dest) {\n throw \"Undef dest\";\n }\n\n if (srcOffset == 0 && count == src.length) {\n arrayCopy_fast(src, dest, destOffset);\n } else if (hasSubarray) {\n arrayCopy_fast(src.subarray(srcOffset, srcOffset + count), dest, destOffset); \n } else if (src.BYTES_PER_ELEMENT == 1 && count > 100) {\n arrayCopy_fast(new Uint8Array(src.buffer, src.byteOffset + srcOffset, count), dest, destOffset);\n } else { \n arrayCopy_slow(src, srcOffset, dest, destOffset, count);\n }\n\n}", "function arrayCopy(src, srcOffset, dest, destOffset, count) {\n if (count == 0) {\n return;\n }\n if (!src) {\n throw \"Undef src\";\n } else if (!dest) {\n throw \"Undef dest\";\n }\n\n if (srcOffset == 0 && count == src.length) {\n arrayCopy_fast(src, dest, destOffset);\n } else if ( src.subarray ) {\n arrayCopy_fast(src.subarray(srcOffset, srcOffset + count), dest, destOffset);\n } else if (src.BYTES_PER_ELEMENT == 1 && count > 100) {\n arrayCopy_fast(new Uint8Array(src.buffer, src.byteOffset + srcOffset, count), dest, destOffset);\n } else {\n arrayCopy_slow(src, srcOffset, dest, destOffset, count);\n }\n\n}", "function arrayCopy(src, srcOffset, dest, destOffset, count) {\n if (count == 0) {\n return;\n }\n\n if (!src) {\n throw \"Undef src\";\n } else if (!dest) {\n throw \"Undef dest\";\n }\n\n if (srcOffset == 0 && count == src.length) {\n arrayCopy_fast(src, dest, destOffset);\n } else if (hasSubarray) {\n arrayCopy_fast(src.subarray(srcOffset, srcOffset + count), dest, destOffset);\n } else if (src.BYTES_PER_ELEMENT == 1 && count > 100) {\n arrayCopy_fast(new Uint8Array(src.buffer, src.byteOffset + srcOffset, count), dest, destOffset);\n } else {\n arrayCopy_slow(src, srcOffset, dest, destOffset, count);\n }\n}", "function arraycopy(src, srcpos, dest, destpos, length) {\n for (var i = 0; i < length; ++i) \n dest[i+destpos] = src[i+srcpos];\n}", "function arrayCopy(src, srcIndex, dst, dstIndex, len) {\n for (var j = 0; j < len; ++j) {\n dst[j + dstIndex] = src[j + srcIndex];\n }\n}", "function arrBufferCopy(sourceArr,destArr,sourceStartIdx,destStartIdx,numVals){\n var i = 0;\n while(sourceArr[sourceStartIdx+i] !== undefined && destArr[destStartIdx+i] !== undefined && numVals > 0){\n destArr[destStartIdx+i] = sourceArr[sourceStartIdx+i];\n numVals--;\n i++;\n }\n}", "function acopy(src, srcStart, dest, destStart, length) {\n for (var i = 0; i < length; i += 1) {\n dest[i + destStart] = src[i + srcStart];\n }\n}", "fill(buffers, totalLength) {\n this._size = Math.min(this.capacity, totalLength);\n let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0;\n while (totalCopiedNum < this._size) {\n const source = buffers[i];\n const target = this.buffers[j];\n const copiedNum = source.copy(target, targetOffset, sourceOffset);\n totalCopiedNum += copiedNum;\n sourceOffset += copiedNum;\n targetOffset += copiedNum;\n if (sourceOffset === source.length) {\n i++;\n sourceOffset = 0;\n }\n if (targetOffset === target.length) {\n j++;\n targetOffset = 0;\n }\n }\n // clear copied from source buffers\n buffers.splice(0, i);\n if (buffers.length > 0) {\n buffers[0] = buffers[0].slice(sourceOffset);\n }\n }", "fill(buffers, totalLength) {\n this._size = Math.min(this.capacity, totalLength);\n let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0;\n while (totalCopiedNum < this._size) {\n const source = buffers[i];\n const target = this.buffers[j];\n const copiedNum = source.copy(target, targetOffset, sourceOffset);\n totalCopiedNum += copiedNum;\n sourceOffset += copiedNum;\n targetOffset += copiedNum;\n if (sourceOffset === source.length) {\n i++;\n sourceOffset = 0;\n }\n if (targetOffset === target.length) {\n j++;\n targetOffset = 0;\n }\n }\n // clear copied from source buffers\n buffers.splice(0, i);\n if (buffers.length > 0) {\n buffers[0] = buffers[0].slice(sourceOffset);\n }\n }", "copy(\n targetBuffer,\n targetStart = 0,\n sourceStart = 0,\n sourceEnd = this.length\n ) {\n const sourceBuffer = this.subarray(sourceStart, sourceEnd);\n targetBuffer.set(sourceBuffer, targetStart);\n return sourceBuffer.length;\n }", "function copy (from, to, offset) {\n validate(from);\n validate(to);\n\n offset = offset || 0;\n\n for (var channel = 0, l = Math.min(from.numberOfChannels, to.numberOfChannels); channel < l; channel++) {\n to.getChannelData(channel).set(from.getChannelData(channel), offset);\n }\n\n return to;\n}", "function arrayCopy(from, fromStartIndex, to, toStartIndex, length) {\n\n for (var toIndex = to.length - 1 + length; toIndex >= toStartIndex; toIndex--) {\n to[toIndex] = to[toIndex - length]\n }\n\n for (var offset = 0; offset < length; offset++) {\n to[toStartIndex + offset] = from[fromStartIndex + offset]\n }\n return to;\n}", "function copy(src, dst, dst_offset) {\n if (src.length + dst_offset > dst.length) throw new Error('buffer is too small');\n\n if (src.copy) {\n src.copy(dst, dst_offset);\n } else {\n dst.set(src, dst_offset);\n }\n}", "function move(\r\n dest,\r\n destPos,\r\n source,\r\n sourcePos,\r\n numSamples)\r\n {\r\n System.arraycopy(source, sourcePos*numChannels, dest, destPos*numChannels, numSamples*numChannels);\r\n }", "function copyInt_(x,n) {\n var i,c;\n for (c=n,i=0;i<x.length;i++) {\n x[i]=c & mask;\n c>>=bpe;\n }\n }", "writeData(data, count) {\n var indices = this._lockTypedArray();\n\n // if data contains more indices than needed, copy from its subarray\n if (data.length > count) {\n\n // if data is typed array\n if (ArrayBuffer.isView(data)) {\n data = data.subarray(0, count);\n indices.set(data);\n } else {\n // data is array, copy right amount manually\n var i;\n for (i = 0; i < count; i++)\n indices[i] = data[i];\n }\n } else {\n // copy whole data\n indices.set(data);\n }\n\n this.unlock();\n }", "function copyOrder(dest, src) {\n dest.length = 0;\n\n for (var i = 0; i < src.length; i++) {\n dest.push(src[i].slice(0));\n }\n }", "function concat_arraybuffers(arr, len) {\n var tmp = new Uint8Array(len);\n arr.reduce(function (i, x) {\n tmp.set(new Uint8Array(x), i);\n return i + x.byteLength;\n }, 0);\n return tmp.buffer;\n}", "function copyingSlice(buff, start, end) {\n if ( start === void 0 ) start = 0;\n if ( end === void 0 ) end = buff.length;\n\n if (start < 0 || end < 0 || end > buff.length || start > end) {\n throw new TypeError((\"Invalid slice bounds on buffer of length \" + (buff.length) + \": [\" + start + \", \" + end + \"]\"));\n }\n if (buff.length === 0) {\n // Avoid s0 corner case in ArrayBuffer case.\n return emptyBuffer();\n }\n else {\n var u8 = buffer2Uint8array(buff), s0 = buff[0], newS0 = (s0 + 1) % 0xFF;\n buff[0] = newS0;\n if (u8[0] === newS0) {\n // Same memory. Revert & copy.\n u8[0] = s0;\n return uint8Array2Buffer(u8.slice(start, end));\n }\n else {\n // Revert.\n buff[0] = s0;\n return uint8Array2Buffer(u8.subarray(start, end));\n }\n }\n}", "function copyBuffer(buf, pos, len) {\n var copy = utils.newBuffer(len);\n buf.copy(copy, 0, pos, pos + len);\n return copy;\n}", "function writeBuffer(buffer, pos, src) {\n src.copy(buffer, pos)\n return src.length\n}", "function writeBuffer(buffer, pos, src) {\n src.copy(buffer, pos)\n return src.length\n}", "function copy_(x, y) {\n var i;\n var k = x.length < y.length ? x.length : y.length;\n for (i = 0; i < k; i++)\n x[i] = y[i];\n for (i = k; i < x.length; i++)\n x[i] = 0;\n }", "function copyInt_(x, n) {\n var i, c;\n for (c = n, i = 0; i < x.length; i++) {\n x[i] = c & mask;\n c >>= bpe;\n }\n }", "function mallocArrayCopy(src) {\n var L = src.byteLength;\n var dst = _malloc(L);\n HEAP8.set(new Uint8Array(src), dst);\n return dst;\n}", "function shift (buffer, offset) {\n validate(buffer);\n\n for (var channel = 0; channel < buffer.numberOfChannels; channel++) {\n var cData = buffer.getChannelData(channel);\n if (offset > 0) {\n for (var i = cData.length - offset; i--;) {\n cData[i + offset] = cData[i];\n }\n }\n else {\n for (var i = -offset, l = cData.length - offset; i < l; i++) {\n cData[i + offset] = cData[i] || 0;\n }\n }\n }\n\n return buffer;\n}", "function fillArray(_ref3) {\n var target = _ref3.target,\n source = _ref3.source,\n _ref3$start = _ref3.start,\n start = _ref3$start === undefined ? 0 : _ref3$start,\n _ref3$count = _ref3.count,\n count = _ref3$count === undefined ? 1 : _ref3$count;\n\n var total = count * source.length;\n var copied = 0;\n for (var i = 0; i < source.length; ++i) {\n target[start + copied++] = source[i];\n }\n\n while (copied < total) {\n // If we have copied less than half, copy everything we got\n // else copy remaining in one operation\n if (copied < total - copied) {\n target.copyWithin(start + copied, start, start + copied);\n copied *= 2;\n } else {\n target.copyWithin(start + copied, start, start + total - copied);\n copied = total;\n }\n }\n\n return target;\n}", "copy(fromIdx, toIdx, size) {\n if (fromIdx === toIdx) {\n return;\n }\n\n if (fromIdx > toIdx) {\n // Iterate forwards\n for (let i = 0; i < size; i++) {\n this.set(toIdx + i, this.get(fromIdx + i));\n }\n } else {\n // Iterate backwards\n for (let i = size - 1; i >= 0; i--) {\n this.set(toIdx + i, this.get(fromIdx + i));\n }\n }\n }", "function copyArray (a, b) {\n\t var i;\n\t a.length = b.length;\n\t for (i = 0; i < b.length; i++) {\n\t a[i] = b[i];\n\t }\n\t}", "function writePixels (sourceUInt32Data, sourceOffset, pixelOffset, count, pixelOffsetInc, adjustSourceOffset, adjustPixelOffset, repeat) {\n var i, p, pi, ri, rc\n \n ; pixelOffsetInc || (pixelOffsetInc = 1)\n ; adjustSourceOffset || (adjustSourceOffset = count)\n ; adjustPixelOffset || (adjustPixelOffset = count)\n ; repeat || (repeat = 1)\n while (repeat--) {\n rc = count\n ; while (rc--) {\n setPixel(sourceUInt32Data[sourceOffset], pixelOffset)\n pixelOffset += pixelOffsetInc\n }\n sourceOffset += adjustSourceOffset\n ; pixelOffset += adjustPixelOffset\n }\n }", "function copyArray (a, b) {\n var i;\n a.length = b.length;\n for (i = 0; i < b.length; i++) {\n a[i] = b[i];\n }\n}", "function copyArray (a, b) {\n var i;\n a.length = b.length;\n for (i = 0; i < b.length; i++) {\n a[i] = b[i];\n }\n}", "_read(size) {\n if (this.pushedBytesLength >= this.byteLength) {\n this.push(null);\n }\n if (!size) {\n size = this.readableHighWaterMark;\n }\n const outBuffers = [];\n let i = 0;\n while (i < size && this.pushedBytesLength < this.byteLength) {\n // The last buffer may be longer than the data it contains.\n const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength;\n const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer;\n const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers);\n if (remaining > size - i) {\n // chunkSize = size - i\n const end = this.byteOffsetInCurrentBuffer + size - i;\n outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));\n this.pushedBytesLength += size - i;\n this.byteOffsetInCurrentBuffer = end;\n i = size;\n break;\n }\n else {\n // chunkSize = remaining\n const end = this.byteOffsetInCurrentBuffer + remaining;\n outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));\n if (remaining === remainingCapacityInThisBuffer) {\n // this.buffers[this.bufferIndex] used up, shift to next one\n this.byteOffsetInCurrentBuffer = 0;\n this.bufferIndex++;\n }\n else {\n this.byteOffsetInCurrentBuffer = end;\n }\n this.pushedBytesLength += remaining;\n i += remaining;\n }\n }\n if (outBuffers.length > 1) {\n this.push(Buffer.concat(outBuffers));\n }\n else if (outBuffers.length === 1) {\n this.push(outBuffers[0]);\n }\n }", "_read(size) {\n if (this.pushedBytesLength >= this.byteLength) {\n this.push(null);\n }\n if (!size) {\n size = this.readableHighWaterMark;\n }\n const outBuffers = [];\n let i = 0;\n while (i < size && this.pushedBytesLength < this.byteLength) {\n // The last buffer may be longer than the data it contains.\n const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength;\n const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer;\n const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers);\n if (remaining > size - i) {\n // chunkSize = size - i\n const end = this.byteOffsetInCurrentBuffer + size - i;\n outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));\n this.pushedBytesLength += size - i;\n this.byteOffsetInCurrentBuffer = end;\n i = size;\n break;\n }\n else {\n // chunkSize = remaining\n const end = this.byteOffsetInCurrentBuffer + remaining;\n outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end));\n if (remaining === remainingCapacityInThisBuffer) {\n // this.buffers[this.bufferIndex] used up, shift to next one\n this.byteOffsetInCurrentBuffer = 0;\n this.bufferIndex++;\n }\n else {\n this.byteOffsetInCurrentBuffer = end;\n }\n this.pushedBytesLength += remaining;\n i += remaining;\n }\n }\n if (outBuffers.length > 1) {\n this.push(Buffer.concat(outBuffers));\n }\n else if (outBuffers.length === 1) {\n this.push(outBuffers[0]);\n }\n }", "function BufferCopy (target, target_start, start, end) {\n var source = this\n\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (!target_start) target_start = 0\n\n // Copy 0 bytes; we're done\n if (end === start) return\n if (target.length === 0 || source.length === 0) return\n\n // Fatal error conditions\n if (end < start)\n throw new Error('sourceEnd < sourceStart')\n if (target_start < 0 || target_start >= target.length)\n throw new Error('targetStart out of bounds')\n if (start < 0 || start >= source.length)\n throw new Error('sourceStart out of bounds')\n if (end < 0 || end > source.length)\n throw new Error('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length)\n end = this.length\n if (target.length - target_start < end - start)\n end = target.length - target_start + start\n\n // copy!\n for (var i = 0; i < end - start; i++)\n target[i + target_start] = this[i + start]\n}", "function BufferCopy (target, target_start, start, end) {\n var source = this\n\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (!target_start) target_start = 0\n\n // Copy 0 bytes; we're done\n if (end === start) return\n if (target.length === 0 || source.length === 0) return\n\n // Fatal error conditions\n if (end < start)\n throw new Error('sourceEnd < sourceStart')\n if (target_start < 0 || target_start >= target.length)\n throw new Error('targetStart out of bounds')\n if (start < 0 || start >= source.length)\n throw new Error('sourceStart out of bounds')\n if (end < 0 || end > source.length)\n throw new Error('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length)\n end = this.length\n if (target.length - target_start < end - start)\n end = target.length - target_start + start\n\n // copy!\n for (var i = 0; i < end - start; i++)\n target[i + target_start] = this[i + start]\n}", "function copyFromBuffer(n, list) {\r\n const ret = Buffer.allocUnsafe(n);\r\n var p = list.head;\r\n var c = 1;\r\n p.data.copy(ret);\r\n n -= p.data.length;\r\n while (p = p.start) {\r\n const buf = p.data;\r\n const nb = (n > buf.length ? buf.length : n);\r\n buf.copy(ret, ret.length - n, 0, nb);\r\n n -= nb;\r\n if (n === 0) {\r\n if (nb === buf.length) {\r\n ++c;\r\n if (p.start)\r\n list.head = p.start;\r\n else\r\n list.head = list.tail = null;\r\n } else {\r\n list.head = p;\r\n p.data = buf.slice(nb);\r\n }\r\n break;\r\n }\r\n ++c;\r\n }\r\n list.length -= c;\r\n return ret;\r\n}", "function copy_(x,y) {\n var i;\n var k=x.length<y.length ? x.length : y.length;\n for (i=0;i<k;i++)\n x[i]=y[i];\n for (i=k;i<x.length;i++)\n x[i]=0;\n }", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function bnpCopyTo(r) {\n for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];\n r.t = this.t;\n r.s = this.s;\n}", "function copy(target, targetStart, start, end) {\n var i;\n if (!start) start = 0;\n if (!end && end !== 0) end = this.length;\n if (!targetStart) targetStart = 0;\n var len = end - start;\n\n if (target === this && start < targetStart && targetStart < end) {\n // descending\n for (i = len - 1; i >= 0; i--) {\n target[i + targetStart] = this[i + start];\n }\n } else {\n // ascending\n for (i = 0; i < len; i++) {\n target[i + targetStart] = this[i + start];\n }\n }\n\n return len;\n}", "function $SYhk$var$copyFromBuffer(n, list) {\n var ret = $SYhk$var$Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n list.length -= c;\n return ret;\n}", "function sc_copyVector(a, len) {\n if (len <= a.length)\n\treturn a.slice(0, len);\n else {\n\tvar tmp = a.concat();\n\ttmp.length = len;\n\treturn tmp;\n }\n}", "extend_if_needed(num) {\n if ((this.buffer.length - this.size) < num) {\n let new_buffer = new Uint8Array(this.size + num * 2);\n new_buffer.set(this.buffer);\n this.buffer = new_buffer;\n } \n }", "function sampleNU(size, buffer, index) {\n const n = index.length;\n if (size >= n) return index;\n\n for (let i = 0; i < size; ++i) {\n buffer[i] = index[i];\n }\n\n for (let i = size; i < n; ++i) {\n const j = i * random();\n if (j < size) {\n buffer[j | 0] = index[i];\n }\n }\n\n return buffer;\n}", "static CopyImageData(source, out)\n {\n for(let i = 0; i < source.length; i++)\n {\n for(let j = 0; j < source[i].length; j++)\n {\n for(let k = 0; k < source[i][j].length; k++)\n {\n out[i][j][k] = source[i][j][k];\n }\n }\n }\n }", "_read(size) { // how much to read (not used often)\n if (this.index == this.source.length) return this.push(null)\n\n this.push((this.source[this.index++]).toString() + '\\n') // we can only push strings and buffers (not numbers)\n }", "random_bytes(dest, len) {\n const memory = instance.exports.memory;\n const view = new Uint8Array(memory.buffer, dest, len);\n getRandomValues(view);\n }", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n }", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}", "function copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}" ]
[ "0.6943671", "0.6926844", "0.6918663", "0.6084323", "0.5985706", "0.5976774", "0.5652309", "0.5578392", "0.5578392", "0.5499082", "0.5368627", "0.5325039", "0.5305069", "0.5243087", "0.52005035", "0.5178007", "0.5163052", "0.51621675", "0.50760424", "0.50664777", "0.5053397", "0.5053397", "0.5052009", "0.5016483", "0.499986", "0.4985254", "0.4951102", "0.49342594", "0.48908663", "0.48847848", "0.48671186", "0.48671186", "0.4851657", "0.4851657", "0.4835402", "0.4835402", "0.48310587", "0.4825565", "0.48128405", "0.48128405", "0.48128405", "0.48128405", "0.48128405", "0.48128405", "0.48128405", "0.48128405", "0.48128405", "0.48125133", "0.48063698", "0.47968137", "0.47928202", "0.47869197", "0.47854733", "0.47709522", "0.4770788", "0.47660768", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648", "0.4765648" ]
0.67485946
3
Creates and renders the Task Chart
create() { if (this.cellmonitor.view !== 'tasks') { throw new Error('SparkMonitor: Drawing tasks graph when view is not tasks'); } this.clearRefresher(); const container = this.cellmonitor.displayElement.find('.taskcontainer').empty()[0]; const tasktrace = { x: this.taskChartDataX, y: this.taskChartDataY, fill: 'tozeroy', type: 'scatter', mode: 'none', fillcolor: '#00aedb', name: 'Active Tasks', }; const executortrace = { x: this.executorDataX, y: this.executorDataY, fill: 'tozeroy', type: 'scatter', mode: 'none', fillcolor: '#F5C936', name: 'Executor Cores', }; const jobtrace = { x: this.jobDataX, y: this.jobDataY, text: this.jobDataText, type: 'scatter', mode: 'markers', fillcolor: '#F5C936', // name: 'Jobs', showlegend: false, marker: { symbol: 23, color: '#4CB5AE', size: 1, }, }; const data = [executortrace, tasktrace, jobtrace]; const layout = { // title: 'Active Tasks and Executors Cores', // showlegend: false, margin: { t: 30, // top margin l: 30, // left margin r: 30, // right margin b: 60, // bottom margin }, xaxis: { type: 'date', // title: 'Time', }, yaxis: { fixedrange: true, }, dragmode: 'pan', shapes: this.shapes, legend: { orientation: 'h', x: 0, y: 5, // traceorder: 'normal', font: { family: 'sans-serif', size: 12, color: '#000', }, // bgcolor: '#E2E2E2', // bordercolor: '#FFFFFF', // borderwidth: 2 }, }; this.taskChartDataBufferX = []; this.taskChartDataBufferY = []; this.executorDataBufferX = []; this.executorDataBufferY = []; this.jobDataBufferX = []; this.jobDataBufferY = []; this.jobDataBufferText = []; const options = { displaylogo: false, scrollZoom: true }; Plotly.newPlot(container, data, layout, options); this.taskChart = container; if (!this.cellmonitor.allcompleted) this.registerRefresher(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function generateChart(object) {\n // Capture task data in an object for easy retrieval:\n var taskData = new Object();\n taskData.xLabels = [];\n taskData.preLevel = [];\n taskData.postLevel = [];\n\n // Loop through the returned REST API object and populate object:\n for (var i = 0; i < object.length; i++) {\n taskData.xLabels.push(object[i].id);\n taskData.preLevel.push(\n object[i].cmb2.taskbox_rest_metabox.taskbook_pre_level\n );\n taskData.postLevel.push(\n object[i].cmb2.taskbox_rest_metabox.taskbook_post_level\n );\n }\n // Reverse results to display the oldest first:\n taskData.xLabels.reverse();\n taskData.preLevel.reverse();\n taskData.postLevel.reverse();\n\n // Set up the bar chart data model:\n var barChartData = {\n xLabels: taskData.xLabels,\n // yLabels: ['Very stressed', 'Somasdfsdfewhat stressed', 'Neutral', 'Somewhat relaxed', 'Very relaxed'],\n datasets: [\n {\n label: \"Pre-task\",\n backgroundColor: color(chartColors.red).rgbString(),\n borderColor: chartColors.red,\n borderWidth: 2,\n pointRadius: 3,\n pointHoverRadius: 5,\n fill: false,\n data: taskData.preLevel,\n },\n {\n label: \"Post-task\",\n backgroundColor: color(chartColors.blue).rgbString(),\n borderColor: chartColors.blue,\n borderWidth: 2,\n pointRadius: 3,\n pointHoverRadius: 5,\n fill: false,\n data: taskData.postLevel,\n },\n ],\n };\n\n // Draw out the chart with the following settings:\n var chart = new Chart(container, {\n type: \"line\",\n data: barChartData,\n options: {\n responsive: true,\n legend: {\n position: \"top\",\n },\n title: {\n display: true,\n text: \"Stress level visualization\",\n },\n elements: {\n line: {\n tension: 0.000001,\n },\n },\n scales: {\n yAxes: [\n {\n ticks: {\n max: 5,\n min: 1,\n stepSize: 1,\n // Dislay the human readable level values on the Y axes:\n callback: function (value, index, values) {\n return getLevel(value);\n },\n },\n },\n ],\n },\n tooltips: {\n mode: \"index\",\n intersect: true,\n },\n },\n });\n\n /**\n * Make chart elements link to individual tasks.\n */\n function handleClick(event) {\n // Get the clicked chart element:\n let activeElement = chart.getElementAtEvent(event);\n // Do nothing if the click is not on a point on the chart:\n if (!activeElement[0]) {\n return;\n }\n // Get the index number of the clicked element:\n let elementID = activeElement[0]._index;\n // Get the post ID from the taskData.xLabels object array:\n let postID = taskData.xLabels[activeElement[0]._index];\n // Go to the selected task:\n window.location.href = \"/single.html?task=\" + postID;\n }\n // Add event listener for clicks on the chart:\n container.addEventListener(\"click\", handleClick, false);\n\n loader.style.display = \"none\";\n}", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Task');\n data.addColumn('number', '% of Time');\n data.addRows([\n ['Setup EEG', 30],\n ['Review EEG', 30],\n ['Troubleshoot Computer', 10],\n ['CME', 10],\n ['Other', 20]\n ]);\n\n // Set chart options\n var options = {'title':'Breakdown of Time at Work',\n 'width':300,\n 'height':300,\n is3D:true,\n 'backgroundColor': {fill:'transparent'}\n };\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.PieChart(document.getElementById('work-chart'));\n chart.draw(data, options);\n }", "function gantt(options) {\n //declare needed variables\n let diagram = eve.initVis(options),\n currentSerie = diagram.series[0],\n maxTaskLength = 0,\n timeDomainStart = null,\n timeDomainEnd = null,\n autoMargin = 0,\n margin = { left: 0, top: 0, right: 0, bottom: 0 },\n axisFormatting = d3.utcFormat('%x'),\n width = 0,\n height = 0,\n dateDiff = 0,\n maxAxisLength = 0,\n singleAxisWidth = 0,\n autoTickCount = 0,\n xScale = null,\n yScale = null,\n xAxis = null,\n yAxis = null,\n tasks = [],\n groups = [],\n xAxisSVG = null,\n taskRects = null,\n taskLabels = null,\n currentRectWidth = 0,\n hasSelection = false,\n minFontSize = 11,\n xPos = 0, yPos = 0,\n bbox = null,\n currentColor = null,\n yAxisSVG = null,\n startDateField = currentSerie.startField || currentSerie.startDateField,\n endDateField = currentSerie.endField || currentSerie.endDateField;\n\n //calculates scales and environmental variables\n function calculateScales(keepAxis) {\n //get min and max values\n maxTaskLength = d3.max(diagram.data, function (d) { return d[currentSerie.sourceField].toString().length; });\n tasks = e.getUniqueValues(diagram.data, currentSerie.sourceField);\n groups = e.getUniqueValues(diagram.data, currentSerie.groupField);\n\n //set domain info\n timeDomainStart = d3.min(diagram.data, function (d) { return new Date(d[startDateField]); });\n timeDomainEnd = d3.max(diagram.data, function (d) { return new Date(d[endDateField]); });\n dateDiff = timeDomainEnd.diff(timeDomainStart);\n\n //set axis formatting via date diff\n if (dateDiff > 365) {\n //set axis formatting\n axisFormatting = d3.utcFormat('%e-%b-%Y');\n } else {\n if (dateDiff < 1) {\n //set axis formatting\n axisFormatting = d3.utcFormat('%X');\n } else {\n //set axis formatting\n axisFormatting = d3.utcFormat('%b-%e');\n }\n }\n\n //calculate margins\n autoMargin = ((diagram.yAxis.labelFontSize / 2) * (maxTaskLength + 1)) + diagram.yAxis.labelFontSize;\n margin.left = diagram.margin.left + autoMargin;\n margin.right = diagram.margin.right;\n margin.top = diagram.margin.top;\n margin.bottom = diagram.margin.bottom;\n\n //set dimension\n width = diagram.plot.width - diagram.plot.left - diagram.plot.right - margin.left - margin.right;\n height = diagram.plot.height - diagram.plot.top - diagram.plot.bottom - margin.top - margin.bottom;\n\n //caclulate tick count\n maxAxisLength = axisFormatting(timeDomainEnd).length;\n singleAxisWidth = (((diagram.xAxis.labelFontSize / 2) * (maxAxisLength)) + diagram.xAxis.labelFontSize);\n autoTickCount = Math.floor(width / singleAxisWidth);\n\n //create scales\n xScale = d3.scaleUtc().domain([timeDomainStart, timeDomainEnd]).range([0, width]).clamp(true);\n yScale = d3.scaleBand().domain(tasks).range([height - margin.top - margin.bottom, 0]).padding(0.1);\n\n //create axes\n xAxis = d3.axisBottom().scale(xScale).ticks(autoTickCount / 2).tickFormat(axisFormatting);\n yAxis = d3.axisLeft().scale(yScale).tickSize(0);\n\n if (currentSerie.labelFontSize === 'auto')\n currentSerie.labelFontSize = 11;\n }\n\n //updates axis\n function updateAxisStyle() {\n //select x axis path and change stroke\n xAxisSVG.selectAll('path')\n .style('stroke-opacity', diagram.xAxis.alpha)\n .style('stroke-width', diagram.xAxis.thickness + 'px')\n .style('stroke', diagram.xAxis.color);\n\n //select all lines in xaxis\n xAxisSVG.selectAll('line')\n .style('fill', 'none')\n .style('stroke-width', diagram.xAxis.thickness + 'px')\n .style('shape-rendering', 'crispEdges')\n .style('stroke-opacity', diagram.xAxis.alpha)\n .style('stroke', diagram.xAxis.color);\n\n //select all texts in xaxis\n xAxisSVG.selectAll('text')\n .style('fill', diagram.xAxis.labelFontColor)\n .style('font-size', diagram.xAxis.labelFontSize + 'px')\n .style('font-family', diagram.xAxis.labelFontFamily + ', Arial, Helvetica, Ubuntu')\n .style('font-style', diagram.xAxis.labelFontStyle === 'bold' ? 'normal' : diagram.xAxis.labelFontStyle)\n .style('font-weight', diagram.xAxis.labelFontStyle === 'bold' ? 'bold' : 'normal')\n .style('text-anchor', 'middle')\n .transition().duration(diagram.animation.duration)\n .ease(diagram.animation.easing.toEasing())\n .text(function (d) {\n return axisFormatting(new Date(d));\n });\n\n //select x axis path and change stroke\n yAxisSVG.selectAll('path')\n .style('stroke-opacity', diagram.yAxis.alpha)\n .style('stroke-width', diagram.yAxis.thickness + 'px')\n .style('stroke', diagram.yAxis.color);\n\n //select all lines in yaxis\n yAxisSVG.selectAll('line')\n .style('fill', 'none')\n .style('stroke-width', diagram.yAxis.thickness + 'px')\n .style('shape-rendering', 'crispEdges')\n .style('stroke-opacity', diagram.yAxis.alpha)\n .style('stroke', diagram.yAxis.color);\n\n //select all texts in yaxis\n yAxisSVG.selectAll('text')\n .style('fill', diagram.yAxis.labelFontColor)\n .style('font-size', diagram.yAxis.labelFontSize + 'px')\n .style('font-family', diagram.yAxis.labelFontFamily + ', Arial, Helvetica, Ubuntu')\n .style('font-style', diagram.yAxis.labelFontStyle === 'bold' ? 'normal' : diagram.yAxis.labelFontStyle)\n .style('font-weight', diagram.yAxis.labelFontStyle === 'bold' ? 'bold' : 'normal')\n .transition().duration(diagram.animation.duration)\n .ease(diagram.animation.easing.toEasing())\n .text(function (d) { return d; });\n }\n\n //initializes axes for both cases\n function createAxes() {\n //create x axis svg\n xAxisSVG = diagramG.append('g')\n .style('fill', 'none')\n .style('shape-rendering', 'crispEdges')\n .attr('transform', 'translate(0,' + (height - margin.bottom - margin.top) + ')')\n .attr('class', 'eve-x-axis')\n .call(xAxis);\n\n //create y axis left svg\n yAxisSVG = diagramG.append('g')\n .style('fill', 'none')\n .style('shape-rendering', 'crispEdges')\n .attr('transform', 'translate(0)')\n .attr('class', 'eve-y-axis')\n .call(yAxis);\n\n //set axes styling\n updateAxisStyle();\n }\n\n //returns a key for the current task\n let getTaskKey = function (d) {\n return d[startDateField] + d[currentSerie.sourceField] + d[endDateField];\n };\n\n //returns rectangular transform for the current task\n let getTaskTransform = function (d, isInit) {\n return 'translate(' + (isInit ? 0 : xScale(new Date(d[startDateField]))) + ',' + yScale(d[currentSerie.sourceField]) + ')';\n };\n\n //returns rectangular transform for the current task\n let getLabelTransform = function (d, isInit) {\n //get y pos\n xPos = (isInit ? 0 : xScale(new Date(d[startDateField])) + 5)\n yPos = yScale(d[currentSerie.sourceField]) + yScale.bandwidth() / 2 + currentSerie.labelFontSize / 2;\n\n //return translation\n return 'translate(' + xPos + ',' + yPos + ')';\n };\n\n //returns rectangle color for the current task status\n let getTaskStatusColor = function (d) {\n //get color\n let taskColor = e.colors[0],\n groups = [];\n\n //iterate all groups\n diagram.data.forEach(function (currentData) {\n if (groups.indexOf(currentData[currentSerie.groupField]) === -1)\n groups.push(currentData[currentSerie.groupField]);\n });\n\n //sort groups\n groups.sort();\n\n //check whethr the currrent serie has group field\n if (currentSerie.groupField) {\n //check legend values\n if (diagram.legend.legendColors && diagram.legend.legendColors.length) {\n //iterate all legend colors\n diagram.legend.legendColors.forEach(function (l) {\n if (l.value === d[currentSerie.groupField])\n taskColor = l.color;\n });\n } else {\n //iterate all legend colors\n groups.forEach(function (currentGroup, groupIndex) {\n if (currentGroup === d[currentSerie.groupField])\n taskColor = groupIndex > e.colors.length ? e.randColor() : e.colors[groupIndex];\n });\n }\n } else {\n //return serie color if there is no group\n taskColor = diagram.legend.legendColors.length > 0 ? diagram.legend.legendColors[0].color : (i >= e.colors.length ? e.randColor() : e.colors[0]);\n }\n\n //return color for the group\n return taskColor;\n };\n\n //animates diagram\n function animateDiagram() {\n //animate rectangles\n taskRects\n .attr('opacity', diagram.animation.effect === 'add' ? 0 : 1)\n .transition().duration(diagram.animation.duration)\n .ease(diagram.animation.easing.toEasing())\n .delay(function (d, i) { return i * diagram.animation.delay; })\n .attr('opacity', 1)\n .style('fill', getTaskStatusColor)\n .attr('transform', function (d) { return getTaskTransform(d, false); })\n .attr('rx', 2)\n .attr('ry', 2)\n .attr('y', 0)\n .attr('height', function (d) { return yScale.bandwidth(); })\n .attr('width', function (d) {\n //set current rectangle width\n currentRectWidth = (xScale(new Date(d[endDateField])) - xScale(new Date(d[startDateField])));\n\n //check width and return\n return currentRectWidth < 0 ? 0 : currentRectWidth;\n });\n\n //animate labels\n taskLabels\n .style('fill-opacity', function (d) {\n //set current rectangle width\n bbox = this.getBBox();\n currentRectWidth = (xScale(new Date(d[endDateField])) - xScale(new Date(d[startDateField])));\n\n //check label visibility\n if (currentSerie.labelVisibility === 'always')\n return currentRectWidth < 0 ? 0 : 1;\n else\n return currentRectWidth > bbox.width ? 1 : 0;\n })\n .transition().duration(diagram.animation.duration)\n .ease(diagram.animation.easing.toEasing())\n .delay(function (d, i) { return i * diagram.animation.delay; })\n .attr('transform', function (d) { return getLabelTransform(d, false); });\n }\n\n //initializes diagram and creates axes\n function initDiagram() {\n //create rectangles\n taskRects = diagramG.selectAll('.eve-gantt-chart')\n .data(diagram.data, getTaskKey)\n .enter().append('rect')\n .attr('class', 'eve-gantt-chart')\n .attr('fill', getTaskStatusColor)\n .attr('fill-opacity', currentSerie.alpha)\n .attr('rx', 2)\n .attr('ry', 2)\n .attr('y', 0)\n .attr('height', function (d) { return yScale.bandwidth(); })\n .attr('width', 0)\n .attr('transform', function (d) { return getTaskTransform(d, true); })\n .style('cursor', 'pointer')\n .on('click', function (d, i) {\n //set d clicked\n if (d.clicked == null) {\n //set d clicked\n d.clicked = true;\n } else {\n //set d clicked\n d.clicked = !d.clicked;\n }\n\n //check whether the item clicked\n if (d.clicked) {\n //decrease opacity\n hasSelection = true;\n diagramG.selectAll('.eve-gantt-chart').attr('fill-opacity', 0.05);\n diagramG.selectAll('.eve-gantt-labels').attr('fill-opacity', 0.05);\n\n //select this\n d3.select(this).attr('fill-opacity', 1);\n d3.select('#' + diagram.container + '_svgText_' + i).attr('fill-opacity', 1);\n } else {\n //decrease opacity\n hasSelection = false;\n diagramG.selectAll('.eve-gantt-chart').attr('fill-opacity', 1);\n diagramG.selectAll('.eve-gantt-labels').attr('fill-opacity', 1);\n }\n })\n .on('mousemove', function (d, i) {\n //show tooltip\n if (!hasSelection) {\n diagram.showTooltip(diagram.getContent(d, currentSerie, diagram.tooltip.format));\n d3.select(this).attr('fill-opacity', 1);\n }\n })\n .on('mouseout', function (d, i) {\n //hide tooltip\n if (!hasSelection) {\n diagram.hideTooltip();\n d3.select(this).attr('fill-opacity', currentSerie.alpha);\n }\n });\n\n //create labels\n taskLabels = diagramG.selectAll('.eve-gantt-labels')\n .data(diagram.data, getTaskKey)\n .enter().append('text')\n .attr('class', 'eve-gantt-labels')\n .style('pointer-events', 'none')\n .style('text-anchor', 'start')\n .style('fill', function (d, i) {\n currentColor = getTaskStatusColor(d, i);\n return currentSerie.labelFontColor === 'auto' ? diagram.getAutoColor(currentColor) : currentSerie.labelFontColor;\n })\n .style('font-family', currentSerie.labelFontFamily)\n .style('font-style', currentSerie.labelFontStyle === 'bold' ? 'normal' : currentSerie.labelFontStyle)\n .style('font-weight', currentSerie.labelFontStyle === 'bold' ? 'bold' : 'normal')\n .style('font-size', currentSerie.labelFontSize + 'px')\n .text(function (d) {\n //return text content\n return diagram.getContent(d, currentSerie, currentSerie.labelFormat)\n })\n .attr('transform', function (d) { return getLabelTransform(d, true); });\n }\n\n //create scales and environment\n calculateScales();\n\n //create diagram g\n let diagramG = diagram.svg.append('g')\n .attr('class', 'eve-vis-g')\n .attr('transform', 'translate(' + margin.left + ',' + diagram.plot.top + ')');\n\n //create axes and init diagram\n createAxes();\n initDiagram();\n animateDiagram();\n\n //update diagram\n diagram.update = function (data, keepAxis) {\n //set diagram data\n diagram.data = data;\n\n //update legend\n diagram.updateLegend();\n\n //re-calculate scales\n calculateScales(keepAxis);\n\n //remove g\n if (diagram.animation.effect) {\n //check whether the effect is fade\n if (diagram.animation.effect === 'fade') {\n //remove with transition\n diagramG.transition().duration(1000).style('opacity', 0).remove();\n } else if (diagram.animation.effect === 'dim') {\n //remove with transition\n diagramG.style('opacity', 0.15);\n } else if (diagram.animation.effect === 'add') {\n //remove with transition\n diagramG.style('opacity', 1);\n } else {\n //remove immediately\n diagramG.remove();\n }\n } else {\n //remove immediately\n diagramG.remove();\n }\n\n //re-append g\n diagramG = diagram.svg.append('g')\n .attr('class', 'eve-vis-g')\n .attr('transform', 'translate(' + margin.left + ',' + diagram.plot.top + ')');\n\n //create axes and init diagram\n createAxes();\n initDiagram();\n\n //animate diagram\n animateDiagram();\n };\n\n //attach clear content method to chart\n diagram.clear = function () {\n //remove g from the content\n diagram.svg.selectAll('.eve-vis-g').remove();\n };\n\n //return abacus diagram\n return diagram;\n }", "function drawChart() {\n const tasksRef = database.ref(\"task\").orderByChild(\"group\").equalTo(group);\n tasksRef.once(\"value\", function(tasksSnapshot) {\n\n let baseValue = 1;\n if(group === \"Beauty\")\n baseValue = 0;\n\n let comCount = {\n \"Mon\": baseValue,\n \"Tue\": baseValue,\n \"Wed\": baseValue,\n \"Thu\": baseValue,\n \"Fri\": baseValue,\n \"Sat\": baseValue,\n \"Sun\": baseValue,\n };\n let notCount = {\n \"Mon\": baseValue,\n \"Tue\": baseValue,\n \"Wed\": baseValue,\n \"Thu\": baseValue,\n \"Fri\": baseValue,\n \"Sat\": baseValue,\n \"Sun\": baseValue,\n };\n\n tasksSnapshot.forEach(function(taskSnapshot) {\n if(taskSnapshot.hasChild(\"status\")) {\n let status = taskSnapshot.child(\"status\").val();\n for(d in status) {\n if(moment(d).isSameOrAfter(moment().subtract(7, \"days\"))) {\n if(status[d])\n comCount[moment(d).format(\"ddd\")] += 1;\n else\n notCount[moment(d).format(\"ddd\")] += 1;\n }\n }\n }\n });\n\n // Create the data table.\n let data = new google.visualization.DataTable();\n\n data.addColumn(\"string\", \"Day\");\n data.addColumn(\"number\", \"Complete\");\n data.addColumn(\"number\", \"Not Needed\");\n\n let maxCount = 0;\n for(let i = 1; i <= 7; i++) {\n let day = moment().subtract(7 - i, \"days\").format(\"ddd\");\n let day_full = moment().subtract(7 - i, \"days\").format(\"ddd (M/D)\");\n maxCount = Math.max(maxCount, comCount[day] + notCount[day] + 1);\n data.addRow([day_full, comCount[day], notCount[day]]);\n }\n\n let tickCount = Math.min(maxCount + 1, defaultTickCount);\n let tickMarks = [];\n for(let i = 0; i < tickCount; i++)\n tickMarks[i] = (i == tickCount - 1) ? maxCount : Math.floor(i * maxCount/ (tickCount - 1));\n\n // Set chart options\n let options = {\n title: \"# of \" + group + \" (in past 7 days)\",\n isStacked: true,\n vAxis: {\n ticks: tickMarks,\n },\n series: {\n 0: {color: completeColor},\n 1: {color: notneededColor},\n },\n chartArea: {\n width: \"95%\",\n },\n bar: {\n groupWidth: \"38.2%\",\n },\n legend: {\n position: \"bottom\",\n },\n };\n\n function selectHandler() {\n let selectedItem = chart.getSelection()[0];\n if (selectedItem) {\n let day = data.getValue(selectedItem.row, 0);\n // alert(\"The user selected \" + day);\n }\n }\n\n // Instantiate and draw our chart, passing in some options.\n let chart = new google.visualization.ColumnChart(chartDiv[0]);\n google.visualization.events.addListener(chart, \"select\", selectHandler);\n chart.draw(data, options);\n });\n }", "function drawChart() {\r\n\r\n // Create our data table.\r\n var data = new google.visualization.DataTable();\r\n data.addColumn('string', 'Task');\r\n data.addColumn('number', 'Hours per Day');\r\n data.addRows([\r\n ['Work', 11],\r\n ['Eat', 2],\r\n ['Commute', 2],\r\n ['Watch TV', 2],\r\n ['Sleep', 7]\r\n ]);\r\n\r\n // Instantiate and draw our chart, passing in some options.\r\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\r\n chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});\r\n }", "function make_graph() {\n $.get(\"/user_progress_analytics\",function (data, status) {\n let pc = document.getElementById('progressBarGraph').getContext('2d');\n let myChart = new Chart(pc, {\n type: 'bar',\n data: {\n labels: [\"Completed\", \"Uncompleted\"],\n datasets: [{\n label: '# of Tasks',\n data: data,\n backgroundColor: [\n 'rgba(75, 192, 192, 0.2)', // GREEN\n 'rgba(255, 99, 132, 0.2)', // RED\n\n // 'rgba(54, 162, 235, 0.2)', // BLUE\n // 'rgba(255, 206, 86, 0.2)', // YELLOW\n // 'rgba(153, 102, 255, 0.2)', // PURPLE\n // 'rgba(255, 159, 64, 0.2)' // Orange\n ],\n borderColor: [\n 'rgba(75, 192, 192, 1)',\n 'rgba(255,99,132,1)',\n //\n // 'rgba(54, 162, 235, 1)',\n // 'rgba(255, 206, 86, 1)',\n // 'rgba(153, 102, 255, 1)',\n // 'rgba(255, 159, 64, 1)'\n ],\n borderWidth: 1\n }]\n },\n options: {\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero:true\n }\n }]\n },\n title: {\n display: true,\n text: 'Overall Project Progress Based On Tasks Completed To Tasks Uncompleted'\n }\n }\n });\n });\n}", "function makeGantt(currentCPU) {\n numCycles = cycleEvents.length;\n\n // Categorize all events into cycles\n addCycleAttribute();\n\n // Only use switch events on the chart, after\n // normalizing their start times within their cycles\n // and calculating the durations between them\n var switchCycleEvents = getCycleEventsForCPU(currentCPU);\n\n timeDomainEnd = getLongestCycleDuration(switchCycleEvents);\n\n var margin = {\n top: 20,\n right: 40,\n bottom: 20,\n left: 70\n }\n\n var height = (numCycles + 1) * 35;\n // Divide window up by number of CPUs displayed. 80 is to deal with set size of sidebar\n // Each chart div has a margin of 20px, so also subtract this off\n var numDisplayed = selectedCPUs.length;\n var width = (document.body.clientWidth / selectedCPUs.length) - 80 - margin.right - margin.left - 20 * numDisplayed;\n var gantt = d3.gantt(chartType).taskTypes(_.range(numCycles,-1,-1))\n .timeDomain(timeDomainEnd).yAttribute(\"cycle\").yLabel(\"Cycle \").margin(margin)\n .height(height)\n .width(width);\n\n // Create a new div for this chart and place it inside our div for all gantt charts\n var chartDiv = document.createElement(\"div\");\n chartDiv.id = \"ganttChart\" + currentCPU;\n chartDiv.style.display = \"inline-block\";\n chartDiv.style.marginLeft = \"20px\";\n\n document.getElementById(\"ganttCharts\").appendChild(chartDiv);\n var chartID = '#ganttChart' + currentCPU;\n\n // actually draw the gantt chart\n gantt(switchCycleEvents, chartID);\n}", "render() {\n const tasksHtmlList = [];\n const tasksList = document.querySelector('#taskOutput');\n const imgTag = document.querySelector('#relax');\n if (this.tasks.length === 0) {\n tasksList.innerHTML = '';\n document.querySelector('#taskLabel').innerHTML = 'No Outstanding Tasks';\n const randomPicture = `TaskPlannerBg${Math.floor(Math.random() * 6)}.jpg`;\n imgTag.src = `./Images/${randomPicture}`;\n imgTag.classList.add('d-block');\n imgTag.classList.remove('d-none');\n } else {\n imgTag.classList.add('d-none');\n imgTag.classList.remove('d-block');\n document.querySelector('#taskLabel').innerHTML = 'Outstanding Tasks';\n this.tasks.forEach((item) => {\n const formattedCreatedDate = item.createdDay.split('-').reverse().join('-');\n const formattedDueDate = item.dueDate.split('-').reverse().join('-');\n const taskHtml = createTaskHtml(item.Id, item.name, item.description, item.assignedTo, formattedDueDate, formattedCreatedDate, item.status, item.rating);\n tasksHtmlList.push(taskHtml);\n });\n const tasksHtml = tasksHtmlList.join('\\n');\n tasksList.innerHTML = tasksHtml;\n }\n }", "function drawChart() {\n\n // Create the data table.\n var data = google.visualization.arrayToDataTable([\n ['Scenario Name', 'Duration', {role: 'style'}]\n ].concat(values));\n\n var options = {\n title: 'Scenario Results',\n legend: { position: 'none' },\n vAxis: { title: 'Duration (seconds)'},\n backgroundColor: bgColor\n };\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.ColumnChart(document.getElementById('resultChart'));\n chart.draw(data, options);\n\n }", "function ganttChart(config) {\n\n var data = config.data;\n var ELEMENT = d3.select(config.element),\n CHART_WIDTH = ELEMENT[0][0].offsetWidth,\n CHART_HEIGHT = d3.max([((data.length * 80) + 100), 300]),\n PROGRESSBAR_WIDTH = 200,\n PROGRESSBAR_BOUNDARY = 380,\n EMPTYBLOCK_WIDTH = ((80 * CHART_WIDTH) / 100),\n EMPTYBLOCK_HEIGHT = 150,\n BUTTON_COLOR = '#15bfd8';\n\n\n var currentDay = {\n start_date: moment().startOf('day').toDate(),\n end_date: moment().endOf('day').toDate(),\n }\n\n\n function goToNext() {\n switch (config.metrics.type) {\n case \"yearly\":\n config.metrics.year = config.metrics.year + 1;\n break;\n case \"overall\":\n for (var i = 0; i < config.metrics.years.length; i++) {\n config.metrics.years[i] = config.metrics.years[i] + config.metrics.years.length;\n };\n break;\n case \"sprint\":\n break;\n case \"monthly\":\n config.metrics.month = moment(config.metrics.month, 'MMMM YYYY').add(1, 'months').format('MMMM YYYY');\n break;\n case \"quarterly\":\n months_count = config.metrics.months.length;\n for (var i = 0; i < months_count; i++) {\n config.metrics.months[i] = moment(config.metrics.months[i], 'MMMM YYYY').add(months_count, 'months').format('MMMM YYYY');\n };\n break;\n }\n\n draw('next');\n }\n\n function goToPrevious() {\n switch (config.metrics.type) {\n case \"yearly\":\n config.metrics.year = config.metrics.year - 1;\n break;\n case \"overall\":\n for (var i = 0; i < config.metrics.years.length; i++) {\n config.metrics.years[i] = config.metrics.years[i] - config.metrics.years.length;\n };\n break;\n case \"sprint\":\n break;\n case \"monthly\":\n config.metrics.month = moment(config.metrics.month, 'MMMM YYYY').subtract(1, 'months').format('MMMM YYYY');\n break;\n case \"quarterly\":\n months_count = config.metrics.months.length;\n for (var i = 0; i < months_count; i++) {\n config.metrics.months[i] = moment(config.metrics.months[i], 'MMMM').subtract(months_count, 'months').format('MMMM YYYY');\n };\n break;\n }\n draw('previous');\n }\n\n draw('initial');\n\n function draw(state) {\n\n var date_boundary = [];\n var subheader_ranges = [];\n var months = [];\n var header_ranges = [];\n\n d3.select(config.element)[0][0].innerHTML = \"\";\n\n if (config.metrics.type == \"monthly\") {\n months = [config.metrics.month];\n header_ranges = getMonthsRange(months);\n subheader_ranges = getDaysRange(months);\n } else if (config.metrics.type == \"overall\") {\n var years = config.metrics.years,\n yearsRange = [];\n years.map(function (year) {\n months = months.concat(getMonthsOftheYear(year))\n yearsRange.push(getYearBoundary(year));\n })\n header_ranges = [{\n name: \"Overall View\",\n start_date: yearsRange[0].start_date,\n end_date: yearsRange[yearsRange.length - 1].end_date,\n }]\n subheader_ranges = yearsRange;\n\n } else {\n if (config.metrics.type == \"quarterly\") {\n months = config.metrics.months;\n subheader_ranges = getMonthsRange(months);\n var year = moment(config.metrics.months[0], 'MMMM YYYY').format('YYYY');\n\n\n header_ranges = [{\n start_date: moment(config.metrics.months[0], 'MMMM YYYY').startOf('month').toDate(),\n end_date: moment(config.metrics.months[config.metrics.months.length - 1], 'MMMM YYYY').endOf('month').toDate(),\n name: year,\n }];\n\n } else if (config.metrics.type == \"yearly\") {\n months = getMonthsOftheYear(config.metrics.year);\n subheader_ranges = getMonthsRange(months);\n header_ranges = [getYearBoundary(config.metrics.year)];\n } else if (config.metrics.type == \"sprint\") {\n months = getMonthsOftheYear(config.metrics.year);\n subheader_ranges = config.metrics.cycles;\n header_ranges = [getYearBoundary(config.metrics.year)];\n\n }\n\n }\n\n date_boundary[0] = moment(months[0], 'MMM YYYY').startOf('month').toDate();\n date_boundary[1] = moment(months[months.length - 1], 'MMM YYYY').endOf('month').toDate();\n\n\n var margin = { top: 20, right: 50, bottom: 100, left: 50 },\n width = d3.max([CHART_WIDTH, 400]) - margin.left - margin.right,\n height = CHART_HEIGHT - margin.top - margin.bottom;\n\n var x = d3.time.scale()\n .domain(date_boundary)\n .range([0, width])\n\n\n var y = d3.scale.ordinal()\n .rangeRoundBands([0, height], 0.1);\n\n y.domain(data.map(function (d, i) {\n return i + 1;\n }));\n\n var xAxis = d3.svg.axis()\n .scale(x)\n .orient(\"bottom\")\n .tickFormat(d3.time.format(\"%d/%m/%Y\"));\n\n var yAxis = d3.svg.axis()\n .scale(y)\n .orient(\"left\")\n .tickSize(0)\n .tickPadding(6);\n\n var first_section = ELEMENT\n .append('div')\n .attr('class', 'first_section')\n .style(\"height\", 40)\n .append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", 40)\n .append('g')\n\n var second_section = ELEMENT\n .append('div')\n .attr('class', 'second_section')\n .style(\"height\", 40)\n .append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", 40)\n .append('g')\n\n\n switch (state) {\n\n case 'initial':\n first_section\n .attr(\"transform\", \"translate( \" + margin.left + \", 30)\")\n second_section\n .attr(\"transform\", \"translate( \" + margin.left + \", 0)\")\n break;\n\n case 'next':\n second_section\n .attr(\"transform\", \"translate( 1000, 0)\")\n .transition()\n .attr(\"transform\", \"translate( \" + margin.left + \", 0)\")\n first_section\n .attr(\"transform\", \"translate( 1000, 30)\")\n .transition()\n .attr(\"transform\", \"translate( \" + margin.left + \", 30)\")\n break;\n\n case 'previous':\n second_section\n .attr(\"transform\", \"translate( -1000, 0)\")\n .transition()\n .attr(\"transform\", \"translate( \" + margin.left + \", 0)\")\n first_section\n .attr(\"transform\", \"translate( -1000, 30)\")\n .transition()\n .attr(\"transform\", \"translate( \" + margin.left + \", 30)\")\n break;\n\n }\n\n\n\n var DRAWAREA = ELEMENT\n .append('div')\n .attr('class', 'draw_area')\n .append(\"svg\")\n .attr('class', 'DRAWAREA')\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n\n var svg = DRAWAREA\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + 0 + \")\")\n .call(appendStartLine);\n\n var lines = svg.append('g').attr(\"transform\", \"translate(0,0)\")\n\n var currentDayArea = svg.append('line')\n .attr('width', getActualWidth(currentDay))\n .attr('class', 'CurrentDay-Area')\n .attr(\"x1\", x(new Date(currentDay.start_date)))\n .attr(\"x2\", x(new Date(currentDay.start_date)))\n .attr(\"y1\", 0)\n .attr(\"y2\", height)\n\n\n var leftClickableArea = svg.append('rect')\n .attr('width', (width) / 2)\n .attr('height', height)\n .attr('fill', 'transparent')\n .on('click', function () {\n goToPrevious();\n config.onAreaClick('left');\n })\n\n var rightClickableArea = svg.append('rect')\n .attr('width', (width) / 2)\n .attr(\"transform\", \"translate(\" + ((width) / 2) + \" ,0)\")\n .attr('height', height)\n .attr('fill', 'transparent')\n .on('click', function () {\n goToNext();\n config.onAreaClick('right');\n })\n\n\n first_section.selectAll(\".bar\")\n .data(header_ranges)\n .enter().append(\"text\")\n .attr('class', 'first-title')\n .attr('y', -5)\n .attr(\"x\", function (d) {\n return x(new Date(d.start_date)) + (getWidth(d) / 2);\n })\n .attr(\"width\", function (d) {\n return getWidth(d);\n })\n .attr(\"height\", y.rangeBand())\n .text(function (d) {\n return d.name\n });\n\n second_section\n .append(\"rect\")\n .attr(\"x\", x(new Date(date_boundary[0])))\n .attr(\"width\", Math.abs(x(new Date(date_boundary[0])) - x(new Date(date_boundary[1]))))\n .attr(\"height\", 40)\n .attr('class', 'Date-Block-Outline');\n\n\n second_section\n .append('g')\n .selectAll(\".bar\")\n .data(subheader_ranges)\n .enter()\n .append(\"rect\")\n .attr(\"x\", function (d) {\n return x(new Date(d.start_date))\n })\n .attr(\"width\", function (d) {\n return getWidth(d);\n })\n .attr(\"height\", 40)\n .attr('class', function (d) {\n return \"Date-Block Date-\" + moment(d.start_date).format(\"MMYYYY\")\n });\n\n second_section\n .append('g')\n .selectAll(\".bar\")\n .data(subheader_ranges)\n .enter().append(\"text\")\n .attr(\"x\", function (d) {\n return (x(new Date(d.start_date)) + 10);\n })\n .attr(\"width\", function (d) {\n return getWidth(d);\n })\n .attr('y', 25)\n .text(function (d) {\n return d.name;\n })\n .attr('class', function (d) {\n return \"second-title Date Date-\" + moment(d).format(\"MMYYYY\")\n });\n\n\n lines.selectAll(\".lines\")\n .data(subheader_ranges)\n .enter()\n .append(\"line\")\n .attr('class', 'date-line')\n .attr(\"x1\", function (d) {\n return x(new Date(d.start_date));\n })\n .attr(\"x2\", function (d) {\n return x(new Date(d.start_date));\n })\n .attr(\"y1\", 0)\n .attr(\"y2\", height)\n\n\n\n if (config.data.length == 0) {\n var EmptyBlockX = ((CHART_WIDTH / 2) - (EMPTYBLOCK_WIDTH / 2)),\n EMPTYBLOCK = DRAWAREA\n .append('g')\n .attr('class', 'EmptyMessageBlock')\n .attr(\"transform\", \"translate(\" + EmptyBlockX + \", 20)\")\n\n EMPTYBLOCK\n .append('rect')\n .attr('fill', '#fff')\n .attr('stroke', '#ccc')\n .attr('x', 0)\n .attr('width', EMPTYBLOCK_WIDTH)\n .attr('height', EMPTYBLOCK_HEIGHT)\n\n EMPTYBLOCK\n .append('text')\n .attr('class', 'EmptyMessage')\n .attr('font-size', 25)\n .attr('y', 25)\n .text(\"There is no objective yet, please click to add one\");\n\n\n var EMPTRYBLOCK_BUTTON = EMPTYBLOCK\n .append('g')\n .attr('class', 'empty_button')\n .attr(\"transform\", \"translate(\" + Math.abs((EMPTYBLOCK_WIDTH / 2) - 50) + \", 100)\")\n .on('click', function (d) {\n config.onEmptyButtonClick();\n })\n\n EMPTRYBLOCK_BUTTON\n .append('rect')\n .attr('width', 100)\n .attr('height', 35)\n .attr('rx', 4)\n .attr('ry', 4)\n .attr('fill', BUTTON_COLOR)\n\n EMPTRYBLOCK_BUTTON\n .append('text')\n .attr('fill', '#fff')\n .attr('y', 25)\n .attr('x', 10)\n .text(\"Click Here\")\n\n var textBlock = EMPTYBLOCK.select('.EmptyMessage');\n\n var EmptyMessageWidth = textBlock.node().getComputedTextLength();\n EmptyMessageX = Math.abs((EMPTYBLOCK_WIDTH / 2) - (EmptyMessageWidth / 2));\n\n textBlock\n .attr(\"transform\", \"translate(\" + EmptyMessageX + \",20)\")\n }\n\n var bars = svg.append('g').attr(\"transform\", \"translate(0, 20)\")\n\n var Blocks = bars.selectAll(\".bar\")\n .data(data)\n .enter()\n .append(\"g\")\n .attr('class', 'Single--Block cp')\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + x(new Date(d.start_date)) + \",\" + 0 + \")\";\n })\n .call(appendBar)\n\n Blocks\n .append('g')\n .attr('transform', function (d) {\n if (startsBefore(d) && isVisible(d)) {\n var position = Math.abs(x(new Date(d.start_date)));\n return \"translate(\" + position + \", 0)\";\n } else {\n return \"translate(0, 0)\";\n }\n })\n .call(appendTitle)\n .call(appendFooter)\n\n Blocks\n .on('click', function (d) {\n config.onClick(d);\n })\n .on('mouseover', function (d, i) {\n svg.selectAll('.Single--Block')\n .style('opacity', function (b, i) {\n return (d.id == b.id) ? 1 : 0.3;\n })\n\n svg.selectAll('.start-lines, .end-lines')\n .style('stroke-width', function (b, i) {\n return (d.id == b.id) ? 3 : 1;\n })\n .style('opacity', function (b, i) {\n return Number(d.id == b.id);\n })\n\n svg.selectAll('.Single--Node')\n .attr(\"width\", function (b) {\n if (d.id == b.id) {\n if (startsBefore(d) || endsAfter(d)) {\n if (getWidth(b) < 500) {\n return (getActualWidth(b) + (500 - getWidth(b)) + 10)\n }\n }\n return ((d3.max([getActualWidth(b), 500])) + 10);\n } else {\n return getActualWidth(b)\n }\n })\n\n svg.selectAll('.ProgressBar')\n .attr('opacity', function (b) {\n return Number(d.id == b.id || getWidth(b) > 480)\n })\n\n svg.selectAll('.Duration')\n .attr('opacity', function (b) {\n return Number(d.id == b.id || getWidth(b) > 200)\n })\n\n svg.selectAll('.TermType')\n .attr('opacity', function (b) {\n return Number(d.id == b.id || getWidth(b) > 80)\n })\n\n second_section.selectAll(\".Date\")\n .style('fill', function (b, i) {\n if (moment(b.start_date, \"MM/DD/YYYY\").isBetween(d.start_date, d.end_date, 'days') || moment(b.end_date, \"MM/DD/YYYY\").isBetween(d.start_date, d.end_date, 'days'))\n return '#4894ff';\n\n })\n second_section.selectAll(\".Date-Block\")\n .style('fill', function (b, i) {\n if (moment(b.start_date, \"MM/DD/YYYY\").isBetween(d.start_date, d.end_date, 'days') || moment(b.end_date, \"MM/DD/YYYY\").isBetween(d.start_date, d.end_date, 'days'))\n return '#f0f6f9';\n\n })\n\n d3.select(this).selectAll('.Title')\n .text(function (d) {\n return d.title\n })\n\n d3.select(this).each(function (d, i) {\n var width = ((d3.max([getWidth(d), 500])) + 10);\n trimTitle(width, this, config.box_padding * 2)\n })\n })\n .on('mouseout', function (d, i) {\n svg.selectAll('.Single--Block')\n .style('opacity', 1)\n svg.selectAll('.start-lines, .end-lines')\n .style('stroke-width', 1)\n .style('opacity', 1)\n\n svg.selectAll('.Single--Node')\n .attr(\"width\", function (b) {\n return (getActualWidth(b) + 10);\n })\n\n svg.selectAll('.ProgressBar')\n .attr('opacity', function (b) {\n return Number(getWidth(b) > PROGRESSBAR_BOUNDARY)\n })\n\n svg.selectAll('.Duration')\n .attr('opacity', function (b) {\n return Number(getWidth(b) > 200)\n })\n\n svg.selectAll('.TermType')\n .attr('opacity', function (b) {\n return Number(getWidth(b) > 80)\n })\n second_section.selectAll(\".Date\")\n .style('fill', '')\n second_section.selectAll(\".Date-Block\")\n .style('fill', '')\n\n d3.select(this).each(function (d, i) {\n var width = getWidth(d);\n trimTitle(width, this, config.box_padding * 2)\n })\n })\n .each(function (d, i) {\n var width = getWidth(d);\n trimTitle(width, this, config.box_padding * 2)\n })\n\n\n function appendBar(d, i) {\n this.append('rect')\n .attr('class', 'Single--Node')\n .attr('rx', 5)\n .attr('ry', 5)\n .attr(\"height\", 60)\n .attr(\"x\", 0)\n .attr(\"y\", function (d, i) {\n return y(i + 1);\n })\n .attr(\"width\", function (d) {\n return (getActualWidth(d) + 10);\n })\n }\n\n function appendTitle(d, i) {\n this.append('text')\n .attr('class', 'Title')\n .attr(\"x\", config.box_padding)\n .attr(\"y\", function (d, i) {\n return (y(i + 1) + 20)\n })\n .text(function (d) {\n return d.title\n })\n }\n\n function appendFooter(d, i) {\n var footer = this.append('g')\n .attr(\"transform\", function (d, i) {\n var position = config.box_padding;\n if (position < 10) {\n position = 0;\n }\n return \"translate(\" + position + \", \" + (y(i + 1) + 45) + \")\";\n })\n .call(renderTerm)\n .call(renderDuration)\n .call(appendProgressBar)\n }\n\n function appendProgressBar(d, i) {\n this.append('rect')\n .attr('class', 'ProgressBar')\n .attr('fill', '#ddd')\n .attr('width', PROGRESSBAR_WIDTH)\n\n this.append('rect')\n .attr('class', 'ProgressBar ProgressBar-Fill')\n .attr('fill', 'red')\n .attr('width', function (d) {\n var width = ((d.completion_percentage * PROGRESSBAR_WIDTH) / 100);\n return width;\n })\n\n this.selectAll('.ProgressBar')\n .attr('rx', 5)\n .attr('ry', 5)\n .attr('y', -7)\n .attr('height', 7)\n .attr('x', 180)\n .attr('opacity', function (d) {\n var width = getWidth(d);\n return Number(width > PROGRESSBAR_BOUNDARY)\n })\n }\n\n function appendStartLine() {\n this.selectAll(\".start-lines\")\n .data(data)\n .enter()\n .append(\"line\")\n .attr('class', 'start-lines')\n .attr('stroke', function (d) {\n return d.color\n })\n .attr(\"x1\", function (d) {\n return x(new Date(d.start_date)) + 10;\n })\n .attr(\"x2\", function (d) {\n return x(new Date(d.start_date)) + 10;\n })\n .attr(\"y1\", 0)\n .attr(\"y2\", function (d, i) {\n return (y(i + 1) + 20);\n })\n\n this.selectAll(\".end-lines\")\n .data(data)\n .enter()\n .append(\"line\")\n .attr('stroke', function (d) {\n return d.color\n })\n .attr('class', 'end-lines')\n .attr(\"x1\", function (d) {\n return x(new Date(d.end_date)) + 5;\n })\n .attr(\"x2\", function (d) {\n return x(new Date(d.end_date)) + 5;\n })\n .attr(\"y1\", 0)\n .attr(\"y2\", function (d, i) {\n return (y(i + 1) + 20);\n })\n\n }\n\n function renderTerm(d, i) {\n this.append('text')\n .attr('class', 'TermType')\n .text(function (d) {\n return d.term\n })\n .attr('opacity', function (d) {\n return Number(getWidth(d) > 80)\n })\n }\n\n function renderDuration(d, i) {\n this.append('text')\n .attr('class', 'Duration')\n .attr('x', 80)\n .text(function (d) {\n return getDuration(d)\n })\n .attr('opacity', function (d) {\n return Number(getWidth(d) > 200)\n })\n }\n\n // function type(d) {\n // d.value = +d.value;\n // return d;\n // }\n\n function getDuration(d) {\n var start_date = moment(d.start_date, \"MM/DD/YYYY\").format(\"DD MMM\"),\n end_date = moment(d.end_date, \"MM/DD/YYYY\").format(\"DD MMM\");\n duration = start_date + \" - \" + end_date;\n return duration;\n }\n\n function trimTitle(width, node, padding) {\n\n var textBlock = d3.select(node).select('.Title')\n\n var textLength = textBlock.node().getComputedTextLength(),\n text = textBlock.text()\n while (textLength > (width - padding) && text.length > 0) {\n text = text.slice(0, -1);\n textBlock.text(text + '...');\n textLength = textBlock.node().getComputedTextLength();\n }\n }\n\n function getWidth(node) {\n if (endsAfter(node)) {\n width = Math.abs(x(new Date(date_boundary[1])) - x(new Date(node.start_date)));\n } else if (startsBefore(node)) {\n width = Math.abs(x(new Date(date_boundary[0])) - x(new Date(node.end_date)));\n } else {\n width = getActualWidth(node);\n }\n return width;\n }\n\n function getActualWidth(node) {\n return Math.abs(x(new Date(node.end_date)) - x(new Date(node.start_date)));\n }\n\n function startsBefore(node) {\n return moment(node.start_date, \"MM/DD/YYYY\").isBefore(date_boundary[0])\n }\n\n function endsAfter(node) {\n return moment(node.end_date, \"MM/DD/YYYY\").isAfter(date_boundary[1]);\n }\n\n function isVisible(node) {\n var start_date_visible = moment(node.start_date, \"MM/DD/YYYY\").isBetween(date_boundary[0], date_boundary[1], 'days'),\n end_date_visible = moment(node.end_date, \"MM/DD/YYYY\").isBetween(date_boundary[0], date_boundary[1], 'days');\n\n return start_date_visible || end_date_visible;\n\n }\n\n function getDaysRange(months) {\n ranges = [];\n months.map(function (month) {\n var startOfMonth = moment(month, 'MMM YYYY').startOf('month')\n var endOfMonth = moment(month, 'MMM YYYY').endOf('month')\n var day = startOfMonth;\n\n while (day <= endOfMonth) {\n ranges.push({\n name: moment(day).format('DD'),\n start_date: day.toDate(),\n end_date: day.clone().add(1, 'd').toDate(),\n });\n day = day.clone().add(1, 'd');\n }\n });\n return ranges;\n }\n\n function getMonthsRange(months) {\n ranges = [];\n months.map(function (month) {\n var startOfMonth = moment(month, 'MMM YYYY').startOf('month')\n var endOfMonth = moment(month, 'MMM YYYY').endOf('month')\n\n ranges.push({\n name: moment(startOfMonth).format('MMMM'),\n start_date: startOfMonth.toDate(),\n end_date: endOfMonth.clone().add(1, 'd').toDate(),\n });\n\n\n });\n\n return ranges;\n }\n\n function getYearBoundary(year) {\n var yearDate = moment(year, 'YYYY');\n startOfYear = moment(yearDate).startOf('year');\n endOfYear = moment(yearDate).endOf('year');\n\n return {\n name: year,\n start_date: startOfYear.toDate(),\n end_date: endOfYear.toDate(),\n };\n }\n\n function getMonthsOftheYear(year) {\n var months = moment.months();\n months = months.map(function (month) {\n month = month + \" \" + year;\n return month;\n });\n return months;\n }\n\n }\n}", "function drawChart() {\n\n // Create the data table.\n var data = google.visualization.arrayToDataTable([\n ['Test Name', 'Passed', 'Failed', 'Skipped']\n ].concat(values));\n\n var options = {\n title: 'Last ' + values.length + ' Test Runs',\n legend: { position: 'bottom' },\n colors: ['green', 'red', 'yellow'],\n backgroundColor: bgColor,\n isStacked: true\n };\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.SteppedAreaChart(document.getElementById('historyChart'));\n chart.draw(data, options);\n \n }", "function createChartControl(htmlDiv, hasTreePanel) {\r\n try{\r\n var ganttChartControl;\r\n\r\n // Create Gantt control\r\n ganttChartControl = new GanttChart();\r\n // Setup paths and behavior\r\n ganttChartControl.setImagePath(\"/images/gantt/\");\r\n ganttChartControl.setEditable(false);\r\n ganttChartControl.showContextMenu(false);\r\n ganttChartControl.showTreePanel(hasTreePanel);\r\n\r\n ganttChartControl.getMonthScaleLabel = function(date) {\r\n return \"\";\r\n }\r\n\r\n\r\n // Build control on the page\r\n ganttChartControl.create(htmlDiv);\r\n ganttChartControl.showDescTask(true, 'n,e,d');\r\n ganttChartControl.showDescProject(true, 'n');\r\n\r\n // Load data structure\r\n ganttChartControl.loadData(\"../scripts/data.xml\", true, true);\r\n } catch (e) {}\r\n}", "function drawChart() {\r\n var data = google.visualization.arrayToDataTable([\r\n ['Task', 'Hours per Day'],\r\n ['windows', 8],\r\n ['MacOS', 4],\r\n ['Android', 1],\r\n ['iOS', 2],\r\n ['その他', 2]\r\n]);\r\n\r\n // Optional; add a title and set the width and height of the chart\r\n var options = {'width':400, 'height':260};\r\n\r\n // Display the chart inside the <div> element with id=\"piechart\"\r\n var chart = new google.visualization.PieChart(document.getElementById('checkOs'));\r\n chart.draw(data, options);\r\n}", "render() {\n const tasksHtmlList = [];\n\n // Loops through tasks array objects to store in tasksHtmlList\n for (let i = 0; i < this.tasks.length; i++) {\n const task = this.tasks[i]; // initialize an array to store the tasks\n\n // Format the date\n const date = new Date(task.dueDate);\n const formattedDate =\n date.getDate() + \"/\" + (date.getMonth() + 1) + \"/\" + date.getFullYear();\n\n // Pass the task id as a parameter\n const taskHtml = createTaskHtml(\n // call the function expression creattaskHtml with parameters\n task.id,\n task.name,\n task.description,\n task.assignedTo,\n formattedDate,\n task.status\n );\n\n tasksHtmlList.push(taskHtml); // push the new task values to taskHtmlList\n }\n\n const tasksHtml = tasksHtmlList.join(\"\\n\");\n\n const tasksList = document.querySelector(\"#tasksList\");\n tasksList.innerHTML = tasksHtml;\n }", "function addTask() {\n event.preventDefault();\n\n var form = document.querySelector(\"form\");\n var newTask = { description: form.description.value };\n\n taskList.tasks.push(newTask);\n\n drawList();//call to the function that appends the elements to the the page\n changeColor(); // call to the function that changes the color of the easy, moderate, or hard labels\n\n var d = document.getElementById(\"difficulty\");\n var checkedName = document.querySelector('input[name=\"assignto\"]:checked').value;\n var dropDown = d.options[d.selectedIndex].value;\n\n if (checkedName == \"Whitney\" && dropDown == \"Easy\") {\n whitneyCounter.easy = whitneyCounter.easy + 1;\n } else if (checkedName == \"Whitney\" && dropDown == \"Hard\") {\n whitneyCounter.hard = whitneyCounter.hard + 1;\n } else if(checkedName == \"Whitney\" && dropDown == \"Moderate\"){\n whitneyCounter.moderate = whitneyCounter.moderate + 1;\n } else if(checkedName == \"Emily\" && dropDown == \"Easy\"){\n emilyCounter.easy = emilyCounter.easy + 1;\n } else if(checkedName == \"Emily\" && dropDown == \"Hard\"){\n emilyCounter.hard = emilyCounter.hard + 1;\n } else if(checkedName == \"Emily\" && dropDown == \"Moderate\"){\n emilyCounter.moderate = emilyCounter.moderate + 1;\n } else if(checkedName == \"Eric\" && dropDown == \"Easy\"){\n ericCounter.easy = ericCounter.easy + 1;\n } else if(checkedName == \"Eric\" && dropDown == \"Hard\"){\n ericCounter.hard = ericCounter.hard + 1;\n } else if(checkedName == \"Eric\" && dropDown == \"Moderate\"){\n ericCounter.moderate = ericCounter.moderate + 1;\n }\n drawMultSeries();//call to function that draws the google chart\n}", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Activity');\n data.addColumn('number', 'Completed');\n data.addRows([\n ['Courses', 3],\n ['Posts', 1],\n ['Job Offers', 1],\n ['Tutorials', 1],\n ['Projects', 2]\n ]);\n\n // Set chart options\n var options = {\n 'title': 'Your activity on Udabuddy',\n 'width': '100%',\n 'height': '100%'\n };\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.ColumnChart(document.getElementById(\n 'chart_div'));\n chart.draw(data, options);\n }", "render() {\n\t\t\t\treturn Chart;\n\t\t\t}", "render() {\n\t\t\t\treturn Chart;\n\t\t\t}", "function initDiagram() {\n //create rectangles\n taskRects = diagramG.selectAll('.eve-gantt-chart')\n .data(diagram.data, getTaskKey)\n .enter().append('rect')\n .attr('class', 'eve-gantt-chart')\n .attr('fill', getTaskStatusColor)\n .attr('fill-opacity', currentSerie.alpha)\n .attr('rx', 2)\n .attr('ry', 2)\n .attr('y', 0)\n .attr('height', function (d) { return yScale.bandwidth(); })\n .attr('width', 0)\n .attr('transform', function (d) { return getTaskTransform(d, true); })\n .style('cursor', 'pointer')\n .on('click', function (d, i) {\n //set d clicked\n if (d.clicked == null) {\n //set d clicked\n d.clicked = true;\n } else {\n //set d clicked\n d.clicked = !d.clicked;\n }\n\n //check whether the item clicked\n if (d.clicked) {\n //decrease opacity\n hasSelection = true;\n diagramG.selectAll('.eve-gantt-chart').attr('fill-opacity', 0.05);\n diagramG.selectAll('.eve-gantt-labels').attr('fill-opacity', 0.05);\n\n //select this\n d3.select(this).attr('fill-opacity', 1);\n d3.select('#' + diagram.container + '_svgText_' + i).attr('fill-opacity', 1);\n } else {\n //decrease opacity\n hasSelection = false;\n diagramG.selectAll('.eve-gantt-chart').attr('fill-opacity', 1);\n diagramG.selectAll('.eve-gantt-labels').attr('fill-opacity', 1);\n }\n })\n .on('mousemove', function (d, i) {\n //show tooltip\n if (!hasSelection) {\n diagram.showTooltip(diagram.getContent(d, currentSerie, diagram.tooltip.format));\n d3.select(this).attr('fill-opacity', 1);\n }\n })\n .on('mouseout', function (d, i) {\n //hide tooltip\n if (!hasSelection) {\n diagram.hideTooltip();\n d3.select(this).attr('fill-opacity', currentSerie.alpha);\n }\n });\n\n //create labels\n taskLabels = diagramG.selectAll('.eve-gantt-labels')\n .data(diagram.data, getTaskKey)\n .enter().append('text')\n .attr('class', 'eve-gantt-labels')\n .style('pointer-events', 'none')\n .style('text-anchor', 'start')\n .style('fill', function (d, i) {\n currentColor = getTaskStatusColor(d, i);\n return currentSerie.labelFontColor === 'auto' ? diagram.getAutoColor(currentColor) : currentSerie.labelFontColor;\n })\n .style('font-family', currentSerie.labelFontFamily)\n .style('font-style', currentSerie.labelFontStyle === 'bold' ? 'normal' : currentSerie.labelFontStyle)\n .style('font-weight', currentSerie.labelFontStyle === 'bold' ? 'bold' : 'normal')\n .style('font-size', currentSerie.labelFontSize + 'px')\n .text(function (d) {\n //return text content\n return diagram.getContent(d, currentSerie, currentSerie.labelFormat)\n })\n .attr('transform', function (d) { return getLabelTransform(d, true); });\n }", "function drawChart() {\n var data = google.visualization.arrayToDataTable([\n ['Task', 'Hours per Day'],\n ['Male', 9],\n ['Female', 27],\n]);\n\n // Optional; add a title and set the width and height of the chart\n var options = {'title':'Gender', 'width':150, 'height':106, colors: ['#F0C419', '#71C285']};\n\n // Display the chart inside the <div> element with id=\"piechart\"\n var chart = new google.visualization.PieChart(document.getElementById('piechart1'));\n chart.draw(data, options);\n}", "function submitTasks() {\n GetAllTasksAndRes(function(tasks, resources) {\n // <visualization>\n $.each(tasks, function(index, task) {\n console.dir(JSON.stringify(task));\n });\n // </visualization>\n\n // @Anand: here you can make the AJAX request to the API\n });\n}", "async function ganttChartObject(projects) {\n\n return new Promise(async function (resolve, reject) {\n \n let arrayOfChartData = [];\n let projectData = [];\n let i = 1;\n\n await Promise.all(projects.map(async eachProject => {\n \n let data = [];\n let labels = [];\n let leastStartDate = \"\";\n\n await Promise.all(eachProject.tasks.map(eachTask => {\n if(eachTask.startDate) {\n leastStartDate = eachTask.startDate;\n }\n labels.push(eachTask.title);\n data.push({\n task: eachTask.title,\n startDate:eachTask.startDate,\n endDate: eachTask.endDate\n })\n }))\n\n if (data.length > 0) {\n data.forEach(v => {\n leastStartDate = new Date(v.startDate) < new Date(leastStartDate) ? v.startDate : leastStartDate;\n })\n }\n\n let chartOptions = {\n order: 1,\n options: {\n type: 'horizontalBar',\n data: {\n labels: labels, \n datasets: [\n {\n data: data.map((t) => {\n if (leastStartDate && t.startDate) {\n return dateDiffInDays(new Date(leastStartDate), new Date(t.startDate));\n }\n }),\n datalabels: {\n color: '#025ced',\n // formatter: function (value, context) {\n // return '';\n // },\n },\n backgroundColor: 'rgba(63,103,126,0)',\n hoverBackgroundColor: 'rgba(50,90,100,0)',\n },\n {\n data: data.map((t) => {\n if (t.startDate && t.endDate) {\n return dateDiffInDays(new Date(t.startDate), new Date(t.endDate));\n }\n }),\n datalabels: {\n color: '#025ced',\n // formatter: function (value, context) {\n // return '';\n // },\n },\n },\n ]\n },\n options : {\n maintainAspectRatio: false,\n title: {\n display: true,\n text: eachProject.title\n },\n legend: { display: false },\n scales: {\n xAxes: [\n {\n stacked: true,\n ticks: {\n callback: function (value, index, values) {\n if (leastStartDate) {\n const date = new Date(leastStartDate);\n date.setDate(value);\n return getDate(date);\n }\n },\n },\n },\n ],\n yAxes: [\n {\n stacked: true,\n },\n ],\n }\n }\n }\n }\n \n arrayOfChartData.push(chartOptions);\n eachProject.order = i;\n projectData.push(eachProject);\n i++;\n \n }))\n\n resolve([arrayOfChartData, projectData]);\n })\n}", "function drawChart() {\n\t var data = google.visualization.arrayToDataTable([\n\t ['Task', 'Hours per Day'],\n\t ['Work', 8],\n\t ['Eat', 2],\n\t ['TV', 4],\n\t ['Gym', 2],\n\t ['Sleep', 8]\n\t]);\n\n\t // Optional; add a title and set the width and height of the chart\n\t var options = {'title':'My Average Day', 'width':300, 'height':340};\n\n\t // Display the chart inside the <div> element with id=\"piechart\"\n\t var chart = new google.visualization.PieChart(document.getElementById('piechart'));\n\t chart.draw(data, options);\n\t}", "function drawchart() {\r\n const filters = getFilters();\r\n const drawData = filterData(\r\n filters[\"startDate\"],\r\n filters[\"endDate\"],\r\n filters[\"provincesFilter\"]\r\n );\r\n timeLapseChart = new TimeLapseChart(\"timelapse-chart\");\r\n timeLapseChart\r\n .setTitle(\"COVID-19 ARGENTINA - EVOLUCIÓN EN EL TIEMPO\")\r\n .setColumnsStyles(columnNames)\r\n .addDatasets(drawData)\r\n .render();\r\n}", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Topping');\n data.addColumn('number', 'Slices');\n data.addRows(render);\n\n // Set chart options\n var options = {\n 'title': 'Cantidad de laboratorios por sede',\n\n\n };\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n\n }", "function process_chart(process) {\n\tvar name = process.name;\n\tvar execution_time = parseInt(process.execution_time);\n\tvar arrival_time = parseInt(process.arrival_time);\n\tvar burst_time = parseInt(process.burst_time);\n\n\treturn '<li class=\"title\" title=\"\">'+name+'</li><li class=\"current\" title=\"'+execution_time+'\"><span class=\"bar\" data-number=\"'+burst_time+\n\t'\"></span><span class=\"number\">'+(burst_time+execution_time)+'</span></li>';\n}", "function makeChart() {\n //get the data for the chart and put it in the appropriate places\n //in the chartData and chartOptions objects\n const data = getData(currentSubject, currentMaxWordLength);\n chartData.datasets[0].data = data.BFS;\n chartData.datasets[1].data = data.DFS;\n chartOptions.scales.yAxes[0].scaleLabel.labelString = data.yAxisLabel;\n\n if (resultsChart) {\n resultsChart.destroy();\n }\n\n //create (or recreate) the chart\n const chartContext = $(\"#results-graph\")[0].getContext('2d');\n const chartConfig = {\"type\": \"line\",\n \"data\": chartData,\n \"options\": chartOptions};\n resultsChart = new Chart(chartContext, chartConfig);\n }", "function renderTasks(index) {\n const taskContainer = document.querySelector('.task-list-container')\n taskContainer.innerHTML = '';\n\n if(allProjects.length && allProjects[index].tasks.length) {\n for (let task of allProjects[index].tasks) {\n const singleTask = document.createElement('div')\n const titleContainer = document.createElement('div')\n const circle = document.createElement('span')\n const taskTitle = document.createElement('h5')\n const taskPriority = document.createElement('h6')\n const taskDueDate = document.createElement('h6')\n const editTaskBtn = document.createElement('button')\n const deleteTaskBtn = document.createElement('button')\n\n singleTask.classList.add('single-task-container')\n titleContainer.classList.add('task-title-container')\n circle.classList.add('dot')\n taskTitle.innerText = task.name;\n taskDueDate.innerText = task.dueDate;\n taskPriority.innerText = task.priority;\n taskPriority.classList.add('task-priority')\n editTaskBtn.innerText = 'Edit';\n editTaskBtn.classList.add('edit-task')\n deleteTaskBtn.innerText = 'X';\n deleteTaskBtn.classList.add('delete-task')\n\n titleContainer.appendChild(circle)\n titleContainer.appendChild(taskTitle)\n titleContainer.appendChild(taskPriority)\n titleContainer.appendChild(taskDueDate)\n singleTask.appendChild(titleContainer)\n singleTask.appendChild(editTaskBtn)\n singleTask.appendChild(deleteTaskBtn)\n taskContainer.appendChild(singleTask)\n }\n\n setListenersToTaks();\n }\n\n}", "function drawEvents(x, y, numHours) {\n var task_g = timeline_svg.append(\"g\")\n .data([{x: x, y: y+17, id: \"task_g_\" + event_counter, class: \"task_g\", groupNum: event_counter}]);\n=======\n}", "function generateTask(taskname) {\n var contrainerElement = document.createElement(\"div\")\n contrainerElement.style = \"border: 1px solid grey; width: 350px; padding: 25px; margin-top: 5px\"\n\n var nemImageElement = new Image()\n nemImageElement.src = imageUrl\n nemImageElement.style = \"height: 50px\"\n contrainerElement.appendChild(nemImageElement)\n\n var labelElement = document.createElement(\"label\")\n labelElement.innerHTML = taskname\n contrainerElement.appendChild(labelElement)\n\n var bodyElement = document.getElementsByTagName(\"body\")[0] //in case there are more than one body\n // console.log(bodyElement)\n bodyElement.appendChild(contrainerElement)\n }", "function createSpreadsheet() {\r\n let request = new XMLHttpRequest();\r\n request.open(\"GET\",\"store.json\",true);\r\n\r\n request.onreadystatechange = function() {\r\n // readyState 4 is \"Done\"\r\n // status is 200 for \"OK\"\r\n if (request.readyState === 4 && request.status === 200) {\r\n let my_JSON_object = JSON.parse(request.responseText);\r\n console.log(my_JSON_object);\r\n }\r\n }\r\n // Send the request\r\n request.send();\r\n //attempting to create a chart here\r\n\r\n//cant figure out how to use require here according to the documentations\r\nlet later = require('later');\r\nlet schedule = require('schedulejs');\r\nlet tasks = [\r\n {id: 1, duration: 60, available: later.parse.text('every weekday')},\r\n {id: 2, duration: 30, dependsOn: [1], resources: ['A']},\r\n {id: 3, duration: 30, dependsOn: [1], resources: [['A','B']]}\r\n];\r\n\r\n// Define a set of resources\r\nlet resources = [\r\n {id: A},\r\n {id: B, available: later.parse.text('after 10:00am and before 6:00pm')}\r\n];\r\n\r\n// Create the schedule for all of the tasks\r\nschedule.create(tasks, resources);\r\n}", "function drawChart() {\n const canvas = document.createElement('canvas');\n let data = [];\n let min = Infinity;\n let max = 0;\n for (let i = 0; i < TIMINGS.length; i++) {\n let series = TIMINGS[i];\n min = Math.min(min, Math.min(...series));\n max = Math.max(max, Math.max(...series));\n }\n\n for (let i = 0; i < TIMINGS.length; i++) {\n let series = TIMINGS[i];\n data.push({\n data: bellCurvify(series, min, max),\n label: getFileName(PATHS[i]),\n\n borderColor: COLORS[i % COLORS.length],\n fill: false\n });\n }\n const context = canvas.getContext('2d');\n let labels = [];\n for (let i = min; i <= max; i++) {\n labels.push('' + i);\n }\n document.body.appendChild(canvas);\n new Chart(context, {\n type: 'line',\n data: {\n labels: labels,\n datasets: data\n },\n options: {}\n });\n}", "function drawChart() {\n let activity_chart_data = new google.visualization.DataTable();\n activity_chart_data.addColumn('string', 'Detected Activity Type');\n activity_chart_data.addColumn('number', '#Entries');\n activity_chart_data.addRow(['IN_VEHICLE', activity_data['IN_VEHICLE']]);\n activity_chart_data.addRow(['ON_BICYCLE', activity_data['ON_BICYCLE']]);\n activity_chart_data.addRow(['ON_FOOT', activity_data['ON_FOOT']]);\n activity_chart_data.addRow(['RUNNING', activity_data['RUNNING']]);\n activity_chart_data.addRow(['STILL', activity_data['STILL']]);\n activity_chart_data.addRow(['TILTING', activity_data['TILTING']]);\n activity_chart_data.addRow(['UNKNOWN', activity_data['UNKNOWN']]);\n\n // Optional; add a title and set the width and height of the chart\n var options = { 'pieHole': 0.4 };\n\n var chart = new google.visualization.PieChart(document.getElementById('activity-chart'));\n chart.draw(activity_chart_data, options);\n }", "makeChart() {\n setTimeout(() => {\n this.chart = this._renderChart();\n }, 100);\n }", "function createTask() {\n let title = document.getElementById(\"title\");\n let desc = document.getElementById(\"desc\");\n let date = document.getElementById(\"date\");\n let time = document.getElementById(\"time\");\n let label = document.getElementById(\"label\");\n let clr = document.querySelector(\"input[name=\\\"color\\\"]:checked\");\n let selectedDate = date.options[date.selectedIndex].text;\n let selectedTime = time.options[time.selectedIndex].text;\n let selectedLabel = label.options[label.selectedIndex].text;\n\n if (selectedDate == 'Pick a date') {\n selectedDate = formatDate(getDate);\n }\n if (selectedTime == 'Pick a time') {\n selectedTime = formatTime(getTime);\n }\n\n let task = {\n title: `${title.value}`,\n desc: `${desc.value}`,\n time: `${selectedTime}`,\n date: `${selectedDate}`,\n label: `${selectedLabel}`,\n color: `${clr.value}`\n }\n\n if (localStorage.getItem('itemLabels') === null) {\n itemLabels = [];\n } else {\n itemLabels = JSON.parse(localStorage.getItem('itemLabels'));\n }\n label = document.getElementById(\"label\");\n itemLabels.forEach(el => {\n let opt = document.createElement('option');\n opt.appendChild(document.createTextNode(el));\n label.appendChild(opt);\n })\n\n tasks.push(task)\n localStorage.setItem('tasks', JSON.stringify(tasks))\n render(lists, tasks);\n}", "renderDoneTask() {\n for (let i = 0; i < this.doneTaskArr.length; i++) {\n const task = new Task(this.doneTaskArr[i]);\n this.taskListDone.appendChild(task.createDoneTask());\n };\n }", "function setupitemReport() {\n //variable for status Completed,In progress, Failed\n \n \n\n //html += '<tr>\\r\\n';\n // for(var item in data[row]) {\n // html += '<td>' + data[row][item] + '</td>\\r\\n';\n //}\n //html += '</tr>\\r\\n';\n \n //alert('successcount ' + status[0] + ' in progress '+ status[1] +' successcount '+ status[2]);\n var ctx2 = document.getElementById(\"ItemReportStatus\").getContext('2d');\n var ItemREportStatus = new Chart(ctx2, {\n type: 'doughnut',\n data: {\n labels: [\"Completed\", \"In progress\", \"Failed\", \"Scanned\"],\n datasets: [{\n label: \"Status of Tasks\",\n backgroundColor: ['#0078d4','#71afe5' ,'#a80000','#71afe5'],\n borderColor: ['#0078d4','#71afe5' ,'#a80000', '#71afe5'],\n data: statusItemReport,\n }]\n },\n options: {}\n });\n \n \n \n\n\n}", "static renderTasks(projectTitle, projectTasks) {\r\n\t\tlet tasklistSection = document.getElementById(\"tasklist-container\");\r\n\t\t// Get rid of any existing group container if there are any\r\n\t\t// This is done to prevent any duplicates or stacking\r\n\t\tif (document.querySelector(\".tasklist-group-container\")) {\r\n\t\t\ttasklistSection.removeChild(document.querySelector(\".tasklist-group-container\"));\r\n\t\t}\r\n\r\n\t\t// Create the content to be added and add the classes\r\n\t\tlet content = document.createElement(\"div\");\r\n\t\tcontent.classList.add(\"tasklist-group-container\");\r\n\t\t// Check if the navigation menu is opened\r\n\t\t// add padding necessary if so\r\n\t\tif (tasklistSection.classList.contains(\"show-menu\")) {\r\n\t\t\tcontent.classList.add(\"show-menu\");\r\n\t\t}\r\n\t\tcontent.insertAdjacentHTML(\r\n\t\t\t\"beforeend\",\r\n\t\t\t`\t\t\t\r\n\t\t\t<div class=\"tasklist-group-content\">\r\n\t\t\t\t<div class=\"tasklist-spine\">\r\n\t\t\t\t\t<h2 class=\"tasklist-group-header\">${projectTitle}</h2>\r\n\t\t\t\t\t<button class=\"tasklist-add-button\">+</button>\r\n\t\t\t\t</div>\r\n\t\t\t\t<ul class=\"tasklist-tasks\">\r\n\t\t\t\t\t\r\n\t\t\t\t</ul>\r\n\t\t\t</div>\r\n\t\t`\r\n\t\t);\r\n\t\tlet taskElementContainer = content.querySelector(\".tasklist-tasks\");\r\n\t\t// Generate a list item for every task\r\n\t\tfor (let task of projectTasks) {\r\n\t\t\tif (task.priority === undefined) {\r\n\t\t\t\ttask.priority = \"low\";\r\n\t\t\t}\r\n\t\t\tif (task.time === undefined) {\r\n\t\t\t\ttask.time = \"11:59PM\";\r\n\t\t\t}\r\n\r\n\t\t\tlet taskElement = document.createElement(\"li\");\r\n\t\t\ttaskElement.classList.add(\"tasklist-task\");\r\n\t\t\ttaskElement.classList.add(task.priority);\r\n\t\t\ttaskElement.insertAdjacentHTML(\r\n\t\t\t\t\"beforeend\",\r\n\t\t\t\t`\r\n\t\t\t\t<div class=\"checkbox-title-div\">\r\n\t\t\t\t\t<input class=\"tasklist-checkbox\" type=\"checkbox\" name=\"finished\">\r\n\t\t\t\t\t<span class=\"tasklist-title\">${task.title}</span>\r\n\t\t\t\t</div>\r\n\t\t\t\t<span class=\"date-time-span\">\r\n\t\t\t\t\t<span class=\"tasklist-date\">${task.date} </span>\r\n\t\t\t\t\t<span class=\"time-hide-mobile tasklist-time\"> - ${task.time}</span>\r\n\t\t\t\t</span>\t\t\r\n\t\t\t`\r\n\t\t\t);\r\n\r\n\t\t\tlet checkbox = taskElement.querySelector(\".tasklist-checkbox\");\r\n\r\n\t\t\t// Visual effect functions for toggling task completion\r\n\t\t\tfunction indicateChecked() {\r\n\t\t\t\tcheckbox.checked = true;\r\n\t\t\t\ttaskElement.classList.add(\"checked\");\r\n\t\t\t\ttaskElement.classList.add(\"crossout\");\r\n\t\t\t}\r\n\t\t\tfunction indicateUnchecked() {\r\n\t\t\t\tcheckbox.checked = false;\r\n\t\t\t\ttaskElement.classList.remove(\"checked\");\r\n\t\t\t\ttaskElement.classList.remove(\"crossout\");\r\n\t\t\t}\r\n\r\n\t\t\t// Make an initial check depending on task data\r\n\t\t\tif (task.checked === true) {\r\n\t\t\t\tindicateChecked();\r\n\t\t\t} else if (task.checked === false) {\r\n\t\t\t\tindicateUnchecked();\r\n\t\t\t}\r\n\r\n\t\t\t// Toggle both values And visual appearance upon clicking the checkbox\r\n\t\t\tcheckbox.addEventListener(\"click\", function() {\r\n\t\t\t\ttask.checked = !task.checked;\r\n\t\t\t\tif (task.checked === true) {\r\n\t\t\t\t\tindicateChecked();\r\n\t\t\t\t} else if (task.checked === false) {\r\n\t\t\t\t\tindicateUnchecked();\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\ttaskElement.addEventListener(\"click\", function(event) {\r\n\t\t\t\t// If you click the checkbox do not run commands\r\n\t\t\t\tif (event.target === checkbox) {\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tModal.renderTaskDescriptionModal(task);\r\n\r\n\t\t\t\t// field element variables\r\n\t\t\t\tlet titleField = document.getElementById(\"task-details-title-field\");\r\n\t\t\t\tlet descriptionField = document.getElementById(\"task-details-description-field\");\r\n\t\t\t\tlet dateField = document.getElementById(\"task-details-date-field\");\r\n\t\t\t\tlet timeField = document.getElementById(\"task-details-time-field\");\r\n\t\t\t\tlet priorityField = document.getElementById(\"task-details-priority-menu\");\r\n\r\n\t\t\t\t// old values are stored for future use\r\n\t\t\t\tlet oldTitle = titleField.value;\r\n\t\t\t\tlet oldDescription = descriptionField.value;\r\n\t\t\t\tlet oldDate = dateField.value;\r\n\t\t\t\tlet oldTime = timeField.value;\r\n\t\t\t\tlet oldPriority = priorityField.value;\r\n\r\n\t\t\t\t// button element variables\r\n\t\t\t\tlet editButton = document.getElementById(\"task-details-edit\");\r\n\t\t\t\tlet deleteButton = document.getElementById(\"task-details-delete\");\r\n\t\t\t\tlet applyButton = document.getElementById(\"task-details-apply\");\r\n\t\t\t\tlet cancelButton = document.getElementById(\"task-details-cancel\");\r\n\r\n\t\t\t\tdeleteButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\tevent.preventDefault();\r\n\t\t\t\t\tModal.renderDeleteTaskModal(task.title);\r\n\r\n\t\t\t\t\tlet confirmDeleteButton = document.getElementById(\"delete-task-confirm\");\r\n\t\t\t\t\tlet cancelDeleteButton = document.getElementById(\"delete-task-cancel\");\r\n\r\n\t\t\t\t\tconfirmDeleteButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\t\tlet projectTitle = document.querySelector(\".tasklist-group-header\")\r\n\t\t\t\t\t\t\t.textContent;\r\n\r\n\t\t\t\t\t\tTaskData.deleteTask(projectTitle, task);\r\n\t\t\t\t\t\ttaskElementContainer.removeChild(taskElement);\r\n\t\t\t\t\t\tModal.deleteModal(document.getElementById(\"delete-task-backdrop\"));\r\n\t\t\t\t\t\tModal.deleteModal(document.getElementById(\"task-details-backdrop\"));\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tcancelDeleteButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\t\tModal.deleteModal(document.getElementById(\"delete-task-backdrop\"));\r\n\t\t\t\t\t});\r\n\t\t\t\t});\r\n\t\t\t\t// Listener for edit task button\r\n\t\t\t\teditButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\teditButton.classList.add(\"hide\");\r\n\t\t\t\t\tdeleteButton.classList.add(\"hide\");\r\n\t\t\t\t\tapplyButton.classList.remove(\"hide\");\r\n\t\t\t\t\tcancelButton.classList.remove(\"hide\");\r\n\r\n\t\t\t\t\t// transform the disabled buttons into enabled ones\r\n\t\t\t\t\tlet inputFields = document.querySelectorAll(\".task-details-modal-required\");\r\n\t\t\t\t\tfor (let input of inputFields) {\r\n\t\t\t\t\t\tinput.disabled = false;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tlet inputDate = format(task.date, \"YYYY-MM-DD\");\r\n\t\t\t\t\tdocument.getElementById(\"task-details-date-field\").value = inputDate;\r\n\t\t\t\t\t// document.getElementById(\"task-details-date-field\").value = \"2020-01-15\";\r\n\r\n\t\t\t\t\t// let placeholderDate = new Date(`${inputDate} ${task.time}`);\r\n\t\t\t\t\t// console.log(placeholderDate);\r\n\t\t\t\t\t// let inputTime = format(new Date(`${inputDate} ${task.time}`), 'hh:mmA');\r\n\t\t\t\t\tlet inputTime = standardToMilitary(task.time);\r\n\t\t\t\t\tdocument.getElementById(\"task-details-time-field\").value = inputTime;\r\n\r\n\t\t\t\t\tapplyButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\t\tif (Modal.validEditTaskForm()) {\r\n\t\t\t\t\t\t\t// Submit if valid\r\n\t\t\t\t\t\t\t// let oldPriority = task.priority;\r\n\t\t\t\t\t\t\ttaskElement.classList.remove(\"high\");\r\n\t\t\t\t\t\t\ttaskElement.classList.remove(\"medium\");\r\n\t\t\t\t\t\t\ttaskElement.classList.remove(\"low\");\r\n\r\n\t\t\t\t\t\t\t// This is done to replace the values of the task object\r\n\t\t\t\t\t\t\t// that is located in the data structure\r\n\t\t\t\t\t\t\tlet oldTask = task;\r\n\t\t\t\t\t\t\tlet newTask = Modal.retrieveEditTaskData();\r\n\t\t\t\t\t\t\tTaskData.updateTaskProperties(oldTask, newTask);\r\n\r\n\t\t\t\t\t\t\t// Replacing the old text content of the Dom elements of the item\r\n\t\t\t\t\t\t\tlet oldTitle = taskElement.querySelector(\".tasklist-title\");\r\n\t\t\t\t\t\t\tlet oldDate = taskElement.querySelector(\".tasklist-date\");\r\n\t\t\t\t\t\t\tlet oldTime = taskElement.querySelector(\".tasklist-time\");\r\n\r\n\t\t\t\t\t\t\toldTitle.textContent = newTask.title;\r\n\t\t\t\t\t\t\toldDate.textContent = newTask.date;\r\n\t\t\t\t\t\t\toldTime.textContent = ` - ${newTask.time}`;\r\n\t\t\t\t\t\t\ttaskElement.classList.add(task.priority);\r\n\r\n\t\t\t\t\t\t\tlet projectTitle = document.querySelector(\".tasklist-group-header\")\r\n\t\t\t\t\t\t\t\t.textContent;\r\n\r\n\t\t\t\t\t\t\tModal.deleteModal(document.getElementById(\"task-details-backdrop\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tcancelButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\t\t// do the opposite of the edit button (reverse its effects)\r\n\t\t\t\t\t\teditButton.classList.remove(\"hide\");\r\n\t\t\t\t\t\tdeleteButton.classList.remove(\"hide\");\r\n\t\t\t\t\t\tapplyButton.classList.add(\"hide\");\r\n\t\t\t\t\t\tcancelButton.classList.add(\"hide\");\r\n\r\n\t\t\t\t\t\t// transform the enabled buttons into disabled ones\r\n\t\t\t\t\t\tlet inputFields = document.querySelectorAll(\".task-details-modal-required\");\r\n\t\t\t\t\t\tfor (let input of inputFields) {\r\n\t\t\t\t\t\t\tinput.disabled = true;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t// Restore the original values before editing\r\n\t\t\t\t\t\ttitleField.value = oldTitle;\r\n\t\t\t\t\t\tdescriptionField.value = oldDescription;\r\n\t\t\t\t\t\tdateField.value = oldDate;\r\n\t\t\t\t\t\ttimeField.value = oldTime;\r\n\t\t\t\t\t\tpriorityField.value = oldPriority;\r\n\t\t\t\t\t});\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t\ttaskElementContainer.insertBefore(taskElement, taskElementContainer.firstChild);\r\n\t\t}\r\n\r\n\t\tfunction openAddTaskModal() {\r\n\t\t\tModal.renderAddTaskModal();\r\n\r\n\t\t\t// add listeners to each input field\r\n\t\t\tlet requiredAddTaskInputs = document.querySelectorAll(\".add-task-modal-required\");\r\n\t\t\tlet dateField = document.getElementById(\"add-task-date-field\");\r\n\t\t\tlet timeField = document.getElementById(\"add-task-time-field\");\r\n\t\t\tfor (let input of requiredAddTaskInputs) {\r\n\t\t\t\tinput.addEventListener(\"blur\", function() {\r\n\t\t\t\t\t// Restrict the date and time fields to only accept dates/times from today onwards\r\n\t\t\t\t\tif (input === dateField) {\r\n\t\t\t\t\t\tModal.validAddTaskDate(input);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t} else if (input === timeField) {\r\n\t\t\t\t\t\tModal.validAddTaskTime(input);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (Modal.emptyFieldError(input)) {\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\r\n\t\t\t// Handle the rendering upon submitting a task\r\n\t\t\tdocument.getElementById(\"add-task-submit\").addEventListener(\"click\", function(event) {\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\t// Check if the form values are valid before running\r\n\t\t\t\tif (Modal.validAddTaskForm()) {\r\n\t\t\t\t\t// Submit if valid\r\n\t\t\t\t\tlet task = Modal.retrieveAddTaskData();\r\n\t\t\t\t\tTasklist.renderTask(task);\r\n\r\n\t\t\t\t\tlet projectTitle = document.querySelector(\".tasklist-group-header\").textContent;\r\n\t\t\t\t\tTaskData.addTask(projectTitle, task);\r\n\r\n\t\t\t\t\tModal.deleteModal(document.getElementById(\"add-task-backdrop\"));\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tcontent.querySelector(\".tasklist-add-button\").addEventListener(\"click\", function() {\r\n\t\t\topenAddTaskModal();\r\n\t\t});\r\n\t\ttasklistSection.appendChild(content);\r\n\t}", "function genChart(){\n var colors=[\"#3366cc\",\"#dc3912\",\"#ff9900\",\"#109618\",\"#990099\",\"#0099c6\",\"#dd4477\",\"#66aa00\",\"#b82e2e\",\"#316395\",\"#994499\",\"#22aa99\",\"#aaaa11\",\"#6633cc\",\"#e67300\",\"#8b0707\",\"#651067\",\"#329262\",\"#5574a6\",\"#3b3eac\",\"#b77322\",\"#16d620\",\"#b91383\",\"#f4359e\",\"#9c5935\",\"#a9c413\",\"#2a778d\",\"#668d1c\",\"#bea413\",\"#0c5922\",\"#743411\"];\n var states=_.map($scope.data.states,function(runs,state){return state;});\n\n var session=_.map($scope.data.queries,\n function(v,key){return {\n \"name\":key,\n \"runs\":_.sortBy(v,state)\n }\n ;});\n var c=[];\n if(session.length){\n c=_.map(session[0].runs,function(run,index){\n var state=run.mode + run.factor;\n var pos=states.indexOf(state);\n // console.log(\"��\",state,pos);\n return colors[pos];\n });\n c=_.flatten(c);\n };\n var options={\n title:'BenchX: ' + $scope.benchmark.suite + \" \" + $scope.benchmark.meta.description,\n vAxis: {title: 'Time (sec)'}\n ,hAxis: {title: 'Query'}\n // ,legend: 'none'\n ,colors: c\n };\n return utils.gchart(session,options);\n\n }", "function drawPieChart() {\r\n var data = google.visualization.arrayToDataTable([\r\n [\"Unified Portal\", \"Project completed\"],\r\n [\"NEB\", 8],\r\n [\"CTEVT\", 8],\r\n [\"UGC\", 5],\r\n [\"Kaiser Library\", 5],\r\n [\"Medical Education Commission\", 5],\r\n ]);\r\n\r\n // Optional; add a title and set the width and height of the chart\r\n var options = { title: \"Progress Chart\" };\r\n\r\n // Display the chart inside the <div> element with id=\"piechart\"\r\n var chart = new google.visualization.PieChart(\r\n document.getElementById(\"piechart\")\r\n ); \r\n chart.draw(data, options);\r\n }", "function renderTasks() {\n\t\t//get info from server\n\t\tvar allTasks = [];\n\t\tfor (var key in localStorage) {\n\t\t\tif (localStorage.hasOwnProperty(key)) {\n\t\t\t\tallTasks.push(JSON.parse(localStorage[key]));\n\t\t\t}\n\t\t}\n\t\t//sort tasks by tabs\n\t\tfunction sortTasksByStatus(sourceArr, taskStatus) {\n\t\t\tvar arr = allTasks.filter(function(item) {\n\t\t\t\treturn item.status === taskStatus;\n\t\t\t})\n\t\t\treturn arr;\n\t\t}\n\t\tvar toDoTasks = sortTasksByStatus(allTasks, 1);\n\t\tvar inProgressTasks = sortTasksByStatus(allTasks, 2);\n\t\tvar doneTasks = sortTasksByStatus(allTasks, 3);\n\t\t\n\t\t//print counters\n\t\trenderCounters(toDoTasks.length, inProgressTasks.length, doneTasks.length);\n\n\t\t//clear DOM\n\t\t$('.tab-content li').remove();\n\n\t\t//print tasks\n\t\tfunction renderTabTasks(arr, tabName) {\n\t\t\tarr.forEach(function(item) {\n\t\t\t\tprintTask(item, tabName)\n\t\t\t});\n\t\t}\n\t\trenderTabTasks(toDoTasks, $('#toDo .list-group'));\n\t\trenderTabTasks(inProgressTasks, $('#inProgress .list-group'));\n\t\trenderTabTasks(doneTasks, $('#done .list-group'));\n\t}", "function drawChart3() {\n var data = google.visualization.arrayToDataTable([\n ['Task', 'Hours per Day'],\n ['Airtel', 4],\n ['MTN', 32],\n]);\n\n // Optional; add a title and set the width and height of the chart\n var options = {'title':'Mobile Network', 'width':150, 'height':106, colors: ['#F0C419', '#F0785A']};\n\n // Display the chart inside the <div> element with id=\"piechart\"\n var chart = new google.visualization.PieChart(document.getElementById('piechart3'));\n chart.draw(data, options);\n}", "function makegraph() {\n\tchart = new CanvasJS.Chart(\"graphDiv\", {\n\t\taxisX: {\n\t\t\ttitle: _(\"Cycle number\"),\n\t\t\t/** x axis label */\n\t\t\ttitleFontSize: 22,\n\t\t\t/** Chart font size */\n\t\t\tlabelFontSize: 18,\n\t\t\tminimum: 0,\n\t\t\tinterval: 2\n\t\t},\n\t\taxisY: {\n\t\t\ttitle: _(\"Amount of DNA\"),\n\t\t\ttitleFontSize: 22,\n\t\t\tlabelFontSize: 18,\n\t\t\tminimum: 0\n\t\t},\n\t\tshowInLegend: false,\n\t\tdata: [{\n\t\t\tcolor: \"red\",\n\t\t\ttype: \"line\",\n\t\t\tmarkerType: \"circle\",\n\t\t\tlineThickness: 3,\n\t\t\tdataPoints: dataplotArray /** Datapoints to be plot, stored in the array */\n\t\t}]\n\t});\n\tchart.render();\n\tchain_reaction_stage.update();\n}", "function generateChart(story,projectName) {\n\t\t$(\"#div1\").show();\n\t\tvar ds;\n\t\tvar finish=0,create=0,working=0;\n\t\t\n\t\tfor (i = 0; i < story.length; i++){\n\t\t\tds = [];\n\t\t\tif (story[i].fields.theme == \"sticky-note-green-theme\")\n\t\t\t\tfinish++;\n\t\t\telse if (story[i].fields.theme == \"sticky-note-blue-theme\")\n\t\t\t\tcreate++;\n\t\t\telse \n\t\t\t\tworking++;\n\t\t\t\n\t\t\t$('#mytitle').html(\"Project : \" + projectName);\n\t\t\tds.push(finish);ds.push(working);ds.push(create);\n\t\t\tconfig.data.datasets.forEach(function(dataset) {dataset.data = ds;});\t\t\t\t\n\t\t\tconfig.data.labels = ['Finish','On Progress','New'];\n\t\t\tmyDoughnut.update();\n\t\t}\t\n\t}", "function drawChart4() {\n var data = google.visualization.arrayToDataTable([\n ['Task', 'Hours per Day'],\n ['IOS', 8],\n ['Android', 28],\n]);\n\n // Optional; add a title and set the width and height of the chart\n var options = {'title':'Phone', 'width':150, 'height':106, colors: ['#B771C2', '#19F0F0']};\n\n // Display the chart inside the <div> element with id=\"piechart\"\n var chart = new google.visualization.PieChart(document.getElementById('piechart4'));\n chart.draw(data, options);\n}", "static process(data){\n console.log(data)\n const user = data.user\n const spending = data.categories\n const total_spending = spending.map(e => e.cost).reduce((memo, e)=>e + memo,0)\n const new_array = []\n const labels = []\n const colors = []\n if(user.income && spending.length > 0 ){\n\n // new_array.push(user.income)\n // labels.push(\"Income\")\n // colors.push(\"rgb(64, 139, 179)\")\n spending.forEach(e => {new_array.push(e.cost); labels.push(e.name)})\n while(colors.length !== labels.length){\n const new_color = `rgb(${Math.floor((Math.random() * 256))}, ${Math.floor((Math.random() * 256))}, ${Math.floor((Math.random() * 256))})`\n if(!colors.includes(new_color)){\n colors.push(new_color)\n }\n }\n if (!document.querySelector(\"div.chart-info\").classList.contains(\"hidden\")){\n document.querySelector(\"div.chart-info\").classList.add(\"hidden\")\n }\n document.querySelector(\"div.myCanvas\").innerHTML = `<canvas class=\"myChart hidden\" id=\"myChart\"></canvas>`\n Chart_Generator.create_chart(total_spending,new_array,labels,colors)\n Chart_Generator.summary(data)\n }else{\n document.querySelector(\"canvas\").style.display = \"\"\n if (document.querySelector(\"div.chart-info\").classList.contains(\"hidden\")){\n document.querySelector(\"div.chart-info\").classList.remove(\"hidden\")\n }\n\n \n }\n }", "static renderTask(task) {\r\n\t\tlet taskElementContainer = document.querySelector(\".tasklist-tasks\");\r\n\t\tlet taskElement = document.createElement(\"li\");\r\n\t\ttaskElement.classList.add(\"tasklist-task\");\r\n\r\n\t\t// Check the priority of the task and give it the appropriate class\r\n\t\tif (task.priority === \"high\") {\r\n\t\t\ttaskElement.classList.add(\"high\");\r\n\t\t} else if (task.priority === \"medium\") {\r\n\t\t\ttaskElement.classList.add(\"medium\");\r\n\t\t} else if (task.priority === \"low\") {\r\n\t\t\ttaskElement.classList.add(\"low\");\r\n\t\t}\r\n\t\ttaskElement.insertAdjacentHTML(\r\n\t\t\t\"beforeend\",\r\n\t\t\t`\r\n\t\t\t<div class=\"checkbox-title-div\">\r\n\t\t\t\t<input class=\"tasklist-checkbox\" type=\"checkbox\" name=\"finished\">\r\n\t\t\t\t<span class=\"tasklist-title\">${task.title}</span>\r\n\t\t\t</div>\r\n\t\t\t<span class=\"date-time-span\">\r\n\t\t\t\t<span class=\"tasklist-date\">${task.date} </span>\r\n\t\t\t\t<span class=\"time-hide-mobile tasklist-time\"> - ${task.time}</span>\r\n\t\t\t</span>\r\n\t\t\t\r\n\t\t`\r\n\t\t);\r\n\r\n\t\tlet checkbox = taskElement.querySelector(\".tasklist-checkbox\");\r\n\r\n\t\t// Visual effect functions for toggling task completion\r\n\t\tfunction indicateChecked() {\r\n\t\t\tcheckbox.checked = true;\r\n\t\t\ttaskElement.classList.add(\"checked\");\r\n\t\t\ttaskElement.classList.add(\"crossout\");\r\n\t\t}\r\n\t\tfunction indicateUnchecked() {\r\n\t\t\tcheckbox.checked = false;\r\n\t\t\ttaskElement.classList.remove(\"checked\");\r\n\t\t\ttaskElement.classList.remove(\"crossout\");\r\n\t\t}\r\n\r\n\t\t// Make an initial check depending on task data\r\n\t\tif (task.checked === true) {\r\n\t\t\tindicateChecked();\r\n\t\t} else if (task.checked === false) {\r\n\t\t\tindicateUnchecked();\r\n\t\t}\r\n\r\n\t\t// Toggle both values And visual appearance upon clicking the checkbox\r\n\t\tcheckbox.addEventListener(\"click\", function() {\r\n\t\t\ttask.checked = !task.checked;\r\n\t\t\tif (task.checked === true) {\r\n\t\t\t\tindicateChecked();\r\n\t\t\t} else if (task.checked === false) {\r\n\t\t\t\tindicateUnchecked();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\t// Add Event listener for click to display task information\r\n\t\ttaskElement.addEventListener(\"click\", function() {\r\n\t\t\t// If you click the checkbox do not run commands\r\n\t\t\tif (event.target === checkbox) {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tModal.renderTaskDescriptionModal(task);\r\n\r\n\t\t\t// field element variables\r\n\t\t\tlet titleField = document.getElementById(\"task-details-title-field\");\r\n\t\t\tlet descriptionField = document.getElementById(\"task-details-description-field\");\r\n\t\t\tlet dateField = document.getElementById(\"task-details-date-field\");\r\n\t\t\tlet timeField = document.getElementById(\"task-details-time-field\");\r\n\t\t\tlet priorityField = document.getElementById(\"task-details-priority-menu\");\r\n\r\n\t\t\t// old values are stored for future use\r\n\t\t\tlet oldTitle = titleField.value;\r\n\t\t\tlet oldDescription = descriptionField.value;\r\n\t\t\tlet oldDate = dateField.value;\r\n\t\t\tlet oldTime = timeField.value;\r\n\t\t\tlet oldPriority = priorityField.value;\r\n\r\n\t\t\tlet editButton = document.getElementById(\"task-details-edit\");\r\n\t\t\tlet deleteButton = document.getElementById(\"task-details-delete\");\r\n\t\t\tlet applyButton = document.getElementById(\"task-details-apply\");\r\n\t\t\tlet cancelButton = document.getElementById(\"task-details-cancel\");\r\n\r\n\t\t\tdeleteButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tModal.renderDeleteTaskModal(task.title);\r\n\r\n\t\t\t\tlet confirmDeleteButton = document.getElementById(\"delete-task-confirm\");\r\n\t\t\t\tlet cancelDeleteButton = document.getElementById(\"delete-task-cancel\");\r\n\r\n\t\t\t\tconfirmDeleteButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\tlet projectTitle = document.querySelector(\".tasklist-group-header\").textContent;\r\n\t\t\t\t\ttaskElementContainer.removeChild(taskElement);\r\n\t\t\t\t\tTaskData.deleteTask(projectTitle, task);\r\n\t\t\t\t\tModal.deleteModal(document.getElementById(\"delete-task-backdrop\"));\r\n\t\t\t\t\tModal.deleteModal(document.getElementById(\"task-details-backdrop\"));\r\n\t\t\t\t});\r\n\r\n\t\t\t\tcancelDeleteButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\tModal.deleteModal(document.getElementById(\"delete-task-backdrop\"));\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t\t// Listener for edit task button\r\n\t\t\teditButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\teditButton.classList.add(\"hide\");\r\n\t\t\t\tdeleteButton.classList.add(\"hide\");\r\n\t\t\t\tapplyButton.classList.remove(\"hide\");\r\n\t\t\t\tcancelButton.classList.remove(\"hide\");\r\n\r\n\t\t\t\t// transform the disabled buttons into enabled ones\r\n\t\t\t\tlet inputFields = document.querySelectorAll(\".task-details-modal-required\");\r\n\t\t\t\tfor (let input of inputFields) {\r\n\t\t\t\t\tinput.disabled = false;\r\n\t\t\t\t}\r\n\t\t\t\t// Clear both the date & time fields\r\n\t\t\t\t// document.getElementById(\"task-details-date-field\").value = \"Date (optional)\";\r\n\t\t\t\t// document.getElementById(\"task-details-time-field\").value = \"Time (optional)\";\r\n\r\n\t\t\t\tlet inputDate = format(task.date, \"YYYY-MM-DD\");\r\n\t\t\t\tdocument.getElementById(\"task-details-date-field\").value = inputDate;\r\n\t\t\t\t// document.getElementById(\"task-details-date-field\").value = \"2020-01-15\";\r\n\t\t\t\t{\r\n\t\t\t\t\t// let placeholderDate = new Date(`${inputDate} ${task.time}`);\r\n\t\t\t\t\t// console.log(placeholderDate);\r\n\t\t\t\t\t// let inputTime = format(new Date(`${inputDate} ${task.time}`), 'hh:mmA');\r\n\t\t\t\t\tlet inputTime = standardToMilitary(task.time);\r\n\t\t\t\t\tdocument.getElementById(\"task-details-time-field\").value = inputTime;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tapplyButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\tif (Modal.validEditTaskForm()) {\r\n\t\t\t\t\t\t// Submit if valid\r\n\t\t\t\t\t\t// let oldPriority = task.priority;\r\n\t\t\t\t\t\ttaskElement.classList.remove(\"high\");\r\n\t\t\t\t\t\ttaskElement.classList.remove(\"medium\");\r\n\t\t\t\t\t\ttaskElement.classList.remove(\"low\");\r\n\r\n\t\t\t\t\t\t// This is done to replace the values of the task object\r\n\t\t\t\t\t\t// that is located in the data structure\r\n\t\t\t\t\t\tlet oldTask = task;\r\n\t\t\t\t\t\tlet newTask = Modal.retrieveEditTaskData();\r\n\t\t\t\t\t\tTaskData.updateTaskProperties(oldTask, newTask);\r\n\r\n\t\t\t\t\t\t// Replacing the old text content of the Dom elements of the item\r\n\t\t\t\t\t\tlet oldTitle = taskElement.querySelector(\".tasklist-title\");\r\n\t\t\t\t\t\tlet oldDate = taskElement.querySelector(\".tasklist-date\");\r\n\t\t\t\t\t\tlet oldTime = taskElement.querySelector(\".tasklist-time\");\r\n\r\n\t\t\t\t\t\toldTitle.textContent = newTask.title;\r\n\t\t\t\t\t\toldDate.textContent = newTask.date;\r\n\t\t\t\t\t\toldTime.textContent = ` - ${newTask.time}`;\r\n\t\t\t\t\t\ttaskElement.classList.add(task.priority);\r\n\r\n\t\t\t\t\t\tlet projectTitle = document.querySelector(\".tasklist-group-header\")\r\n\t\t\t\t\t\t\t.textContent;\r\n\r\n\t\t\t\t\t\tModal.deleteModal(document.getElementById(\"task-details-backdrop\"));\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\tcancelButton.addEventListener(\"click\", function(event) {\r\n\t\t\t\t\tevent.preventDefault();\r\n\r\n\t\t\t\t\t// do the opposite of the edit button (reverse its effects)\r\n\t\t\t\t\teditButton.classList.remove(\"hide\");\r\n\t\t\t\t\tdeleteButton.classList.remove(\"hide\");\r\n\t\t\t\t\tapplyButton.classList.add(\"hide\");\r\n\t\t\t\t\tcancelButton.classList.add(\"hide\");\r\n\r\n\t\t\t\t\t// transform the enabled buttons into disabled ones\r\n\t\t\t\t\tlet inputFields = document.querySelectorAll(\".task-details-modal-required\");\r\n\t\t\t\t\tfor (let input of inputFields) {\r\n\t\t\t\t\t\tinput.disabled = true;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t// Restore the original values before editing\r\n\t\t\t\t\ttitleField.value = oldTitle;\r\n\t\t\t\t\tdescriptionField.value = oldDescription;\r\n\t\t\t\t\tdateField.value = oldDate;\r\n\t\t\t\t\ttimeField.value = oldTime;\r\n\t\t\t\t\tpriorityField.value = oldPriority;\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t\t// Check if the container exists before inserting\r\n\t\t// If it is not, just make a new one first then insert\r\n\t\tlet taskContainer = document.querySelector(\".tasklist-tasks\");\r\n\t\tif (taskContainer) {\r\n\t\t\ttaskContainer.insertBefore(taskElement, taskContainer.firstChild);\r\n\t\t} else {\r\n\t\t\ttaskContainer = document.createElement(\"ul\");\r\n\t\t\ttaskContainer.classList.add(\"tasklist-tasks\");\r\n\t\t\ttaskContainer.insertBefore(taskElement, taskContainer.firstChild);\r\n\r\n\t\t\tlet groupContainer = document.querySelector(\".tasklist-group-container\");\r\n\t\t\tgroupContainer.insertBefore(taskContainer, groupContainer.firstChild);\r\n\t\t}\r\n\t}", "function createChart(options){var data=Chartist.normalizeData(this.data,options.reverseData,true);// Create new svg object\nthis.svg=Chartist.createSvg(this.container,options.width,options.height,options.classNames.chart);// Create groups for labels, grid and series\nvar gridGroup=this.svg.elem('g').addClass(options.classNames.gridGroup);var seriesGroup=this.svg.elem('g');var labelGroup=this.svg.elem('g').addClass(options.classNames.labelGroup);var chartRect=Chartist.createChartRect(this.svg,options,defaultOptions.padding);var axisX,axisY;if(options.axisX.type===undefined){axisX=new Chartist.StepAxis(Chartist.Axis.units.x,data.normalized.series,chartRect,Chartist.extend({},options.axisX,{ticks:data.normalized.labels,stretch:options.fullWidth}));}else {axisX=options.axisX.type.call(Chartist,Chartist.Axis.units.x,data.normalized.series,chartRect,options.axisX);}if(options.axisY.type===undefined){axisY=new Chartist.AutoScaleAxis(Chartist.Axis.units.y,data.normalized.series,chartRect,Chartist.extend({},options.axisY,{high:Chartist.isNumeric(options.high)?options.high:options.axisY.high,low:Chartist.isNumeric(options.low)?options.low:options.axisY.low}));}else {axisY=options.axisY.type.call(Chartist,Chartist.Axis.units.y,data.normalized.series,chartRect,options.axisY);}axisX.createGridAndLabels(gridGroup,labelGroup,this.supportsForeignObject,options,this.eventEmitter);axisY.createGridAndLabels(gridGroup,labelGroup,this.supportsForeignObject,options,this.eventEmitter);if(options.showGridBackground){Chartist.createGridBackground(gridGroup,chartRect,options.classNames.gridBackground,this.eventEmitter);}// Draw the series\ndata.raw.series.forEach(function(series,seriesIndex){var seriesElement=seriesGroup.elem('g');// Write attributes to series group element. If series name or meta is undefined the attributes will not be written\nseriesElement.attr({'ct:series-name':series.name,'ct:meta':Chartist.serialize(series.meta)});// Use series class from series data or if not set generate one\nseriesElement.addClass([options.classNames.series,series.className||options.classNames.series+'-'+Chartist.alphaNumerate(seriesIndex)].join(' '));var pathCoordinates=[],pathData=[];data.normalized.series[seriesIndex].forEach(function(value,valueIndex){var p={x:chartRect.x1+axisX.projectValue(value,valueIndex,data.normalized.series[seriesIndex]),y:chartRect.y1-axisY.projectValue(value,valueIndex,data.normalized.series[seriesIndex])};pathCoordinates.push(p.x,p.y);pathData.push({value:value,valueIndex:valueIndex,meta:Chartist.getMetaData(series,valueIndex)});}.bind(this));var seriesOptions={lineSmooth:Chartist.getSeriesOption(series,options,'lineSmooth'),showPoint:Chartist.getSeriesOption(series,options,'showPoint'),showLine:Chartist.getSeriesOption(series,options,'showLine'),showArea:Chartist.getSeriesOption(series,options,'showArea'),areaBase:Chartist.getSeriesOption(series,options,'areaBase')};var smoothing=typeof seriesOptions.lineSmooth==='function'?seriesOptions.lineSmooth:seriesOptions.lineSmooth?Chartist.Interpolation.monotoneCubic():Chartist.Interpolation.none();// Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n// index, value and meta data\nvar path=smoothing(pathCoordinates,pathData);// If we should show points we need to create them now to avoid secondary loop\n// Points are drawn from the pathElements returned by the interpolation function\n// Small offset for Firefox to render squares correctly\nif(seriesOptions.showPoint){path.pathElements.forEach(function(pathElement){var point=seriesElement.elem('line',{x1:pathElement.x,y1:pathElement.y,x2:pathElement.x+0.01,y2:pathElement.y},options.classNames.point).attr({'ct:value':[pathElement.data.value.x,pathElement.data.value.y].filter(Chartist.isNumeric).join(','),'ct:meta':Chartist.serialize(pathElement.data.meta)});this.eventEmitter.emit('draw',{type:'point',value:pathElement.data.value,index:pathElement.data.valueIndex,meta:pathElement.data.meta,series:series,seriesIndex:seriesIndex,axisX:axisX,axisY:axisY,group:seriesElement,element:point,x:pathElement.x,y:pathElement.y});}.bind(this));}if(seriesOptions.showLine){var line=seriesElement.elem('path',{d:path.stringify()},options.classNames.line,true);this.eventEmitter.emit('draw',{type:'line',values:data.normalized.series[seriesIndex],path:path.clone(),chartRect:chartRect,index:seriesIndex,series:series,seriesIndex:seriesIndex,seriesMeta:series.meta,axisX:axisX,axisY:axisY,group:seriesElement,element:line});}// Area currently only works with axes that support a range!\nif(seriesOptions.showArea&&axisY.range){// If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n// the area is not drawn outside the chart area.\nvar areaBase=Math.max(Math.min(seriesOptions.areaBase,axisY.range.max),axisY.range.min);// We project the areaBase value into screen coordinates\nvar areaBaseProjected=chartRect.y1-axisY.projectValue(areaBase);// In order to form the area we'll first split the path by move commands so we can chunk it up into segments\npath.splitByCommand('M').filter(function onlySolidSegments(pathSegment){// We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\nreturn pathSegment.pathElements.length>1;}).map(function convertToArea(solidPathSegments){// Receiving the filtered solid path segments we can now convert those segments into fill areas\nvar firstElement=solidPathSegments.pathElements[0];var lastElement=solidPathSegments.pathElements[solidPathSegments.pathElements.length-1];// Cloning the solid path segment with closing option and removing the first move command from the clone\n// We then insert a new move that should start at the area base and draw a straight line up or down\n// at the end of the path we add an additional straight line to the projected area base value\n// As the closing option is set our path will be automatically closed\nreturn solidPathSegments.clone(true).position(0).remove(1).move(firstElement.x,areaBaseProjected).line(firstElement.x,firstElement.y).position(solidPathSegments.pathElements.length+1).line(lastElement.x,areaBaseProjected);}).forEach(function createArea(areaPath){// For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n// and adding the created DOM elements to the correct series group\nvar area=seriesElement.elem('path',{d:areaPath.stringify()},options.classNames.area,true);// Emit an event for each area that was drawn\nthis.eventEmitter.emit('draw',{type:'area',values:data.normalized.series[seriesIndex],path:areaPath.clone(),series:series,seriesIndex:seriesIndex,axisX:axisX,axisY:axisY,chartRect:chartRect,index:seriesIndex,group:seriesElement,element:area});}.bind(this));}}.bind(this));this.eventEmitter.emit('created',{bounds:axisY.bounds,chartRect:chartRect,axisX:axisX,axisY:axisY,svg:this.svg,options:options});}", "function DrawCPUChart()\n{\n // create/delete rows \n if (cpuTable.getNumberOfRows() < aggrDataPoints.length)\n { \n var numRows = aggrDataPoints.length - cpuTable.getNumberOfRows();\n cpuTable.addRows(numRows);\n } else {\n for(var i=(cpuTable.getNumberOfRows()-1); i >= aggrDataPoints.length; i--)\n {\n cpuTable.removeRow(i); \n }\n }\n \n // Populate data table with time/cpu data points. \n for(var i=0; i < cpuTable.getNumberOfRows(); i++)\n {\n //if(parseFloat(aggrDataPoints[i].cpu) < 500) continue;\n cpuTable.setCell(i, 0, new Date(parseInt(aggrDataPoints[i].timestamp)));\n cpuTable.setCell(i, 1, parseFloat(aggrDataPoints[i].cpu));\n }\n\n // Draw line chart.\n chartOptions.title = 'CPU Usage (%)';\n cpuChart.draw(cpuView, chartOptions); \n}", "function drawChart() {\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Topping');\n data.addColumn('number', 'Slices');\n data.addRows(Object.entries(ar_chart));\n\n // Set chart options\n var options = {'title':'Percentage of file size',\n 'width':500,\n 'height':200};\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n }", "function renderTasks () {\n // Set which tasks to render\n var tasksBeingViewed = [];\n if (mode === 'future') tasksBeingViewed = futureTasks;\n if (mode === 'today') tasksBeingViewed = todaysTasks;\n if (mode === 'prev') tasksBeingViewed = previousTasks;\n\n // If there's no tasks to show, show that message\n if (!tasksBeingViewed || tasksBeingViewed.length == 0) {\n var noTaskHtml = '<h2>No Tasks</h2>';\n $('#task-item-div').html(noTaskHtml);\n return;\n }\n\n // Create HTML to add to the page\n var htmlToShow = '';\n for (let i in tasksBeingViewed) {\n let task = tasksBeingViewed[i];\n // Process filiters \n // Complete filter \n if (hasCompleteFilter && task.complete !== completeFilter) {\n continue;\n }\n // Priority filter \n if (hasPriorityFilter && task.priority !== priorityFilter) {\n continue;\n }\n // Category filter \n if (hasCategoryFilter && task.category !== categoryFilter) {\n continue;\n }\n\n htmlToShow += '<div class=\"task-item\" id=\"task-item-' + task._id + '\">';\n htmlToShow += '<h4 class=\"task-description task-item-content\">' + task.description + '</h4>';\n htmlToShow += '<h6 class=\"task-item-content\"><i> Due: ' + task.deadline + '</i></h6>';\n htmlToShow += '<h5 class=\"task-item-content\"><i>Priority: </i>' + task.priority + '</h5>';\n htmlToShow += '<h5 class=\"task-item-content\"><i>Category: </i>' + task.category + '</h5>';\n // Show collaborators if there are other people too (i.e. not just current user)\n if (task.users.length > 1) {\n var collaborators = ''; \n for (let j in task.users) {\n // Skip the logged in user\n if (task.users[j] === userLoggedIn) continue;\n collaborators += task.users[j] + ' ';\n }\n htmlToShow += '<h5 class=\"task-item-content\"><i>Collaborators: </i>' + collaborators + '</h5>';\n } \n htmlToShow += '<div class=\"task-item-controls\" id=\"task-item-controls-' + task._id + '\">';\n htmlToShow += '<div class=\"row header-row task-status-row\">';\n htmlToShow += '<div class=\"col-md-6\" style=\"text-align:left\">';\n var completeText = task.complete ? 'Complete' : 'Incomplete';\n htmlToShow += '<h5 class=\"task-status\">' + completeText + '</h5></div>';\n htmlToShow += '<div class=\"col-md-6\" style=\"text-align:right\">';\n htmlToShow += '<button type=\"button\" class=\"btn btn-danger btn-xs task-item-control-btn\" id=\"delete-task-btn-' + task._id + '\">Delete</button> ';\n var completeButtonHtml = '<button type=\"button\" class=\"btn btn-success btn-xs task-item-control-btn\" id=\"complete-task-btn-' + task._id + '\">Mark Complete</button>'; \n if (task.complete) {\n completeButtonHtml = '<button type=\"button\" class=\"btn btn-warning btn-xs task-item-control-btn\" id=\"complete-task-btn-' + task._id + '\">Mark Incomplete</button>'; \n }\n htmlToShow += completeButtonHtml;\n htmlToShow += '</div></div></div></div>';\n }\n $('#task-item-div').html(htmlToShow);\n\n // Add click listenders for buttons \n for (let i in tasksBeingViewed) {\n let task = tasksBeingViewed[i];\n if (task.complete) {\n // Change the background color of complete tasks \n $('#task-item-' + task._id).css('background-color', 'rgba(0,0,0,.5)');\n $('#task-item-controls-' + task._id).css('background-color', 'rgba(0,0,0,.5)');\n }\n // NOTE - this needs to be done this way to avoid closure issues\n (function (task, i) {\n // Delete button\n $('#delete-task-btn-' + task._id).on('click', function () {\n $.post('api/deleteTask', {tid: task._id}, function (data) {\n if (data.status === 'ok') {\n // Remove the deleted task from the list and re-render\n if (mode === 'future') {\n futureTasks.splice(i, 1);\n renderTasks();\n }\n if (mode === 'today') {\n todaysTasks.splice(i, 1);\n renderTasks();\n }\n if (mode === 'prev') {\n previousTasks.splice(i, 1);\n renderTasks();\n }\n }\n });\n });\n\n // Toggle task complete button\n $('#complete-task-btn-' + task._id).on('click', function () {\n // Toggle completion\n $.post('api/toggleTaskCompletion', {tid: task._id}, function (data) {\n if (data.status === 'ok') {\n // Edit the toggled task list and rerender\n if (mode === 'future') {\n futureTasks[i].complete = !futureTasks[i].complete;\n renderTasks();\n }\n if (mode === 'today') {\n todaysTasks[i].complete = !todaysTasks[i].complete;\n renderTasks();\n }\n if (mode === 'prev') {\n previousTasks[i].complete = !previousTasks[i].complete;\n renderTasks();\n }\n }\n });\n });\n }(task, i)); \n } \n }", "function createChart(options) {\n this.data = Chartist.normalizeData(this.data);\n var data = {\n raw: this.data,\n normalized: Chartist.getDataArray(this.data, options.reverseData, true)\n };\n\n // Create new svg object\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n // Create groups for labels, grid and series\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if (options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.raw.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data, chartRect, options.axisX);\n }\n\n if (options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNum(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNum(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n // Draw the series\n data.raw.series.forEach(function (series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g');\n\n // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n });\n\n // Use series class from series data or if not set generate one\n seriesElement.addClass([\n options.classNames.series,\n (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n ].join(' '));\n\n var pathCoordinates = [],\n pathData = [];\n\n data.normalized[seriesIndex].forEach(function (value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n var path = smoothing(pathCoordinates, pathData);\n\n // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n if (seriesOptions.showPoint) {\n\n path.pathElements.forEach(function (pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNum).join(','),\n 'ct:meta': pathElement.data.meta\n });\n\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if (seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n }\n\n // Area currently only works with axes that support a range!\n if (seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\n // We project the areaBase value into screen coordinates\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\n // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\n // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n return solidPathSegments.clone(true)\n .position(0)\n .remove(1)\n .move(firstElement.x, areaBaseProjected)\n .line(firstElement.x, firstElement.y)\n .position(solidPathSegments.pathElements.length + 1)\n .line(lastElement.x, areaBaseProjected);\n\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true);\n\n // Emit an event for each area that was drawn\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "function drawGantt() {\r\n // first, if detail is displayed, reload class\r\n if (dojo.byId('objectClass') && !dojo.byId('objectClass').value\r\n && dojo.byId(\"objectClassName\") && dojo.byId(\"objectClassName\").value) {\r\n dojo.byId('objectClass').value = dojo.byId(\"objectClassName\").value;\r\n }\r\n if (dojo.byId(\"objectId\") && !dojo.byId(\"objectId\").value && dijit.byId(\"id\")\r\n && dijit.byId(\"id\").get(\"value\")) {\r\n dojo.byId(\"objectId\").value = dijit.byId(\"id\").get(\"value\");\r\n }\r\n var startDateView = new Date();\r\n if (dijit.byId('startDatePlanView')) {\r\n startDateView = dijit.byId('startDatePlanView').get('value');\r\n }\r\n var endDateView = null;\r\n if (dijit.byId('endDatePlanView')) {\r\n endDateView = dijit.byId('endDatePlanView').get('value');\r\n }\r\n var showWBS = null;\r\n if (dijit.byId('showWBS')) {\r\n showWBS = dijit.byId('showWBS').get('checked');\r\n }\r\n // showWBS=true;\r\n var gFormat = \"day\";\r\n if (g) {\r\n gFormat = g.getFormat();\r\n }\r\n g = new JSGantt.GanttChart('g', dojo.byId('GanttChartDIV'), gFormat);\r\n setGanttVisibility(g);\r\n g.setCaptionType('Caption'); // Set to Show Caption\r\n // (None,Caption,Resource,Duration,Complete)\r\n // g.setShowStartDate(1); // Show/Hide Start Date(0/1)\r\n // g.setShowEndDate(1); // Show/Hide End Date(0/1)\r\n g.setDateInputFormat('yyyy-mm-dd'); // Set format of input dates\r\n // ('mm/dd/yyyy', 'dd/mm/yyyy',\r\n // 'yyyy-mm-dd')\r\n g.setDateDisplayFormat('default'); // Set format to display dates\r\n // ('mm/dd/yyyy', 'dd/mm/yyyy',\r\n // 'yyyy-mm-dd')\r\n g.setFormatArr(\"day\", \"week\", \"month\", \"quarter\"); // Set format options (up\r\n if (dijit.byId('selectBaselineBottom')) {\r\n g.setBaseBottomName(dijit.byId('selectBaselineBottom').get('displayedValue'));\r\n }\r\n if (dijit.byId('selectBaselineTop')) {\r\n g.setBaseTopName(dijit.byId('selectBaselineTop').get('displayedValue'));\r\n }\r\n // to 4 :\r\n // \"minute\",\"hour\",\"day\",\"week\",\"month\",\"quarter\")\r\n if (ganttPlanningScale) {\r\n g.setFormat(ganttPlanningScale);\r\n }\r\n g.setStartDateView(startDateView);\r\n g.setEndDateView(endDateView);\r\n if (dijit.byId('criticalPathPlanning')) g.setShowCriticalPath(dijit.byId('criticalPathPlanning').get('checked'));\r\n var contentNode = dojo.byId('gridContainerDiv');\r\n if (contentNode) {\r\n g.setWidth(dojo.style(contentNode, \"width\"));\r\n }\r\n jsonData = dojo.byId('planningJsonData');\r\n if (jsonData.innerHTML.indexOf('{\"identifier\"') < 0 || jsonData.innerHTML.indexOf('{\"identifier\":\"id\", \"items\":[ ] }')>=0) {\r\n if (dijit.byId('leftGanttChartDIV')) dijit.byId('leftGanttChartDIV').set('content',null);\r\n if (dijit.byId('rightGanttChartDIV')) dijit.byId('rightGanttChartDIV').set('content',null);\r\n if (dijit.byId('topGanttChartDIV')) dijit.byId('topGanttChartDIV').set('content',null); \r\n if (jsonData.innerHTML.length > 10 && jsonData.innerHTML.indexOf('{\"identifier\":\"id\", \"items\":[ ] }')<0) {\r\n showAlert(jsonData.innerHTML);\r\n }\r\n hideWait();\r\n return;\r\n }\r\n var now = formatDate(new Date());\r\n // g.AddTaskItem(new JSGantt.TaskItem( 0, 'project', '', '', 'ff0000', '',\r\n // 0, '', '10', 1, '', 1, '' , 'test'));\r\n if (g && jsonData) {\r\n var store = eval('(' + jsonData.innerHTML + ')');\r\n var items = store.items;\r\n // var arrayKeys=new Array();\r\n var keys = \"\";\r\n for (var i = 0; i < items.length; i++) {\r\n var item = items[i];\r\n // var topId=(i==0)?'':item.topid;\r\n var topId = item.topid;\r\n // pStart : start date of task\r\n var pStart = now;\r\n var pStartFraction = 0;\r\n pStart = (trim(item.initialstartdate) != \"\") ? item.initialstartdate\r\n : pStart;\r\n pStart = (trim(item.validatedstartdate) != \"\") ? item.validatedstartdate\r\n : pStart;\r\n pStart = (trim(item.plannedstartdate) != \"\") ? item.plannedstartdate\r\n : pStart;\r\n pStart = (trim(item.realstartdate) != \"\") ? item.realstartdate : pStart;\r\n pStart = (trim(item.plannedstartdate)!=\"\" && trim(item.realstartdate) && item.plannedstartdate<item.realstartdate)?item.plannedstartdate:pStart;\r\n if (trim(item.plannedstartdate) != \"\" && trim(item.realenddate) == \"\") {\r\n pStartFraction = item.plannedstartfraction;\r\n }\r\n // If real work in the future, don't take it in account\r\n if (trim(item.plannedstartdate) && trim(item.realstartdate)\r\n && item.plannedstartdate < item.realstartdate\r\n && item.realstartdate > now) {\r\n pStart = item.plannedstartdate;\r\n }\r\n // pEnd : end date of task\r\n var pEnd = now;\r\n //var pEndFraction = 1;\r\n pEnd = (trim(item.initialenddate) != \"\") ? item.initialenddate : pEnd;\r\n pEnd = (trim(item.validatedenddate) != \"\") ? item.validatedenddate : pEnd;\r\n pEnd = (trim(item.plannedenddate) != \"\") ? item.plannedenddate : pEnd;\r\n\r\n pRealEnd = \"\";\r\n pPlannedStart = \"\";\r\n pWork = \"\";\r\n if (dojo.byId('resourcePlanning')) {\r\n pRealEnd = item.realenddate;\r\n pPlannedStart = item.plannedstartdate;\r\n pWork = item.leftworkdisplay;\r\n g.setSplitted(true);\r\n } else {\r\n pEnd = (trim(item.realenddate) != \"\") ? item.realenddate : pEnd;\r\n }\r\n if (pEnd < pStart)\r\n pEnd = pStart;\r\n //\r\n var realWork = parseFloat(item.realwork);\r\n var plannedWork = parseFloat(item.plannedwork);\r\n var validatedWork = parseFloat(item.validatedwork);\r\n var progress = 0;\r\n if (item.isglobal && item.isglobal==1 && item.progress) { \r\n progress=item.progress;\r\n } else {\r\n if (plannedWork > 0) {\r\n progress = Math.round(100 * realWork / plannedWork);\r\n } else {\r\n if (item.done == 1) {\r\n progress = 100;\r\n }\r\n }\r\n }\r\n // pGroup : is the task a group one ?\r\n var pGroup = (item.elementary == '0') ? 1 : 0;\r\n //MODIF qCazelles - GANTT\r\n if (item.reftype=='Project' || item.reftype=='Fixed' || item.reftype=='Replan' || item.reftype=='Construction' || item.reftype=='ProductVersionhasChild' || item.reftype=='ComponentVersionhasChild' ) pGroup=1;\r\n //END MODIF qCazelles - GANTT\r\n // runScript : JavaScript to run when click on task (to display the\r\n // detail of the task)\r\n var runScript = \"runScript('\" + item.reftype + \"','\" + item.refid + \"','\"+ item.id + \"');\";\r\n var contextMenu = \"runScriptContextMenu('\" + item.reftype + \"','\" + item.refid + \"','\"+ item.id + \"');\";\r\n // display Name of the task\r\n var pName = ((showWBS) ? item.wbs : '') + \" \" + item.refname; // for\r\n // testeing\r\n // purpose, add\r\n // wbs code\r\n // var pName=item.refname;\r\n // display color of the task bar\r\n var pColor = (pGroup)?'003000':'50BB50'; // Default green\r\n if (! pGroup && item.notplannedwork > 0) { // Some left work not planned : purple\r\n pColor = '9933CC';\r\n } else if (trim(item.validatedenddate) != \"\" && item.validatedenddate < pEnd) { // Not respected constraints (end date) : red\r\n if (item.reftype!='Milestone' && ( ! item.assignedwork || item.assignedwork==0 ) && ( ! item.leftwork || item.leftwork==0 ) && ( ! item.realwork || item.realwork==0 )) {\r\n pColor = (pGroup)?'650000':'BB9099';\r\n } else {\r\n pColor = (pGroup)?'650000':'BB5050';\r\n }\r\n } else if (! pGroup && item.reftype!='Milestone' && ( ! item.assignedwork || item.assignedwork==0 ) && ( ! item.leftwork || item.leftwork==0 ) && ( ! item.realwork || item.realwork==0 ) ) { // No workassigned : greyed green\r\n pColor = 'aec5ae';\r\n }\r\n \r\n if (item.redElement == '1') {\r\n pColor = 'BB5050';\r\n }\r\n else if(item.redElement == '0') {\r\n pColor = '50BB50';\r\n } \r\n \r\n // pMile : is it a milestone ? \r\n var pMile = (item.reftype == 'Milestone') ? 1 : 0;\r\n if (pMile) {\r\n pStart = pEnd;\r\n }\r\n pClass = item.reftype;\r\n pId = item.refid;\r\n pScope = \"Planning_\" + pClass + \"_\" + pId;\r\n pOpen = (item.collapsed == '1') ? '0' : '1';\r\n var pResource = item.resource;\r\n var pCaption = \"\";\r\n if (dojo.byId('listShowResource')) {\r\n if (dojo.byId('listShowResource').checked) {\r\n pCaption = pResource;\r\n }\r\n }\r\n if (dojo.byId('listShowLeftWork')\r\n && dojo.byId('listShowLeftWork').checked) {\r\n if (item.leftwork > 0) {\r\n pCaption = item.leftworkdisplay;\r\n } else {\r\n pCaption = \"\";\r\n }\r\n }\r\n var pDepend = item.depend;\r\n topKey = \"#\" + topId + \"#\";\r\n curKey = \"#\" + item.id + \"#\";\r\n if (keys.indexOf(topKey) == -1) {\r\n topId = '';\r\n }\r\n keys += \"#\" + curKey + \"#\";\r\n g.AddTaskItem(new JSGantt.TaskItem(item.id, pName, pStart, pEnd, pColor,\r\n runScript, contextMenu, pMile, pResource, progress, pGroup, \r\n topId, pOpen, pDepend,\r\n pCaption, pClass, pScope, pRealEnd, pPlannedStart,\r\n item.validatedworkdisplay, item.assignedworkdisplay, item.realworkdisplay, item.leftworkdisplay, item.plannedworkdisplay,\r\n item.priority, item.planningmode, \r\n item.status, item.type, \r\n item.validatedcostdisplay, item.assignedcostdisplay, item.realcostdisplay, item.leftcostdisplay, item.plannedcostdisplay,\r\n item.baseTopStart, item.baseTopEnd, item.baseBottomStart, item.baseBottomEnd, item.isoncriticalpath));\r\n }\r\n g.Draw();\r\n g.DrawDependencies();\r\n } else {\r\n // showAlert(\"Gantt chart not defined\");\r\n return;\r\n }\r\n highlightPlanningLine();\r\n}", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Topping');\n data.addColumn('number', 'Slices');\n data.addRows([\n ['Acertos', acertos],\n ['Erros', erros]\n ]);\n\n // Set chart options\n var options = {'width':800,\n 'height':600,\n 'backgroundColor': 'none',\n 'fontSize': 15,\n 'is3D':true};\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n }", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Topping');\n data.addColumn('number', 'Slices');\n data.addRows(rendergrafica);\n\n // Set chart options\n var options = {\n 'title': 'cantidad de pruebas por laboratorio',\n\n\n };\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n\n }", "function genChart(){ \n var cols = [ {\n id : \"t\",\n label : \"host\",\n type : \"string\"\n } ];\n angular.forEach(data.hit, function(v, index) {\n cols.push({\n id : \"R\" + index,\n label : v.hostname,\n type : \"number\"\n });\n });\n var rows = [];\n angular.forEach(data.hit, function(q, i) {\n var d = [ {\n v : q.name\n } ];\n angular.forEach(data.hit, function(r, i2) {\n d.push({\n v : r.runtime\n });\n });\n rows.push({\n c : d\n });\n });\n var options={\n title:'Compare: ' + data.suite + \" \" + data.query,\n vAxis: {title: 'Time (sec)'}\n ,hAxis: {title: 'System'}\n // ,legend: 'none'\n };\n return {\n type : \"ColumnChart\",\n options : options,\n data : {\n \"cols\" : cols,\n \"rows\" : rows\n }\n };\n }", "function drawTaskLine(canvas, context, taskStartColumn, taskEndColumn, xSpaceIncrement, yPos, parsedTask) {\n\tif (canvas.getContext) {\n\t\tvar xPos1 = taskStartColumn * xSpaceIncrement + xSpaceIncrement / 2;\n\t\tvar xPos2 = taskEndColumn * xSpaceIncrement + xSpaceIncrement / 2;\n\n\t\t\tvar category = [];\n\t\t\tvar category_id;\n\t\t\tvar category_color;\n\t\t\tconsole.log(parsedTask);\n\t\t\tcategory_color = parsedTask.category_color;\n\t\t\tconsole.log(category_color);\n\n\n\t\t\t$.getJSON('/retrieveCategories', function(data, status) {\n\n\t\tvar color = '#'+ category_color;\n\t\tdrawLine(context, xPos1, xPos2, yPos, color);\n\t\tdrawCircles(context, xPos1, xPos2, yPos, color);\n\t\tdrawName(context, xPos1, yPos, taskStartColumn, parsedTask.task_name);\n\n\n\t\t});\n\n\n\t}\n}", "function createCongestionChart(starttime, occupancy) {\n\tdocument.getElementById(\"congestionChart\").style.display = \"block\";\n\tdocument.getElementById(\"congestionChartTitle\").innerText = \"Congestion\";\n\tdocument.getElementById(\"congestion-desc\").innerText = \"percentage of time cars are on a sensor\";\n\tif (chartCongestion != null) \n\t\tchartCongestion.destroy();\n\tdocument.getElementById('chartCongestion').getContext('2d').clearRect(0, 0, this.width, this.height);\n\tchartCongestion = new Chart(document.getElementById(\"chartCongestion\").getContext(\"2d\"), {\n\t\ttype: 'line',\n\t\tdata: {\n\t\t\tlabels: starttime,\n\t\t\tdatasets: [{\n\t\t\t\tlabel: 'left',\n\t\t\t\tdata: occupancy,\n\t\t\t\tborderColor: 'rgb(0, 64, 128)',\n\t\t\t\tbackgroundColor: 'rgb(0, 64, 128)',\n\t\t\t\tfill: false,\n\t\t\t\tshowLine: true,\n\t\t\t\tpointRadius: 1\n\t\t\t}]\n\t\t},\n\t\toptions: {\n\t\t\tanimation: {\n\t\t\t\tduration: 0.3\n\t\t\t},\n\t\t\thover: {\n\t\t\t\tanimationDuration: 0\n\t\t\t},\n\t\t\tresponsiveAnimationDuration: 0\n\t\t},\n\t\tdefaults: {\n\t\t\tline: {\n\t\t\t\tshowLine: true,\n\t\t\t}\n\t\t}\n\t});\n}", "drawTask(){\n debugger;\n let template = \"\";\n this.tasks.forEach(Task => {template += Task.templateTask});\n return template\n }", "render(){\n const tasksHtmlList = [];\n for (let i=0; i<this.tasks.length; i++){\n const task = this.tasks[i];\n\n const due = new Date(task.dueDate);\n //format date dd/mm/yy \n const formattedDate = due.getDate() + '/' + (due.getMonth()+1) + '/' \n + (due.getFullYear());\n\n const taskHtml = createTaskHtml(task.id, task.name,task.description,task.assignedTo,formattedDate,task.staTus);\n tasksHtmlList.push(taskHtml);\n }//closed render for loop\n const tasksHtml = tasksHtmlList.join('\\n');\n \n const tasksList = document.querySelector('#taskCard');\n tasksList.innerHTML = tasksHtml;\n \n}", "function createTimeline() {\n const container = document.getElementById(\"timeline\");\n\n // Create a DataSet (allows two way data-binding)\n const items = new vis.Dataset(\n //Populate the DataSet with query\n connection.query(\"SELECT ? FROM date_and_time\", (err, results) => {\n if (err) {\n throw err;\n }\n\n items.clear();\n\n for (let i = 0; i < results.length; i++) {\n items.add = [\n {\n id: results[i].id,\n content: results[i].city_name,\n start: results[i].date_and_time\n }\n ];\n }\n console.log(items);\n })\n );\n\n // Configuration for the Timeline\n const options = {};\n // Create a Timeline\n const timeline = new vis.Timeline(container, items, options);\n module.exports = timeline;\n}", "function createChart(options) {\n var data = Chartist.normalizeData(this.data, options.reverseData, true);\n\n // Create new svg object\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n // Create groups for labels, grid and series\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if (options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.normalized.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);\n }\n\n if (options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n if (options.showGridBackground) {\n Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);\n }\n\n // Draw the series\n data.raw.series.forEach(function (series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g');\n\n // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n });\n\n // Use series class from series data or if not set generate one\n seriesElement.addClass([\n options.classNames.series,\n (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n ].join(' '));\n\n var pathCoordinates = [],\n pathData = [];\n\n data.normalized.series[seriesIndex].forEach(function (value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n var path = smoothing(pathCoordinates, pathData);\n\n // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n if (seriesOptions.showPoint) {\n\n path.pathElements.forEach(function (pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),\n 'ct:meta': Chartist.serialize(pathElement.data.meta)\n });\n\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if (seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized.series[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n seriesMeta: series.meta,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n }\n\n // Area currently only works with axes that support a range!\n if (seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\n // We project the areaBase value into screen coordinates\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\n // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\n // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n return solidPathSegments.clone(true)\n .position(0)\n .remove(1)\n .move(firstElement.x, areaBaseProjected)\n .line(firstElement.x, firstElement.y)\n .position(solidPathSegments.pathElements.length + 1)\n .line(lastElement.x, areaBaseProjected);\n\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true);\n\n // Emit an event for each area that was drawn\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized.series[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "function renderTasks(selectedProject){\n\n if(selectedProject === undefined) return;\n selectedProject.tasks.forEach( task => {\n\n const taskDiv = document.createElement('div');\n taskDiv.classList.add('task');\n\n const taskLabel = document.createElement('label');\n taskLabel.classList.add('task-label');\n taskLabel.htmlFor = task.id;\n taskLabel.append(task.name);\n\n const taskCheck = document.createElement('input');\n taskCheck.setAttribute('type','checkbox');\n taskCheck.id = task.id;\n taskCheck.checked = task.complete;\n\n const taskRemove = document.createElement('button');\n taskRemove.classList.add('btn-task-remove');\n taskRemove.innerText = 'x';\n\n taskRemove.addEventListener('click', () => {\n \n selectedProject.tasks.splice(selectedProject.tasks.indexOf(task),1);\n saveAndRender();\n });\n taskDiv.addEventListener('change', () => {\n task.complete = !task.complete;\n if(task.complete === true) alert(task.name + ' done!');\n saveAndRender();\n });\n tasksContainer.appendChild(taskDiv);\n taskDiv.appendChild(taskCheck);\n taskDiv.appendChild(taskLabel);\n taskDiv.appendChild(taskRemove);\n });\n }", "function createChart(options) {\n\t this.data = Chartist.normalizeData(this.data);\n\t var data = {\n\t raw: this.data,\n\t normalized: Chartist.getDataArray(this.data, options.reverseData, true)\n\t };\n\t\n\t // Create new svg object\n\t this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n\t // Create groups for labels, grid and series\n\t var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n\t var seriesGroup = this.svg.elem('g');\n\t var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\t\n\t var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n\t var axisX, axisY;\n\t\n\t if(options.axisX.type === undefined) {\n\t axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data, chartRect, Chartist.extend({}, options.axisX, {\n\t ticks: data.raw.labels,\n\t stretch: options.fullWidth\n\t }));\n\t } else {\n\t axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data, chartRect, options.axisX);\n\t }\n\t\n\t if(options.axisY.type === undefined) {\n\t axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data, chartRect, Chartist.extend({}, options.axisY, {\n\t high: Chartist.isNum(options.high) ? options.high : options.axisY.high,\n\t low: Chartist.isNum(options.low) ? options.low : options.axisY.low\n\t }));\n\t } else {\n\t axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data, chartRect, options.axisY);\n\t }\n\t\n\t axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\t axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\t\n\t // Draw the series\n\t data.raw.series.forEach(function(series, seriesIndex) {\n\t var seriesElement = seriesGroup.elem('g');\n\t\n\t // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n\t seriesElement.attr({\n\t 'ct:series-name': series.name,\n\t 'ct:meta': Chartist.serialize(series.meta)\n\t });\n\t\n\t // Use series class from series data or if not set generate one\n\t seriesElement.addClass([\n\t options.classNames.series,\n\t (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n\t ].join(' '));\n\t\n\t var pathCoordinates = [],\n\t pathData = [];\n\t\n\t data.normalized[seriesIndex].forEach(function(value, valueIndex) {\n\t var p = {\n\t x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized[seriesIndex]),\n\t y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized[seriesIndex])\n\t };\n\t pathCoordinates.push(p.x, p.y);\n\t pathData.push({\n\t value: value,\n\t valueIndex: valueIndex,\n\t meta: Chartist.getMetaData(series, valueIndex)\n\t });\n\t }.bind(this));\n\t\n\t var seriesOptions = {\n\t lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n\t showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n\t showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n\t showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n\t areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n\t };\n\t\n\t var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n\t seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n\t // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n\t // index, value and meta data\n\t var path = smoothing(pathCoordinates, pathData);\n\t\n\t // If we should show points we need to create them now to avoid secondary loop\n\t // Points are drawn from the pathElements returned by the interpolation function\n\t // Small offset for Firefox to render squares correctly\n\t if (seriesOptions.showPoint) {\n\t\n\t path.pathElements.forEach(function(pathElement) {\n\t var point = seriesElement.elem('line', {\n\t x1: pathElement.x,\n\t y1: pathElement.y,\n\t x2: pathElement.x + 0.01,\n\t y2: pathElement.y\n\t }, options.classNames.point).attr({\n\t 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNum).join(','),\n\t 'ct:meta': pathElement.data.meta\n\t });\n\t\n\t this.eventEmitter.emit('draw', {\n\t type: 'point',\n\t value: pathElement.data.value,\n\t index: pathElement.data.valueIndex,\n\t meta: pathElement.data.meta,\n\t series: series,\n\t seriesIndex: seriesIndex,\n\t axisX: axisX,\n\t axisY: axisY,\n\t group: seriesElement,\n\t element: point,\n\t x: pathElement.x,\n\t y: pathElement.y\n\t });\n\t }.bind(this));\n\t }\n\t\n\t if(seriesOptions.showLine) {\n\t var line = seriesElement.elem('path', {\n\t d: path.stringify()\n\t }, options.classNames.line, true);\n\t\n\t this.eventEmitter.emit('draw', {\n\t type: 'line',\n\t values: data.normalized[seriesIndex],\n\t path: path.clone(),\n\t chartRect: chartRect,\n\t index: seriesIndex,\n\t series: series,\n\t seriesIndex: seriesIndex,\n\t axisX: axisX,\n\t axisY: axisY,\n\t group: seriesElement,\n\t element: line\n\t });\n\t }\n\t\n\t // Area currently only works with axes that support a range!\n\t if(seriesOptions.showArea && axisY.range) {\n\t // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n\t // the area is not drawn outside the chart area.\n\t var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\t\n\t // We project the areaBase value into screen coordinates\n\t var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\t\n\t // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n\t path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n\t // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n\t return pathSegment.pathElements.length > 1;\n\t }).map(function convertToArea(solidPathSegments) {\n\t // Receiving the filtered solid path segments we can now convert those segments into fill areas\n\t var firstElement = solidPathSegments.pathElements[0];\n\t var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\t\n\t // Cloning the solid path segment with closing option and removing the first move command from the clone\n\t // We then insert a new move that should start at the area base and draw a straight line up or down\n\t // at the end of the path we add an additional straight line to the projected area base value\n\t // As the closing option is set our path will be automatically closed\n\t return solidPathSegments.clone(true)\n\t .position(0)\n\t .remove(1)\n\t .move(firstElement.x, areaBaseProjected)\n\t .line(firstElement.x, firstElement.y)\n\t .position(solidPathSegments.pathElements.length + 1)\n\t .line(lastElement.x, areaBaseProjected);\n\t\n\t }).forEach(function createArea(areaPath) {\n\t // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n\t // and adding the created DOM elements to the correct series group\n\t var area = seriesElement.elem('path', {\n\t d: areaPath.stringify()\n\t }, options.classNames.area, true);\n\t\n\t // Emit an event for each area that was drawn\n\t this.eventEmitter.emit('draw', {\n\t type: 'area',\n\t values: data.normalized[seriesIndex],\n\t path: areaPath.clone(),\n\t series: series,\n\t seriesIndex: seriesIndex,\n\t axisX: axisX,\n\t axisY: axisY,\n\t chartRect: chartRect,\n\t index: seriesIndex,\n\t group: seriesElement,\n\t element: area\n\t });\n\t }.bind(this));\n\t }\n\t }.bind(this));\n\t\n\t this.eventEmitter.emit('created', {\n\t bounds: axisY.bounds,\n\t chartRect: chartRect,\n\t axisX: axisX,\n\t axisY: axisY,\n\t svg: this.svg,\n\t options: options\n\t });\n\t }", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Pool');\n data.addColumn('string', 'Address');\n data.addColumn('number', 'Hashrate');\n var column_data = new google.visualization.DataTable();\n column_data.addColumn('string', 'Pool');\n column_data.addColumn('string', 'Address');\n column_data.addColumn('number', 'Workers');\n column_data.addColumn('number', 'Kh/s/worker');\n var pi_data = new google.visualization.DataTable();\n pi_data.addColumn('string', 'Address');\n pi_data.addColumn('number', 'count');\n $.ajax({\n\turl:\"http://givememona.tk/json/pools.json\",\n\ttype:\"GET\",\n\tsuccess: function(ret){\n\t var txt = ret[\"responseText\"];\n\t var html = $.parseHTML(txt);\n\t var ptag = html[5];\n\t var json = $.parseJSON(ptag.innerHTML);\n\t var pinfos = json.pool_infos;\n\t var pool_total_hash = 0;\n\t var pool_total_workers = 0;\n\t for (var i in pinfos) {\n\t\tvar pool = pinfos[i];\n\t\tvar pool_address = \"http://\" + pool.pool_address;\n\t\tpool.hashrate /= 1000; //to MH\n\t\tpool.network_hashrate /= 1000 * 1000; //to MH\n\t\tdata.addRow([pool.pool_name, pool_address, pool.hashrate]);\n\t\tif (pool.workers != 0) {\n\t\t hashrate_per_worker = pool.hashrate/pool.workers*1000;\n\t\t} else {\n\t\t hashrate_per_worker = 0;\n\t\t}\n\t\tcolumn_data.addRow([pool.pool_name, pool_address, pool.workers,hashrate_per_worker]);\n\t\tvar atag = document.createElement('a');\n\t\tatag.href = pool_address;\n\t\tatag.target = '_blank';\n\t\tatag.appendChild(document.createTextNode(pool.pool_name));\n\t\tvar item = document.createElement('li')\n\t\titem.appendChild(atag);\n\t\tdocument.getElementById('pool_link_list').appendChild(item);\n\t\tpool_total_hash += pool.hashrate;\n\t\tpool_total_workers += pool.workers\n\t }\n\t var no_res_pools = json.no_response;\n\t var no_res_list = \"\"\n\t for (var i in no_res_pools) {\n\t\tvar no_res = no_res_pools[i];\n\t\tno_res_list = no_res_list + no_res + \",\";\n\t }\n\t no_res_list = no_res_list + \"?\";\n\t $(\"#cur_diff\").html(json.cur_diff.toFixed(2));\n\t $(\"#blocksuntildiffchangemin\").html(json.blocksuntildiffchange * 1.5 / 60);\n\t $(\"#nethash\").html(pool.network_hashrate.toFixed(2));\n\t $(\"#total_pool_hash\").html(pool_total_hash.toFixed(2));\n\t $(\"#total_workers\").html(pool_total_workers);\n\t $(\"#average_workers_hash\").html((pool_total_hash/pool_total_workers*1000).toFixed(2));\n\t $(\"#time\").html(json.time);\n\t $(\"#net_watt\").html((pool.network_hashrate/watt_pfm).toFixed(2));\n\t //draw pie chart\n\t var others = pool.network_hashrate - pool_total_hash;\n\t others = Math.max(0, others);\n\t data.sort([{column: 2, desc:true}, {column: 0}]);\n\t data.addRow([\"Others (\" + no_res_list + \")\",\"hoge\",others]);\n\t var view = new google.visualization.DataView(data);\n\t view.setColumns([0, 2]);\n\t chart.draw(view, options);\n\t //draw column chart\n\t column_data.sort([{column: 2, desc:true}, {column: 0}]);\n\t var column_view = new google.visualization.DataView(column_data);\n\t column_view.setColumns([0,2,3]);\n\t column_chart.draw(column_view, column_options);\n\t //finder chart\n\t finders = json.finder_address\n\t for (var f in finders) {\n\t\tpi_data.addRow([f, finders[f]]);\n\t }\n\t pi_data.sort([{column: 1, desc:true}, {column: 0}]);\n\t var pi_view = new google.visualization.DataView(pi_data);\n\t pi_view.setColumns([0,1]);\n\t pi_chart.draw(pi_view, pi_options);\n\t},\n\tfail: function() {\n\t}\n });\n\n\n // Instantiate and draw our chart, passing in some options.\n chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n pi_chart = new google.visualization.PieChart(document.getElementById('finder_chart_div'));\n column_chart = new google.visualization.ColumnChart(document.getElementById('column_chart_div'));\n\n var selectHandler = function(e) {\n\twindow.location = data.getValue(chart.getSelection()[0]['row'],1);\n }\n var column_selectHandler = function(e) {\n\twindow.location = column_data.getValue(column_chart.getSelection()[0]['row'],1);\n }\n // Add custom selection handler.\n google.visualization.events.addListener(chart, 'select', selectHandler);\n google.visualization.events.addListener(column_chart, 'select', column_selectHandler);\n\n}", "function taskMain(data) {\n let len = document.getElementsByClassName('rend').length\n const html = `\n <div class=\"row rend\" style=\"margin-bottom:0px !important;\">\n <div class=\"col\">\n <span><i class=\"material-icons white-text\" id=\"${len}\" style=\"margin-top: 1.5rem; margin-left: 2rem;\">delete</i></span>\n </div>\n <div class=\"col\">\n <p>\n <label>\n <span class=\"white-text lighten-5 eventC1\">${data.task}</span>\n <br>\n <span style=\"color:#d50000;\">${data.Ttime}</span>\n </label>\n </p>\n </div>\n </div> \n `;\n\n taskBody.innerHTML += html\n}", "function drawChart() {\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Weather Element');\n data.addColumn('number', 'Dec');\n data.addColumn('number', 'Feb');\n data.addColumn('number', 'Jan');\n data.addColumn('number', 'Nov');\n data.addColumn('number', 'Oct');\n data.addColumn('number', 'Sep');\n\n data.addRows([\n ['Snow - Heavy', 6,0,2,2,0,0],\n ['Snow - Light', 2,0,0,0,0,0],\n ['Snow - Normal', 4,0,2,0,0,0]\n ]);\n\n var options = {\n 'title': 'Snowy Weather by Months',\n 'width': 500,\n 'height': 600,\n 'isStacked': true};\n \n var chart = new google.visualization.ColumnChart(document.getElementById('chart_div2'));\n chart.draw(data, options);\n }", "function CreateChart(values,type){\n let data = GetDataFromDB(values,type);\n buildFlightsChart(data)\n}", "function drawTimeSeriesChart() {\n let jsonData = $.ajax({\n url: \"total_deaths_json\",\n dataType: \"json\",\n async: false\n }).responseText;\n\n // Create our data table out of JSON data loaded from server.\n let data = new google.visualization.DataTable(jsonData); // Set chart options\n let options = {\n 'title': 'Total deaths time series',\n 'height': 500,\n 'width': 1000,\n };\n\n // Instantiate and draw our chart, passing in some options.\n let chart = new google.visualization.LineChart(document.getElementById(\"time-series-chart\"));\n chart.draw(data, options);\n}", "function createTimeline() {\n var chart = new SmoothieChart();\n chart.addTimeSeries(random, { strokeStyle: 'rgba(0, 255, 0, 1)', fillStyle: 'rgba(0, 255, 0, 0.2)', lineWidth: 4 });\n chart.streamTo(document.getElementById(\"chart\"), 500);\n // HACK: because the chart needs some init data\n random.append(new Date().getTime(), 0);\n random.append(new Date().getTime(), 1);\n random.append(new Date().getTime(), 1);\n }", "function drawChart(numPositiveTweets, numNeutralTweets, numNegativeTweets) {\n\n var data = google.visualization.arrayToDataTable([\n ['Task', 'Connotation of Tweets'],\n ['Positive Tweets', numPositiveTweets],\n ['Neutral Tweets', numNeutralTweets],\n ['Negative Tweets', numNegativeTweets]\n ]);\n\n // Optional; add a title and set the width and height of the chart\n var options = {'title':'Connotation of Tweets', 'width':528, 'height':400,\n 'backgroundColor':'grey', 'colors':['green','orange', 'red']};\n\n // Display the chart inside the <div> element with id=\"piechart\"\n var chart = new google.visualization.PieChart(document.getElementById('pieChart'));\n chart.draw(data, options);\n}", "function createChart(options) {\n var data = Chartist.normalizeData(this.data, options.reverseData, true);\n\n // Create new svg object\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n // Create groups for labels, grid and series\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if(options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.normalized.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);\n }\n\n if(options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n if (options.showGridBackground) {\n Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);\n }\n\n // Draw the series\n data.raw.series.forEach(function(series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g');\n\n // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n });\n\n // Use series class from series data or if not set generate one\n seriesElement.addClass([\n options.classNames.series,\n (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n ].join(' '));\n\n var pathCoordinates = [],\n pathData = [];\n\n data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n var path = smoothing(pathCoordinates, pathData);\n\n // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n if (seriesOptions.showPoint) {\n\n path.pathElements.forEach(function(pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),\n 'ct:meta': Chartist.serialize(pathElement.data.meta)\n });\n\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if(seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized.series[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n seriesMeta: series.meta,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n }\n\n // Area currently only works with axes that support a range!\n if(seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\n // We project the areaBase value into screen coordinates\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\n // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\n // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n return solidPathSegments.clone(true)\n .position(0)\n .remove(1)\n .move(firstElement.x, areaBaseProjected)\n .line(firstElement.x, firstElement.y)\n .position(solidPathSegments.pathElements.length + 1)\n .line(lastElement.x, areaBaseProjected);\n\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true);\n\n // Emit an event for each area that was drawn\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized.series[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "function createChart(options) {\n var data = Chartist.normalizeData(this.data, options.reverseData, true);\n\n // Create new svg object\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n // Create groups for labels, grid and series\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if(options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.normalized.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);\n }\n\n if(options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n if (options.showGridBackground) {\n Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);\n }\n\n // Draw the series\n data.raw.series.forEach(function(series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g');\n\n // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n });\n\n // Use series class from series data or if not set generate one\n seriesElement.addClass([\n options.classNames.series,\n (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n ].join(' '));\n\n var pathCoordinates = [],\n pathData = [];\n\n data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n var path = smoothing(pathCoordinates, pathData);\n\n // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n if (seriesOptions.showPoint) {\n\n path.pathElements.forEach(function(pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),\n 'ct:meta': Chartist.serialize(pathElement.data.meta)\n });\n\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if(seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized.series[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n seriesMeta: series.meta,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n }\n\n // Area currently only works with axes that support a range!\n if(seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\n // We project the areaBase value into screen coordinates\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\n // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\n // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n return solidPathSegments.clone(true)\n .position(0)\n .remove(1)\n .move(firstElement.x, areaBaseProjected)\n .line(firstElement.x, firstElement.y)\n .position(solidPathSegments.pathElements.length + 1)\n .line(lastElement.x, areaBaseProjected);\n\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true);\n\n // Emit an event for each area that was drawn\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized.series[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "function createChart(options) {\n var data = Chartist.normalizeData(this.data, options.reverseData, true);\n\n // Create new svg object\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n // Create groups for labels, grid and series\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if(options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.normalized.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);\n }\n\n if(options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n if (options.showGridBackground) {\n Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);\n }\n\n // Draw the series\n data.raw.series.forEach(function(series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g');\n\n // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n });\n\n // Use series class from series data or if not set generate one\n seriesElement.addClass([\n options.classNames.series,\n (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n ].join(' '));\n\n var pathCoordinates = [],\n pathData = [];\n\n data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n var path = smoothing(pathCoordinates, pathData);\n\n // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n if (seriesOptions.showPoint) {\n\n path.pathElements.forEach(function(pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),\n 'ct:meta': Chartist.serialize(pathElement.data.meta)\n });\n\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if(seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized.series[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n seriesMeta: series.meta,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n }\n\n // Area currently only works with axes that support a range!\n if(seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\n // We project the areaBase value into screen coordinates\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\n // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\n // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n return solidPathSegments.clone(true)\n .position(0)\n .remove(1)\n .move(firstElement.x, areaBaseProjected)\n .line(firstElement.x, firstElement.y)\n .position(solidPathSegments.pathElements.length + 1)\n .line(lastElement.x, areaBaseProjected);\n\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true);\n\n // Emit an event for each area that was drawn\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized.series[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "function createChart(options) {\n var data = Chartist.normalizeData(this.data, options.reverseData, true);\n\n // Create new svg object\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n // Create groups for labels, grid and series\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if(options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.normalized.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);\n }\n\n if(options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n if (options.showGridBackground) {\n Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);\n }\n\n // Draw the series\n data.raw.series.forEach(function(series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g');\n\n // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n });\n\n // Use series class from series data or if not set generate one\n seriesElement.addClass([\n options.classNames.series,\n (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n ].join(' '));\n\n var pathCoordinates = [],\n pathData = [];\n\n data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n var path = smoothing(pathCoordinates, pathData);\n\n // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n if (seriesOptions.showPoint) {\n\n path.pathElements.forEach(function(pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),\n 'ct:meta': Chartist.serialize(pathElement.data.meta)\n });\n\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if(seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized.series[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n seriesMeta: series.meta,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n }\n\n // Area currently only works with axes that support a range!\n if(seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\n // We project the areaBase value into screen coordinates\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\n // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\n // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n return solidPathSegments.clone(true)\n .position(0)\n .remove(1)\n .move(firstElement.x, areaBaseProjected)\n .line(firstElement.x, firstElement.y)\n .position(solidPathSegments.pathElements.length + 1)\n .line(lastElement.x, areaBaseProjected);\n\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true);\n\n // Emit an event for each area that was drawn\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized.series[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "function createChart(options) {\n var data = Chartist.normalizeData(this.data, options.reverseData, true);\n\n // Create new svg object\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n // Create groups for labels, grid and series\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if(options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.normalized.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);\n }\n\n if(options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n if (options.showGridBackground) {\n Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);\n }\n\n // Draw the series\n data.raw.series.forEach(function(series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g');\n\n // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n });\n\n // Use series class from series data or if not set generate one\n seriesElement.addClass([\n options.classNames.series,\n (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n ].join(' '));\n\n var pathCoordinates = [],\n pathData = [];\n\n data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n var path = smoothing(pathCoordinates, pathData);\n\n // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n if (seriesOptions.showPoint) {\n\n path.pathElements.forEach(function(pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),\n 'ct:meta': Chartist.serialize(pathElement.data.meta)\n });\n\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if(seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized.series[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n seriesMeta: series.meta,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n }\n\n // Area currently only works with axes that support a range!\n if(seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\n // We project the areaBase value into screen coordinates\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\n // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\n // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n return solidPathSegments.clone(true)\n .position(0)\n .remove(1)\n .move(firstElement.x, areaBaseProjected)\n .line(firstElement.x, firstElement.y)\n .position(solidPathSegments.pathElements.length + 1)\n .line(lastElement.x, areaBaseProjected);\n\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true);\n\n // Emit an event for each area that was drawn\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized.series[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "function createChart(options) {\n var data = Chartist.normalizeData(this.data, options.reverseData, true);\n\n // Create new svg object\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);\n // Create groups for labels, grid and series\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if(options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.normalized.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);\n }\n\n if(options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n if (options.showGridBackground) {\n Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);\n }\n\n // Draw the series\n data.raw.series.forEach(function(series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g');\n\n // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n });\n\n // Use series class from series data or if not set generate one\n seriesElement.addClass([\n options.classNames.series,\n (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))\n ].join(' '));\n\n var pathCoordinates = [],\n pathData = [];\n\n data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ?\n seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());\n // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n var path = smoothing(pathCoordinates, pathData);\n\n // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n if (seriesOptions.showPoint) {\n\n path.pathElements.forEach(function(pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),\n 'ct:meta': Chartist.serialize(pathElement.data.meta)\n });\n\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if(seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized.series[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n seriesMeta: series.meta,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n }\n\n // Area currently only works with axes that support a range!\n if(seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);\n\n // We project the areaBase value into screen coordinates\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);\n\n // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];\n\n // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n return solidPathSegments.clone(true)\n .position(0)\n .remove(1)\n .move(firstElement.x, areaBaseProjected)\n .line(firstElement.x, firstElement.y)\n .position(solidPathSegments.pathElements.length + 1)\n .line(lastElement.x, areaBaseProjected);\n\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true);\n\n // Emit an event for each area that was drawn\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized.series[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "function drawChart() {\r\n drawSentimentBreakdown();\r\n drawSentimentTimeline();\r\n drawPopularityTimeline();\r\n}", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Topping');\n data.addColumn('number', 'Slices');\n data.addRows(rendergrafica);\n\n // Set chart options\n var options = {\n 'title': 'Cantidad de laboratorios por categoria',\n\n\n };\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n\n }", "function graphCreate(id) {\n ctx = document.getElementById(id).getContext(\"2d\");\n myLine = new Chart(ctx)\n myLineChart = myLine.Line(producersIds[id].data, {\n tooltipTemplate: \"<%if (label){%><%=label%>: <%}%><%= value %>kb\",\n });\n producersIds[id].canvas = ctx;\n producersIds[id].myLine = myLine;\n producersIds[id].myLineChart = myLineChart;\n\n}", "function drawChart() {\n\n\t\t// Get the dataGraphic array form PHP\n\t\tvar dataOptionsGraphic = JSON.parse(jsonDataGraphic);\n\n\t\tfor (col in dataOptionsGraphic) {\n\t\t\tdataOptionsGraphic[col][5] = strTooltipStart + dataOptionsGraphic[col][1] + strTooltipEnd;\n\t\t}\n\n\t\t// Header of the data Graphic\n\t\tvar headDataGraphic = [M.util.get_string('choice', 'evoting'), M.util.get_string('countvote', 'evoting'), {\n\t\t\ttype: 'string',\n\t\t\trole: 'style'\n\t\t}, {\n\t\t\ttype: 'string',\n\t\t\trole: 'annotation'\n\t\t}, 'id', {\n\t\t\t'type': 'string',\n\t\t\t'role': 'tooltip',\n\t\t\t'p': {\n\t\t\t\t'html': true\n\t\t\t}\n\t\t}, {\n\t\t\ttype: 'string'\n\t\t}];\n\t\t// Create the complete data of the Graphic by integrated header data\n\t\tdataOptionsGraphic.splice(0, 0, headDataGraphic);\n\t\toptionsGraph = {\n\t\t\ttitle: \"\",\n\t\t\tallowHtml: true,\n\t\t\theight: 450,\n\t\t\tlegend: {\n\t\t\t\tposition: 'none'\n\t\t\t},\n\t\t\tanimation: {\n\t\t\t\tduration: 500,\n\t\t\t\teasing: 'out'\n\t\t\t},\n\n\t\t\tvAxis: {\n\t\t\t\tgridlines: {\n\t\t\t\t\tcolor: '#000000'\n\t\t\t\t},\n\t\t\t\ttextPosition: 'out',\n\t\t\t\ttextStyle: {\n\t\t\t\t\tcolor: '#007cb7',\n\t\t\t\t\tfontName: 'Oswald, Times-Roman',\n\t\t\t\t\tbold: true,\n\t\t\t\t\titalic: false\n\t\t\t\t}\n\n\t\t\t},\n\t\t\thAxis: {\n\t\t\t\ttitle: M.util.get_string('totalvote', 'evoting') + \" : \" + sumVote,\n\t\t\t\tminValue: \"0\",\n\t\t\t\tmaxValue: max,\n\t\t\t\tgridlines: {\n\t\t\t\t\tcolor: '#e6e6e6'\n\t\t\t\t},\n\t\t\t\ttextStyle: {\n\t\t\t\t\tcolor: '#e6e6e6'\n\t\t\t\t},\n\t\t\t\ttitleTextStyle: {\n\t\t\t\t\tcolor: '#007cb7',\n\t\t\t\t\tfontName: 'Oswald, Times-Roman',\n\t\t\t\t\tbold: false,\n\t\t\t\t\titalic: false\n\t\t\t\t}\n\t\t\t},\n\t\t\tbaselineColor: '#007cb7',\n\t\t\ttooltip: {\n\t\t\t\tisHtml: true\n\t\t\t},\n\n\t\t\tannotations: {\n\t\t\t\ttextStyle: {\n\t\t\t\t\tfontName: 'Oswald,Helvetica,Arial,sans-serif',\n\t\t\t\t\tbold: false,\n\t\t\t\t\titalic: false,\n\t\t\t\t\tcolor: '#007cb7',\n\t\t\t\t\tauraColor: 'rgba(255,255,255,0)',\n\t\t\t\t\topacity: 1,\n\t\t\t\t\tx: 20\n\t\t\t\t},\n\t\t\t\talwaysOutside: false,\n\t\t\t\thighContrast: true,\n\t\t\t\tstemColor: '#000000'\n\t\t\t},\n\t\t\tbackgroundColor: '#f6f6f6',\n\t\t\tchartArea: {\n\t\t\t\tleft: '5%',\n\t\t\t\ttop: '5%',\n\t\t\t\theight: '75%',\n\t\t\t\twidth: '100%'\n\t\t\t}\n\t\t};\n\n\t\tdataGraph = google.visualization.arrayToDataTable(dataOptionsGraphic);\n\t\tdataGraph.setColumnProperty(0, {\n\t\t\tallowHtml: true\n\t\t});\n\t\tviewGraph = new google.visualization.DataView(dataGraph);\n\t\tviewGraph.setColumns([0, 1, 2, 3, 5]);\n\n\t\t// Create and draw the visualization.\n\t\tchart = new google.visualization.BarChart(document.getElementById('chartContainer'));\n\t\t$(\".answerCount\").each(function () {\n\t\t\tidOption = $(this).prop('id');\n\t\t});\n\t\tupdateOptionGraphicMax();\n\n\t\tmanageGoodAnswer();\n\t}", "function drawChart() {\n // define chart to be drawn using DataTable object\n const data = new google.visualization.DataTable();\n\n // add date & time column\n data.addColumn(\"string\", \"Date & Time\");\n\n // add other category columns such as co2\n columns.forEach(column => {\n // find full text in relevent option for the current column\n const fullColumnName = $(`#cmbCategories option[value='${column}']`).text();\n data.addColumn(\"number\", fullColumnName);\n });\n\n // add rows created beforehand\n data.addRows(rows);\n\n // chart options\n const options = {\n hAxis: {\n title: \"Date & Time\"\n },\n vAxis: {\n title: \"Values\"\n },\n width: \"100%\",\n height: 700,\n };\n\n // instantiate and draw the chart\n const chart = new google.visualization.LineChart(document.getElementById(\"outputChart\"));\n\n // after chart is completely loaded and rendered\n google.visualization.events.addListener(chart, \"ready\", function () {\n // enable view chart button\n $(\"#btnViewChart\").attr(\"disabled\", false);\n\n // hide loading spinner\n $(\"#imgLoading\").hide();\n });\n\n chart.draw(data, options);\n }", "async function renderGraph(){\n var config = {\n type: 'line',\n data: {\n labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],\n datasets: [{\n label: '',\n backgroundColor: \"rgba(240, 114, 41, 0.2)\",\n borderColor: \"rgba(240, 114, 41, 1)\",\n data: [\n await getFromStorage(\"month_january_count\", 0),\n await getFromStorage(\"month_february_count\", 0),\n await getFromStorage(\"month_march_count\", 0),\n await getFromStorage(\"month_april_count\", 0),\n await getFromStorage(\"month_may_count\", 0),\n await getFromStorage(\"month_june_count\", 0),\n await getFromStorage(\"month_july_count\", 0),\n await getFromStorage(\"month_august_count\", 0),\n await getFromStorage(\"month_september_count\", 0),\n await getFromStorage(\"month_october_count\", 0),\n await getFromStorage(\"month_november_count\", 0),\n await getFromStorage(\"month_december_count\", 0)\n ],\n fill: true,\n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n title: {\n display: false,\n },\n tooltips: {\n mode: 'index',\n intersect: false,\n },\n hover: {\n mode: 'nearest',\n intersect: true\n },\n scales: {\n xAxes: [{\n display: false,\n scaleLabel: {\n display: false,\n labelString: 'Month'\n }\n }],\n yAxes: [{\n display: false,\n scaleLabel: {\n display: false,\n },\n ticks: {\n padding: 10,\n },\n }]\n },\n legend: { \n display: false \n },\n elements: {\n point:{\n radius: 0\n }\n },\n layout: {\n padding: {\n left: 0,\n right: 0,\n top: 5,\n bottom: 2\n }\n }\n }\n };\n\n var ctx = document.getElementById('canvas').getContext('2d');\n ctx.height = 90;\n window.myLine = new Chart(ctx, config);\n}", "function displayChart() {\n try {\n bb.generate({\n \"data\": DATA,\n \"axis\": X_AXIS,\n \"grid\": GRID,\n \"bindto\": CHART_ID\n });\n }\n catch (e) {\n console.log(e);\n }\n console.log(\"We built the chart.\");\n}", "function drawGrid() {\n\t\t\t// add container styles\n\t\t\t$container.addClass('container gantt');\n\t\t\t\n\t\t\t// empty container\n\t\t\t$container.empty();\n\t\t\t\t\t\t\n\t\t\t// render contents into container\n\t\t\t$container.append(gridTmpl(controller));\t\n\t\t\tinitEls();\n\t\t\t\n\t\t\t// adjust layout components\n\t\t\tadjustLayout();\n\t\t\tinitHScroller();\t\t\t\n\t\t}", "function updateProfileView(tasks) {\r\n\r\n // for each task\r\n tasks.forEach(task => {\r\n\r\n let taskDiv = createTaskDiv(task) // make the div for the task\r\n\r\n // add the taskDiv to the appropriate category\r\n if (task.status == false) $('#completed').append(taskDiv)\r\n else if (task.startDate === task.endDate) $('#daily').append(taskDiv);\r\n else $('#weekly').append(taskDiv);\r\n });\r\n}", "function DrawHDDChart()\n{\n // create/delete rows \n if (hddTable.getNumberOfRows() < aggrDataPoints.length)\n { \n var numRows = aggrDataPoints.length - hddTable.getNumberOfRows();\n hddTable.addRows(numRows);\n } else {\n for(var i=(hddTable.getNumberOfRows()-1); i >= aggrDataPoints.length; i--)\n {\n hddTable.removeRow(i); \n }\n }\n\n // Populate data table with time/hdd data points. \n for(var i=0; i < hddTable.getNumberOfRows(); i++)\n {\n hddTable.setCell(i, 0, new Date(parseInt(aggrDataPoints[i].timestamp)));\n hddTable.setCell(i, 1, parseInt(aggrDataPoints[i].hdd));\n }\n\n // Draw line chart.\n chartOptions.title = 'HDD Usage (%)';\n hddChart.draw(hddView, chartOptions); \n}", "function DrawCostChart()\n{\n // create/delete rows \n if (costTable.getNumberOfRows() < aggrDataPoints.length)\n { \n var numRows = aggrDataPoints.length - costTable.getNumberOfRows();\n costTable.addRows(numRows);\n } else {\n for(var i=(costTable.getNumberOfRows()-1); i >= aggrDataPoints.length; i--)\n {\n costTable.removeRow(i); \n }\n }\n \n // Populate data table with time/cost data points. \n for(var i=0; i < costTable.getNumberOfRows(); i++)\n {\n //if(parseFloat(aggrDataPoints[i].cost) < 500) continue;\n costTable.setCell(i, 0, new Date(parseInt(aggrDataPoints[i].timestamp)));\n costTable.setCell(i, 1, parseFloat(aggrDataPoints[i].cost));\n }\n\n // Draw line chart.\n chartOptions.title = 'Cost Chart';\n costChart.draw(costView, chartOptions); \n}", "function createChart(id, title, dataArray) {\n let chart = new CanvasJS.Chart(id, {\n title: {\n text: title\n },\n axisX: {\n title: \"Value of n\",\n valueFormatString: \"#,###\"\n },\n axisY: {\n title: \"Average runtime (ms)\"\n },\n toolTip: {\n shared: true\n },\n legend: {\n cursor: \"pointer\",\n verticalAlign: \"top\",\n horizontalAlign: \"center\",\n dockInsidePlotArea: true,\n },\n data: dataArray\n });\n return chart;\n}", "renderUndoneTask() {\n for (let i = 0; i < this.undoneTaskArr.length; i++) {\n const task = new Task(this.undoneTaskArr[i]);\n this.taskListUnDone.appendChild(task.createUndoneTask())\n\n };\n }", "function BuildChart() {\n vm.ctx = document.getElementById('myChart').getContext('2d');\n vm.salesProgress = new Chart(vm.ctx, {\n type: 'bar',\n data: {\n labels: vm.labels,\n datasets: [{\n label: 'goal',\n data: vm.goals,\n backgroundColor: [\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)',\n 'rgba(255, 206, 86, 0.6)'\n ],\n borderColor: [\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)',\n 'rgba(255, 206, 86, 1)'\n ],\n borderWidth: 1\n },\n {\n label: 'written',\n data: vm.territoryWritten,\n\n backgroundColor: [\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)',\n 'rgba(255, 99, 132, 0.6)'\n ],\n borderColor: [\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)',\n 'rgba(255, 99, 132, 1)'\n ],\n borderWidth: 1\n },\n {\n label: 'delivered',\n data: vm.territoryDelivered,\n backgroundColor: [\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)',\n 'rgba(54, 162, 235, 0.6)'\n ],\n borderColor: [\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)',\n 'rgba(54, 162, 235, 1)'\n ],\n borderWidth: 1\n }\n ]\n },\n options: {\n maintainAspectRatio: false,\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n //xAxes: [{\n\n // gridLines: {\n // lineWidth: 1.5,\n // //color: 'rgba(25, 25, 25, 0.4)',\n // drawBorder: true\n // }\n //}]\n\n }\n //animation: {\n // onProgress: function (animation) {\n // progress.value = animation.animationObject.currentStep / animation.animationObject.numSteps;\n // }\n //}\n\n }\n });\n }", "function deviceLivetime(){\n var container = document.getElementById('g-chart-deviceLivetime');\n var chart = new google.visualization.Timeline(container);\n var dataTable = new google.visualization.DataTable();\n\n dataTable.addColumn({ type: 'string', id: 'Devicename' });\n dataTable.addColumn({ type: 'date', id: 'Start' });\n dataTable.addColumn({ type: 'date', id: 'End' });\n\n var rows = [];\n deviceLivetime_arr.forEach(function(el){\n rows.push([ el[0], new Date(el[1]), new Date(el[2]) ]);\n });\n\n dataTable.addRows(rows);\n\n var height = 100 + 35*deviceLivetime_arr.length;\n var options = {\n backgroundColor: \"#f9e7d5\",\n height: height\n };\n\n chart.draw(dataTable, options);\n }", "function draw() {\n const data = getData();\n const svg = d3.select('body').append('svg');\n const plot = getPlotArea();\n const paddingGroup = chartUtils.setupSvgAndPaddingGroup(svg, plot);\n const scales = makeScales(data, plot);\n defineDashedLine(svg);\n appendYAxisDashedLines(paddingGroup, scales, plot);\n appendXAxis(paddingGroup, scales, plot);\n appendYAxis(paddingGroup, scales);\n appendBars(paddingGroup, data, scales, plot);\n appendScoreToday(paddingGroup, data, scales);\n appendScoreLastYear(paddingGroup, data, scales);\n appendChartTitle(svg, plot);\n appendYAxisTitle(svg, plot);\n appendFootnote(svg, plot);\n }", "function drawChart() {\n console.log(\"drawChart ran\");\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Day');\n data.addColumn('number', 'Temperature');\n var i = 0;\n /*Loops through the days of the week and for each\n day there is weather info it adds a row */\n for (i = 0; i < days_of_the_week.length; i++) {\n if (day_and_temp_map.has(days_of_the_week[i])) {\n data.addRow([days_of_the_week[i], day_and_temp_map.get(days_of_the_week[i])]);\n }\n }\n\n // Set chart options\n var options = {\n 'title': 'Weather forecast chart',\n 'width': 500,\n 'height': 300\n };\n\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.BarChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n }", "function drawChart() {\n var user_data1 = google.visualization.arrayToDataTable([\n ['Task', 'Collect users data'],\n ['KYC verified users', countv],\n ['KYC pending users', countt-countv-1]\n ]);\n\n var book_data = google.visualization.arrayToDataTable([\n ['Task', 'Count'],\n ['Books available', cavail],\n ['Books Total', totalb]\n ]);\n\n var genre_data = google.visualization.arrayToDataTable([\n ['Task', 'Count of books with their categories'],\n ['Art', a],\n ['Music', m],\n ['Poetry', p],\n ['Humour', h],\n ['Fantasy', f],\n ['Business', bu],\n ['Biography', bi],\n ['Cookbooks', c],\n ['Engineering', e],\n ['Young adult', y]\n ]);\n\n\n // Optional; add a title and set the width and height of the chart\n var user1 = {'title':'User Details - KYC', 'width':550, 'height':400};\n var book = {'title':'Book Details', 'width':550, 'height':400};\n var genre = {'title':'Book Genres', 'width':550, 'height':400};\n\n // Display the chart inside the <div> element with id=\"piechart\"\n var chart = new google.visualization.PieChart(document.getElementById('user-details1'));\n chart.draw(user_data1, user1);\n var chart = new google.visualization.BarChart(document.getElementById('book-details'));\n chart.draw(book_data, book);\n var chart = new google.visualization.PieChart(document.getElementById('book-genres'));\n chart.draw(genre_data, genre);\n }", "function _drawVisualization() {\n // Create and populate a data table.\n var data = new google.visualization.DataTable();\n data.addColumn('datetime', 'start');\n data.addColumn('datetime', 'end');\n data.addColumn('string', 'content');\n data.addColumn('string', 'group');\n\n var date = new Date(2014, 04, 25, 8, 0, 0);\n\n var loader_text = '<img src=\"/res/qsl/img/loader33x16.png\" width=\"33px\" height=\"16px\"> L-105';\n var inspe_text =\n '<div title=\"Inspection\" class=\"order\">' +\n '<i class=\"fa fa-lg fa-wrench\"></i> ' +\n 'Inspection' +\n '</div>';\n var inspe_start = new Date(date);\n var inspe_end = new Date(date.setHours(date.getHours() + 6));\n\n data.addRow([inspe_start, inspe_end, inspe_text, loader_text]);\n\n var vessl_text =\n '<div title=\"Snoekgracht\" class=\"order\">' +\n '<i class=\"fa fa-lg fa-anchor\"></i> ' +\n 'Snoekgracht' +\n '</div>';\n var inspe_start = new Date(date.setHours(date.getHours() + 6));\n var inspe_end = new Date(date.setHours(date.getHours() + 48));\n\n data.addRow([inspe_start, inspe_end, vessl_text, loader_text]);\n\n // specify options\n var options = {\n width: \"100%\",\n //height: \"300px\",\n height: \"auto\",\n layout: \"box\",\n editable: true,\n eventMargin: 5, // minimal margin between events\n eventMarginAxis: 0, // minimal margin beteen events and the axis\n showMajorLabels: false,\n axisOnTop: true,\n // groupsWidth : \"200px\",\n groupsChangeable: true,\n groupsOnRight: false,\n stackEvents: false\n };\n\n // Instantiate our timeline object.\n that.timeline = new links.Timeline(document.getElementById(that.optio.vva_id_regn));\n\n // Draw our timeline with the created data and options\n that.timeline.draw(data, options);\n }", "function drawChart() {\n\n // Create the data table.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Color');\n data.addColumn('number', 'Ranking');\n\n data.addRows(graphData);\n\n // Set chart options\n var options = {\n title: 'T-Shirt Rankings',\n height: 600,\n legend: {position: 'none'},\n vAxis: {format:'#'}\n };\n // Instantiate and draw our chart, passing in some options.\n var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n }", "function createChart(options) {\n var data = Chartist.normalizeData(this.data, options.reverseData, true); // Create new svg object\n\n this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart); // Create groups for labels, grid and series\n\n var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);\n var seriesGroup = this.svg.elem('g');\n var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);\n var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);\n var axisX, axisY;\n\n if (options.axisX.type === undefined) {\n axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {\n ticks: data.normalized.labels,\n stretch: options.fullWidth\n }));\n } else {\n axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);\n }\n\n if (options.axisY.type === undefined) {\n axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {\n high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,\n low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low\n }));\n } else {\n axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);\n }\n\n axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);\n\n if (options.showGridBackground) {\n Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);\n } // Draw the series\n\n\n data.raw.series.forEach(function (series, seriesIndex) {\n var seriesElement = seriesGroup.elem('g'); // Write attributes to series group element. If series name or meta is undefined the attributes will not be written\n\n seriesElement.attr({\n 'ct:series-name': series.name,\n 'ct:meta': Chartist.serialize(series.meta)\n }); // Use series class from series data or if not set generate one\n\n seriesElement.addClass([options.classNames.series, series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex)].join(' '));\n var pathCoordinates = [],\n pathData = [];\n data.normalized.series[seriesIndex].forEach(function (value, valueIndex) {\n var p = {\n x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),\n y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])\n };\n pathCoordinates.push(p.x, p.y);\n pathData.push({\n value: value,\n valueIndex: valueIndex,\n meta: Chartist.getMetaData(series, valueIndex)\n });\n }.bind(this));\n var seriesOptions = {\n lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),\n showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),\n showLine: Chartist.getSeriesOption(series, options, 'showLine'),\n showArea: Chartist.getSeriesOption(series, options, 'showArea'),\n areaBase: Chartist.getSeriesOption(series, options, 'areaBase')\n };\n var smoothing = typeof seriesOptions.lineSmooth === 'function' ? seriesOptions.lineSmooth : seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none(); // Interpolating path where pathData will be used to annotate each path element so we can trace back the original\n // index, value and meta data\n\n var path = smoothing(pathCoordinates, pathData); // If we should show points we need to create them now to avoid secondary loop\n // Points are drawn from the pathElements returned by the interpolation function\n // Small offset for Firefox to render squares correctly\n\n if (seriesOptions.showPoint) {\n path.pathElements.forEach(function (pathElement) {\n var point = seriesElement.elem('line', {\n x1: pathElement.x,\n y1: pathElement.y,\n x2: pathElement.x + 0.01,\n y2: pathElement.y\n }, options.classNames.point).attr({\n 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),\n 'ct:meta': Chartist.serialize(pathElement.data.meta)\n });\n this.eventEmitter.emit('draw', {\n type: 'point',\n value: pathElement.data.value,\n index: pathElement.data.valueIndex,\n meta: pathElement.data.meta,\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: point,\n x: pathElement.x,\n y: pathElement.y\n });\n }.bind(this));\n }\n\n if (seriesOptions.showLine) {\n var line = seriesElement.elem('path', {\n d: path.stringify()\n }, options.classNames.line, true);\n this.eventEmitter.emit('draw', {\n type: 'line',\n values: data.normalized.series[seriesIndex],\n path: path.clone(),\n chartRect: chartRect,\n index: seriesIndex,\n series: series,\n seriesIndex: seriesIndex,\n seriesMeta: series.meta,\n axisX: axisX,\n axisY: axisY,\n group: seriesElement,\n element: line\n });\n } // Area currently only works with axes that support a range!\n\n\n if (seriesOptions.showArea && axisY.range) {\n // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that\n // the area is not drawn outside the chart area.\n var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min); // We project the areaBase value into screen coordinates\n\n var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase); // In order to form the area we'll first split the path by move commands so we can chunk it up into segments\n\n path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {\n // We filter only \"solid\" segments that contain more than one point. Otherwise there's no need for an area\n return pathSegment.pathElements.length > 1;\n }).map(function convertToArea(solidPathSegments) {\n // Receiving the filtered solid path segments we can now convert those segments into fill areas\n var firstElement = solidPathSegments.pathElements[0];\n var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1]; // Cloning the solid path segment with closing option and removing the first move command from the clone\n // We then insert a new move that should start at the area base and draw a straight line up or down\n // at the end of the path we add an additional straight line to the projected area base value\n // As the closing option is set our path will be automatically closed\n\n return solidPathSegments.clone(true).position(0).remove(1).move(firstElement.x, areaBaseProjected).line(firstElement.x, firstElement.y).position(solidPathSegments.pathElements.length + 1).line(lastElement.x, areaBaseProjected);\n }).forEach(function createArea(areaPath) {\n // For each of our newly created area paths, we'll now create path elements by stringifying our path objects\n // and adding the created DOM elements to the correct series group\n var area = seriesElement.elem('path', {\n d: areaPath.stringify()\n }, options.classNames.area, true); // Emit an event for each area that was drawn\n\n this.eventEmitter.emit('draw', {\n type: 'area',\n values: data.normalized.series[seriesIndex],\n path: areaPath.clone(),\n series: series,\n seriesIndex: seriesIndex,\n axisX: axisX,\n axisY: axisY,\n chartRect: chartRect,\n index: seriesIndex,\n group: seriesElement,\n element: area\n });\n }.bind(this));\n }\n }.bind(this));\n this.eventEmitter.emit('created', {\n bounds: axisY.bounds,\n chartRect: chartRect,\n axisX: axisX,\n axisY: axisY,\n svg: this.svg,\n options: options\n });\n }", "generateChartsHTML() {\n\n\t\tlet plantingDate = new Date();\n\t\tlet harvestDate = new Date();\n\t\tlet harvestDateMin = new Date();\n\t\tlet harvestDateMax = new Date();\n\t\tlet rangeSelectorMin = new Date();\n\t\tlet rangeSelectorMax = new Date();\n\t\tlet ccChartDataArray = {}; // Associative array to store chart data\n\t\tlet biomassDates = [];\n\t\tlet biomassValues = [];\n\t\tlet cnDates = [];\n\t\tlet cnValues = [];\n\t\tlet cnMax = 60;\n\n\t\tlet cnRows = [];\n\t\tlet biomassRows = [];\n\n\t\tif (this.props.hasOwnProperty(\"userInputJson\") && this.props[\"userInputJson\"] !== null && this.props[\"userInputJson\"] !== undefined) {\n\n\t\t\tlet plantingYear = this.props[\"userInputJson\"][\"year_planting\"];\n\t\t\tlet harvestYear = plantingYear + 1;\n\t\t\tlet plantingDOY = this.props[\"userInputJson\"][\"doy_planting\"];\n\t\t\tlet harvestDOY = this.props[\"userInputJson\"][\"doy_harvest\"] - config.coverCropTerminationOffsetDays;\n\t\t\tplantingDate = new Date(plantingYear, 0, plantingDOY);\n\t\t\tharvestDate = new Date(harvestYear, 0, harvestDOY);\n\n\t\t\tharvestDateMin = new Date(harvestYear, 0, harvestDOY - (windowDurationDays/2));\n\t\t\tharvestDateMax = new Date(harvestYear, 0, harvestDOY + (windowDurationDays/2));\n\t\t\trangeSelectorMin = new Date(plantingYear, 0, plantingDOY - 1);\n\t\t\trangeSelectorMax = new Date(harvestYear, 0, harvestDOY + windowDurationDays);\n\t\t}\n\n\t\tccChartDataArray = this.state.ccDataArray;// generate charts for with cover crop case\n\t\tfor (let key in ccChartDataArray) {\n\t\t\tif(key.toString() === \"C:N ratio\"){\n\t\t\t\tif(ccChartDataArray[key].chartData !== undefined && ccChartDataArray[key].chartData.datasets.length) {\n\t\t\t\t\tcnRows = ccChartDataArray[key].chartData.datasets[0].data;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(key.toString() === \"TWAD\"){\n\t\t\t\tif(ccChartDataArray[key].chartData !== undefined && ccChartDataArray[key].chartData.datasets.length) {\n\t\t\t\t\tbiomassRows = ccChartDataArray[key].chartData.datasets[0].data;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet prevCnDate = null;\n\n\t\tcnRows.forEach(function(element) {\n\t\t\tlet dt = element.x;\n\n\t\t\t// Adds 0s for missing date to make graph cleaner\n\t\t\tif(prevCnDate != null){\n\t\t\t\tlet dayDiff = calculateDayDifference(prevCnDate, dt);\n\t\t\t\twhile(dayDiff > 1){\n\t\t\t\t\tlet newDate = addDays(prevCnDate, 1);\n\t\t\t\t\tcnDates.push(newDate);\n\t\t\t\t\tcnValues.push(null);\n\t\t\t\t\tdayDiff--;\n\t\t\t\t\tprevCnDate = newDate;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcnDates.push(dt);\n\t\t\tcnValues.push(element.y);\n\t\t\tprevCnDate = element.x;\n\t\t});\n\n\t\tcnMax = Math.max(...cnValues);\n\t\tif(cnMax < 21){\n\t\t\tcnMax = 26;\n\t\t}\n\n\t\tlet prevBiomassDate = null;\n\t\tbiomassRows.forEach(function(element) {\n\t\t\tlet dt = element.x;\n\n\t\t\t// Adds 0s for missing date to make graph cleaner\n\t\t\tif(prevBiomassDate != null){\n\t\t\t\tlet dayDiff = calculateDayDifference(prevBiomassDate, dt);\n\t\t\t\twhile(dayDiff > 1){\n\t\t\t\t\tlet newDate = addDays(prevBiomassDate, 1);\n\t\t\t\t\tbiomassDates.push(newDate);\n\t\t\t\t\tbiomassValues.push(null);\n\t\t\t\t\tdayDiff--;\n\t\t\t\t\tprevBiomassDate = newDate;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbiomassDates.push(dt);\n\t\t\tbiomassValues.push(element.y);\n\t\t\tprevBiomassDate = element.x;\n\t\t});\n\n\n\t\tlet resultHtml = [];\n\t\tlet selectorOptions = {\n\t\t\tx: 0.01,\n\t\t\ty: 1.15,\n\t\t\tbuttons: [\n\t\t\t// \t{\n\t\t\t// \tstep: \"month\",\n\t\t\t// \tstepmode: \"backward\",\n\t\t\t// \tcount: 1,\n\t\t\t// \tlabel: \"1m\"\n\t\t\t// }, {\n\t\t\t// \tstep: \"month\",\n\t\t\t// \tstepmode: \"backward\",\n\t\t\t// \tcount: 6,\n\t\t\t// \tlabel: \"6m\"\n\t\t\t// }, {\n\t\t\t// \tstep: \"year\",\n\t\t\t// \tstepmode: \"todate\",\n\t\t\t// \tcount: 1,\n\t\t\t// \tlabel: \"YTD\"\n\t\t\t// }, {\n\t\t\t// \tstep: \"year\",\n\t\t\t// \tstepmode: \"backward\",\n\t\t\t// \tcount: 1,\n\t\t\t// \tlabel: \"1y\"\n\t\t\t// },\n\t\t\t\t{\n\t\t\t\tstep: \"all\",\n\t\t\t\tlabel: \"show all\"\n\t\t\t}],\n\n\t\t};\n\n\t\tlet biomass = {\n\t\t\tx: biomassDates, //[\"2019-01-01\", \"2019-03-01\", \"2019-06-01\", \"2019-09-03\"],\n\t\t\ty: biomassValues, //[0, 15, 19, 21],\n\t\t\tname: \"Plant Biomass\",\n\t\t\ttype: \"scatter\",\n\t\t\tmode: \"lines\",\n\t\t\tconnectgaps: false,\n\t\t\tline: {color: \"DeepSkyBlue\"}\n\t\t};\n\n\t\tlet cn = {\n\t\t\tx: cnDates, //[\"2019-01-01\", \"2019-03-01\", \"2019-06-01\", \"2019-09-03\"],\n\t\t\ty: cnValues, //[0, 3, 10, 13],\n\t\t\tname: \"C:N\",\n\t\t\tyaxis: \"y2\",\n\t\t\ttype: \"scatter\",\n\t\t\tmode: \"lines\", //lines+marks\n\t\t\tconnectgaps: false,\n\t\t\tline: {color: \"Orange\"}\n\t\t};\n\n\t\tlet data = [biomass, cn];\n\n\t\tlet highlightShapes = [\n\t\t\t{\n\t\t\t\ttype: \"rect\",\n\t\t\t\txref: \"x\",\n\t\t\t\tyref:\"paper\",\n\t\t\t\tx0: harvestDateMin,\n\t\t\t\ty0: 0,\n\t\t\t\tx1: harvestDateMax,\n\t\t\t\ty1: 1,\n\t\t\t\tfillcolor: \"rgb(204, 255, 235)\", //\"LightYellow\",\n\t\t\t\topacity: 0.5,\n\t\t\t\tlayer: \"below\",\n\t\t\t\tline: {width: 1, dash: \"dot\"}\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: \"line\",\n\t\t\t\txref: \"x\",\n\t\t\t\tyref:\"paper\",\n\t\t\t\tx0: plantingDate,\n\t\t\t\ty0: 0,\n\t\t\t\tx1: plantingDate,\n\t\t\t\ty1: 1.1,\n\t\t\t\tline: {width: 2}\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: \"line\",\n\t\t\t\txref: \"x\",\n\t\t\t\tyref:\"paper\",\n\t\t\t\tx0: harvestDate,\n\t\t\t\ty0: 0,\n\t\t\t\tx1: harvestDate,\n\t\t\t\ty1: 1.1,\n\t\t\t\tline: {width: 2}\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: \"rect\",\n\t\t\t\txref: \"paper\",\n\t\t\t\tyref:\"y2\",\n\t\t\t\tx0: 0,\n\t\t\t\ty0: 0,\n\t\t\t\tx1: 1,\n\t\t\t\ty1: 20,\n\t\t\t\tfillcolor: \"rgb(240, 240, 194)\",\n\t\t\t\topacity: 0.3,\n\t\t\t\tlayer: \"below\",\n\t\t\t\tline: {width: 0.1}\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: \"rect\",\n\t\t\t\txref: \"paper\",\n\t\t\t\tyref:\"y2\",\n\t\t\t\tx0: 0,\n\t\t\t\ty0: 20,\n\t\t\t\tx1: 1,\n\t\t\t\ty1: cnMax,\n\t\t\t\tfillcolor: \"rgb(240, 220, 220)\",\n\t\t\t\topacity: 0.3,\n\t\t\t\tlayer: \"below\",\n\t\t\t\tline: {width: 0.1}\n\t\t\t},\n\t\t];\n\n\t\tlet annotations = [\n\t\t\t{\n\t\t\t\tx: plantingDate,\n\t\t\t\ty: 1.06,\n\t\t\t\txref: \"x\",\n\t\t\t\tyref: \"paper\",\n\t\t\t\ttext: \" IN \",\n\t\t\t\tborderpad: 4,\n\t\t\t\tbgcolor: \"SlateGray\",\n\t\t\t\tshowarrow: false,\n\t\t\t\tfont: {\n\t\t\t\t\tsize: 14,\n\t\t\t\t\tcolor: \"White\"\n\t\t\t\t},\n\t\t\t\topacity: 0.8,\n\t\t\t\t// arrowhead: 3,\n\t\t\t\t// ax: -30,\n\t\t\t\t// ay: -40,\n\t\t\t\t//yanchor: \"top\",\n\t\t\t\txshift: -20\n\t\t\t},\n\t\t\t{\n\t\t\t\tx: harvestDate,\n\t\t\t\ty: 1.06,\n\t\t\t\txref: \"x\",\n\t\t\t\tyref: \"paper\",\n\t\t\t\ttext: \"OUT\",\n\t\t\t\tshowarrow: false,\n\t\t\t\tborderpad: 4,\n\t\t\t\tbgcolor: \"SlateGray\",\n\t\t\t\tfont: {\n\t\t\t\t\tsize: 14,\n\t\t\t\t\tcolor: \"White\"\n\t\t\t\t},\n\t\t\t\topacity: 0.8,\n\t\t\t\t// arrowhead: 3,\n\t\t\t\t// ax: -30,\n\t\t\t\t// ay: -40,\n\t\t\t\t//yanchor: \"top\",\n\t\t\t\txshift: -22\n\n\t\t\t},\n\t\t\t// {\n\t\t\t// \ttext: \"Immobilization Begins<sup>*</sup>\",\n\t\t\t// \tshowarrow: true,\n\t\t\t// \tx: 0.5,\n\t\t\t// \ty: 20.25,\n\t\t\t// \tvalign: \"top\",\n\t\t\t// \txref:\"paper\",\n\t\t\t// \tyref: \"y2\",\n\t\t\t// \t// borderwidth: 1,\n\t\t\t// \t// bordercolor: \"black\",\n\t\t\t// \t// hovertext: \"Termination of CR with a C:N ratio ranging from 0-20 has the potential to result in soil N mineralization <br>\" +\n\t\t\t// \t// \t\"Termination of CR with a C:N ratio ranging >20 has the potential to result in soil N immobilization\",\n\t\t\t// }\n\t\t];\n\n\t\tlet layout = {\n\t\t\ttitle: \"Cover Crop Growth & C:N Prediction\",\n\t\t\twidth: 930,\n\t\t\theight: 600,\n\t\t\t// responsive: true,\n\t\t\txaxis: {\n\t\t\t\trangeselector: selectorOptions,\n\t\t\t\trangeslider: {borderwidth: 1},\n\t\t\t\trange: [rangeSelectorMin, rangeSelectorMax],\n\t\t\t\tshowline: true,\n\t\t\t\tlinecolor: \"LightGray\",\n\t\t\t\tzeroline: true,\n\t\t\t\tticks: \"outside\"\n\t\t\t},\n\t\t\tyaxis: {\n\t\t\t\ttitle: {\n\t\t\t\t\ttext: \"Plant Biomass (lb/acre)\",\n\t\t\t\t\tfont: {\n\t\t\t\t\t\tcolor: \"DeepSkyBlue\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\ttickfont: {color: \"DeepSkyBlue\"},\n\t\t\t\tshowgrid: false,\n\t\t\t\tshowline: true,\n\t\t\t\tlinecolor: \"LightGray\",\n\t\t\t\tticks: \"outside\"\n\t\t\t\t// range: [0,5000],\n\t\t\t\t// rangemode: \"tozero\"\n\t\t\t},\n\t\t\tyaxis2: {\n\t\t\t\ttitle: {\n\t\t\t\t\ttext: \"C:N\",\n\t\t\t\t\tfont: {\n\t\t\t\t\t\tcolor: \"Orange\"\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\ttickfont: {color: \"Orange\"},\n\t\t\t\toverlaying: \"y\",\n\t\t\t\tside: \"right\",\n\t\t\t\tshowgrid: false,\n\t\t\t\tshowline: true,\n\t\t\t\tlinecolor: \"LightGray\",\n\t\t\t\tticks: \"outside\"\n\t\t\t},\n\t\t\tshapes: highlightShapes,\n\t\t\tannotations: annotations,\n\t\t\tlegend: {x:0.88, y: 1.40, borderwidth: 0.5}\n\t\t};\n\n\n\t\tresultHtml.push(\n\t\t\t\t\t<div >\n\t\t\t\t\t\t<Plot\n\t\t\t\t\t\t\tdata={data}\n\t\t\t\t\t\t\tlayout={layout}\n\t\t\t\t\t\t\tconfig={{\n\t\t\t\t\t\t\t\t\"displayModeBar\": false\n\t\t\t\t\t\t\t}}\n\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>);\n\n\t\treturn resultHtml;\n\t}", "function renderSingleTask(task) {\n $(\"#task-list\").append(taskTemplate(task));\n}" ]
[ "0.6817981", "0.6662202", "0.6630699", "0.65272075", "0.64862126", "0.624846", "0.6194933", "0.6166404", "0.6163558", "0.615988", "0.6149903", "0.6101587", "0.60888565", "0.60379153", "0.6008593", "0.5998947", "0.59807456", "0.59807456", "0.5971516", "0.5971319", "0.5955703", "0.5955347", "0.59497464", "0.59438914", "0.5935029", "0.59316826", "0.59108144", "0.5891357", "0.58903486", "0.58708656", "0.58637786", "0.5856707", "0.58485687", "0.58417475", "0.5840521", "0.58312774", "0.5829443", "0.5822507", "0.5814711", "0.5799864", "0.5796095", "0.579263", "0.57919854", "0.5791797", "0.5776357", "0.576348", "0.57571167", "0.5755827", "0.57516336", "0.5747161", "0.57431674", "0.57423437", "0.5733443", "0.57295847", "0.5727467", "0.5716483", "0.57159686", "0.5715183", "0.571035", "0.57093793", "0.5707644", "0.5693773", "0.5688951", "0.56865734", "0.56621575", "0.56588507", "0.5655831", "0.56521595", "0.5640844", "0.5639406", "0.5639275", "0.56384426", "0.56384426", "0.56384426", "0.56384426", "0.56384426", "0.56384426", "0.5636603", "0.5635182", "0.562559", "0.5624105", "0.5621481", "0.56117797", "0.5611274", "0.5610648", "0.56074834", "0.5605206", "0.5602124", "0.5600209", "0.5599096", "0.55965954", "0.55942", "0.5591476", "0.55903596", "0.55883974", "0.558617", "0.5575425", "0.5575014", "0.55690044", "0.5563914" ]
0.7537642
0
Registers a refresher to update the TaskChart.
registerRefresher() { this.clearRefresher(); this.taskinterval = setInterval(() => { this.refreshTaskChart(); }, 800); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "@action.bound refreshChart() {\n this.newChart();\n }", "function refreshChart() {\n ctrlChart.isLoading = true;\n // Update with the actual data.\n\n // Refresh electricity data.\n Electricity.refresh(FilterFactory.get('activeElectricityHash'));\n // Redraw the chart.\n render();\n }", "refreshMarket() {\n this.refresher();\n showNotification(__('Refreshing market data...'), 'success');\n }", "scheduleRefresh() {}", "scheduleRefresh() {}", "function updateCharts(){\n var uploadValues = vm.loadLineGraphUpload();\n if (vm.uploadHistogram) {\n vm.uploadHistogram.load({\n columns: [\n uploadValues[1]\n ]\n });\n }\n var downloadValues = vm.loadLineGraphDownload();\n if (vm.downloadHistogram) {\n vm.downloadHistogram.load({\n columns: [\n downloadValues[1]\n ]\n });\n }\n if (vm.barChart) {\n vm.barChart.load({\n columns: [\n [$filter('translate')('map.barChart.UNFILTERED_TESTS'), vm.markers.length],\n [$filter('translate')('map.barChart.TOTAL'), vm.markersOrig.length]\n ]\n });\n }\n if (vm.pieChart) {\n vm.pieChart.load({\n columns: [\n [$filter('translate')('map.pieChart.UNFILTERED'), pieChartData()],\n [$filter('translate')('map.pieChart.FILTERED'), 100 - pieChartData()]\n ]\n })\n }\n vm.refreshCharts = ! vm.refreshCharts;\n }", "updateChart () {\n \n }", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.create();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.create();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\r\n var infos = responseTimeVsRequestInfos;\r\n prepareSeries(infos.data);\r\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\r\n infos.createGraph();\r\n }else{\r\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\r\n createLegend(choiceContainer, infos);\r\n infos.createGraph();\r\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\r\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\r\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\r\n });\r\n }\r\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}", "function refreshResponseTimeVsRequest() {\n var infos = responseTimeVsRequestInfos;\n prepareSeries(infos.data);\n if (isGraph($(\"#flotResponseTimeVsRequest\"))){\n infos.createGraph();\n }else{\n var choiceContainer = $(\"#choicesResponseTimeVsRequest\");\n createLegend(choiceContainer, infos);\n infos.createGraph();\n setGraphZoomable(\"#flotResponseTimeVsRequest\", \"#overviewResponseTimeVsRequest\");\n $('#footerResponseRimeVsRequest .legendColorBox > div').each(function(i){\n $(this).clone().prependTo(choiceContainer.find(\"li\").eq(i));\n });\n }\n}" ]
[ "0.6577296", "0.5763539", "0.5738956", "0.55238926", "0.55238926", "0.55052876", "0.5476098", "0.54275936", "0.54275936", "0.54275936", "0.54275936", "0.54275936", "0.54275936", "0.54275936", "0.54275936", "0.54275936", "0.54275936", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.541637", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5413129", "0.5407916", "0.5407916", "0.5407916", "0.5407916", "0.5407916", "0.5407916", "0.5407916", "0.5407916", "0.5407916" ]
0.8037925
0
Removes the TaskChart Refresher.
clearRefresher() { if (this.taskinterval) { clearInterval(this.taskinterval); this.taskinterval = null; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function removeChart() {\n chart.destroy();\n }", "registerRefresher() {\n this.clearRefresher();\n this.taskinterval = setInterval(() => {\n this.refreshTaskChart();\n }, 800);\n }", "_destroyChart () {\n if (this.chart) {\n // TODO: remove events once they're implemented\n // if (this.chart.off) {\n // this.chart.off();\n // }\n delete this.chart;\n }\n }", "destroy() {\n clearInterval(this.poll);\n this.chart.destroy();\n }", "function removeData(chart, timeline) {\n chart.data.datasets[0].data = data_traffic_chart[timeline];\n chart.update();\n}", "disposeChart() {\n if (this.chart) {\n this.chart.dispose();\n this.chart = null;\n logger.debug(`ParticipantScore: disposed of chart - ${this.props.graphType}`);\n }\n }", "componentWillUnmount() {\r\n this.chart.destroy();\r\n }", "removeFigure(){\n\n this[figure] = null;\n }", "willDestroyElement() {\n this._super(...arguments);\n\n this.set('_chartsCanvas', null);\n }", "componentWillUnmount() {\n this.chart.destroy();\n }", "function removeOldChart() {\n var oldChart = document.getElementById('DB')\n if (oldChart != undefined) {\n var parent = oldChart.parentNode\n parent.removeChild(oldChart)\n }\n\n}", "function clearGraph() {\n if (interval) {\n clearInterval(interval)\n interval = null\n }\n if (chart) {\n chart.destroy()\n chart = null\n }\n}", "removeGraphData() {\n this.PieGraph.data.labels = [];\n this.PieGraph.data.datasets.forEach((dataset) => {\n dataset.data = [];\n });\n this.PieGraph.update();\n }", "function removeData(graph) {\n //Clears all datasets\n graph.data.datasets = [];\n\n //Updates the chart to display to changes\n graph.update();\n}", "componentWillUnmount() {\n this.state.charts.forEach( function (chart) {\n chart.ref.destroy();\n });\n }", "destroy() {\n if (this.ticking) {\n Ticker_1.Ticker.system.remove(this.tick, this);\n }\n this.ticking = false;\n this.addHooks = null;\n this.uploadHooks = null;\n this.renderer = null;\n this.completes = null;\n this.queue = null;\n this.limiter = null;\n this.uploadHookHelper = null;\n }", "onRemove() {\n if (this.div_) {\n this.div_.parentNode.removeChild(this.div_);\n this.div_ = null;\n }\n }", "function removePointInfo()\r\n{\r\n chartGroup.removeChild(currentNodeInfo);\r\n currentNodeInfo = null;\r\n}", "function ClearChart() {\n d3.select('svg').remove();\n}", "function DeleteCharts() {\n var chartDiv = document.getElementById('chart-div');\n chartDiv.innerHTML = '';\n}", "function unloadChartSpinner(chart) {\n var parent = chart.parentElement;\n var spinner = $(parent).find($(\".loading-spinner\"));\n $(spinner).fadeOut(\"fast\");\n $(chart).fadeIn(\"fast\");\n}", "_detach() {\n if (this._overlayRef && this._overlayRef.hasAttached()) {\n this._overlayRef.detach();\n }\n this._tooltipInstance = null;\n }", "_dispose() {\n\n delete window.FlowUI['_loaders'][this.id];\n\n }", "unMount() {\n this.removeListeners();\n SimpleBar.instances.delete(this.el);\n }", "onremove() {\n // Slider and binder\n if(this.binder)\n this.binder.destroy();\n if(this.slider)\n this.slider.destroy();\n\n // Destroy classes & objects\n this.binder = this.slider = this.publication = this.series = this.ui = this.config = null;\n }", "function removeData(chart) {\n chart.data.labels.shift();\n chart.data.datasets.forEach(function (dataset) {\n dataset.data.shift();\n });\n chart.update();\n }", "_onEndAnim() {\n if (this._overlay) {\n this._peer.getChart().getPlotArea().removeChild(this._overlay);\n this._overlay = null;\n }\n }", "unMount() {\n this.removeListeners();\n SimpleBar.instances.delete(this.el);\n }", "function remove() {\n\t\tif (graphContainer) {\n\t\t\t// Select the parent element because the graph container is a group (e.g. for zooming)\n\t\t\td3.select(graphContainer.node().parentNode).remove();\n\t\t}\n\t}", "function remove() {\n\t\tif (graphContainer) {\n\t\t\t// Select the parent element because the graph container is a group (e.g. for zooming)\n\t\t\td3.select(graphContainer.node().parentNode).remove();\n\t\t}\n\t}", "function removeTab(evt){ //accept either the span event object or the panel\n var $span = $(evt.target);\n var panelRef = $span.parent().children(\"a\").attr(\"href\");\n var panelId = panelRef.substr(1);\n destroyChartMap(panelId);\n $(panelRef).remove();\n $span.parent().remove();\n delete panelGraphs[panelId];\n $graphTabs.tabs('refresh'); //tell JQUI to sync up\n if($graphTabs.find(\"li\").length == 0){\n editingPanelId = null; //dissociate the chart from the this edit session\n $(\"#btnEditGraphTop\").attr(\"disabled\",\"disabled\");\n $(\"button.add-to-graph\").attr(\"disabled\",\"disabled\");\n lastTabAnchorClicked.click();\n } else {\n $('#graph-tabs a:last').click();\n }\n $(\"#graph_title\").attr('value','');\n}", "_removeStatsPusher() {\n if (this._statsPusher) {\n this._holdStatsTimer();\n clearInterval(this._statsPusher);\n this._statsPusher = null;\n }\n }", "clear() {\n var _a;\n if ((_a = this.canvas.flow) === null || _a === void 0 ? void 0 : _a.rootStep) {\n this.canvas.flow.rootStep.destroy(true, false);\n this.canvas.reRender();\n }\n }", "function destroyChart(chartCanvasId) {\n let chartStatus = Chart.getChart(chartCanvasId);\n if (chartStatus != undefined) {\n chartStatus.destroy();\n }\n }", "function removeData(chart) {\n let dataLength = chart.data.datasets[0].data.length;\n for(let i = 0; i < dataLength; i++){\n chart.data.datasets[0].data.pop();\n chart.data.labels.pop();\n }\n chart.update();\n}", "function deleteTask() {\n this.parentNode.parentNode.removeChild(this.parentNode);\n }", "removeCanvas() {\n const lastEntry = this.canvases.pop();\n lastEntry.wave.parentElement.removeChild(lastEntry.wave);\n lastEntry.patientWave.parentElement.removeChild(lastEntry.patientWave);\n lastEntry.times.parentElement.removeChild(lastEntry.times);\n if (this.hasProgressCanvas) {\n lastEntry.progress.parentElement.removeChild(lastEntry.progress);\n lastEntry.patientProgress.parentElement.removeChild(\n lastEntry.patientProgress\n );\n }\n }", "removeOnProgressListener(callback) {\n this.removeListener(FILE_TRANSFER_PROGRESS, callback);\n }", "remove() {\n this.target.removeListener(this.event, this.callback, {\n context: this.context,\n remaining: this.remaining\n });\n }", "_removeCallback() {\n this._renderCallback()\n this._viewer.dcContainer.removeChild(this._delegate)\n this._state = DC.LayerState.REMOVED\n }", "unregister(d) {\n const index = this._disposables.indexOf(d);\n if (index !== -1) {\n this._disposables.splice(index, 1);\n }\n }", "function clearTask(creep)\n{\n creep.memory.lockedTask = null;\n setTask(creep, null); \n}", "function clearTask(creep)\n{\n creep.memory.lockedTask = null;\n setTask(creep, null); \n}", "detach() {\n\t\tif (this.panel) {\n\t\t\tthis.panel.destroy();\n\t\t}\n\t}", "function onSeriesClear() {\n var $thisSeries = this;\n var $thisChart = $thisSeries.ChartProvider;\n var $thisSpecter = $thisChart.Parent;\n\n if (isDefined($thisSeries.onClear)) {\n $thisSeries.onClear();\n }\n\n $thisChart = $thisSpecter.getChart($thisChart.Name);\n delete $thisChart.Selected;\n $thisChart.InDrillMode = false;\n\n\n if (isDefined($thisSeries.DrillItem)) {\n //clear the drillitems Selected values \n\n var drillChart = $thisSpecter.getChart($thisSeries.DrillItem.Name);\n drillChart.CanRender = false;\n if (isDefined(drillChart.Selected)) {\n var currSeries;\n $.each(drillChart.Selected, function (i, sItem) {\n if (currSeries != sItem.$series) {\n currSeries = sItem.$series;\n currSeries.Clear();\n }\n });\n }\n\n $thisSpecter.RemoveFilter($thisSeries.DrillItem.Name);\n }\n\n $thisChart.Render();\n $thisSpecter.RemoveFilter($thisChart.Name);\n\n $.each($thisSeries.LinkedItems, function (index, item) {\n switch (item.Type) {\n case \"Chart\":\n var chart = $thisSpecter.getChart(item.Name);\n if (item.Action == \"SLICE\") {\n if (isDefined(item.Parameters)) {\n $.each(item.Parameters, function (i, parameter) {\n var targetchartprm = findAndGetObj(chart.Parameters, \"Name\", parameter.Name)\n delete targetchartprm.Value;\n });\n }\n if (isUndefined(chart.CanRender) || chart.CanRender == true) {\n chart.Render();\n }\n }\n else if (item.Action == \"SELECT\") {\n\n }\n else if (item.Action == \"RENDER\") {\n if (isUndefined(chart.CanRender) || chart.CanRender == true) {\n chart.Render();\n }\n }\n\n break;\n case \"Slicer\":\n var slicer = $thisSpecter.getSlicer(item.Name);\n if (isUndefined(slicer.CanRender) || slicer.CanRender == true) {\n if (item.Action == \"SLICE\") {\n $.each(item.Parameters, function (i, parameter) {\n var targetchartprm = findAndGetObj(slicer.Parameters, \"Name\", parameter.Name)\n if (isDefined(targetchartprm))\n delete targetchartprm.Value;\n });\n slicer.Render();\n }\n else if (item.Action == \"SELECT\") {\n //since it is triggered by chart event will be undefined\n slicer.Clear();\n }\n }\n break;\n case \"RangePicker\":\n var range = $thisSpecter.getRangePicker(item.Name);\n if (isUndefined(range.CanRender) || range.CanRender == true) {\n if (item.Action == \"SLICE\") {\n $.each(item.Parameters, function (i, parameter) {\n var targetchartprm = findAndGetObj(range.Parameters, \"Name\", parameter.Name)\n if (isDefined(targetchartprm))\n delete targetchartprm.Value;\n });\n range.Render();\n }\n else if (item.Action == \"SELECT\") {\n //since it is triggered by chart event will be undefined\n range.Clear();\n }\n }\n break;\n }\n\n });\n}", "function removeParent() {\n this.removeEventListener(\"click\", removeParent, false);\n const index = Object.keys(dataSet).indexOf(this.id);\n delete dataSet[this.id];\n myBarchart.colors.splice(index, 1);\n this.parentNode.remove();\n $('span[draggable=\"true\"]').eq(index).remove();\n for(let index of myBarchart.colors.keys()) {\n dragger[index].setAttribute(\"color-id\", index);\n }\n freshCanvas();\n myBarchart.draw();\n}", "remove() {\n if (this.div) {\n this.div.parentNode.removeChild(this.div);\n this.div = null;\n }\n }", "delete() {\n clearInterval(this.watcher);\n this.elem.innerHTML = \"\";\n this.object = null;\n this.parent = null;\n }", "remove() { this.tooltip.remove(); this.element.remove(); }", "function registerDestroyListener() {\n $scope.$on('$destroy', function () {\n chartService.destroyChart(configuration);\n $element.remove();\n });\n }", "dispose() {\n this._renderer = null;\n clearTimeout(this._refreshId);\n super.dispose();\n }", "function removeExplosao() {\n\t\t\tdiv.remove();\n\t\t\twindow.clearInterval(tempoExplosao);\n\t\t\ttempoExplosao=null;\n\t\t}", "function clearChart() {\n localStorage.removeItem('results');\n $('#highscore-chart').innerHTML = '';\n}", "destroy() {\n if (cycles.has(this)) {\n clearTimeout(cycles.get(this))\n }\n }", "componentWillUnmount() {\n this.disposeChart();\n }", "destroy() {\n this.remove(this.callback);\n }", "_revert() {\n this.get('_chart').revert();\n }", "$onDestroy() {\n this.tlc_.unlisten(TimelineEventType.SHOW, this.update_, false, this);\n this.scope_ = null;\n this.element_ = null;\n }", "function destroy() {\n // remove protected internal listeners\n removeEvent(INTERNAL_EVENT_NS.aria);\n removeEvent(INTERNAL_EVENT_NS.tooltips);\n Object.keys(options.cssClasses).forEach(function (key) {\n removeClass(scope_Target, options.cssClasses[key]);\n });\n while (scope_Target.firstChild) {\n scope_Target.removeChild(scope_Target.firstChild);\n }\n delete scope_Target.noUiSlider;\n }", "removeSelf(){\n this.destroy();\n }", "teardown () {\n if (this.active) {\n // remove self from gm's watcher list\n // this is a somewhat expensive operation so we skip it\n // if the gm is being destroyed.\n if (!this.gm._isBeingDestroyed) {\n remove(this.gm._watchers, this)\n }\n let i = this.deps.length\n while (i--) {\n this.deps[i].removeSub(this)\n }\n this.active = false\n }\n }", "remove(overlayRef) {\n const index = this._attachedOverlays.indexOf(overlayRef);\n if (index > -1) {\n this._attachedOverlays.splice(index, 1);\n }\n // Remove the global listener once there are no more overlays.\n if (this._attachedOverlays.length === 0) {\n this.detach();\n }\n }", "remove(overlayRef) {\n const index = this._attachedOverlays.indexOf(overlayRef);\n if (index > -1) {\n this._attachedOverlays.splice(index, 1);\n }\n // Remove the global listener once there are no more overlays.\n if (this._attachedOverlays.length === 0) {\n this.detach();\n }\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if (!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "detach() {\n this._scrolledIndexChange.complete();\n this._viewport = null;\n }", "detach() {\n this._scrolledIndexChange.complete();\n this._viewport = null;\n }", "destroy() {\n this.eventTracker.removeAll();\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if (!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if (!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "onRemove() {\n if (this.div_ && this.div_.parentNode) {\n this.hide();\n this.div_.parentNode.removeChild(this.div_);\n this.div_ = null;\n }\n }", "remove() {\n this.target.removeEventListener(this.eventType, this.fn, false);\n }", "function remove()\n{\n // Stop any timers to prevent CPU usage\n // Remove any preferences as needed\n // widget.setPreferenceForKey(null, dashcode.createInstancePreferenceKey(\"your-key\"));\n}", "function remove()\n{\n // Stop any timers to prevent CPU usage\n // Remove any preferences as needed\n // widget.setPreferenceForKey(null, dashcode.createInstancePreferenceKey(\"your-key\"));\n}", "destroy () {\n\t\tthis.options.element.removeEventListener('click', this.onClickToElement);\n\t\tthis.options.element.removeChild(this.options.element.querySelector('.pollsr'));\n\t}", "function detach() {\n\t // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n\t // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n\t if(!this.initializeTimeoutId) {\n\t window.removeEventListener('resize', this.resizeListener);\n\t this.optionsProvider.removeMediaQueryListeners();\n\t } else {\n\t window.clearTimeout(this.initializeTimeoutId);\n\t }\n\t\n\t return this;\n\t }", "detach() {\n this._scrolledIndexChange.complete();\n\n this._viewport = null;\n }", "reset() {\n this.dataset = [];\n this.svg.selectAll(\"circle\").remove();\n this.svg.selectAll(\"g\").remove();\n $(\"#metrics\").removeClass(\"visible\").addClass(\"invisible\");\n }", "remove() {\n this.value = this.getContext().remove();\n }", "function clear_chart(chart_ctx, chart_canvas) {\n chart_ctx.clearRect(0, 0, chart_canvas.width, chart_canvas.height);\n}", "function deleteTask() {\n this.parentNode.parentNode.removeChild(this.parentNode);\n}", "function remove()\n{\n // Stop any timers to prevent CPU usage\n // Remove any preferences as needed\n // widget.setPreferenceForKey(null, createInstancePreferenceKey(\"your-key\"));\n}", "disposed() {\n\t\tif (isServerSide()) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._internalPollingInterval) {\n\t\t\tclearInterval(this._internalPollingInterval);\n\t\t\tthis._internalPollingInterval = null;\n\t\t}\n\n\t\tif (this.svg) {\n\t\t\tthis.svg.remove();\n\t\t}\n\t}", "function remove()\n{\n // Stop any timers to prevent CPU usage\n\t\n // Remove preferences\n widget.setPreferenceForKey(null, createInstancePreferenceKey('url'));\n widget.setPreferenceForKey(null, createInstancePreferenceKey('username'));\n}", "removeTickerFunc()\n {\n this.pixiApp.ticker.remove(this.tickerFunc);\n }", "remove () {\r\n\t\tvar svg = d3.select(this.element);\r\n\t\tsvg.selectAll('*').remove();\r\n\t}", "destroy()\n {\n this.renderer = null;\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if(!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if(!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if(!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if(!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if(!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "function detach() {\n // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore\n // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout\n if(!this.initializeTimeoutId) {\n window.removeEventListener('resize', this.resizeListener);\n this.optionsProvider.removeMediaQueryListeners();\n } else {\n window.clearTimeout(this.initializeTimeoutId);\n }\n\n return this;\n }", "remove_stdev_series(chart) {\n if (\n chart.stdev_up_series != undefined &&\n chart.stdev_down_series != undefined\n )\n chart.ref.removeSeries(chart.stdev_up_series);\n chart.ref.removeSeries(chart.stdev_down_series);\n chart.stdev_up_series = undefined;\n chart.stdev_down_series = undefined;\n }", "deleteCanvas() {\n this.canvas.remove();\n }", "detach() {\n const that = this;\n that._removeEventListeners();\n }", "removeData(id) {\n let current = this.head\n let previous = null\n\n // If the task to be removed is head, then remove it directly\n // else, iterate through the list and find the particular task to be removed.\n if (current.data.id === id) {\n // Update subsequent task to 'in_progress' if the current task to be removed is also 'in_progress'\n if (current.next && current.data.status === STATUS_INPROGRESS) {\n current.next.data.status = STATUS_INPROGRESS\n }\n this.head = current.next\n } else {\n while (current && previous === null) {\n if (current.next.data.id === id) {\n previous = current\n }\n current = current.next\n }\n if (current.next && current.data.status === STATUS_INPROGRESS) {\n current.next.data.status = STATUS_INPROGRESS\n }\n previous.next = current.next\n }\n\n this.size--\n }", "destroy() {\n //this.unobserve(this.slider.selector);\n this.unobserve(window);\n const tx = document.documentElement;\n tx.removeEventListener(\"pointermove\", this.onpointermove);\n tx.removeEventListener(\"mousemove\", this.mousemoveUpdater);\n /*this.slider.selector.removeEventListener(\"touchend\", this.mtimerUpdater);\n this.slider.selector.removeEventListener(\"mouseup\", this.mtimerUpdater);\n this.slider.selector.removeEventListener(\"mousedown\", this.mtimerUpdater);\n this.slider.selector.removeEventListener(\"mousemove\", this.mousemoveHandler);*/\n\n this.coordinator = null;\n }", "delete() {\n this.removeAllConnections()\n \n let parent = this.getParent()\n let diagram = this.getDiagram()\n \n if (parent) {\n parent.removeChild(this)\n } else {\n diagram.removePane(this)\n }\n \n this.redrawAllConnectionsInDiagram()\n }", "function remove()\n{\n // Stop any timers to prevent CPU usage\n // Remove any preferences as needed\n // widget.setPreferenceForKey(null, dashcode.createInstancePreferenceKey(\"your-key\"));\n\n // widget.setPreferenceForKey(null, dashcode.createInstancePreferenceKey(PREF_KEY_NAME));\n widget.setPreferenceForKey(null, PREF_KEY_NAME);\n}", "destroy () {\n console.log('IntegrationAgent.destroy:', this.integration._id);\n let self = this;\n \n // Shut down the change observer\n self.observer.stop();\n \n // Remove the HealthTracker data\n HealthTracker.remove(self.trackerKey);\n \n // Remove the cron job to check status & cache\n if (Clustering.isMaster()) {\n SyncedCron.remove(self.trackerKey);\n self.updateQueryJobKeys.forEach((jobKey) => {\n SyncedCron.remove(jobKey);\n });\n }\n }" ]
[ "0.6907121", "0.64784753", "0.6354735", "0.63445723", "0.58928794", "0.5878664", "0.5799613", "0.57671416", "0.5760118", "0.5749632", "0.5739396", "0.573142", "0.5695605", "0.56889904", "0.56596625", "0.56160873", "0.56099874", "0.56058615", "0.55969024", "0.55946594", "0.5585045", "0.55563295", "0.55558175", "0.55546516", "0.5549153", "0.55257696", "0.55160886", "0.5514039", "0.5506074", "0.5506074", "0.55035776", "0.54879636", "0.54865205", "0.54816973", "0.54788166", "0.5475545", "0.5461912", "0.5453459", "0.54507387", "0.54449344", "0.5429701", "0.5421339", "0.5421339", "0.54211235", "0.5416952", "0.5406792", "0.5399658", "0.5398961", "0.5390822", "0.5380995", "0.5377535", "0.53706276", "0.53650665", "0.5361161", "0.5357441", "0.5345206", "0.53426665", "0.5336888", "0.5334938", "0.5321379", "0.53135806", "0.5303909", "0.5303909", "0.52723736", "0.5266573", "0.5266573", "0.525404", "0.52489775", "0.52489775", "0.5248899", "0.52471226", "0.52467763", "0.52467763", "0.5238731", "0.5232042", "0.5228469", "0.52243346", "0.52153355", "0.5211395", "0.5210141", "0.52063274", "0.5205889", "0.5203899", "0.52003205", "0.51983434", "0.5197814", "0.51946133", "0.51946133", "0.51946133", "0.51946133", "0.51946133", "0.51946133", "0.5194185", "0.5193244", "0.5192756", "0.5190594", "0.51838964", "0.5181207", "0.5180614", "0.5180062" ]
0.73217994
0
Called when all cell execution is completed and all jobs have completed.
onAllCompleted() { this.clearRefresher(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function handleFinish(values) {\n job.current = getJob(values, job.current, writeMessage);\n setBusy(job.current.pendingTime);\n }", "_onComplete() {\n // Ensure worker queues for all paths are stopped at the end of the query\n this.stop();\n }", "function allDone() {\n pub.stop();\n console.info('Alle Tests beendet.');\n console.info(app.persistence.getResults());\n $(document).trigger('testQueueDone');\n }", "runToComplete() {\n // Clock tick\n this.clock++;\n // Update the actual browser (Jobs Table, \"CPU\" section, \"Ready Queue\" section, \"Average\" section, and Gantt Chart)\n this.updater.update_table();\n this.updater.update_page();\n\n // Run all the CPUs on clock tick\n for (var i = 0; i < this.cpus.length; i++) {\n var cpu = this.cpus[i];\n switch (this.schedulerAlgo) {\n case \"FCFS\":\n cpu.runFCFS();\n break;\n case \"SJF\":\n cpu.runSJF();\n break;\n case \"SRTF\":\n cpu.runSRTF();\n break;\n case \"RR\":\n cpu.runRR();\n break;\n case \"PNP\":\n cpu.runPNP();\n break;\n case \"PP\":\n cpu.runPP();\n break;\n default:\n // Default is FCFS\n cpu.runFCFS();\n }\n }\n\n if (!this.ended) {\n this.runToComplete();\n }\n }", "function AllDone(){\n \n}", "_finished( ) { \n\n\t\tif( this.verbose ) { this.log( \"All stages finished.\" ); }\n\n\t\tif( this.rollback ) {\n\t\t\tif( this.verbose ) { this.log( \"Processing failed.\" ); }\n\t\t\tthis.callback.failure( \"failed because of stage \\\"\" + this.failed + \"\\\"\" );\n\t\t} else {\n\t\t\tif( this.verbose ) { this.log( \"Processing succeeded.\" ); }\n\t\t\tthis.callback.success( this.results ); \n\t\t}\n\t\t\n\t}", "_jobOver() {\n this._nbJobsRunning--;\n if (this._nbJobsRunning == 0) {\n this.emit('all-done');\n this._holdStatsTimer();\n }\n this._nbJobsCompleted++;\n this._worker();\n }", "onSparkJobEnd(data) {\n this.addJobData(data.jobId, new Date(data.completionTime), 'ended');\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function onAllFinished() {\n //we're finished crawling so we set the endtime to the current time and still crawling to false\n endTime = new Date().getTime();\n stillCrawling = false;\n //clear the console for final output since stillCrawling is now false reportCrawling will not write again\n console.clear();\n //output how many urls wer crawld and how long it took\n console.log(`Finished crawling ${crawler.crawledUrls.length} urls in ${(endTime - startTime) / 1000} seconds\\n`);\n //if pages have been added to errorPages we will print them\n if (errorPages.length > 0) {\n console.log('The Following Pages Had Errors:');\n printErrors();\n } \n //else we congratulate the user\n else {\n console.log('Congratulations There Were No Errors!');\n }\n}", "function complete() {\n\tconsole.log('Completed');\n}", "function allDone(){\n\t\tinitCalculator(currenciesData,feesData,userData);\n\t}", "function successCb(){\n\t\t\t\tdbm.updateJobFinish(uuid, function(err, rows, fields){\n\t\t\t\t\tif(err) log.error('update status error:', err);\n\t\t\t\t\tdelete jobpool[uuid];\n\t\t\t\t})\n\t\t\t}", "onBatchEnd() {\n this.logEventBatch(this.batchedEvents);\n const changeEvts = this.batchedEvents.filter((event) => event.isTreeChange);\n // TODO this is a bit spaghetti-ish, we should probably\n // have an event that fires and is listened to. This code shouldn't\n // know about the node tree.\n window.nodeTree.processTreeChanges(changeEvts);\n this.batchedEvents = [];\n }", "function _onAllFilesProcessed()\n {\n process.exit(0);\n }", "function finishProcess(){\n self.updateBars(callback);\n }", "function async_completed() {\n\tasync_completions += 1;\n\tD.log(\"completions: \" + async_completions + \" out of \" + async_completions_waiting);\n\tif ( async_completions == async_completions_waiting ) {\n\t completion();\n\t}\n }", "function complete()\n\t{\n\t\t_queryInProgress = false;\n\t\t_dispatcher.trigger(_options.completeEvent);\n\t}", "function completelyDone() {\n _rdbConn.close();\n console.log(\"ALL DONE\");\n}", "workFinishCall() {\n\t\t// all nodes have been downloaded\n if (this.finishCount === this.worklist.length) {\n this.state = 'finish'\n this.finishDate = utils.formatDate()\n userTasks.splice(userTasks.indexOf(this), 1)\n finishTasks.unshift(this)\n clearInterval(this.countSpeed)\n sendMessage()\n this.recordInfor(`${this.name} 下载完成`)\n this.finishStore()\n } else {\n\t\t\t// running next\n this.updateStore()\n this.downloadSchedule()\n }\n }", "function finished(err){\n }", "finishAll() {\n let model = []\n // Stop all the agents\n Object.values(this.agents).forEach(agent => {\n //agent.stop();\n model = agent.model;\n this.unregister(agent);\n });\n //Execute the callback\n if (this.callbacks.onFinish)\n // pasa las acciones que se hicieron y la data\n this.callbacks.onFinish({ actions: this.getActions(), data: this.data, model});\n }", "function end() {\n stopProgressInfo();\n cancelAllJobs();\n if (fromDate) {\n clock.uninstall();\n }\n if (!isEnded) {\n isEnded = true;\n emitEnd();\n }\n}", "async onBatchEnd(batch, logs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onBatchEnd(batch, logs);\n }\n }", "_onFinishedEvent() {\n this._finished += 1;\n\n if (this._finished === this._babylonNumAnimations) {\n this._looped = 0;\n this._finished = 0;\n\n // Pause the animations\n this._babylonAnimatables.forEach(animatable => {\n animatable.speedRatio = 0;\n });\n\n this._promises.play.resolve();\n\n // Stop evaluating interpolators if they have already completed\n if (!this.weightPending && !this.timeScalePending) {\n this._paused = true;\n }\n }\n }", "function finalizeJobs() {\n getCompletedJobs().then(function (jobs) {\n var Job = mongoose.model('Job');\n var ReportLog = mongoose.model('ReportLog');\n jobs.forEach(function (job) {\n var current=job.current;\n var modDate = new Date();\n\n Job.findOneAndUpdate({ '_id' : new mongoose.Types.ObjectId(job._id) }, { current:current ,modified: modDate, status: 'F' }, function(err, updatedJob) {\n if(err)\n console.error('Error updating job -> ', err);\n else {\n //creating jobLog\n createJobLogs(updatedJob, current);\n\n completeDurationLogs(job._id);\n }\n });\n });\n });\n }", "function bridjeActionExecutionComplete()\n{\n initBridjeActionElements();\n window.bootstrapActionExecutionComplete && bootstrapActionExecutionComplete();\n}", "function onFinish() {\n console.log('finished!');\n}", "function complete() {\n // Play the animation and audio effect after task completion.\n\n setProperty(\"isComplete\", true);\n\n // Set distanceProgress to be at most the distance for the mission, subtract the difference from the offset.\n if (getProperty(\"missionType\") === \"audit\") {\n var distanceOver = getProperty(\"distanceProgress\") - getProperty(\"distance\");\n var oldOffset = svl.missionContainer.getTasksMissionsOffset();\n var newOffset = oldOffset - distanceOver;\n svl.missionContainer.setTasksMissionsOffset(newOffset);\n }\n\n // Reset the label counter\n if ('labelCounter' in svl) {\n labelCountsAtCompletion = {\n \"CurbRamp\": svl.labelCounter.countLabel(\"CurbRamp\"),\n \"NoCurbRamp\": svl.labelCounter.countLabel(\"NoCurbRamp\"),\n \"Obstacle\": svl.labelCounter.countLabel(\"Obstacle\"),\n \"SurfaceProblem\": svl.labelCounter.countLabel(\"SurfaceProblem\"),\n \"NoSidewalk\": svl.labelCounter.countLabel(\"NoSidewalk\"),\n \"Other\": svl.labelCounter.countLabel(\"Other\")\n };\n svl.labelCounter.reset();\n }\n\n if (!svl.isOnboarding()){\n svl.storage.set('completedFirstMission', true);\n }\n }", "static _handle_action_complete_triggers() {\n\n // run queued trigger functions\n while (!Actor._action_complete_trigger_queue.is_empty())\n Actor._action_complete_trigger_queue.out()();\n }", "function onCompletion(err) {\n if (err) { return console.error(err);}\n else { console.log(\"All done.\") }\n}", "onRunComplete(browsers, results) {\n\n }", "_onTasksDone() {\n // meant to be implemented by subclass if needed\n }", "function run() {\n //setup new jobs if any\n setupNewJobs();\n\n //process all other active jobs\n processJobs();\n\n //finalize completed jobs\n finalizeJobs();\n }", "complete(results, file) {\n const bytesUsed = results.meta.cursor;\n // Ensure any final (partial) batch gets emitted\n const batch = tableBatchBuilder.getBatch({bytesUsed});\n if (batch) {\n asyncQueue.enqueue(batch);\n }\n asyncQueue.close();\n }", "complete() {\n if (!this.caching) return;\n debug('complete');\n this[internal].cachedHeight = null;\n this[internal].updateCachedHeight();\n }", "function onProcessFinal() {\n chai_1.expect(loopResult, 'LoopResult should contain 10').to.contain(10);\n chai_1.expect(loopResult, 'LoopResult should contain 5').to.contain(5);\n chai_1.expect(loopResult, 'LoopResult should contain 1').to.contain(1);\n done();\n }", "function onFinished(notAborted, arr) {\n Machine.find(function(err, instances){\n console.log(\"Done with importing!\");\n });\n }", "async onFinished() {}", "function done() {\n \tvar storage = config.storage;\n\n \tProcessingQueue.finished = true;\n\n \tvar runtime = now() - config.started;\n \tvar passed = config.stats.all - config.stats.bad;\n\n \temit(\"runEnd\", globalSuite.end(true));\n \trunLoggingCallbacks(\"done\", {\n \t\tpassed: passed,\n \t\tfailed: config.stats.bad,\n \t\ttotal: config.stats.all,\n \t\truntime: runtime\n \t});\n\n \t// Clear own storage items if all tests passed\n \tif (storage && config.stats.bad === 0) {\n \t\tfor (var i = storage.length - 1; i >= 0; i--) {\n \t\t\tvar key = storage.key(i);\n\n \t\t\tif (key.indexOf(\"qunit-test-\") === 0) {\n \t\t\t\tstorage.removeItem(key);\n \t\t\t}\n \t\t}\n \t}\n }", "function runAllJobs () {\n\n\t// Print time of jobs\n\tLog.log('Running all jobs at '+Date()+'...')\n\n\tasync.waterfall([\n\n\t\t// Update inventory\n\t\tfunction (callback) {\n\t\t\tupdateInventory(function (err) {\n\t\t\t\tcallback(err);\n\t\t\t})\n\t\t},\n\n\t\t// Get orders\n\t\tfunction (callback) {\n\t\t\tgetOrders(function (err) {\n\t\t\t\tcallback(err);\n\t\t\t})\n\t\t},\n\n\t\t// Update Shipments\n\t\tfunction (callback) {\n\t\t\tupdateShipments(function (err) {\n\t\t\t\tcallback(err);\n\t\t\t});\n\t\t},\n\n\t\t// Capture orders\n\t\tfunction (callback) {\n\t\t\tcaptureShippedOrders(function (err) {\n\t\t\t\tcallback(err);\n\t\t\t})\n\t\t},\n\n\t], function (err) {\n\n\t\t// Log error\n\t if (err) {\n\t\t\tLog.log(err);\n\t\t\tif (!config.debug) Raven.captureException(err);\n\t\t}\n\n\t\t// Email logs\n\t\temailLogs();\n\t});\n}", "function finishedProcess(){\n console.log('xxxxxxxxxxxxxxxxxxxx process manually terminated xxxxxxxxxxxxxxxxxxxxxx')\n printTotals();\n clearInterval(pound.statusUpdateIntervalId);\n process.exit();\n }", "_onEnd() {}", "function finishPendingActions() {\n if (grid.api) {\n grid.api.grid.refresh();\n }\n }", "_done() {\n this.worker = this.task = -1;\n this.callbacks = []; this.callback = 0;\n }", "handleRunnerCompletion () {\n console.log(this.#statusOutput) // tests that failed\n\n this.emit('completion')\n const { completed, failed, success, expectedFailures, skipped } = this.#stats\n console.log(\n `[${this.#folderName}]: ` +\n `Completed: ${completed}, failed: ${failed}, success: ${success}, ` +\n `expected failures: ${expectedFailures}, ` +\n `unexpected failures: ${failed - expectedFailures}, ` +\n `skipped: ${skipped}`\n )\n\n process.exit(0)\n }", "endAll() {\n this.animations.forEach((anim) => anim.onEnd());\n this.animations = [];\n }", "function finishAllAnimations() {\n runningAnimations.forEach(function (animation) {\n animation.finishNow();\n });\n clearTimeout(fadeInTimer);\n clearTimeout(animateHeightTimer);\n clearTimeout(animationsCompleteTimer);\n runningAnimations.length = 0;\n }", "onEnd() {\n\t\tthis.debug('onEnd');\n\t}", "done() {\n assert_equals(this._state, TaskState.STARTED)\n this._state = TaskState.FINISHED;\n\n let message = '< [' + this._label + '] ';\n\n if (this._result) {\n message += 'All assertions passed. (total ' + this._totalAssertions +\n ' assertions)';\n _logPassed(message);\n } else {\n message += this._failedAssertions + ' out of ' + this._totalAssertions +\n ' assertions were failed.'\n _logFailed(message);\n }\n\n this._resolve();\n }", "finishProcessing() {\n this.busy = false;\n this.successful = true;\n }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "function testComplete() {\n process.nextTick(function() {\n if (testQueue.length > 0) {\n testQueue.shift()();\n }\n else {\n t.equal(async, expectAsync, \"captured all expected async callbacks\");\n t.equal(testQueue.length, 0, \"all tests have been processed\");\n }\n });\n }", "function finished(result) {\n\t\t\t--self.evaluating;\n\t\t\tself.off('Error', captureError);\n\t\t\tif (callback) callback(err, result);\n\t\t}", "signalComplete() {\n this.observableFunctions.complete();\n }", "function loadComplete() {\n cnt--;\n if (!cnt) {\n execComplete();\n }\n }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "async onTrainEnd(logs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onTrainEnd(logs);\n }\n }", "_complete() {\n this.wrapperEl.addClass(this.options.classes.completed);\n this.element.addClass(this.options.classes.completed);\n this.element.trigger(SnapPuzzleEvents.complete, this);\n }", "completed(data) {}", "_taskComplete() {\n //\n }", "function final() { console.log('Done and Final'); process.exit() ; }", "end() {\n this.status = 'finished';\n }", "function manageExecutionCompletion(rec) {\r\n\r\n deleteWopoDataRecord(rec);\r\n sendEmailOfExecutionCompletion(rec);\r\n}", "function onJobEnded (message) {\r\n let job = findJobById(message.data.jobId);\r\n if (job) {\r\n console.log('job ended', job.id, message.data.exitCode);\r\n job.ended(message.data.exitCode);\r\n }\r\n\r\n // Start a job if below the concurrent jobs limit.\r\n let activeJobCount = countActiveJobs();\r\n if (activeJobCount < settings.concurrentJobsLimit) {\r\n job = findNextWaitingJob();\r\n if (job) {\r\n job.create();\r\n }\r\n }\r\n\r\n // Disconnect the port if there are no jobs.\r\n if (!job && (activeJobCount === 0)) {\r\n console.log('no jobs - disconnecting native-app');\r\n state.port.disconnect();\r\n state.port = null;\r\n\r\n // Make the icon dark because the queue is idle.\r\n browser.browserAction.setIcon({\r\n path: null\r\n });\r\n }\r\n}", "async end(job, success, results) {\n // context object gets an update to avoid a\n // race condition with checkStopped\n job.ended = true;\n return self.db.updateOne({ _id: job._id }, {\n $set: {\n ended: true,\n status: success ? 'completed' : 'failed',\n results: results\n }\n });\n }", "function tryOnComplete() {\n if (numCallbacks == numComplete && allCallbacksCreated) {\n onComplete();\n }\n }", "onFinish() {\n\t\tif (this.props.onFinish) {\n\t\t\tthis.props.onFinish();\n\t\t}\n\t}", "complete() {}", "function timerComplete () {\n\t\tcurrentStack = [];\n\t\ttimer = undefined;\n\t}", "onSparkTaskEnd(data) {\n this.addData(data.finishTime, this.numActiveTasks);\n this.numActiveTasks -= 1;\n this.addData(data.finishTime, this.numActiveTasks);\n }", "function finished() {\n var title = options.title + (status === 'ok' ? ' Passed' : ' Failed');\n exports._INTERNAL.notify({\n 'icon' : icons[status],\n 'title' : title,\n 'message' : lastLine\n });\n\n if (done) {\n done(status);\n } else {\n process.exit(status === 'error' ? 2 : 0);\n }\n }", "function suiteDone() {\n _scenariooReporter.default.useCaseEnded(options);\n }", "onFinish() {}", "complete() {\n\n if (!this._running) return;\n this._running = false;\n\n // get sure all measures are completed\n this.completeMeasure();\n\n let values = [];\n\n for (let profile of this._profiles) {\n values.push(profile.elapsed);\n }\n\n // Build report data\n this._data = {\n 'name': this._name,\n 'entries': this._profiles.length,\n 'median': Util.median(values),\n 'max': values[0],\n 'min': values[values.length - 1]\n };\n\n this.dispatch();\n }", "finish() {\n this.done = true;\n }", "function handleComplete(size, status, index) {\n console.log(\"completed\");\n drawProgress(1, status);\n }", "runOnTaskFinishedHandlers(item) {\n this.onTaskFinishedHandlers.forEach(handler => {\n handler(item, this);\n });\n }", "function all_done() {\n console.log('\\n------------------------------------------ All Done ------------------------------------------\\n');\n broadcast_state('registered_owners');\n process.env.app_first_setup = 'no';\n\n logger.debug('hash is', helper.getHash());\n helper.write({ hash: helper.getHash() });\t\t\t\t\t\t\t//write state file so we know we started before\n ws_server.check_for_updates(null);\t\t\t\t\t\t\t\t//call the periodic task to get the state of everything\n}", "writeCells(args) {\n\t\targs.done();\n\t}", "function onCalcComplete()\n\t{\n\t\t////////////////////////////////\n\t\t//Display Results\n\t\t////////////////////////////////\n\t\t\n\t\t//The data on the map screen.\n\t\tsetImpactValues(dataProvider.getDgOutputs());\n\t\t\n\t\t//The inputValues\n\t\tsetInputValues(dataProvider.getDgInputs());\n\t\t\n\t\t//The damage table\n\t\tsetDamage(dataProvider.getTxtDamage());\n\t\t\n\t\t//Set Impact Energy Table\n\t\tsetEnergyValues(dataProvider.getDgEnergy());\n\t\t\n\t\t//Get the what happenes to the impactor text.\n\t\t setImpactorText(dataProvider.getTxtImpactor());\n\t\t \n\t\t// get fireball dats.\n\t\t setFireballSeen(dataProvider.getDgFirevall());\n\t\t\n\t\tdrawScale();\n\t\t\n\t}", "function stateSetComplete()\n\t\t{\n\t\t\t_cb();\n\t\t}", "async endQuery() {\n const queriesEnded = [];\n this._cmSearchProviders.forEach(({ provider }) => {\n queriesEnded.push(provider.endQuery());\n provider.changed.disconnect(this._onCmSearchProviderChanged, this);\n });\n Signal.disconnectBetween(this._searchTarget.model.cells, this);\n this._cmSearchProviders = [];\n this._unRenderedMarkdownCells.forEach((cell) => {\n // Guard against the case where markdown cells have been deleted\n if (!cell.isDisposed) {\n cell.rendered = true;\n }\n });\n this._unRenderedMarkdownCells = [];\n await Promise.all(queriesEnded);\n }", "function onEndExecution() {\n endExecutionHook();\n}", "function finished(err) {\n if(err) {\n console.log(err);\n }\n common.verbose('Command complete.');\n}", "onFinish() {\n this.props.store.dispatch(ACTIONS.FINISH);\n }", "complete() {\n if (this.time === undefined) {\n this.computeTime();\n }\n if (!this.fieldsComputed) {\n this.computeFields();\n }\n }", "function finished (err) {\n\t\tif (err){\n\t\t\tconsole.error(\"oops, something went wrong.\");\n\t\t\tconsole.error(err);\n\t\t} else {\n\t\t\tconsole.log(\"Data saved successfully\");\n\t\t\tpickColor();\n\t\t}\n\t}", "_finished(files, responseText, e) {\n for (let file of files){\n file.status = $3ed269f2f0fb224b$export$2e2bcd8739ae039.SUCCESS;\n this.emit(\"success\", file, responseText, e);\n this.emit(\"complete\", file);\n }\n if (this.options.uploadMultiple) {\n this.emit(\"successmultiple\", files, responseText, e);\n this.emit(\"completemultiple\", files);\n }\n if (this.options.autoProcessQueue) return this.processQueue();\n }", "finishCSVProcessing() {\n googleanalytics.SendEvent('Transaction', 'Data', 'Download CSV', 1);\n this.saveCSV(this.returnAllFilters([...this.props.walletitems]));\n this._OnCSVFinished();\n this.setState({\n CSVProgress: 0,\n });\n }", "end(cb) {\n this.pcolInstance.end(cb);\n }", "_loadingComplete() {\n this._loaded = true;\n this._registry.off(\"load\", this._onLoad, this);\n this._registry.off(\"error\", this._onError, this);\n\n if (this._failed && this._failed.length) {\n if (this._callback) {\n this._callback.call(this._scope, \"Failed to load some assets\", this._failed);\n }\n this.fire(\"error\", this._failed);\n } else {\n if (this._callback) {\n this._callback.call(this._scope);\n }\n this.fire(\"load\", this._assets);\n }\n }", "function finish() {\n// if (--finished == 0) {\n if (!isFinished) {\n isFinished = true;\n Physics.there.style(self.from.getContainerBodyId(), {\n opacity: 0\n });\n\n self.dfd.resolve();\n }\n }", "onUpdate() {\n for (const computeCell of this.computeCells) {\n computeCell.onInputUpdate();\n }\n }", "wait_AnimationEnd() {\n if (this.tmpPiece.parabolic.end == true) {\n this.unvalidateCells();\n this.check_GameOver();\n this.check_Reset();\n this.checkSelected();\n this.locked = true;\n }\n }" ]
[ "0.6444477", "0.63232344", "0.6282233", "0.62659574", "0.6121789", "0.60781753", "0.6031305", "0.6014177", "0.59923667", "0.59923667", "0.59923667", "0.59923667", "0.5947562", "0.5925103", "0.5856467", "0.5783831", "0.5769498", "0.57582635", "0.57485646", "0.5747945", "0.57306993", "0.5720532", "0.57147396", "0.5714173", "0.570476", "0.5676281", "0.56704783", "0.56482023", "0.5625302", "0.56168836", "0.56120545", "0.56002045", "0.55921954", "0.55908215", "0.55898154", "0.55696356", "0.55664", "0.55505157", "0.5542015", "0.5518329", "0.55089617", "0.549341", "0.5491252", "0.54908466", "0.54885334", "0.54854506", "0.5483322", "0.5479952", "0.54791945", "0.5468141", "0.54620814", "0.5440435", "0.5436138", "0.54255337", "0.54083747", "0.53795046", "0.537492", "0.53739506", "0.5369386", "0.53656423", "0.5350005", "0.5350005", "0.5349088", "0.53486466", "0.53442574", "0.53403246", "0.53372264", "0.5329655", "0.5321179", "0.5306402", "0.53050315", "0.530463", "0.5294161", "0.5275547", "0.5266564", "0.5264732", "0.5262881", "0.5260992", "0.52538913", "0.52459645", "0.5235464", "0.5220084", "0.5213674", "0.52132875", "0.5211385", "0.52111876", "0.52095944", "0.52068293", "0.5195525", "0.5192954", "0.5186419", "0.5185677", "0.51806337", "0.51794213", "0.51732814", "0.5172892", "0.5172301", "0.51675767", "0.51653266", "0.51634973" ]
0.64539725
0
Data Handling Functions Called when a Spark job starts.
onSparkJobStart(data) { this.addJobData(data.jobId, new Date(data.submissionTime), 'started'); this.addExecutorData(data.submissionTime, data.totalCores); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onSparkTaskStart(data) {\n this.addData(data.launchTime, this.numActiveTasks);\n this.numActiveTasks += 1;\n this.addData(data.launchTime, this.numActiveTasks);\n }", "preIngestData() {}", "function startApp() {\n //first calls, default dataset? \n }", "loadData() {\n\n }", "function loadProcessData() {\n\n if(this.status == 200 &&\n this.responseText != null &&\n this.responseText != null) {\n // success!\n\n const csvInput = new CSVReader(this.responseText);\n csvInput.setData(this.responseText);\n\n // main({dataModel: dataFrameToStateModel(\n // {csvInput: csvInput, metadata: chartJsonData})\n // });\n main();\n\n\n } else {\n console.log('fail');\n };\n\n}", "onSparkJobEnd(data) {\n this.addJobData(data.jobId, new Date(data.completionTime), 'ended');\n }", "function processedSFData() {\n\t\tthis.moteid = idMote;\n\t\tthis.sensorType = sensorType;\n\t\tthis.lastTimestamp = lastTimeStamp;\n\t\tthis.lastValue = lastValue;\n\t\tthis.arrayValuesDay = valuesDay;\n\t\tthis.populationDay = populationDay;\n\t\tthis.arrayValuesWeek = valuesWeek;\n\t\tthis.populationWeek = populationWeek;\n\t\tthis.platform = platform;\n\t\tthis.unit = unit;\n\t}", "loadingData() {}", "loadingData() {}", "function start() { \n initiate_graph_builder();\n initiate_job_info(); \n initiate_aggregate_info();\n initiate_node_info();\n}", "function preload () { \n training_data = loadStrings('./data/train_10000.csv', () => console.log(\"Training data loaded\"))\n testing_data = loadStrings('./data/test_1000.csv', () => console.log(\"Testing data loaded\"))\n}", "function LoadData(){\n\tLoadDataFiles();\n\tExtractDataFromFiles();\n}", "function initData(){\n container.prepend(progressInfo);\n jQuery.get(getPageURL(0, resource)).done(function(data) {\n records = processData(data, true);\n initView(new recline.Model.Dataset({records:records}));\n numReq = getRequestNumber(data.result.total, pageSize);\n for (var i = 1; i <= numReq; i++) {\n requestData(getPageURL(i, resource));\n };\n });\n }", "load() {\n\t\tif (this.props.onDataRequire) {\n\t\t\tthis.props.onDataRequire.call(this, this, 0, 1048576, this.props.columns);\n\t\t}\n\t}", "prepareDataUsageGraphData() {\n this.prepareUsageGraphData(\n this.streamUsageGraphData,\n this.streamData,\n 'logs_home_data_stream',\n );\n this.prepareUsageGraphData(\n this.archiveUsageGraphData,\n this.archiveData,\n 'logs_home_data_archive',\n );\n this.prepareUsageGraphData(\n this.indiceUsageGraphData,\n this.indiceData,\n 'logs_home_data_index',\n );\n }", "function initializeData() {\n\t//Records data endpoints for user\n var startDate = subset[0].date;\n outputData.startDate = startDate;\n\n var endDate = subset[subset.length-1].date;\n outputData.endDate = endDate;\n\n var startClose = subset[0].close;\n outputData.startClose = startClose;\n\n var endClose = subset[subset.length-1].close;\n outputData.endClose = endClose;\n\n var monthNames = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n \n datesText = \"Above is the performance of the S&P 500 from the week of \" + monthNames[startDate.getMonth()] + \" \" + \n startDate.getDate() + \", \" + startDate.getFullYear() + \" to the week of \" + monthNames[endDate.getMonth()] + \n \" \" + endDate.getDate() + \", \" + endDate.getFullYear() + \".\";\n\n //Adds properties to data\n subset = enhanceData(subset);\n\n //Sets global variables\n currentPrice = startClose;\n marketCurrentShares = marketCurrentValue / currentPrice;\n if (inMarketDefault) {\n \tuserCurrentShares = marketCurrentShares;\n \tlastTradeDate = startDate;\n \tlastTradeWeek = 0;\n \tlastTradePrice = startClose;\n \ttotalTrades++;\n }\n}", "function getAndProcessData() { \n\t\tchooseFileSource();\n\t}", "function initData(){\n dynarexDataIsland.init();\n loadFunctionTimes();\n setEventListener();\n}", "_handleData() {\n // Pull out what we need from props\n const {\n _data,\n _dataOptions = {},\n } = this.props;\n\n // Pull out what we need from context\n const {\n settings = {},\n } = this.context;\n\n // Pull the 'getData' method that all modules which need data fetching\n // must implement\n const {\n getData = (() => Promise.resolve({ crap: 5 })),\n } = this.constructor;\n\n /**\n * Check if data was loaded server-side.\n * If not - we fetch the data client-side\n * and update the state\n *\n * We'll also add add the global settings to\n * the request implicitely\n */\n if (!_data) {\n getData(Object.assign({}, { __settings: settings }, _dataOptions))\n .then(_data => this.setState({ ['__data']: _data }))\n .catch(_data => this.setState({ ['__error']: _data }));\n }\n }", "function loadData() {\n\n d3.queue()\n .defer(d3.csv, './data/data.csv')\n .await(processData); \n\n }", "function start() {\n hentData();\n}", "function initSensorData() {\r\n // let dbRes = getAllRoomInfo();\r\n // dbRes.promise.then(res => {\r\n // if (res.rowCount > 0) {\r\n // let roomList = res.rows;\r\n // roomList.forEach(item => {\r\n var room_no = 1;\r\n sensorDataMap[room_no] = {\r\n roomNo: +room_no,\r\n pm2p5CC: '未测出',\r\n temperature: '未测出',\r\n humidity: '未测出',\r\n pm10CC: '未测出'\r\n };\r\n // });\r\n // }\r\n module.exports.startUpdateSensorData();\r\n // dbRes.client.end();\r\n // });\r\n console.log(\"function\");\r\n}", "function init(){\n getData();\n}", "function init() {\n createDataReader('heartbeat', true);\n createDataReader('timing');\n createDataReader('telemetry');\n }", "async initializeDataLoad() {\n }", "postIngestData() {}", "function prepareProcessedData() {\n // #BUG: Had to add resourcesDirectory for Android...\n state.processedData = JSON.parse(Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory + 'common/data-base.json').read().text);\n}", "function loadData() {\n // STAND\n loadStandData();\n // PIT\n loadPitData();\n // IMAGES\n loadImageData();\n // NOTES\n loadNotesData();\n // PRESCOUTING\n loadPrescouting(\"./resources/prescout.csv\");\n\n}", "function queueData() {\n\n queue()\n //.defer(d3.csv, 'data/merged7daysSinglePoints.csv', parse)\n .defer(d3.csv, 'data/merged7days.csv', parse)\n //.defer(d3.csv,'data/Merge3.csv',parse)\n .await(dataLoaded);\n}", "function dbInitilization(){\n \n // Queries scheduled will be serialized.\n db.serialize(function() {\n \n // Queries scheduled will run in parallel.\n db.parallelize(function() {\n\n db.run('CREATE TABLE IF NOT EXISTS countries (id integer primary key autoincrement unique, name)')\n db.run('CREATE TABLE IF NOT EXISTS recipes (id integer primary key autoincrement unique, name, type, time, ingredient, method, id_Country)')\n })\n }) \n}", "function startWorker() {\n var stdin = new net.Stream(0, 'unix'),\n app = requireApp(getAppPath());\n stdin.on('data', function (json) {\n process.sparkEnv = env = JSON.parse(json.toString());\n });\n stdin.on('fd', function(fd) {\n sys.error('Spark server(' + process.pid + ') listening on '\n + (env.socket ? 'unix socket ' + env.socket : 'http' + (env.sslKey ? 's' : '') + '://' + (env.host || '*') + ':' + env.port)\n + ' in ' + env.name + ' mode');\n enableSSL(app, env);\n app.listenFD(fd);\n });\n stdin.resume();\n\n ['SIGINT', 'SIGHUP', 'SIGTERM'].forEach(function(signal) {\n process.on(signal, function() {\n process.exit();\n });\n });\n}", "async getCsvData() {\n await this.emptyIfFull();\n await this.runPython();\n await this.fetchScrapedData();\n await this.setPortData();\n await this.setAirfieldData();\n Meteor.call('setTimeofScrape');\n this.setState({ loading: false });\n }", "function init() {\n\t\t\tconsole.log(\"init()\");\n\t\t\tresetData();\n\t\t\trefreshTotalCount();\n\t\t\taddAdbRow();\n\t\t\tconsole.log(\"done init()\");\n\t\t}", "function initData() {\n initLtr_factor();\n initBosunit();\n initHero();\n initSelect25();\n initMS();\n}", "function init() {\n fetchData();\n}", "helpData() {\n console.log(\"2) finsemble.bootConfig timeout values\");\n console.log(\"\\tstartServiceTimeout value\", this.startServiceTimeout);\n console.log(\"\\tstartComponentTimeout value\", this.startComponentTimeout);\n console.log(\"\\tstartTaskTimeout value\", this.startTaskTimeout);\n console.log(\"\");\n console.log(\"3) Current boot stage:\", this.currentStage);\n console.log(\"\");\n console.log(`4) Lastest/current status of dependencyGraph for ${this.currentStage} stage`, this.dependencyGraphs[this.currentStage].getCurrentStatus());\n console.log(\"\");\n console.log(\"5) Dependency graphs by stage\", this.dependencyGraphs);\n console.log(\"\");\n console.log(\"6) Boot config data by stage\", this.bootConfigs);\n console.log(\"\");\n console.log(\"7) Active Checkpoint Engines\", this.checkpointEngines);\n console.log(\"\");\n console.log(\"8) Registered tasks\", this.registeredTasks);\n console.log(\"\");\n console.log(\"9) List of outstanding start timers\", this.startTimers);\n console.log(\"\");\n console.log(\"10) Dependency graphs display by stage\");\n this.outputDependencyGraphs(this.dependencyGraphs);\n console.log(\"\");\n }", "function getData() {\n StatusService.startWaiting();\n $q.all([ScenarioModelService.load(),\n ProcessService.load(),\n LciaMethodService.load(),\n FragmentFlowService.load({scenarioID: scenarioID, fragmentID: fragmentID}),\n ParamModelService.load(scenarioID)])\n .then(handleSuccess,\n StatusService.handleFailure);\n }", "function onData() {\n if ( packages instanceof Array ) {\n temp.mkdir('staniol_components', function ( err, tempDir ) {\n var components = new Components({\n components : packages,\n directory : tempDir\n });\n components.prepare(function (bundle) {\n emitter.emit('lessGet', bundle);\n });\n });\n } else {\n var components = new Components({\n components : packages\n });\n components.process(function (bundle) {\n emitter.emit('lessGet', bundle);\n });\n }\n }", "onStreamStart() {\n if (this.onStartTrigger.length > 0) {\n this.onStartTrigger.forEach(trigger => {\n controller.handleData(trigger);\n })\n }\n }", "on_assign_data() {\n }", "initialise() {\n cLogger('Initialising data state');\n // listen for socket events\n socketManager.setListener(this);\n // load the users\n this.getAllUsers();\n // load the entries\n this.getAllEntries();\n }", "function init(){\n employeeData();\n}", "function loadData() {\n Papa.parse(csvFile, {\n download: true,\n header: true,\n dynamicTyping: true,\n complete: (results) => {\n console.log(\"All data: \"+results.data)\n trainModel(results.data)\n }\n })\n}", "function _init() {\n addEvent();\n getData();\n }", "function init() {\n\td3.csv('data/indicators.csv', function(error, data) {\n\t\tindicatorData = data;\n\n\t\trender();\n\t\t$(window).resize(utils.throttle(onResize, 250));\n\t});\n}", "function processedGFData() {\n\t\tthis.moteid = idMote;\n\t\tthis.sensorType = sensorType;\n\t\tthis.lastTimestamp = lastTimeStamp;\n\t\tthis.lastValue = lastValue;\n\t\tthis.arrayValuesDay = valuesDay;\n\t\tthis.populationDay = populationDay;\n\t\tthis.arrayValuesWeek = valuesWeek;\n\t\tthis.populationWeek = populationWeek;\n\t\tthis.platform = platform;\n\t\tthis.unit= unit;\n\t}", "startRecord(state, data){\n state.record = data\n state.recordStartTime = Date.now()\n }", "function InitStatusData() {\n //Defaults\n }", "function init() {\n getShareJobs();\n }", "function initData(callback) {\n initLanguage(); // set the system language if not set\n DB.loadAll(function() {\n if(getUsers() === null){\n setUsers(DB.users);\n console.log('storing users in localStorage');\n }\n if(getBeverages() === null){\n setBeverages(DB.beverages);\n console.log('Storing beverages in localstorage');\n }\n if(getOrders() === null){\n setOrders([]);\n }\n if(callback) callback();\n });\n}", "onTaskDataGenerated() {}", "function loadData() {\r\n\r\n queue()\r\n .defer(d3.csv, \"data/hpi_sa.csv\")\r\n .defer(d3.csv, \"data/hpi_nsa.csv\")\r\n .await(function (error, sa, nsa) {\r\n\r\n if (error) throw error;\r\n\r\n sa.forEach(function (d) {\r\n d.YEAR = parseDate(d.YEAR);\r\n\r\n d.USA = +d.USA;\r\n d.USA = Math.round(d.USA); \r\n });\r\n\r\n nsa.forEach(function (d) {\r\n d.YEAR = parseDate(d.YEAR);\r\n\r\n d.USA = +d.USA;\r\n d.USA = Math.round(d.USA); \r\n });\r\n\r\n saData = sa;\r\n nsaData = nsa;\r\n\r\n updateVisualization();\r\n\r\n });\r\n}", "function loadData() {\n \n queue()\n .defer(d3.csv(\"data/Subjects.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/Subjects.csv: \",this.parent, formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/Activities.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/Activities.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/Calls.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/Calls.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/FluSymptoms.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/FluSymptoms.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/Health.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/Health.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/MusicGenreAwareness.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/MusicGenreAwareness.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/MusicGenreImmersion.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/MusicGenreImmersion.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/MusicGenrePreference.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/MusicGenrePreference.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/Politics.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/Politics.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n/*\n .defer(d3.csv(\"data/Proximity.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/Proximity.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n*/\n .defer(d3.csv(\"data/RelationshipsFromSurveys.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/RelationshipsFromSurveys.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\")\n .defer(d3.csv(\"data/SMS.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/SMS.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get, \"error\") \n\n .defer(d3.csv(\"data/WLAN2.csv\")\n .on(\"progress\", function() { console.log(\"Loading data/WLAN2.csv: \", formatPercent(d3.event.loaded/d3.event.total)); }) \n .get)\n \n .await(transformData);\n}", "onSparkTaskEnd(data) {\n this.addData(data.finishTime, this.numActiveTasks);\n this.numActiveTasks -= 1;\n this.addData(data.finishTime, this.numActiveTasks);\n }", "handleStart(inputData) {\n return this.startHandler(inputData);\n }", "function queueData() {\n\n queue()\n .defer(d3.csv, 'data/merged7days.csv', parse)\n //.defer(d3.csv,'data/Merge3.csv',parse)\n .await(dataLoaded);\n}", "function init() {\n getJobType();\n }", "componentDidMount() {\n document.addEventListener(\"keydown\", this.handleKeyDown);\n\n store.subscribe(() => {\n this.time_adjustment_secs = store.getState().timeAdjuster\n\n if (store.getState().serverStatus === 'UPLOADED'\n && !this.state.isRenderIntitialized\n && Object.keys(this.state.eegData).length == 0)\n {\n // File has been successfully uploaded\n // Must be called before echartRef becomes active\n this.setState({isRenderIntitialized: true})\n \n this.updateNavVariables()\n \n // Bind events and show loading\n let echart = this.echartRef.getEchartsInstance()\n this.bindInteractionEvents()\n echart.showLoading({\n color: '#cccccc'\n })\n this.initialDataLoad()\n // LEGACY\n // this.requestData(0, 10)\n }\n })\n }", "function driver_run()\n{\n ClassRepo.initialize(\"demo_data.json\");\n ScheduleBuilder.initialize(\"ScheduleBuilder\");\n Form.initialize(\"IGETCForm\");\n IGETCTable.initialize(\"IGETCTable\", builder);\n Analytics.initialize();\n}", "async function setupAndStart() {\n showLoadingView();\n $(\"table\").empty();\n categories = [];\n await fillTable();\n hideLoadingView()\n}", "function initCloudEventSource() {\n\n var eventSource = new EventSource(sparkBaseURL + sparkDeviceID + '/events/?access_token=' + sparkAccessToken);\n\n eventSource.addEventListener('error', function(e) {\n console.log('Failed to connect to Spark API.'); },false);\n\n eventSource.addEventListener('deviceStatus', function(e) {\n var parsedData = JSON.parse(e.data);\n var deviceData = JSON.parse(parsedData.data);\n updateUI(deviceData, 'cloud');\n }, false);\n\n }", "function initJts() {\n\n\t//const dataJhu = \"https://cdn.jsdelivr.net/gh/CSSEGISandData/COVID-19@master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\";\n\tconst dataJhu = \"https://raw.githack.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\";\n\n\trequestFile( dataJhu, onLoadCases );\n\n\n}", "function initViewData() {\n loadDataChart();\n displayLogIn();\n}", "function renderChart(){ //function is used to control the flow of when data is being loaded back into the program.\n//Calls the ready function once all data is imported into the program.\n\n d3.queue() //used to ensure that all data is loaded into the program before execution\n .defer(d3.csv, \"Data/shentel-troubles-may.csv\", function(d) {\n if(d.Longitude == 0 || d.Latitude == 0){ //statement can be updated in case of flaws in readable data from csv.\n console.log(\"invalid Lat/long at house id: \"+ d.StoreName)\n\n }else{\n locations.push([+d.Latitude, +d.Longitude, d.ServiceType]); //adding information from csv one by one\n serviceType.push(d.ServiceType); //adding information from csv one by one.\n\n }\n //sets the key as the id plus converts string to int\n })\n .await(ready);\n}", "componentWillMount() {\n console.log('before initData call');\n this.initData(); \n\t}", "function processedFFData() {\n\t\tthis.moteid = idMote;\n\t\tthis.sensorType = sensorType;\n\t\tthis.lastTimestamp = lastTimeStamp;\n\t\tthis.lastValue = lastValue;\n\t\tthis.arrayValuesDay = valuesDay;\n\t\tthis.populationDay = populationDay;\n\t\tthis.arrayValuesWeek = valuesWeek;\n\t\tthis.populationWeek = populationWeek;\n\t\tthis.platform = platform;\n\t\tthis.unit = unit;\n\t}", "constructor (sqlContext /*: SQLContext*/) {\n var jvm_DataFrameReader = java.import(\"org.apache.spark.sql.DataFrameReader\");\n this.sqlContext = sqlContext;\n this.jvm_obj = new jvm_DataFrameReader(sqlContext.jvm_obj);\n }", "function createDataSet(dataRecieved){\n\n\n}", "async function loadData() {\n // Get the health of the connection\n let health = await connection.checkConnection();\n\n // Check the status of the connection\n if (health.statusCode === 200) {\n // Delete index\n await connection.deleteIndex().catch((err) => {\n console.log(err);\n });\n // Create Index\n await connection.createIndex().catch((err) => {\n console.log(err);\n });\n // If index exists\n if (await connection.indexExists()) {\n const parents = await rest.getRequest(rest.FlaskUrl + \"/N\");\n // If parents has the property containing the files\n if (parents.hasOwnProperty(\"data\")) {\n //Retrieve the parent list\n let parrentArray = parents.data;\n\n // Get amount of parents\n NumberOfParents = parrentArray.length;\n console.log(\"Number of parents to upload: \" + NumberOfParents);\n // Each function call to upload a JSON object to the index\n // delayed by 50ms\n parrentArray.forEach(delayedFunctionLoop(uploadParentToES, 50));\n }\n }\n } else {\n console.log(\"The connection failed\");\n }\n}", "function modelReady() \n{\n print(\"Model REady\");\n loadData(); \n}", "conformData() {\n\t\tiflog(\"SourceData.conformData(): processing\");\n\t\ttry {\n\t\t\tif ( sourceData.schemaID === CSVVersion0Columns ) {\n\t\t\t\tiflog(\"SourceData.conformData(): Detected Versio 0 CarbonBraid Schema\");\n\t\t\t\tthis.processCSVVersion0(sourceData.data)\n\t\t\t} else if ( sourceData.schemaID === CSVVersion04072020Columns ) {\n\t\t\t\tiflog(\"SourceData.conformData(): Detected 04072020 CarbonBraid Schema\");\n\t\t\t\tthis.processCSVVersion04072020(sourceData.data)\n\t\t\t} else if ( sourceData.schemaID === CSVVersion04212020Columns ) {\n\t\t\t\tiflog(\"SourceData.conformData(): Detected 04072020 CarbonBraid Schema V2\");\n\t\t\t\tthis.processCSVVersion04212020(sourceData.data) \n\t\t\t} else {\n\t\t\t\tiflog(\"SourceData.conformData(): data is in unkown format\");\n\t\t\t\t// STATE: Error, the data couldn't be processed or wasn't detected correctly\n\t\t\t\t// TODO: Schema Dif\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.totalPatients += sourceData.data.length;\n\t\t\tiflog(\"SourceData.conformData(): data processed\")\n\t\t} catch (err) {\n\t\t\tiflog(\"SourceData.conformData(): data not processed: \" + err)\n\t\t\t// STATE: Error, the data couldn't be processed or wasn't detected correctly\n\t\t}\n\t}", "static LoadAndComputation(dataFile,instanceFile,variableFile,type) {\n codeManager.isComputing = true;\n Promise.all([\n d3.csv(dataFile),\n d3.csv(instanceFile),\n d3.csv(variableFile),\n ]).then(files=>{\n // reset variables\n netSP.plots.length = 0;\n netSP.encode.length = 0;\n // store data in format: instance -> variable -> time series\n netSP.data = ReadFile.IVTFormat(files,type);\n // add information to interaction tab\n Interaction.dropDownMenuForInteraction();\n // get percentages\n // DataProcessing.Percentages(data);\n // get z-score\n // DataProcessing.GetZScore(data);\n // get relative change\n // DataProcessing.GetRelativeChange(data);\n\n // Normalize the net scatter plot\n DataProcessing.NormalizationNetScatterPlot(netSP.data);\n\n // DataProcessing.Z_Normalization2D(netSP.data);\n // encode the plots\n EncodePlots.NetScatterPlot(); // start here to record data\n // attributes for every plot\n Management.FormPlots();\n // store data point to every net scatter plot\n DataProcessing.NetScatterPlot(netSP.data);\n\n // Store bins to NetSP.plot[index].arrows and points\n DataProcessing.AdaptiveBinning();\n\n // Compute quantities and metrics for every plot\n Management.ComputeMetrics();\n\n // clustering and draw\n Management.ClusterAndDraw();\n Management.Visualization();\n\n // // write data to myData\n // let myData = {};\n // let myXArr = [], myYArr = [];\n // let V = netSP.variableInfo.length;\n // for (let i = 0; i < V-1; i++) {\n // for (let j = i+1; j < V; j++) {\n // let myP = netSP.variableInfo[i][1] + ' vs. ' + netSP.variableInfo[j][1];\n // myData[myP] = {};\n // for (let t = 0; t < netSP.timeInfo.length; t++) {\n // myData[myP][netSP.timeInfo[t]] = {};\n // if (t > 0) {\n // let index = netSP.encode.findIndex(e=>e[0]===netSP.variableInfo[i][1] && e[1]===netSP.variableInfo[j][1] && e[2]===netSP.timeInfo[t]);\n // if (index!==-1) {\n // for (let v = 0; v < netSP.plots[index].arrows.length; v++) {\n // let nameIndex = netSP.plots[index].arrows[v].instance[0];\n // let name = netSP.plots[index].data[nameIndex].name;\n // let x1 = netSP.plots[index].arrows[v].end[0];\n // let y1 = netSP.plots[index].arrows[v].end[1];\n // myData[myP][netSP.timeInfo[t]][name] = [x1,y1];\n // myXArr.push(x1);\n // myYArr.push(y1);\n // }\n // }\n // } else {\n // let index = netSP.encode.findIndex(e=>e[0]===netSP.variableInfo[i][1] && e[1]===netSP.variableInfo[j][1] && e[2]===netSP.timeInfo[t+1]);\n // if (index!==-1) {\n // for (let v = 0; v < netSP.plots[index].arrows.length; v++) {\n // let nameIndex = netSP.plots[index].arrows[v].instance[0];\n // let name = netSP.plots[index].data[nameIndex].name;\n // let x0 = netSP.plots[index].arrows[v].start[0];\n // let y0 = netSP.plots[index].arrows[v].start[1];\n // myData[myP][netSP.timeInfo[t]][name] = [x0,y0];\n // myYArr.push(y0);\n // myXArr.push(x0);\n // }\n // }\n // }\n // }\n // }\n // }\n // // let myXMax = Math.max(...myXArr);\n // // let myXMin = Math.min(...myXArr);\n // // let myYMax = Math.max(...myYArr);\n // // let myYMin = Math.min(...myYArr);\n // // for (let p in myData) {\n // // for (let t in myData[p]) {\n // // for (let v in myData[p][t]) {\n // // myData[p][t][v][0] = (myData[p][t][v][0] - myXMin)/(myXMax-myXMin);\n // // myData[p][t][v][1] = (myData[p][t][v][1] - myYMin)/(myYMax-myYMin);\n // // }\n // // }\n // // }\n //\n // // save max score to file\n // let csv = JSON.stringify(myData);\n // let hiddenElement = document.createElement('a');\n // hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);\n // hiddenElement.target = '_blank';\n // hiddenElement.download = 'employment_tf.json';\n // hiddenElement.click();\n\n codeManager.isComputing = false;\n codeManager.needComputation = false;\n codeManager.needUpdate = true;\n d3.select('.cover').classed('hidden', true);\n\n // print running time\n console.log('running time of normalization: '+(timeMeasure[1]-timeMeasure[0]).toString()+'ms');\n console.log('running time of binning: '+(timeMeasure[3]-timeMeasure[2]).toString()+'ms');\n console.log('running time of computing metrics: '+(timeMeasure[5]-timeMeasure[4]).toString()+'ms');\n });\n }", "function dataReady() {\n // números grandes, precisa normalizar\n neuralNet.normalizeData();\n // treinar a neuralNet com os dados carregados\n neuralNet.train({epochs:50}, loaded);\n}", "function init() {\n //Creating instances for each visualization\n \n d3.csv(\"data/timesMergedData.csv\", function (error, schoolData) {\n \n var filterChart = new FilterChart(schoolData);\n });\n }", "initDataFromCSV() {\n this.setState({\n data: dataTable.map((prop, key) => {\n return this.produceCustomer(prop[0], prop[1], prop[2], prop[3], 0);\n })\n });\n }", "function initializeDataControllers() {\n\t\tmediator.subscribe('application:menu:DatasetListPopulated', function(selectedDataset){\n\t\t\t\tmediator.publish('application:controller:LoadDataset', selectedDataset);\n\t\t\t});\n\t\tmediator.subscribe('application:menu:DatasetSelected', function(selectedDataset) {\n\t\t\t\tmediator.publish('application:controller:LoadDataset', selectedDataset);\n\t\t\t});\n\t}", "train() {\n if(!this.running && ! this.recording)\n {\n this.disableButtons(true);\n this.trainingData().then((t)=> {\n this.updateRows();\n if(this.USE_WORKER)\n {\n this.myWorker.postMessage({action:\"train\",data:t});\n }\n else\n {\n this.myModel.train(t);\n this.trainingEnd();\n }\n });\n }\n }", "function init() {\n\t\t\tresetData();\n\t\t\trefreshTotalCount();\n\t\t\tloadVocabs();\n\t\t}", "function enter() {\n fetchData(true);\n }", "function run() {\n //setup new jobs if any\n setupNewJobs();\n\n //process all other active jobs\n processJobs();\n\n //finalize completed jobs\n finalizeJobs();\n }", "createMiningJobs() {}", "function processDataFromDocusky() {\n\tparseDocInfo();\n\ttoolSetting();\n}", "async function preTrainingProcess({ mlmodel, }) { // ONLY AWS MACHINE LEARNING MODEL UPDATER\r\n const MLModel = periodic.datas.get('standard_mlmodel');\r\n const Datasource = periodic.datas.get('standard_datasource');\r\n try{\r\n let mongo_mlmodel = await MLModel.load({ query: { _id: mlmodel._id, }, });\r\n mongo_mlmodel = mongo_mlmodel.toJSON? mongo_mlmodel.toJSON(): mongo_mlmodel;\r\n let datasource = mongo_mlmodel.datasource;\r\n let trainingDataRows = await FETCH_PROVIDER_BATCH_DATA[ 'original' ]({ mlmodel: mongo_mlmodel, batch_type: 'training', });\r\n let testingDataRows = await FETCH_PROVIDER_BATCH_DATA[ 'original' ]({ mlmodel: mongo_mlmodel, batch_type: 'testing', });\r\n let strategy_data_schema = JSON.parse(mongo_mlmodel.datasource.strategy_data_schema);\r\n let included_columns = datasource.included_columns? JSON.parse(datasource.included_columns) : {};\r\n let headers = trainingDataRows[0];\r\n trainingDataRows.splice(0, 1);\r\n testingDataRows.splice(0, 1);\r\n let historical_result_idx = headers.indexOf('historical_result');\r\n let columnTypes = {};\r\n for (let [key, val,] of Object.entries(strategy_data_schema)) {\r\n columnTypes[ key ] = val.data_type;\r\n }\r\n let training_data_transposed = math.transpose(trainingDataRows);\r\n let testing_data_transposed = math.transpose(testingDataRows);\r\n let included_headers = headers.filter(header => included_columns[header]? true : false);\r\n training_data_transposed = training_data_transposed.filter((column, idx) => {\r\n let header = headers[idx];\r\n let truthy = (included_columns[header])? true : false;\r\n return truthy;\r\n });\r\n testing_data_transposed = testing_data_transposed.filter((column, idx) => {\r\n let header = headers[idx];\r\n return (included_columns[header])? true : false;\r\n });\r\n let { decoders, encoders, encoder_counts,} = createHotEncodeMap({ csv_headers: included_headers, training_data_transposed, columnTypes,});\r\n let auto_progress_configs = {\r\n 'aws': { \r\n interval: 20000,\r\n max_progress: 20,\r\n },\r\n 'sagemaker_ll': { \r\n interval: 7000,\r\n max_progress: 60,\r\n },\r\n 'sagemaker_xgb': { \r\n interval: 8000,\r\n max_progress: 60,\r\n },\r\n 'decision_tree': { \r\n interval: 3000,\r\n max_progress: 60,\r\n progress_value: 1,\r\n },\r\n 'random_forest': { \r\n interval: 4000,\r\n max_progress: 60,\r\n progress_value: 1,\r\n },\r\n 'neural_network': { \r\n interval: 5000,\r\n max_progress: 60,\r\n progress_value: 1,\r\n },\r\n };\r\n await Datasource.update({\r\n id: datasource._id.toString(),\r\n isPatch: true,\r\n updatedoc: {\r\n decoders, \r\n encoders, \r\n encoder_counts,\r\n },\r\n updatedat: new Date(),\r\n });\r\n let providers = THEMESETTINGS.machinelearning.providers;\r\n let digifi_models = THEMESETTINGS.machinelearning.digifi_models[mongo_mlmodel.type] || [];\r\n providers.forEach(provider => {\r\n PROVIDER_DATASOURCE_FUNCS[provider]({ mlmodel, headers: included_headers, training_data_transposed, testing_data_transposed, columnTypes, });\r\n helpers.mlAutoProgress({ provider, model_id: mlmodel._id.toString(), interval: auto_progress_configs[provider].interval, organization: mlmodel.organization.toString(), max_progress: auto_progress_configs[provider].max_progress, });\r\n });\r\n PROVIDER_DATASOURCE_FUNCS['digifi']({ mlmodel, headers: included_headers, training_data_transposed, testing_data_transposed, columnTypes, });\r\n digifi_models.forEach(provider => {\r\n helpers.mlAutoProgress({ provider, model_id: mlmodel._id.toString(), interval: auto_progress_configs[provider].interval, organization: mlmodel.organization.toString(), max_progress: auto_progress_configs[provider].max_progress, progress_value: auto_progress_configs[provider].progress_value });\r\n });\r\n } catch(e){\r\n logger.warn(e.message);\r\n await MLModel.update({\r\n id: mlmodel._id.toString(),\r\n isPatch: true,\r\n updatedoc: {\r\n status: 'failed',\r\n },\r\n updatedat: new Date(),\r\n });\r\n }\r\n}", "function useData(data) {\n data = data || EMBED.getData();\n //debugger;\n var url_string = window.location.href; \n var url = new URL(url_string);\n SegmentActualId = url.searchParams.get(\"SegmentActualId\");\n updateGlobalVariable(SegmentActualId, \"SegmentActualId\", true, true);\n if (flagLoaded == false) {\n styleData();\n flagLoaded = true;\n }\n \n var ParsedPreparedLotsJson = returnParsedIfJson(data.PreparedLotsJson, \"PreparedLotsJson\");\n if (PreparedLotsJson == undefined || !deepEqual(PreparedLotsJson, returnParsedIfJson(data.PreparedLotsJson, \"PreparedLotsJson\"))) {\n PreparedLotsJson = ParsedPreparedLotsJson;\n \n }\n\n var ParsedProductDescriptionJson = returnParsedIfJson(data.ProductDescriptionJson, \"ProductDescriptionJson\");\n if (ProductDescriptionJson == undefined || !deepEqual(ProductDescriptionJson, returnParsedIfJson(data.ProductDescriptionJson, \"DataGridJsonData\"))) {\n ProductDescriptionJson = ParsedProductDescriptionJson;\n \n }\n PreparedLotsDataGrid();\n ProductDescriptionDatagrid();\n}", "function setup() {\n\tif(docClient == null) {\n\t\tdocClient = new AWS.DynamoDB.DocumentClient();\n\t}\n\tif(tblName == null) {\n\t\ttblName = process.env.stageName + \"-pds-data\";\n\t}\n}", "startSearching() {\n // Initializing the pre search data so that the data can be recovered when search is finished\n this._preSearchData = this.crudStore.getData();\n }", "function loadData() {\n\n //Users name.\n loadName()\n\n //Users config.\n loadConfig()\n}", "function callback(){\n console.log(\"Charts Data Executed\");\n}", "componentDidMount() {\n if (this.props.dataset.length === 0) {\n const { dispatch } = this.props;\n dispatch(fetchDataset());\n }\n }", "async function startETL() {\n await db.dropCustomersTable().then((res) => console.log(\"Drop customers table...\"));\n await db.createCustomersTable().then((res) => console.log(\"Customers table created...\"));\n\n /** Here is for map1.csv and data1.csv */\n let header = await getData(\"./etl/map1.csv\");\n let headerMap = await mapHeader(header[0]);\n // console.log(headerMap);\n\n let data = await getData(\"./etl/data1.csv\");\n data.map((record) => {\n // console.log(\"Inserting data\");\n let temp = {};\n Object.keys(record).forEach(key => {\n temp[headerMap[key]] = record[key];\n })\n // console.log(temp);\n loadDataToDB(temp);\n });\n\n /** Here is for map2.csv and data2.csv */\n let header2 = await getData(\"./etl/map2.csv\");\n let headerMap2 = await mapHeader(header2[0]);\n // console.log(headerMap);\n\n let data2 = await getData(\"./etl/data2.csv\");\n data2.map((record) => {\n // console.log(\"Inserting data\");\n let temp = {};\n Object.keys(record).forEach(key => {\n temp[headerMap2[key]] = record[key];\n })\n // console.log(temp);\n loadDataToDB(temp);\n });\n}", "function processData(data) {\n // data come in within an array\n // can separate out here and assign\n // to different variables\n\n var streamsData = data[0],\n districtData = data[1],\n channelImproveData = data[2];\n\n // here you could do other data clean-up/processing/binding\n // if you needed to\n\n // when done, send the datasets to the drawMap function\n drawMap(streamsData, districtData, channelImproveData);\n drawLegend();\n\n }", "function initAndStart (){\r\n csv({\r\n file: 'result_upcoming.csv',\r\n columns: upcoming_headers\r\n }, function (err, arr) {\r\n upcomingPlayed = arr;\r\n csv({\r\n file: 'result_played.csv',\r\n columns: played_headers\r\n }, function (err, arr) {\r\n resultPlayed = arr;\r\n app.listen(8080, () => {\r\n console.log('server started on port 8080\\n' +\r\n 'API endpoints:\\n' +\r\n 'http://localhost:8080/matches/team/team_name - get list of matches by team\\n' +\r\n 'http://localhost:8080/matches/team/team_name/?status=status - get list of matches by team filtered by status\\n' +\r\n 'http://localhost:8080/matches/tournament/tournament_name - get list of matches by tournament\\n' +\r\n 'http://localhost:8080/matches/tournament/tournament_name?status=status - get list of matches by tournament filtered by status\\n');\r\n });\r\n\r\n });\r\n });\r\n}", "componentDidMount() {\n this.calculateAverageDatset();\n }", "_eventDataContructor(){\n self = this;\n getJSON('http://api.vx1.ekranj.si/v5/sources/14d1aad8-49a9-44eb-aba3-94feb70e184d/elements',\n function(err, data) {\n if (err !== null) {\n alert('Something went wrong: ' + err);\n } else {\n //sorting by weight\n data = sortByWeight(data)\n }\n //storing event data to store\n self.props.captureData(data);\n });\n }", "function startApplication() {\n\n // Start loading our datasets in parallel using D3-queue,\n // then create a callback for the function responsible\n // for building the dashboard\n d3.queue().defer(d3.csv, '../_data/REF2014_Results.csv').defer(d3.csv, '../_data/learning-providers-plus.csv').await(function (err, mainData, extraData) {\n // After waiting for datasets to load, do cleaning and pass data for\n // creating the dashboard\n var dataset = dataManager.mergeDatasets(mainData, extraData);\n var dataset2 = mainData;\n\n // Router, shows dashboard content relevant to category selected from navigation\n // Get nav elements from the DOM\n var ecaPhd = document.getElementsByClassName('header__nav-item')[0].childNodes[1],\n universityMgmt = document.getElementsByClassName('header__nav-item')[1].childNodes[1],\n industryResrch = document.getElementsByClassName('header__nav-item')[2].childNodes[1];\n\n var navArr = [ecaPhd, universityMgmt, industryResrch];\n\n // Show Early career academics and PhDs by default as the landing page\n var main = _ecaPhd.mainEca;\n var mainDOM = document.querySelector('main');\n mainDOM.innerHTML = main;\n mainDOM.setAttribute('id', 'eca-phd');\n\n // Create relevant dashboard\n createDashboardEca(dataset, dataset2);\n\n // Highlight active nav item\n navArr.forEach(function (navItem) {\n\n // Listen for click event on navigation items\n navItem.addEventListener('click', function (event) {\n // Prevent link default action\n event.preventDefault();\n\n // Get the route of the clicked navigation item\n var href = navItem.href.split('/');\n var dashboard = href[href.length - 1];\n var elements = navItem.parentElement.parentElement.children;\n\n // Highlight the selected category by adding an active class on the\n // corresponding navigation item \n for (var i = 0; i <= 2; i++) {\n if (elements[i].classList.contains('active')) {\n elements[i].classList.remove('active');\n }\n }\n navItem.parentElement.classList.add('active');\n\n // Main routing functionality\n // Early Career Academics & PhDs Dashboard\n if (dashboard === 'eca-phd') {\n main = _ecaPhd.mainEca;\n document.title = 'REF2014 Results Dashboard - Early Career Academics & PhDs';\n mainDOM.innerHTML = main;\n mainDOM.setAttribute('id', 'eca-phd');\n createDashboardEca(dataset, dataset2);\n }\n // University Management Dashboard\n else if (dashboard === 'university-management') {\n main = _universityManagement.universityManagement;\n document.title = 'REF2014 Results Dashboard - University Management';\n mainDOM.innerHTML = main;\n mainDOM.setAttribute('id', 'um');\n createDashboardUm(dataset, dataset2);\n }\n // Industry Collaborators and Research Strategists Dashboard\n else if (dashboard === 'industry-research') {\n main = _industryResearch.industryResearch;\n document.title = 'REF2014 Results Dashboard - Industry Collaborators & Research Strategists';\n mainDOM.innerHTML = main;\n mainDOM.setAttribute('id', 'ir');\n createDashboardIr(dataset, dataset2);\n }\n });\n });\n });\n}", "function festivosProcessData(serverData) {\n processData(serverData);\n }", "function setup() {\n if (DEBUG)\n {\n console.log('Mosca server is up and running');\n console.log(`Publish rate: ${FREQ} Hz`)\n }\n\n countLinesInFile(dataFilename, (err, numLines) => {\n if (!err){\n numberOfLines = numLines\n }\n });\n}", "function initialize() {\n//here you would load your data\n}", "function initData() {\n\tsensorTypes = {};\n}", "onCreatedHandler() {\n this.fetchData();\n }" ]
[ "0.6682271", "0.634833", "0.5602043", "0.5578953", "0.55323356", "0.5530881", "0.5526608", "0.5514517", "0.5514517", "0.55013907", "0.5458517", "0.54127014", "0.5411505", "0.54040676", "0.5393013", "0.5376476", "0.5364742", "0.5354428", "0.53214115", "0.5308976", "0.52749586", "0.52565426", "0.5236062", "0.52189535", "0.52182114", "0.5217969", "0.52159256", "0.51995283", "0.51761705", "0.5174687", "0.5147441", "0.51468205", "0.51257634", "0.5102641", "0.5095372", "0.5092004", "0.5089564", "0.50860864", "0.5085465", "0.50805914", "0.50591743", "0.50499904", "0.50440574", "0.5036801", "0.5018873", "0.5016391", "0.5009379", "0.49991214", "0.49950618", "0.4991935", "0.498805", "0.49817923", "0.4976977", "0.4972306", "0.49522674", "0.49514958", "0.4950285", "0.49395588", "0.49328473", "0.49303928", "0.49238095", "0.49225628", "0.49225032", "0.4919297", "0.49190715", "0.4908052", "0.49046376", "0.4900526", "0.48992607", "0.48979375", "0.48899317", "0.48878902", "0.48766792", "0.48737475", "0.48689133", "0.4868376", "0.48679903", "0.48611847", "0.4855643", "0.48479155", "0.48421305", "0.48414978", "0.48391676", "0.4832865", "0.48312992", "0.48293635", "0.48292458", "0.48267856", "0.48241508", "0.48132163", "0.48060724", "0.4804351", "0.48040706", "0.48024404", "0.47991508", "0.47973165", "0.47943097", "0.47865054", "0.4786392", "0.478543" ]
0.7563005
0
Called when a Spark job ends.
onSparkJobEnd(data) { this.addJobData(data.jobId, new Date(data.completionTime), 'ended'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onSparkTaskEnd(data) {\n this.addData(data.finishTime, this.numActiveTasks);\n this.numActiveTasks -= 1;\n this.addData(data.finishTime, this.numActiveTasks);\n }", "function end() {\n stopProgressInfo();\n cancelAllJobs();\n if (fromDate) {\n clock.uninstall();\n }\n if (!isEnded) {\n isEnded = true;\n emitEnd();\n }\n}", "_finished( ) { \n\n\t\tif( this.verbose ) { this.log( \"All stages finished.\" ); }\n\n\t\tif( this.rollback ) {\n\t\t\tif( this.verbose ) { this.log( \"Processing failed.\" ); }\n\t\t\tthis.callback.failure( \"failed because of stage \\\"\" + this.failed + \"\\\"\" );\n\t\t} else {\n\t\t\tif( this.verbose ) { this.log( \"Processing succeeded.\" ); }\n\t\t\tthis.callback.success( this.results ); \n\t\t}\n\t\t\n\t}", "function handleFinish(values) {\n job.current = getJob(values, job.current, writeMessage);\n setBusy(job.current.pendingTime);\n }", "function onJobEnded (message) {\r\n let job = findJobById(message.data.jobId);\r\n if (job) {\r\n console.log('job ended', job.id, message.data.exitCode);\r\n job.ended(message.data.exitCode);\r\n }\r\n\r\n // Start a job if below the concurrent jobs limit.\r\n let activeJobCount = countActiveJobs();\r\n if (activeJobCount < settings.concurrentJobsLimit) {\r\n job = findNextWaitingJob();\r\n if (job) {\r\n job.create();\r\n }\r\n }\r\n\r\n // Disconnect the port if there are no jobs.\r\n if (!job && (activeJobCount === 0)) {\r\n console.log('no jobs - disconnecting native-app');\r\n state.port.disconnect();\r\n state.port = null;\r\n\r\n // Make the icon dark because the queue is idle.\r\n browser.browserAction.setIcon({\r\n path: null\r\n });\r\n }\r\n}", "end() {\n this.status = 'finished';\n }", "end() {\n this.log('end');\n }", "async onEnd() {\n\t\tawait this.say('Exiting...');\n\t}", "function onEndExecution() {\n endExecutionHook();\n}", "end() {\n process.exit();\n }", "end(){\n this.request({\"component\":this.component,\"method\":\"end\",\"args\":[\"\"]})\n this.running = false\n }", "function endPython(){\n LED_RGBC.end(function (err,code,signal) {\n if (err) throw err;\n console.log('The exit code was: ' + code);\n console.log('The exit signal was: ' + signal);\n console.log('finished');\n });\n}", "_onComplete() {\n // Ensure worker queues for all paths are stopped at the end of the query\n this.stop();\n }", "onEnd() {\n\t\tthis.debug('onEnd');\n\t}", "end() {\n this.cancel();\n this.callback();\n }", "end() {\n\t\tif (this.process)\n\t\t\tthis.process.kill()\n\t}", "function finish() {\n process.exit(0);\n }", "function handleFinish(event) {\n cleanup(null, responseData)\n }", "async finalise() {\n Util.log(`### ${this.dagType} finalise ###`);\n return await this.dagObj.finalise();\n }", "function onFinish() {\n console.log('finished!');\n}", "end() {\n // Debugging line.\n Helper.printDebugLine(this.end, __filename, __line);\n\n // Let the user know that the cache stored in the database will be cleared.\n let tmpSpinner = new Spinner('Clearing cache stored in the database %s');\n tmpSpinner.start();\n\n this.clearCacheDB().then(() => {\n // Remove the information with the spinner.\n tmpSpinner.stop(true);\n\n // If we used the database as cache, the user should know this.\n if (Global.get('useDB')) {\n this.output.writeLine(`Used database until page ${Global.get('useDB')}`, true);\n }\n\n // Write some ending lines.\n this.output.writeUserInput(this);\n this.getReadableTime();\n\n // Close the write stream to the log file.\n this.output.logger.end();\n this.removeLockFile();\n }).catch(error => {\n console.log(error);\n });\n }", "onEnd() {\n this.requestQueueLength--;\n if (this.requestQueueLength || !this.callbacks.onEnd) {\n return;\n }\n this.callbacks.onEnd(this.requestQueueLength);\n }", "onTerminate() {}", "function doneClosing()\n\t{\n\t\tthat.terminate();\n\t}", "end() {\n\t\tthis.Vars._Status = strings.getString(\"Terms.ShuttingDown\")\n\t\tthis.Vars._event = 'ShuttingDown'\n\t\tthis.Vars._displayStatusMessage = true\n\t\tupdateSession(this.ID)\n\t\tthis.Session.stdin.write('\\nshutdown\\n');\n\t}", "function handleFinish(_event) {\n cleanup(null, responseData)\n }", "async end(job, success, results) {\n // context object gets an update to avoid a\n // race condition with checkStopped\n job.ended = true;\n return self.db.updateOne({ _id: job._id }, {\n $set: {\n ended: true,\n status: success ? 'completed' : 'failed',\n results: results\n }\n });\n }", "function nodeEnd() {\n // signal all current processing requests that a terminate request has been received\n isTerminating = true;\n // if it is processing, ensure all events return before stopping\n if (processing) {\n (function wait() {\n if (processing) {\n setTimeout(wait, 100);\n } else {\n agora_process.kill();\n }\n })()\n } else {\n agora_process.kill();\n }\n}", "function finishProcess(){\n self.updateBars(callback);\n }", "end() {\n }", "end() {\n }", "stop() {\n this.finishAll();\n }", "_onEnd() {}", "end(event) {\n\n }", "ended (exitCode, detail) {\r\n if (this.cancelRequested) {\r\n this.setState('cancelled');\r\n this.append('Job cancelled.');\r\n } else {\r\n this.setState((exitCode > 0) ? 'errored' : 'ended');\r\n if (detail) {\r\n this.append(`Job ended with error: ${detail}`);\r\n }\r\n }\r\n }", "finish() {\n\t\tthis.IS_STARTED = false;\n\t}", "onFinish() {\n this.props.store.dispatch(ACTIONS.FINISH);\n }", "finish() {}", "stop () {\n listener.end();\n }", "function handleAnimationEnd() {\n node.classList.remove(`${prefix}animated`, animationName);\n node.removeEventListener('animationend', handleAnimationEnd);\n\n resolve('Animation ended');\n }", "function quit() {\n log.info('Exiting now.');\n process.nextTick(process.exit);\n }", "function handleAnimationEnd() {\r\n node.classList.remove(`${prefix}animated`, animationName);\r\n node.removeEventListener('animationend', handleAnimationEnd);\r\n\r\n resolve('Animation ended');\r\n }", "async end() {\n return;\n }", "finish() {\n this._ctx.restore();\n }", "exitCommandEnd(ctx) {\n\t}", "onend() {\n if (this.done)\n return;\n this.done = true;\n this.parser = null;\n this.handleCallback(null);\n }", "function end() {\n task = null;\n stack.ack();\n run.call(self); // restart to high level scope\n }", "function end() {\n task = null;\n stack.ack();\n run.call(self); // restart to high level scope\n }", "function end() {\n task = null;\n stack.ack();\n run.call(self); // restart to high level scope\n }", "function end() {\n task = null;\n stack.ack();\n run.call(self); // restart to high level scope\n }", "async end() {\n await this.recordedRateController.end();\n\n try {\n switch (this.outputFormat) {\n case TEXT_FORMAT:\n this._exportToText();\n break;\n case BINARY_LE_FORMAT:\n this._exportToBinaryLittleEndian();\n break;\n case BINARY_BE_FORMAT:\n this._exportToBinaryBigEndian();\n break;\n default:\n logger.error(`Output format ${this.outputFormat} is not supported.`);\n break;\n }\n\n logger.debug(`Recorded Tx submission times for worker #${this.workerIndex} in round #${this.roundIndex} to ${this.pathTemplate}`);\n } catch (err) {\n logger.error(`An error occurred for worker #${this.workerIndex} in round #${this.roundIndex} while writing records to ${this.pathTemplate}: ${err.stack || err}`);\n }\n }", "finish() {\n this.done = true;\n }", "function finished(err){\n }", "function receiverOnFinish () {\n this[kWebSocket].emitClose();\n}", "function receiverOnFinish () {\n this[kWebSocket].emitClose();\n}", "function receiverOnFinish() {\n this[kWebSocket].emitClose();\n}", "function receiverOnFinish() {\n this[kWebSocket].emitClose();\n}", "finish()\n {\n console.log({status: \"done\"});\n\n // Close the process so we don't have anything left hanging\n process.exit();\n }", "exitCallEnd(ctx) {\n\t}", "function finishJob(job, callback) {\n if (typeof (job) === 'undefined') {\n return callback(new wf.BackendInternalError(\n 'WorkflowRedisBackend.finishJob job(Object) required'));\n }\n\n var multi = client.multi();\n var p;\n\n for (p in job) {\n if (typeof (job[p]) === 'object') {\n job[p] = JSON.stringify(job[p]);\n }\n }\n\n return client.lrem('wf_running_jobs', 0, job.uuid,\n function (err, res) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n\n if (res <= 0) {\n return callback(new wf.BackendPreconditionFailedError(\n 'Only running jobs can be finished'));\n }\n if (job.execution === 'running') {\n job.execution = 'succeeded';\n }\n\n multi.srem('wf_runner:' + job.runner_id, job.uuid);\n if (job.execution === 'succeeded') {\n multi.rpush('wf_succeeded_jobs', job.uuid);\n } else if (job.execution === 'canceled') {\n multi.rpush('wf_canceled_jobs', job.uuid);\n } else if (job.execution === 'retried') {\n multi.rpush('wf_retried_jobs', job.uuid);\n } else if (job.execution === 'waiting') {\n multi.rpush('wf_waiting_jobs', job.uuid);\n } else {\n multi.rpush('wf_failed_jobs', job.uuid);\n }\n\n multi.hmset('job:' + job.uuid, job);\n multi.hdel('job:' + job.uuid, 'runner_id');\n if (typeof (job.locks) !== 'undefined') {\n multi.hdel('wf_locked_targets', job.uuid);\n }\n return multi.exec(function (err, replies) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n } else {\n return getJob(job.uuid, callback);\n }\n });\n });\n }", "function finishedProcess(){\n console.log('xxxxxxxxxxxxxxxxxxxx process manually terminated xxxxxxxxxxxxxxxxxxxxxx')\n printTotals();\n clearInterval(pound.statusUpdateIntervalId);\n process.exit();\n }", "function receiverOnFinish() {\n this[kWebSocket$1].emitClose();\n}", "end() {\n this.session.close();\n }", "function end() {\n process.exit(0);\n}", "end() { }", "exit() {\n this.exit();\n }", "function END() {}", "function onEnd() {\n //console.log('' + this);\n scope.emit('end', this);\n }", "onStop () {\n this.leave()\n }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "function finishConnection() {\n\tmongoose.connection.close(function () {\n\t\t\t console.log('Mongodb connection disconnected');\n\t\t\t console.log('Exiting script');\n\t\t });\n}", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function final() { console.log('Done and Final'); process.exit() ; }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "async function shutdown () {\n console.log(' ### RECEIVED SHUTDOWN SIGNAL ###. ');\n await resqueDriver.shutdown();\n console.log('Worker is now ready to exit, bye bye...');\n process.exit(0);\n}", "endConnection() {\n this.connection.end()\n }", "function suiteDone() {\n _scenariooReporter.default.useCaseEnded(options);\n }", "function endConnectionToSQL (){\n connection.end();\n console.log(`Your connection to SQL database is has been intentionally terminated`); \n }", "function finishUpload()\n {\n aws_params.MultipartUpload = {\n Parts: aws_parts \n };\n console.log('Completing...', aws_parts);\n\n s3.completeMultipartUpload(aws_params, function(err, data) {\n if (err) setError('Error completing upload: ' + err);\n else \n { \n uploadDone();\n }\n });\n }", "function finished(result) {\n\t\t\t--self.evaluating;\n\t\t\tself.off('Error', captureError);\n\t\t\tif (callback) callback(err, result);\n\t\t}", "function complete() {\n Y.log('complete');\n }", "function successCb(){\n\t\t\t\tdbm.updateJobFinish(uuid, function(err, rows, fields){\n\t\t\t\t\tif(err) log.error('update status error:', err);\n\t\t\t\t\tdelete jobpool[uuid];\n\t\t\t\t})\n\t\t\t}", "function terminate() {\n if (terminating) return\n terminating = true\n \n // don't restart workers\n cluster.removeListener('disconnect', onDisconnect)\n // kill all workers\n Object.keys(cluster.workers).forEach(function (id) {\n console.log('sending kill signal to worker %s', id)\n cluster.workers[id].kill('SIGTERM')\n })\n process.exit(0)\n }", "function endProcess()\n{\n\tprocess.exit()\n}", "stop() {\n if (this._currentTask) {\n this._currentTask.return();\n }\n }", "function finish(message, data) {\n console.log(message);\n console.log(data);\n process.exit();\n}", "function terminate() {\n if (terminating) return;\n terminating = true;\n\n // don't restart workers\n cluster.removeListener('disconnect', onDisconnect)\n // kill all workers\n Object.keys(cluster.workers).forEach(function (id) {\n console.log('[worker %s] receiving kill signal', id);\n cluster.workers[id].kill('SIGTERM');\n });\n}", "async stop () {\n for (const watcher of this._jobWatchers) {\n clearInterval(watcher)\n }\n\n await this._orbitdb.disconnect()\n }", "function end(){\n return end;\n}", "onFinish() {\n\t\tif (this.props.onFinish) {\n\t\t\tthis.props.onFinish();\n\t\t}\n\t}", "stop() {\n this.pendingJobs = [];\n }", "function endProcedure(){\n \n clearData();\n closeConnection();\n console.log(\"ENDED_PROCEDURE\");\n}", "songEnded() {\n\t\tconsole.log(\"Song ended. Current index: \" + app.queueIndex);\n\t\t// Check if this is the same song in the queue\n\t\tif (app.queueIndex == app.playQueue.length - 1){\n\t\t\t// Tell Vue components song has stopped playing\n\t\t\tapp.$emit(\"songPlaying\", false);\n\t\t\treturn;\n\t\t}\n\n\t\t// Otherwise move on to the next song in the queue\n\t\tthis.nextSong();\n\t}", "function exit() {\n sensor.unexport();\n process.exit();\n}", "function onTerminate() {\n console.log('')\n \n // Handle Database Connection\n switch (config.schema.get('db.driver')) {\n case 'mongo':\n dbMongo.closeConnection()\n break\n case 'mysql':\n dbMySQL.closeConnection()\n break\n }\n\n // Gracefully Exit\n process.exit(0)\n}", "stop(){\n this.logger.info('stopping work');\n this.execute = false;\n if(this.is_beanstalk_connected) { this.beanstalk_connection.quit();}\n if(this.is_db_connected) { this.db_connection.close();}\n }" ]
[ "0.66854334", "0.64587086", "0.60315955", "0.5923702", "0.5905105", "0.5833336", "0.5798342", "0.5795892", "0.577486", "0.57483506", "0.57294565", "0.5614498", "0.5584179", "0.557839", "0.55777717", "0.55251354", "0.54955137", "0.54932195", "0.5484814", "0.5482978", "0.54742277", "0.5473004", "0.54720694", "0.54718316", "0.54628015", "0.5462031", "0.5461609", "0.54486185", "0.5429941", "0.54257727", "0.54257727", "0.54069656", "0.53955305", "0.5389524", "0.5385564", "0.53683764", "0.5338784", "0.53348315", "0.53317696", "0.5323448", "0.530657", "0.5300727", "0.5295396", "0.52883214", "0.5284212", "0.5258433", "0.5254891", "0.5254891", "0.5254891", "0.5254891", "0.5251818", "0.5249246", "0.5246765", "0.52378327", "0.52378327", "0.5236532", "0.5236532", "0.5234521", "0.5223116", "0.52171534", "0.52083546", "0.52071357", "0.52040017", "0.52011263", "0.5194212", "0.5185964", "0.5185849", "0.51819986", "0.5172466", "0.51662153", "0.51610076", "0.51491576", "0.51491576", "0.51491576", "0.51491576", "0.51484555", "0.5146803", "0.5146803", "0.51444453", "0.5144173", "0.51400536", "0.5138748", "0.512896", "0.5126094", "0.51238126", "0.51229507", "0.5118023", "0.51105326", "0.5105614", "0.50968", "0.50939786", "0.5091022", "0.50873464", "0.5079649", "0.5072758", "0.5060791", "0.5055972", "0.50548595", "0.5050467", "0.5048865" ]
0.77688205
0
Called when a Spark task is started.
onSparkTaskStart(data) { this.addData(data.launchTime, this.numActiveTasks); this.numActiveTasks += 1; this.addData(data.launchTime, this.numActiveTasks); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "start() {\n this.taskFunction_.apply(null, Array.prototype.slice.call(arguments));\n this.onTaskDone();\n }", "onSparkJobStart(data) {\n this.addJobData(data.jobId, new Date(data.submissionTime), 'started');\n this.addExecutorData(data.submissionTime, data.totalCores);\n }", "start() {\r\n // Add your logic here to be invoked when the application is started\r\n }", "start() {\n // Add your logic here to be invoked when the application is started\n }", "function startWorker() {\n var stdin = new net.Stream(0, 'unix'),\n app = requireApp(getAppPath());\n stdin.on('data', function (json) {\n process.sparkEnv = env = JSON.parse(json.toString());\n });\n stdin.on('fd', function(fd) {\n sys.error('Spark server(' + process.pid + ') listening on '\n + (env.socket ? 'unix socket ' + env.socket : 'http' + (env.sslKey ? 's' : '') + '://' + (env.host || '*') + ':' + env.port)\n + ' in ' + env.name + ' mode');\n enableSSL(app, env);\n app.listenFD(fd);\n });\n stdin.resume();\n\n ['SIGINT', 'SIGHUP', 'SIGTERM'].forEach(function(signal) {\n process.on(signal, function() {\n process.exit();\n });\n });\n}", "start() {\n this.executeNextTask();\n }", "start() {\n this.currentTaskType = \"teil-mathe\";\n this.v.setup();\n this.loadTask();\n }", "started() {\n\n }", "started() {\n\n }", "started() {\n\n }", "started () {\n\n }", "started () {\n\n }", "started () {\n\n }", "function handleBegin() {\n task.inProgress = true;\n handleTaskChange(task.id, task);\n }", "function start() { \n initiate_graph_builder();\n initiate_job_info(); \n initiate_aggregate_info();\n initiate_node_info();\n}", "started() {\r\n\r\n\t}", "setupStart() {\n const config = this._configuration;\n const environment = config.environment ? config.environment : 'Sandbox';\n const params = [config.domain, environment, config.description];\n\n Cordova.exec(\n () => {},\n () => {},\n 'SparkProxy',\n 'setupStart',\n params);\n }", "started() { }", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "started() {\n\n\t}", "start(){\n let _this = this;\n // run the main sequence every process_frequency seconds\n _this.logger.info('starting work');\n _this.execute = true;\n _this.run();\n }", "started() {\n\t}", "start() {\n running = true;\n if (splitsStorage.usesSegments()) mySegmentsUpdaterTask.start();\n }", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "async started() {\n\n\t}", "start() {// Your initialization goes here.\n }", "onStartButtonClicked() {\n this.setState({taskStarted: new Date()});\n }", "started () {}", "start() {\n }", "preStart() {\n }", "async started() {}", "async started() {}", "async started() {}", "async started() {}", "async started() {}", "start() {\n this.do(\"start\")\n }", "startBootTaskDependency(readyItem) {\n systemLog_1.default.log({ indent: true }, `starting boot task: ${readyItem.name}`);\n logger_1.default.system.debug(`bootEngine.processReadyList starting boot task ${readyItem.name} in ${this.currentStage}`, readyItem);\n if (this.registeredTasks[readyItem.name]) {\n // invoke the registered boot task\n this.registeredTasks[readyItem.name](this.handleTaskResponse);\n }\n else {\n logger_1.default.system.error(`bootEngine.processReadyList: unknown task ${readyItem.name}`, readyItem);\n systemLog_1.default.error({}, `bootEngine.processReadyList: unknown task ${readyItem.name}`);\n }\n }", "signalTaskRunning() {\n this.taskRunning = true;\n }", "async prepareTask() {\n this.options.task && (this.task = await this.addService('task', new this.TaskTransport(this.options.task)));\n \n if(!this.task) {\n return;\n }\n\n if(this.options.task.calculateCpuUsageInterval) {\n await this.task.add('calculateCpuUsage', this.options.task.calculateCpuUsageInterval, () => this.calculateCpuUsage());\n }\n }", "start() {\n //DO BEFORE START APP CONFIGURATION/INITIALIZATION\n super.start();\n }", "function start_calibration_task() {\n // Stimuli switch - How do we check if the calibration is finished?\n check_calibration_finished(); \n\n // Interactivity switch - How are we collecting gaze training data?\n collect_training_data(); \n\n // 2nd stimuli switch - How are we progressing further into the calibration step?\n continue_calibration();\n}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "started() {}", "start() {}", "start() {}", "start() {}", "start() {}", "start() {}", "start() {}", "start () {}", "onStart() {\n log('starting the core...');\n history.start({pushStart: false});\n\n /**\n * App has started.\n *\n * @event App#start\n */\n this.channel.trigger('start');\n\n // Remove loading class\n $('.-loading').removeClass('-loading');\n }", "pushStart() {\n Cordova.exec(\n () => {},\n () => {},\n 'SparkProxy',\n 'pushStart',\n []);\n }", "init() {\n moduleUtils.patchModule(\n 'cos-nodejs-sdk-v5/sdk/task.js',\n 'init',\n tencentCOSWrapper\n );\n }", "function startApp() {\n //first calls, default dataset? \n }", "start() {\n if (cluster.isMaster) {\n throw new Error('Start can be called only on slave node');\n }\n\n // Use in not pluster\n if (!this.config.enabled) {\n return;\n }\n\n this.waitSignal(SIGNAL_DISCONNECT, () => {\n this._log('disconnect signal from master');\n cluster.worker.disconnect();\n });\n\n this._log('start');\n\n // Start APP\n this._startMemoryMonitoring();\n\n process.chdir(this.config.cwd);\n\n this.initPlugins();\n\n require(resolve(this.config.app));\n }", "async initialize() {\n\n this.config = config;\n this.sketches = this.config.sketches;\n this._start();\n }", "constructor() {\n super(new Task());\n }", "start() {\n super.start();\n }", "start() {\n Emitters.get(APPLICATION).emit(ON_START);\n this._app.start();\n }", "start() {\n\t\tthis.startTime = Date.now();\n\t}", "_onStart() {\n this.running = true;\n this._startTime = Date.now();\n\n this._log('query:start'); // Register this query so we can stop it if the DHT stops\n\n\n this.dht._queryManager.queryStarted(this);\n }", "started() {\n\n\t\tthis.app.listen(Number(this.settings.port), err => {\n\t\t\tif (err)\n\t\t\t\treturn this.broker.fatal(err);\n\t\t\tthis.logger.info(`API Server started on port ${this.settings.port}`);\n\t\t});\n\n\t}", "async startup() {\n }", "async startup() { }", "async startup() { }", "async prepareTask() {\n this.options.task && (this.task = await this.addService('task', new this.TaskTransport(this.options.task)));\n\n if(!this.task) {\n return; \n }\n\n if(this.options.task.workerChangeInterval) {\n await this.task.add('workerChange', this.options.task.workerChangeInterval, () => this.changeWorker());\n }\n }", "function startTask() {\n const task = {\n id: nextTaskId(),\n name: taskNameElement.value.trim(),\n length: sliderElement.value * 60, // Length in seconds\n date: new Date(),\n type: !currentTask\n ? taskTypes.work\n : currentTask.type == taskTypes.rest\n ? taskTypes.work\n : taskTypes.rest,\n status: taskStates.running,\n };\n if (!isValidTask(task)) return;\n\n // Start countdown worker\n countdownWorker = new Worker(\"js/counter.js\");\n countdownWorker.onmessage = onmessageReceived;\n countdownWorker.postMessage(task.length);\n\n // Store the task\n createTask(task);\n\n // Adapt UI\n setState(\n task.type == taskTypes.work ? pomodoroStates.running : pomodoroStates.rest\n );\n console.info(\n `${\n task.type == taskTypes.work ? \"Creada la tarea\" : \"Creado el descanso\"\n }: `,\n task\n );\n}", "async startup(){}", "start() {\n this.ipfs.start(() => {\n super.start()\n })\n }", "start() {\n\t\tthis.registerListeners();\n\t}", "start() {\n this.running = true;\n }", "startTask(task) {\n const url = this.getTaskWorkerUrl();\n\n // start task\n const body = {\n [ATTR_PROG]: PROG,\n [ATTR_NAME]: task.name,\n [ATTR_DATA]: serializer.encode(task.data),\n [ATTR_MAX_PROCESSING_TIME]:\n typeof task.maxProcessingTime === \"function\"\n ? task.maxProcessingTime()\n : null,\n };\n\n const params = this.getAppEnv();\n\n return http.post(url, body, { params });\n }", "startWhenReady (cb) {\n this.app.events.once('ready', () => this.start(cb))\n }", "start() {\n console.log(\"Die Klasse App sagt Hallo!\");\n }", "async started() {\n this.broker.logger.info('[service][company]===>', 'started')\n }", "initialize() {\n this._forkProcess();\n }", "function init() {\r\n if (log.isDebugEnabled()) log.debug(\"init WorkFlowScriptExample.js\");\r\n}", "function markTaskStartDB(conn_str, sql, task, onDone) {\n\tsqlserver.query(conn_str, sql, [task.job_id, task.index, task.pid], function(err, dataTable) {\n\t\tif (typeof onDone === 'function') onDone(err);\n\t});\n}", "async started() {\n\t\tthis._createAxios();\n\t\tthis.dataAccess = await this.login();\n\t}", "setUp() {\n // Set up task button handlers.\n $(\"#task-id\").on('change', evt => this.setTask(evt.target.value - 1));\n $(\"#task-prev\").on('click', evt => this.setTask(this.taskIdx - 1));\n $(\"#task-next\").on('click', evt => this.setTask(this.taskIdx + 1));\n\n // Start with the first task.\n // Get worker IDs and populate list.\n this.refresh();\n }", "async started () {\n\t\tthis.tortoise\n\t\t\t.on(Tortoise.EVENTS.CONNECTIONCLOSED, () => {\n\t\t\t\tthis.logger.error('Tortoise connection is closed');\n\t\t\t})\n\t\t\t.on(Tortoise.EVENTS.CONNECTIONDISCONNECTED, (error) => {\n\t\t\t\tthis.logger.error('Tortoise connection is disconnected', error);\n\t\t\t})\n\t\t\t.on(Tortoise.EVENTS.CONNECTIONERROR, (error) => {\n\t\t\t\tthis.logger.error('Tortoise connection is error', error);\n\t\t\t});\n\n\t\tawait Promise.all(this.settings.jobs.map((job) => {\n\t\t\treturn this.tortoise\n\t\t\t\t.queue(job.name, { durable: true })\n\t\t\t\t.exchange(this.settings.amqp.exchange, 'direct', job.route, { durable: true })\n\t\t\t\t.prefetch(1)\n\t\t\t\t.subscribe(async (msg, ack, nack) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.broker.call(`${this.name}.${job.method}`, { msg, ack, nack });\n\t\t\t\t\t\tack();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.logger.error('Job processing has error', error);\n\t\t\t\t\t\tnack(true);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t}), this);\n\t}" ]
[ "0.6616614", "0.66153246", "0.59093875", "0.5892997", "0.5872101", "0.58540756", "0.57423764", "0.561637", "0.561637", "0.561637", "0.5596873", "0.5596873", "0.5596873", "0.5589091", "0.5549775", "0.5527974", "0.54829204", "0.5478452", "0.5469953", "0.5469953", "0.5469953", "0.5469953", "0.5469953", "0.5469953", "0.5469953", "0.5469953", "0.5459814", "0.5428196", "0.54205364", "0.5404805", "0.5404805", "0.5404805", "0.5404805", "0.5404805", "0.5404805", "0.5404805", "0.5367723", "0.535718", "0.53500205", "0.53103775", "0.53094983", "0.5309329", "0.5309329", "0.5309329", "0.5309329", "0.5309329", "0.5307933", "0.5303639", "0.53006595", "0.5277986", "0.52685535", "0.5229857", "0.5227312", "0.5227312", "0.5227312", "0.5227312", "0.5227312", "0.5227312", "0.5227312", "0.5227312", "0.5227312", "0.5227312", "0.5224847", "0.5224847", "0.5224847", "0.5224847", "0.5224847", "0.5224847", "0.5204673", "0.5163895", "0.5157065", "0.5156106", "0.51534176", "0.5131088", "0.5102226", "0.5095025", "0.50749743", "0.50549215", "0.50507146", "0.5044059", "0.50330025", "0.5022565", "0.50194716", "0.50194716", "0.49971527", "0.49940208", "0.49922115", "0.49901804", "0.49767116", "0.49740648", "0.49682516", "0.49677497", "0.49581122", "0.49544084", "0.4937087", "0.49327293", "0.49268192", "0.49247357", "0.49002445", "0.48890188" ]
0.7180664
0
Called when a Spark task is ended.
onSparkTaskEnd(data) { this.addData(data.finishTime, this.numActiveTasks); this.numActiveTasks -= 1; this.addData(data.finishTime, this.numActiveTasks); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onSparkJobEnd(data) {\n this.addJobData(data.jobId, new Date(data.completionTime), 'ended');\n }", "function end() {\n stopProgressInfo();\n cancelAllJobs();\n if (fromDate) {\n clock.uninstall();\n }\n if (!isEnded) {\n isEnded = true;\n emitEnd();\n }\n}", "function end() {\n task = null;\n stack.ack();\n run.call(self); // restart to high level scope\n }", "function end() {\n task = null;\n stack.ack();\n run.call(self); // restart to high level scope\n }", "function end() {\n task = null;\n stack.ack();\n run.call(self); // restart to high level scope\n }", "function end() {\n task = null;\n stack.ack();\n run.call(self); // restart to high level scope\n }", "end() {\n this.log('end');\n }", "stop() {\n if (this._currentTask) {\n this._currentTask.return();\n }\n }", "_finished( ) { \n\n\t\tif( this.verbose ) { this.log( \"All stages finished.\" ); }\n\n\t\tif( this.rollback ) {\n\t\t\tif( this.verbose ) { this.log( \"Processing failed.\" ); }\n\t\t\tthis.callback.failure( \"failed because of stage \\\"\" + this.failed + \"\\\"\" );\n\t\t} else {\n\t\t\tif( this.verbose ) { this.log( \"Processing succeeded.\" ); }\n\t\t\tthis.callback.success( this.results ); \n\t\t}\n\t\t\n\t}", "function finishTask(self){\n clearInterval(timeVar);\n var neededId = getNeededId(self);\n EndDate = new Date();\n EndTimeString = EndDate.toLocaleTimeString();\n EndDateString = EndDate.toLocaleDateString();\n e_datetime = EndDateString.concat('|',EndTimeString);\n updateTimeData(DateTimeStorage, e_datetime, 'finished', neededId);\n sel = '#'+neededId;\n $(sel).remove();\n}", "end() {\n this.cancel();\n this.callback();\n }", "onTaskEnd (taskId, callback) {\n\t\tconst task = this.taskMap[taskId];\n\t\tif (task == null) {\n\t\t\tsetImmediate (callback);\n\t\t\treturn;\n\t\t}\n\t\tconst onEvent = () => {\n\t\t\tif (task.isEnded || (this.taskMap[task.id] === undefined)) {\n\t\t\t\tcallback ();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.statusEventEmitter.once (task.id, onEvent);\n\t\t};\n\t\tthis.statusEventEmitter.once (task.id, onEvent);\n\t}", "_taskComplete() {\n //\n }", "async finalise() {\n Util.log(`### ${this.dagType} finalise ###`);\n return await this.dagObj.finalise();\n }", "end() {\n this.status = 'finished';\n }", "end(){\n this.request({\"component\":this.component,\"method\":\"end\",\"args\":[\"\"]})\n this.running = false\n }", "finish() {\n this.done = true;\n }", "onEnd() {\n\t\tthis.debug('onEnd');\n\t}", "_onTasksDone() {\n // meant to be implemented by subclass if needed\n }", "async onEnd() {\n\t\tawait this.say('Exiting...');\n\t}", "_onComplete() {\n // Ensure worker queues for all paths are stopped at the end of the query\n this.stop();\n }", "finish() {\n\t\tthis.IS_STARTED = false;\n\t}", "function nodeEnd() {\n // signal all current processing requests that a terminate request has been received\n isTerminating = true;\n // if it is processing, ensure all events return before stopping\n if (processing) {\n (function wait() {\n if (processing) {\n setTimeout(wait, 100);\n } else {\n agora_process.kill();\n }\n })()\n } else {\n agora_process.kill();\n }\n}", "onTaskDone() {\n assertFalse(this.isDone_);\n this.isDone_ = true;\n\n // Function to run the next task in the queue.\n const runNextTask = this.taskQueue_.runNextTask.bind(\n this.taskQueue_, Array.prototype.slice.call(arguments));\n\n // If we need to start the next task asynchronously, we need to wrap\n // it with the test framework code.\n if (this.completeAsync_) {\n window.setTimeout(\n NetInternalsTest.activeTest.continueTest(\n WhenTestDone.EXPECT, runNextTask),\n 0);\n return;\n }\n\n // Otherwise, just run the next task directly.\n runNextTask();\n }", "end() {\n // Debugging line.\n Helper.printDebugLine(this.end, __filename, __line);\n\n // Let the user know that the cache stored in the database will be cleared.\n let tmpSpinner = new Spinner('Clearing cache stored in the database %s');\n tmpSpinner.start();\n\n this.clearCacheDB().then(() => {\n // Remove the information with the spinner.\n tmpSpinner.stop(true);\n\n // If we used the database as cache, the user should know this.\n if (Global.get('useDB')) {\n this.output.writeLine(`Used database until page ${Global.get('useDB')}`, true);\n }\n\n // Write some ending lines.\n this.output.writeUserInput(this);\n this.getReadableTime();\n\n // Close the write stream to the log file.\n this.output.logger.end();\n this.removeLockFile();\n }).catch(error => {\n console.log(error);\n });\n }", "end() {\n\t\tif (this.process)\n\t\t\tthis.process.kill()\n\t}", "function endPython(){\n LED_RGBC.end(function (err,code,signal) {\n if (err) throw err;\n console.log('The exit code was: ' + code);\n console.log('The exit signal was: ' + signal);\n console.log('finished');\n });\n}", "function taskComplete(){\n inquirer\n .prompt([\n {\n type: 'confirm',\n name: 'exit',\n message: 'Do you want to exit the program?'\n }\n ])\n .then(function(answer) {\n if (answer.exit){\n connection.end();\n } else {\n start();\n };\n });\n}", "doneTask () {\n this.currentTask.isDone = true;\n fireDataBase.setTask(this.currentTask.id, this.currentTask);\n }", "end() {\n process.exit();\n }", "function onFinish() {\n console.log('finished!');\n}", "end(event) {\n\n }", "_done() {\n this.worker = this.task = -1;\n this.callbacks = []; this.callback = 0;\n }", "onend() {\n if (this.done)\n return;\n this.done = true;\n this.parser = null;\n this.handleCallback(null);\n }", "function doneClosing()\n\t{\n\t\tthat.terminate();\n\t}", "finish()\n {\n console.log({status: \"done\"});\n\n // Close the process so we don't have anything left hanging\n process.exit();\n }", "_onEnd() {}", "done() {\n assert_equals(this._state, TaskState.STARTED)\n this._state = TaskState.FINISHED;\n\n let message = '< [' + this._label + '] ';\n\n if (this._result) {\n message += 'All assertions passed. (total ' + this._totalAssertions +\n ' assertions)';\n _logPassed(message);\n } else {\n message += this._failedAssertions + ' out of ' + this._totalAssertions +\n ' assertions were failed.'\n _logFailed(message);\n }\n\n this._resolve();\n }", "function end(done) {\n done();\n}", "function onEndExecution() {\n endExecutionHook();\n}", "async end() { }", "function handleFinish(_event) {\n cleanup(null, responseData)\n }", "function handleFinish(event) {\n cleanup(null, responseData)\n }", "function finished(err){\n }", "function onEnd() {\n //console.log('' + this);\n scope.emit('end', this);\n }", "end() {\n\t\tthis.Vars._Status = strings.getString(\"Terms.ShuttingDown\")\n\t\tthis.Vars._event = 'ShuttingDown'\n\t\tthis.Vars._displayStatusMessage = true\n\t\tupdateSession(this.ID)\n\t\tthis.Session.stdin.write('\\nshutdown\\n');\n\t}", "stop () {\n\t\tthis.updateTask.stop ();\n\t}", "function taskDone(e) {\n\tJSL.event(e).stop();\n\tvar lnk = JSL.event(e).getTarget();\n\tvar data = {\"success\":\"Done\"};\n\tloading();\n\tJSL.ajax(lnk.href+\"&ajax=1\").load(function(data) {\n\t\tloaded();\n\t\tif(data.success) removeTask(lnk);\n\t\tshowMessage(data);\n\t},\"json\");\n}", "function handleFinish(values) {\n job.current = getJob(values, job.current, writeMessage);\n setBusy(job.current.pendingTime);\n }", "async end() {\n return;\n }", "workFinishCall() {\n\t\t// all nodes have been downloaded\n if (this.finishCount === this.worklist.length) {\n this.state = 'finish'\n this.finishDate = utils.formatDate()\n userTasks.splice(userTasks.indexOf(this), 1)\n finishTasks.unshift(this)\n clearInterval(this.countSpeed)\n sendMessage()\n this.recordInfor(`${this.name} 下载完成`)\n this.finishStore()\n } else {\n\t\t\t// running next\n this.updateStore()\n this.downloadSchedule()\n }\n }", "finish() {}", "async onFinished() {}", "stop() {\n this.finishAll();\n }", "function finishTask(pomoID) {\n setStatus(pomoID, SESSION_STATUS.complete);\n setCurrentPomo(INVALID_POMOID);\n closeFinishDialog();\n updateTable();\n}", "stop () {\n\t\tthis.updateTask.stop ();\n\t\tthis.sessionMap = { };\n\t}", "function finishProcess(){\n self.updateBars(callback);\n }", "end() {\n }", "end() {\n }", "onEnd() {\n console.log('finished playing video');\n this.props.removeVideo(this.props.id, this.props.channel);\n }", "function suiteDone() {\n _scenariooReporter.default.useCaseEnded(options);\n }", "stop() {\n running = false;\n mySegmentsUpdaterTask.stop();\n }", "finishProcessing() {\n this.busy = false;\n this.successful = true;\n }", "function complete() {\n // Play the animation and audio effect after task completion.\n\n setProperty(\"isComplete\", true);\n\n // Set distanceProgress to be at most the distance for the mission, subtract the difference from the offset.\n if (getProperty(\"missionType\") === \"audit\") {\n var distanceOver = getProperty(\"distanceProgress\") - getProperty(\"distance\");\n var oldOffset = svl.missionContainer.getTasksMissionsOffset();\n var newOffset = oldOffset - distanceOver;\n svl.missionContainer.setTasksMissionsOffset(newOffset);\n }\n\n // Reset the label counter\n if ('labelCounter' in svl) {\n labelCountsAtCompletion = {\n \"CurbRamp\": svl.labelCounter.countLabel(\"CurbRamp\"),\n \"NoCurbRamp\": svl.labelCounter.countLabel(\"NoCurbRamp\"),\n \"Obstacle\": svl.labelCounter.countLabel(\"Obstacle\"),\n \"SurfaceProblem\": svl.labelCounter.countLabel(\"SurfaceProblem\"),\n \"NoSidewalk\": svl.labelCounter.countLabel(\"NoSidewalk\"),\n \"Other\": svl.labelCounter.countLabel(\"Other\")\n };\n svl.labelCounter.reset();\n }\n\n if (!svl.isOnboarding()){\n svl.storage.set('completedFirstMission', true);\n }\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "function complete() {\n Y.log('complete');\n }", "stop () {\n listener.end();\n }", "endTransaction() {\n this.finished = true;\n\n performance.mark(`${this.uuid}-end`);\n performance.measure(\n `${this.uuid}-duration`,\n `${this.uuid}-start`,\n `${this.uuid}-end`\n );\n\n this.duration = (performance.getEntriesByName(\n `${this.uuid}-duration`\n )[0].duration)/100000000000;\n\n performance.clearMarks([`${this.uuid}-start`, `${this.uuid}-end`]);\n performance.clearMeasures(`${this.uuid}-duration`);\n }", "function complete() {\n Y.log('complete');\n }", "onFinish() {\n this.props.store.dispatch(ACTIONS.FINISH);\n }", "onEnd() {\n this.requestQueueLength--;\n if (this.requestQueueLength || !this.callbacks.onEnd) {\n return;\n }\n this.callbacks.onEnd(this.requestQueueLength);\n }", "function final() { console.log('Done and Final'); process.exit() ; }", "terminate() {\n this.stopping = true;\n return this.done;\n }", "terminate() {\n this.stopping = true;\n return this.done;\n }", "songEnded() {\n\t\tconsole.log(\"Song ended. Current index: \" + app.queueIndex);\n\t\t// Check if this is the same song in the queue\n\t\tif (app.queueIndex == app.playQueue.length - 1){\n\t\t\t// Tell Vue components song has stopped playing\n\t\t\tapp.$emit(\"songPlaying\", false);\n\t\t\treturn;\n\t\t}\n\n\t\t// Otherwise move on to the next song in the queue\n\t\tthis.nextSong();\n\t}", "function finishedProcess(){\n console.log('xxxxxxxxxxxxxxxxxxxx process manually terminated xxxxxxxxxxxxxxxxxxxxxx')\n printTotals();\n clearInterval(pound.statusUpdateIntervalId);\n process.exit();\n }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "function finish(){\n if( settings.onFinish ) {\n settings.onFinish( data );\n }\n }", "end () {\n require('./actions/end')(this)\n }", "async end() {\n await this.recordedRateController.end();\n\n try {\n switch (this.outputFormat) {\n case TEXT_FORMAT:\n this._exportToText();\n break;\n case BINARY_LE_FORMAT:\n this._exportToBinaryLittleEndian();\n break;\n case BINARY_BE_FORMAT:\n this._exportToBinaryBigEndian();\n break;\n default:\n logger.error(`Output format ${this.outputFormat} is not supported.`);\n break;\n }\n\n logger.debug(`Recorded Tx submission times for worker #${this.workerIndex} in round #${this.roundIndex} to ${this.pathTemplate}`);\n } catch (err) {\n logger.error(`An error occurred for worker #${this.workerIndex} in round #${this.roundIndex} while writing records to ${this.pathTemplate}: ${err.stack || err}`);\n }\n }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "function complete() {\n $archive.removeClass(\"processing\");\n Y.log('complete');\n }", "function _end (fn) {\n\n //set end callback\n if (typeof (fn) != 'undefined')\n this._endFn = fn;\n\n //go go go\n _exec.call(this);\n }", "exitCommandEnd(ctx) {\n\t}", "end(_endTime) { }", "onFinish() {}", "async finish() {\n const waterlineStop = promisify(Waterline.stop);\n await waterlineStop(this.waterline);\n }", "end() { }", "onStop () {\n this.leave()\n }", "_completeExit() {\n this._ngZone.onMicrotaskEmpty.pipe(take(1)).subscribe(() => {\n this._ngZone.run(() => {\n this._onExit.next();\n this._onExit.complete();\n });\n });\n }", "endConnection() {\n this.connection.end()\n }", "function done() {\n \tvar storage = config.storage;\n\n \tProcessingQueue.finished = true;\n\n \tvar runtime = now() - config.started;\n \tvar passed = config.stats.all - config.stats.bad;\n\n \temit(\"runEnd\", globalSuite.end(true));\n \trunLoggingCallbacks(\"done\", {\n \t\tpassed: passed,\n \t\tfailed: config.stats.bad,\n \t\ttotal: config.stats.all,\n \t\truntime: runtime\n \t});\n\n \t// Clear own storage items if all tests passed\n \tif (storage && config.stats.bad === 0) {\n \t\tfor (var i = storage.length - 1; i >= 0; i--) {\n \t\t\tvar key = storage.key(i);\n\n \t\t\tif (key.indexOf(\"qunit-test-\") === 0) {\n \t\t\t\tstorage.removeItem(key);\n \t\t\t}\n \t\t}\n \t}\n }", "function end() {\n host.active--;\n //callback(this);\n process(host);\n }", "end() {\n this.killCurrentTranscoder();\n }", "end() {\n this.killCurrentTranscoder();\n }", "function trackVideoEnd() {\n\n flushParams();\n correlateMediaPlaybackEvents();\n s.Media.stop(videoFileName, videoStreamLength);\n s.Media.close(videoFileName);\n }", "_end(done){\r\n this.fork.stdout.on('data', data => {\r\n this.stdio.stdout.splitPush(data)\r\n })\r\n\r\n this.fork.stderr.on('data', data => {\r\n this.stdio.stderr.splitPush(data)\r\n })\r\n\r\n this.fork.on('exit', (signal, code) => { \r\n done(null, JSON.stringify({\r\n source: this.source.pathname,\r\n args: this.args,\r\n stdio: this.stdio,\r\n signal,\r\n code\r\n }, null, 2))\r\n })\r\n }", "function doneTasks() {\n\n\t\tif (doneTasksBuffer.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet title = (doneTasksBuffer.length === 1) ?\n\t\t\t'Task finished' :\n\t\t\tdoneTasksBuffer.length + ' tasks finished'\n\n\t\tnotify('done', title, doneTasksBuffer.join(', '));\n\n\t\tdoneTasksBuffer = [];\n\t\tdoneTasksFn = null;\n\n\t}" ]
[ "0.6952476", "0.6588027", "0.6549342", "0.6549342", "0.6549342", "0.6549342", "0.6171832", "0.61573046", "0.6145893", "0.61072534", "0.60762584", "0.6073113", "0.6072836", "0.6064975", "0.6041452", "0.6039907", "0.58820724", "0.5860562", "0.5854848", "0.5846717", "0.58235437", "0.58102655", "0.58059883", "0.5782623", "0.57684815", "0.5750209", "0.5707356", "0.57013416", "0.5694394", "0.5693089", "0.5690818", "0.5680871", "0.5664974", "0.56570214", "0.5652794", "0.5641638", "0.563564", "0.5614137", "0.5609388", "0.56049097", "0.5598089", "0.55920774", "0.55903596", "0.5580333", "0.5577655", "0.55595326", "0.5552922", "0.55518115", "0.55427486", "0.5538971", "0.5519623", "0.5507169", "0.55045074", "0.5477202", "0.5474004", "0.5471759", "0.5463871", "0.54568183", "0.54568183", "0.5450781", "0.54365534", "0.54311156", "0.54292524", "0.54008764", "0.5398404", "0.5398404", "0.5398404", "0.5398404", "0.5390114", "0.5377913", "0.5371433", "0.5365757", "0.5359526", "0.5352467", "0.5350495", "0.5350495", "0.535037", "0.53489345", "0.533843", "0.53234327", "0.53234303", "0.53188884", "0.53184825", "0.53184825", "0.53153974", "0.53129107", "0.53116536", "0.5309337", "0.528772", "0.528361", "0.5278401", "0.5275853", "0.5275788", "0.52555805", "0.52536285", "0.52489364", "0.52489364", "0.5243097", "0.52311677", "0.5223428" ]
0.74958163
0
var Information = "" console.log(Information) } fn()
function fn1(x,y) { var a = x var b = y console.log(a + b) // console.log(b) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function info()\n{\n console.log('Normal Functions') ;\n}", "function Info(text){\r\n\tvar txt=\"\";\r\n\tfor( var i = 0; i < arguments.length; i++ ) txt+=arguments[i];\r\n\tconsole.log(txt);\r\n}", "static info(){\r\n\t\t\tconsole.log('A dog is a mammal');\r\n\t\t}", "function someFunction(param) { // function declaration\n return `It has some parameter: ${param}`;\n}", "function myName(){\n var Sophia = \"Hi, my name is Sophia Sangervasi\";\n console.log(Sophia);\n }", "function printMyDetails(){\n let message = (`Hello World, this is ${myDetails.name} with HNGi7 ID ${myDetails.HNG_ID} using ${myDetails.language} for stage 2 task and my email is ${myDetails.emailAddress}`)\n \n console.log(message);\n}", "function hola (sergio){\n console.log(\"Como estas\" + \" \" + sergio)\n}", "function returnInfo() {\n let info = \"return this information!\";\n return info;\n}", "function details() // function defination\r\n \r\n {\r\n var a=10 ;\r\n console.log(a);\r\n }", "function saludar(){\n if(true){\n var vNombre = \"Baila\";\n }\n console.log(`Hola ${vNombre}`);\n}", "function ausgabe(outputStr) {\r\n console.log(outputStr);\r\n}", "function ausgabe(outputStr) {\r\n console.log(outputStr);\r\n}", "function ausgabe(outputStr) {\r\n console.log(outputStr);\r\n}", "function logToConsole(info) {\n return console.log(info + \" is something important to keep in mind\");\n }", "function Nama(a){\n console.log('Hello, My Name is ' + a)\n}", "biodata(){\n console.log(`hello my Name is ${this.name}. I am ${this.age} years old. my roll no. is ${this.roll_no}`)\n }", "function hi () {\n return 'Hi'\n}", "function hola(nombre,apellido){\n console.log(`Hola ${nombre} ${apellido}. Bienvenido!`);\n}", "function printSomething(string){\n\tconsole.log(string);\n}", "function textCustomer() {\n {\n let firstName = 'Molly' \n return console.log('Hi ' + firstName + ', your book is now in')\n }\n}", "function care()\r\n{\r\n\tvar emotion = \"happyy\"\r\n\tvar money = 5000\r\n\tvar support =\"always supportive\"\r\n\tvar hadurlunch = \"yes\"\r\n\tconsole.log(emotion,money,support,hadurlunch)\r\n}", "function hi(){\r\n\tvar name = \"Chris\";\r\n\tconsole.log(name);\r\n}", "function showRequestInfo(text) {\n //console.log(\"Inside showRequestInfo(text): \" + text)\n var infoText = text\n console.log(infoText)\n}", "function myName (name) {\n console.log(`My name is ${name}`);\n}", "function saludar2(nombre)\r\n{\r\n console.log(`Hola ${nombre}`);\r\n}", "function hi() {\n var name = \"Lucy\";\n console.log(name);\n}", "function printDetails (firstName,lastName,mood){\n return `The person ${getFullName(\"Filip\",\"Janev\")} is feeling ${mood}`\n\n}", "function myName(name) {\n console.log(`My name is ${name}`);\n}", "function outptMsg() {\n console.log(\"Hello World\");//inside curly braces, block of code\n}", "function outptMsg() {\n console.log(\"Hello World\");//inside curly braces, block of code\n}", "function pr(string)\n{\n console.log(string);\n}", "function hello(str){\n return str;\n }", "function one(input){\r\n console.log(\"\\nYour input is \" + input);\r\n}", "function OutString() {\r\n}", "function says(str){\n console.log(str);\n}", "function d(info) {\n console.log(info);\n $(\"#noticeboard\").append(\"<br>\" + info);\n}", "function miFuncion(){\n let nombre = 'Eduardo';\n console.log(nombre);\n}", "function saluda(nombre){\n console.log(\"hola \" + nombre);\n}", "info() {}", "info() {}", "function hello(firstName, lastName) {\nlet myName = firstName + ' ' + lastName;\nconsole.log(myName);\n}", "function ambito(variableGlobal){\n\n let variableLocal = \"Variable local\";\n\n console.log(variableGlobal);\n console.log(variableLocal);\n console.log(numeroGlobal.toString());\n}", "function foo(str) {\n\tvar name = \"foo\";\n\tconsole.log(str);\n}", "function ficha (nombre = 'Martin', actividad = 'Enseñar Java'){\n console.log(`1 La persona: ${nombre}, se ecarga de ${actividad}`)\n}", "function demoName(name){\n\n console.log(\"Name is : \", name);\n console.log(`\n Hello there!!!, ${name}...\n\n How are you?\n It's been a long while since I have seen you ${name}\n `);\n}", "function infoOutput(idString, data)\r\n{\r\n let elementRef = document.getElementById(idString);\r\n elementRef.innerHTML = \"<b>\" + data + \"</b>\";\r\n}", "function meYeah() {\n return 'Me, yeah Me.<br>';\n \n}", "function halo() {\n return '\"Halo Sanbers!\"';\n}", "function logInfo(info)\n{\n $('<p>' + info + '</p>').appendTo(document.body);\n}", "function disp_details(name, age, mail) {\n console.log(name);\n console.log(age);\n //console.log(mail);\n}", "function printSomething(){\n console.log(\"Something..\");\n }", "function hola(nombreyapellidos){\n console.log(\"como estas, \" + nombreyapellidos)\n}", "function hello(arg) {\n return `Hello, ${arg}!`\n}", "function saludar(nombre, apellido) { \n console.log(`Hola ${nombre} ${apellido}`);\n}", "function hello(){\n //console.log(\"Hi\");\n return \"Hi\";\n}", "function showInfo(info) {\n \"use strict\";\n console.log(this);\n console.log(info);\n}", "function helloWord() {\n console.log(\" cette fct hello ne return pas de val , il affiche juste un log !!!! \");\n}", "function sayHello3(name, age){\n // `(백틱)으로 String을 입력하고 필요한 변수를 ${변수명}을 통해 넣어준다.\n console.log(`Hello ${name} you are ${age} years old.`);\n}", "function printVar2() {\n const costanza = 'Belongs to the local scope of a function.'\n console.log(costanza); //Belongs to the local scope of a function.\n\n}", "function display(result) {\n console.log(`the result is: ${result}`)\n}", "function namastey() {\r\n return 'Hello in India';\r\n}", "function successPrint(){\n console.log(\"My name is Akash\");\n}", "function Global_1() { \n document.write(str + \"World! <br>\");\n}", "function myString(stringvalue) { //al stringvalue, cuando se haga el console.log se le da el valor. \n return stringvalue + 'Hola';\n}", "function nombre() {\n var miApellido = \"Rodriguez\";\n console.log(miNombre + \" \" + miApellido);\n}", "function SaludarConProfesion(nombre=\"Persona\", profesion=\"Estudiante\"){\nreturn `Hola soy ${nombre} mi profesion es ${profesion}`\n}", "function namstey() {\n return \"Hello in India\";\n}", "function mojaFunkcija() {\n let poruka = \"Zdravo svete!\";\n console.log(poruka);\n}", "function saludar() {\n console.log(`Hola ${nombre}`);//ESTOY HACIENDO REFERENCIA A LA VARIABLE GLOBAL nombre, AUNQUE NO LA HAYA RECIBIDO COMO PARAMETRO\n}", "function pizzaVegeterijana() {\n return `Hello`;\n}", "get info() {\n return `\nId: ${this.Id}\nName: ${this.name}\nPrice: ${this.price}\nAuthor: ${this.author}\nPublish Date: ${this.publishDate}\n`;\n }", "toString() {\n let info = \"<p>El nombre de la Centuria es \" + this.nombreCenturia + \"<br>\";\n info += \"El nombre de la Legion es \" + this.nombreLegion + \"<br>\"\n info += \"La centuria esta destinada en \" + this.provincia + \"<br></p>\";\n return (info);\n }", "function hai(){\n\treturn \"haiiii\"\n}", "function output(str) {\n print(str);\n}", "function printName() {\n console.log(\"vardas\", vardas);\n}", "function print() {\r\n return \"Lara Mahfouz\";\r\n }", "function myName() {\n\t\tvar name = 'Justin Hong';\n\t\tconsole.log(name);\n\t}", "function sayHello(name , age){\n return console.log(`Hello ${name} you are ${age} years old`);\n }", "function dynamicGreeting(firstName, lastName){\r\n let fullName = `${firstName} ${lastName}`\r\n console.log(`Hello my name is ${fullName}`)\r\n}", "function someProcess() {\n let myName = \"X-AE-12\";\n console.log(myName);\n}", "function statement() {\n\n}", "function greet(name){ //parameter\n console.log('Hello '+ name + \", My name is Hal.\");\n}// NOTE no semicolon", "function printf(naaam) {\n console.log(naaam)\n}", "function hello(name) { \n return `Hello there, ${name} !`;\n}", "function haveFun(activityName='play soccer', time=3){\n console.log(`Today I'll go ${activityName} for ${time} hours.`);\n}", "function hello(first, last){\n let myName = first + ' ' + last;\n console.log(`Hello, ${myName}.`); //In order for $ to work use backtics ``\n}", "function hello(name=\"World!\")\n{\n console.log(`Hello ${name}`);\n}", "function print(value){ // => the word value here is a parameter/placeholder/passenger\r\n console.log(value);\r\n }", "function saludo(nombre = 'Visitante')\r\n{\r\n return `Hola ${nombre}`\r\n}", "function sayHello(first_name, last_name){\n console.log(`Hellow there ${first_name} ${last_name}!`)\n}", "function showMessage_v2() {\n userName = \"Poster\"\n let alertMess= \"Hello, world \" + userName; // Hello, world Póter\n console.log(alertMess); // Hello, world Póter\n}", "function greeting(yourName) {\r\n var result = 'Hello' + ' ' + yourName;\r\n console.log(result);\r\n}", "function sayHello(who){\n console.log(`Hello, ${who}`);\n}", "function theFunction(name, profession) {\n console.log(\"My name is \" + name + \" and I am a \" + profession + \".\");\n}", "function info(text) {\n\tdocument.getElementById('info').innerText = text;\n}", "function Kenalan () {\n console.log(`Nama Saya, Jane`)\n console.log(`Saya Suka Masak`)\n console.log(`Sekian`)\n}", "function displayPerson(person){\n let personInfo = \"First Name: \" + person.firstName + \"\\n\";\n personInfo = \"Last Name: \" + person.lastName + \"\\n\";\n personInfo += \"Gender: \" + person.gender + \"\\n\";\n personInfo += \"Height: \" + person.height + \"\\n\";\n personInfo += \"Weight: \" + person.weight + \"\\n\";\n personInfo += \"Date of Birth: \" + person.dob + \"\\n\";\n personInfo += \"Occupation: \" + person.occupation + \"\\n\";\n personInfo += \"Eye Color: \" + person.eyeColor + \"\\n\";\n alert(personInfo);\n}", "function sayName(name){\n return console.log(`hello ${name}`);\n}", "function printUserData() {\n\n\treturn `Hello World, this is ${data.name} with HNGi7 ID ${data.hngi_id} and email ${data.email} using ${data.language} for stage 2 task`;\n\t\n}", "function info() {\n\tseperator();\n\tOutput('<span>>info:<span><br>');\n\tOutput('<span>Console simulator by Mario Duarte https://codepen.io/MarioDesigns/pen/JbOyqe</span></br>');\n}", "function sayName() {\r\n console.log(\"Line no 6: \", name)\r\n}" ]
[ "0.6570786", "0.65148836", "0.649348", "0.645016", "0.6449499", "0.6415561", "0.63766986", "0.6336509", "0.63353133", "0.6320371", "0.63149875", "0.63149875", "0.63149875", "0.629983", "0.6297747", "0.6274274", "0.62443835", "0.62426233", "0.6231536", "0.6215583", "0.6197755", "0.618992", "0.61719495", "0.6169579", "0.6166747", "0.61596453", "0.6158644", "0.61547166", "0.61491334", "0.61491334", "0.61336744", "0.61186945", "0.611697", "0.61165303", "0.610629", "0.6106169", "0.60840607", "0.60598636", "0.6059801", "0.6059801", "0.60553104", "0.6051826", "0.60492307", "0.6048098", "0.60365254", "0.6030518", "0.6025635", "0.60168266", "0.6012717", "0.59994286", "0.5992644", "0.5989987", "0.5985725", "0.5973896", "0.59664154", "0.595655", "0.5951062", "0.5950093", "0.59481955", "0.59457207", "0.59430027", "0.5941531", "0.5937966", "0.59352183", "0.59351325", "0.59248185", "0.59240854", "0.5923302", "0.5909887", "0.5908961", "0.59081465", "0.5905654", "0.5901936", "0.5901564", "0.59001994", "0.58998305", "0.58921605", "0.58919746", "0.5891234", "0.58884203", "0.5883418", "0.5882656", "0.5879701", "0.5879606", "0.58792144", "0.58760995", "0.5874782", "0.5871723", "0.5857471", "0.5856688", "0.58562815", "0.5856041", "0.58509994", "0.584698", "0.58405435", "0.58399403", "0.58387536", "0.5837591", "0.5836443", "0.5833898", "0.5833856" ]
0.0
-1
Simple helper function, which return all filters from state by given key.
function getFilters(key, movies) { return movies.reduce((acc, movie) => { if (!acc.includes(movie[key])) { return [...acc, movie[key]]; } return acc; }, []); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getAll(filter) {\n\t\t// this flattens the hash into an array\n\t\tlet result = _.map(this._cache);\n\n\t\tif (typeof filter === 'object') {\n\t\t\tresult = _.where(result, filter);\n\t\t}\n\n\t\treturn result;\n\t}", "isFiltered(key) {\n const item = this._.get(key);\n return item ? item.filtered : false;\n }", "function getFilters() {\n var filters = [];\n\n _.forEach($scope.data.filters, function(value, key){\n //filter applied\n if(value.filterApplied && value.filterValue) {\n\n var filterObject = {}\n filterObject.key = value.key;\n filterObject.type = value.filterApplied;\n\n //convert string to number if necessary\n if(value.type == 'number' || value.type == 'currency'){\n if(value.filterApplied == 'range') {\n filterObject.value = value.filterValue\n } else {\n filterObject.value = parseInt(value.filterValue);\n }\n } else {\n filterObject.value = value.filterValue;\n }\n\n if(value.type == 'category' && value.filterValue.length == 0) {\n return\n }\n else {\n //push into filter array\n filters.push(filterObject);\n }\n\n }\n //push in if either of these filters\n else if(value.filterApplied == 'is-unknown' || value.filterApplied == 'has-any-value'){\n var filterObject = {}\n filterObject.key = value.key;\n filterObject.type = value.filterApplied;\n filters.push(filterObject);\n }\n //exception for date is unknown, etc\n else if (value.filterApplied == 'date-is-unknown' || value.filterApplied == 'date-has-any-value'){\n\n var filterObject = {}\n filterObject.key = value.key;\n filterObject.type = value.filterApplied;\n\n filters.push(filterObject);\n }\n })\n return filters;\n}", "function get_filters() {\n\tvar filters = [];\n\tif($(\"input[id=toggle-all]\").is(\":checked\")) {\n\t\tfilters = all_filters;\n\t} else {\n\t\t$(\"input[id^=toggle]\").each(function(index,element) {\n\t\t\tif($(element).is(\":checked\")) {\n\t\t\t\tconsole.log(element);\n\t\t\t\tfilters.push($(element).val());\n\t\t\t}\n\t\t});\n\t}\n\n\tif(filters.length == 0){\n\t\tfilters = all_filters;\n\t}\n\n\treturn filters\n}", "keys(key) {\n return state[`keys.${key}`] || [];\n }", "function widgetThat(key) {\n return new Map([...widgets].filter(([, v]) => v[key]));\n }", "function filterKey(array, key) {\n\treturn array.filter(function(value) {\n\t\treturn value[key] === true;\n\t})\n}", "function FilteredGroupsThatIncludeState(groups, search_state_name) {\n var filtered_groups = []\n for (var key in groups) {\n if (groups.hasOwnProperty(key)) {\n if (groups[key].filter( (state_name) => { return state_name == search_state_name } ).length > 0) {\n filtered_groups.push(key)\n }\n }\n }\n return filtered_groups\n}", "filtered(data) {\n if (!this.state.filter) {\n return data;\n }\n\n let parts = this.state.filter.split(\" \").map(f => f.toLowerCase());\n\n return data.filter(d => {\n return parts.every(p => {\n let [ns, key] = d.key;\n\n if (ns !== null && ns.toLowerCase().indexOf(p) != -1) {\n return true;\n }\n\n if (typeof key !== \"object\") {\n return false;\n }\n\n let any = false;\n\n for (let keyName in key) {\n let v = key[keyName];\n\n if (typeof v === \"string\") {\n any = v.toLowerCase().indexOf(p) != -1;\n\n if (any) {\n break;\n }\n }\n }\n\n return any;\n });\n });\n }", "function getAllFilters(callWithRequest) {\n const mgr = new FilterManager(callWithRequest);\n return mgr.getAllFilters();\n}", "function filterAll() {\n return filterIndex((refilter = crossfilter_filterAll)(values));\n }", "function getUsedKeys(filter) {\n if (!filter) {\n return [];\n }\n const usedKeys = [];\n if (filter.$and) {\n for (const subfilter of filter.$and) {\n for (const key of getUsedKeys(subfilter)) {\n if (!usedKeys.includes(key)) {\n usedKeys.push(key);\n }\n }\n }\n } else if (filter.$or) {\n for (const subfilter of filter.$or) {\n for (const key of getUsedKeys(subfilter)) {\n if (!usedKeys.includes(key)) {\n usedKeys.push(key);\n }\n }\n }\n } else if (filter.yg) {\n // Single filter grouped in brackets\n usedKeys.push(...getUsedKeys(filter.yg));\n } else {\n usedKeys.push(...Object.keys(filter));\n }\n\n return usedKeys;\n}", "getFilters() {\r\n let filters = {};\r\n filters.limit = this.state.limit;\r\n filters.offset = this.state.offset;\r\n filters.md5sum = this.state.tag_md5sum;\r\n filters.controller = 'tagmanager/scans';\r\n filters.omit_tag = this.state.tagTitle ? 't' : 'f';\r\n return filters;\r\n }", "function getCheckFilters(filter) {\n switch (filter) {\n case 'brand':\n return getCheckFilterByClass('brand-filter-input');\n case 'returnable':\n return getCheckFilterByClass('returnable-filter-input');\n }\n}", "function getFilters(obj, type) {\n return _.result(obj, 'filters').reduce((arr, filter) => {\n const fn = filter[type];\n return fn ? [...arr, fn.bind(obj)] : arr;\n }, []);\n }", "filterList(filter) {\n this.filter = filter.toLowerCase();\n const stateInstances = {};\n const keys = Object.keys(this.instances);\n for (let i = 0; i < keys.length; i += 1) {\n if (!this.isFiltered(keys[i])) {\n stateInstances[keys[i]] = this.instances[keys[i]];\n }\n }\n\n this.setState({ instances: stateInstances });\n }", "function filterByState(state){\r\n\r\n let filtered = countyNames.filter(e=> e.state === state)\r\n let result = []\r\n filtered.forEach(e=>result.push(e.county+ \":\" + e.state))\r\n //result.push(\"all:\"+state)\r\n return(result)\r\n}", "getFilterInfo(name) {\n let filterInfo = [],\n notSpecific = name === undefined ? true : false\n this.selectedFilters.forEach(nameSelected => {\n if (notSpecific) {\n name = (typeof nameSelected === 'string'\n ? nameSelected\n : nameSelected[0]\n ).toLowerCase()\n }\n\n Object.entries(ENV.APP.filters).some(categoryFilter => {\n return Object.entries(categoryFilter[1]).some(filters => {\n return filters[1].some(filterName => {\n filterName = filterName.name || filterName\n if (\n filterName.toLowerCase() === name &&\n filterInfo.every(entry => entry[0] !== name)\n ) {\n filterInfo.push([name, categoryFilter[0], underscore(filters[0])])\n return true\n }\n })\n })\n })\n })\n return filterInfo\n }", "filteredListings() {\n const filter = this.state.filters.name\n if (this.state.filters.name === 'All') return this.sortedListings()\n return this.sortedListings().filter(category => {\n return category.categories.some(category => category.name === filter)\n })\n }", "function get_checkbox_filters(type) {\n var filters = {};\n var boxes = Y.all('#filter-form .'+type+' input[type=checkbox]');\n Y.log('Getting starting '+type+' filters');\n boxes.each(function(box) {\n var name = box.getData('filter-refine');\n var checked = box.get('checked');\n Y.log('Checking filter '+name+'.');\n if (checked) {\n Y.log('Filter '+name+' is active!');\n filters[name] = checked;\n }\n });\n return filters;\n }", "getState() {\n return this._filterHandler.cachedFilter;\n }", "getState() {\n return this._filterHandler.cachedFilter;\n }", "function getFilters(item, slot) {\n let result = new Set();\n if (slot in item._props && item._props[slot].length) {\n for (let sub of item._props[slot]) {\n if (\"_props\" in sub && \"filters\" in sub._props) {\n for (let filter of sub._props.filters) {\n for (let f of filter.Filter) {\n result.add(f);\n }\n }\n }\n }\n }\n\n return result;\n}", "function sampleFilterHandler (key) {\n let x = [...sampleFilter];\n x[key] = {...x[key], active: !x[key].active};\n setSampleFilter(x);\n x = null;\n }", "getCookiesFilters() {\n\t\tconst cookiesFilters = Cookies.get();\n\t\tif (cookiesFilters.price) {\n\t\t\tcookiesFilters.price = cookiesFilters.price.split('_');\n\t\t}\n\t\tif (cookiesFilters.size) {\n\t\t\tcookiesFilters.size = cookiesFilters.size.split('_');\n\t\t}\n\n\t\tfor (const propC in cookiesFilters) {\n\t\t\tfor (const propF in this.filters) {\n\t\t\t\tif (propC === propF) {\n\t\t\t\t\tthis.filters[propF] = cookiesFilters[propC];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "getState() {\n return Object.keys(this.items).reduce((acc, k) => {\n const value = this.items[k]\n if (hasKey(value))\n acc.push(value)\n else if (value)\n acc.push(k)\n return acc;\n }, []);\n }", "function getInputs() {\n return filter.value == 'all' ? target.value : target.value + \"/\" + filter.value + \"/\" + key.value;\n}", "function filterfunction() {\n let filterdata = tableData;\n Object.entries(filters).forEach(([key, value]) => {\n filterdata = filterdata.filter(uSighting => uSighting[key] === value);\n });\n buildtable(filterdata);\n\n}", "function TabAjaxFilterByKey(key) {\n return $('input[name^=\"filter\"][filter=\"' + key + '\"]').val();\n}", "filter () {\n let ch = this.next();\n let args = [];\n let nextFilter = function (v) { return v };\n let name = this.name();\n\n if (!options.filters[name]) {\n options.onError('Cannot find filter by the name of: ' + name);\n }\n\n ch = this.white();\n\n while (ch) {\n if (ch === ':') {\n ch = this.next();\n args.push(this.expression('|'));\n }\n\n if (ch === '|') {\n nextFilter = this.filter();\n break\n }\n\n if (ch === ',') { break }\n\n ch = this.white();\n }\n\n var filter = function filter (value, ignored, context, globals, node) {\n var argValues = [value];\n\n for (var i = 0, j = args.length; i < j; ++i) {\n argValues.push(Node$1.value_of(args[i], context, globals, node));\n }\n\n return nextFilter(options.filters[name].apply(null, argValues))\n };\n\n // Lowest precedence.\n filter.precedence = 1;\n return filter\n }", "function allFilters() {\n const emptyFilters = facetSearchData.reduce((acc, facet) => (\n { ...acc, [facet.datafield]: [] }\n ), {});\n return emptyFilters;\n}", "function getFilters(callback) {\n var filterList=[];\n fetch('/filters', {\n accept: \"application/json\"\n })\n .then(response => response.json())\n .then(response => {\n response.forEach((element) => {\n let curr = {\n label:element.filter,\n value:element.id,\n }\n\n filterList.push(curr);\n });\n return filterList\n })\n .then(callback)\n}", "function filterAll() {\n\t return filterIndexBounds((refilter = crossfilter_filterAll)(values));\n\t }", "function filterData() {\n selectedData = dataByState.filter(function (d) {\n return selectedStates.indexOf(d.key) > -1\n })\n }", "function build_filter( key, handle ){\n\t\tvar filter = $scope.filter[ handle ]\n\t\tif ( filter == null ){\n\t\t\treturn angular.copy( { optional:true } );\n\t\t}\n\t\treturn angular.copy({ filter:'regex( '+key+', \"'+ filter +'\", \"i\" )' });\n\t}", "function getFilters(element) {\n var id = element.attr('databind-id');\n var filters = filtersCache[id];\n if(!filters) {\n filters = [];\n var filterEls = element.children('twx-data-filter');\n angular.forEach(filterEls, function (el) {\n filters.push(new Function('value', '$filter', el.attributes['filter-body'].value)); // jshint ignore:line\n });\n filtersCache[id] = filters;\n }\n return filters;\n }", "function buildFilter() {\r\n // add array to hold all filter key-value pairs\r\n var inputArray = {};\r\n\r\n // select input value, log input value, then append non-null values to array\r\n var stateInput = d3.select('#stateSelect').property('value');\r\n console.log(stateInput);\r\n if (stateInput !== '') {\r\n inputArray['state'] = stateInput;\r\n };\r\n \r\n // select input value, log input value, then append non-null values to array\r\n var countryInput = d3.select('#countrySelect').property('value');\r\n console.log(countryInput);\r\n if (countryInput !== '') {\r\n inputArray['country'] = countryInput.toLowerCase();\r\n };\r\n \r\n // select input value, log input value, then append non-null values to array\r\n var shapeInput = d3.select('#shapeSelect').property('value');\r\n console.log(shapeInput);\r\n if (shapeInput !== '') {\r\n inputArray['shape'] = shapeInput;\r\n };\r\n \r\n console.log(inputArray);\r\n return inputArray;\r\n}", "function getFilters() {\r\n var filtersData = localStorage.getItem(\"TimeLapseFiltersData\");\r\n if (filtersData != null) {\r\n return JSON.parse(filtersData);\r\n } else {\r\n return {\r\n startDate: defaultStartDate,\r\n endDate: defaultEndDate,\r\n provincesFilter: columnNames.reduce(function(acc, curr) {\r\n acc[curr] = true;\r\n return acc;\r\n }, {})\r\n };\r\n }\r\n}", "function querySearch (query) {\r\n var results = query ? self.states.filter( createFilterFor(query) ) : [];\r\n return results;\r\n }", "filter(filters) {\n for (const prop of Object.keys(filters)) {\n if (typeof filters[prop] === 'function') {\n continue;\n }\n const val = this.getGraphQLValue(filters[prop]);\n if (val === '{}') {\n continue;\n }\n this.head.push(`${prop}:${val}`);\n }\n return this;\n }", "filter(filters) {\n for (const prop of Object.keys(filters)) {\n if (typeof filters[prop] === 'function') {\n continue;\n }\n const val = this.getGraphQLValue(filters[prop]);\n if (val === '{}') {\n continue;\n }\n this.head.push(`${prop}:${val}`);\n }\n return this;\n }", "function getFilters() {\n\tvar arr = [];\n\tfor (var i = 0; i < 4; i ++) {\n\t\tarr.push({\n\t\t\tid: \"fId_\" + i,\n\t\t\ttitle: \"Filter \" + i,\n\t\t\ttype: \"select\", // probably only ever need this type\n\t\t\tselected: null,\n\t\t\toptions: getOptions(i)\n\t\t});\n\t}\n\treturn arr;\n}", "filterBuilderFilter() {\n const that = this,\n filterSettings = that.filterBuilder.value,\n caseSensitive = that.context.filterType === 'string' ? that.caseSensitive.checked : false,\n filterResult = { filters: [] };\n\n function recursion(currentContext, collection) {\n const filterObject = new Smart.Utilities.FilterGroup(),\n operator = currentContext[1];\n\n collection.logicalOperator = operator;\n\n for (let i = 0; i < currentContext.length; i++) {\n if (i === 1) {\n continue;\n }\n\n const node = currentContext[i];\n\n if (Array.isArray(node)) {\n if (Array.isArray(node[0])) {\n const subCollection = { filters: [] };\n\n collection.filters.push(subCollection);\n recursion(node, subCollection);\n }\n else {\n filterObject.addFilter(operator, that.createFilterBuilderFilter(filterObject, node, caseSensitive));\n }\n }\n }\n\n if (filterObject.filters.length > 0) {\n collection.filters.push(filterObject);\n }\n }\n\n recursion(filterSettings, filterResult);\n that.filterBuilderObject = filterResult;\n that.cachedFilter = {\n filterBuilder: JSON.parse(JSON.stringify(that.filterBuilder.value), function (key, value) {\n return /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})Z$/.test(value) ? new Date(value) : value;\n }),\n caseSensitive: caseSensitive\n };\n }", "function buildBooleanFilters() {\n var result = {};\n\n if (CONFIG.provider.hasOwnProperty('filters')) {\n var filters = CONFIG.provider.filters;\n\n // Check for boolean filters.\n if (filters.hasOwnProperty('boolean')) {\n for (var i = 0; i < filters.boolean.length; i++) {\n var filter = filters.boolean[i];\n result[filter.field] = {\n 'name': filter.name,\n };\n }\n }\n }\n\n return result;\n }", "filterSimCardBy(key){\n if(key){\n // Reset when re-select supplier\n this.pagination = this.resetPagination()\n this.currentSupplierActive = key\n let initBody = SimCardUtil.getDefaultConfigRequestFilter()\n initBody.Supplier = key // supplier name\n this.requestFilterListItems(initBody)\n }\n }", "function get_filter(type_of_service){\n var filter = [];\n $('.'+type_of_service+':checked').each(function(){\n filter.push($(this).val());\n });\n\n return filter;\n }", "getFilteredTodos() {\r\n const {todos, filter} = this.state;\r\n switch(filter) {\r\n case 'Active':\r\n return todos.filter(todo => (todo.active));\r\n case 'Finished':\r\n return todos.filter(todo => (!todo.active))\r\n default:\r\n return todos; \r\n }\r\n }", "keys() {\n\t\treturn Object.keys(this.state());\n\t}", "_getAllItem(filter, keys = constant.DB_FETCH[this.actualDbName]) {\n\t\tif (!this.db) this.db = factory.resolveInstance(this.actualDbName);\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.db.find(filter).select(keys).lean().exec((error, value) => {\n\t\t\t\terror && console.log(error);\n\t\t\t\tif (value) {\n\t\t\t\t\treturn resolve({ value: value });\n\t\t\t\t} else {\n\t\t\t\t\treturn resolve({ error: \"Something went wrong.\" });\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}", "function toggleFilter(key, valueList) {\n //Search if the filter already exists and if so, remove the filter and refresh the views.\n // Else add the new filter to filters_list and fetch new filtered data.\n var current_filters_for_key = null;\n var newValues = valueList.map(function(d) { return d.key; });\n if(key in filters_list) {\n current_filters_for_key = filters_list[key];\n var newList = [];\n newValues.forEach(function(newValue) {\n if(!(current_filters_for_key.includes(newValue))) {\n newList.push(newValue);\n }\n });\n current_filters_for_key.forEach(function(oldValue) {\n if(!(newValues.includes(oldValue))) {\n newList.push(oldValue);\n }\n });\n current_filters_for_key = newList;\n } else {\n current_filters_for_key = valueList.map(function(d) { return d.key; });\n }\n //Update filter values for the sent key\n if(current_filters_for_key.length > 0)\n filters_list[key] = current_filters_for_key;\n else {\n delete filters_list[key];\n }\n //Refresh Views with new data\n fetchAndRender(filters_list);\n}", "filterBooksBySearch(key,value) {\n //update state by search parameters passed from search module to actions to store\n this.setState({\n key: key,\n query: value.toLowerCase()\n });\n }", "function selected (key, val) {\n this.filters[key] = val;\n console.log(this.filters);\n}", "getConditions(cb) {\n this.session.get({ url: this.url + '/api/filter/conditions' }, cb);\n }", "function findStates()\n{\n var filter = '';\n\n superGroupSearchService.findStates(filter, populateStates);\n\n return false;\n}", "@computed\n get activeFilters() {\n if (this.filters.length == 0) {\n return [];\n }\n return map(this.filters, d => {\n const active =\n isEmpty(this.activeFilterIdsById) ||\n this.activeFilterIdsById[d.id] != undefined;\n return { ...d, active };\n });\n }", "function getActions() {\n\t var newFilters = [];\n\t var oldFilters = [];\n\n\t stateWatchers.forEach(function (watcher, i) {\n\t var nextVal = next[i];\n\t var prevVal = prev[i];\n\t newFilters = newFilters.concat(nextVal);\n\t oldFilters = oldFilters.concat(prevVal);\n\n\t // no update or fetch if there was no change\n\t if (nextVal === prevVal) return;\n\n\t if (nextVal) doUpdate = true;\n\n\t // don't trigger fetch when only disabled filters\n\t if (!onlyDisabled(nextVal, prevVal)) doFetch = true;\n\t });\n\n\t // make sure change wasn't only a state move\n\t // checking length first is an optimization\n\t if (doFetch && newFilters.length === oldFilters.length) {\n\t if (onlyStateChanged(newFilters, oldFilters)) doFetch = false;\n\t }\n\t }", "getQueryParameters(key) {\n if (key) {\n const values = this.queryParams[key.toLowerCase()];\n if (typeof values == 'string') {\n const result = [];\n result.push(values);\n return result;\n }\n else if (Array.isArray(values)) {\n return values;\n }\n }\n else {\n return this.queryParams;\n }\n return null;\n }", "filterResults({searchValue, areaFilters, typeFilters}) {\n const argsString = JSON.stringify(arguments[0]); // eslint-disable-line\n if (this.useCache && this.cache[argsString]) {\n return this.cache[argsString];\n }\n\n const {allParams} = this.state;\n\n // no filters\n if (!searchValue && !areaFilters.length && !typeFilters.length) {\n return this.memoize(argsString, this.state.allParams);\n }\n\n // all filters\n if (searchValue && areaFilters.length && typeFilters.length) {\n return this.memoize(argsString, this.filterTitle(searchValue, this.filterArea(areaFilters, this.filterType(typeFilters, allParams))));\n }\n\n // search and area\n if (searchValue && areaFilters.length) {\n return this.memoize(argsString, this.filterTitle(searchValue, this.filterArea(areaFilters, allParams)));\n }\n\n // search and type\n if (searchValue && typeFilters.length) {\n return this.memoize(argsString, this.filterTitle(searchValue, this.filterType(typeFilters, allParams)));\n }\n\n // area and type\n if (areaFilters.length && typeFilters.length) {\n return this.memoize(argsString, this.filterArea(areaFilters, this.filterType(typeFilters, allParams)));\n }\n \n // search only\n if (searchValue) {\n return this.memoize(argsString, this.filterTitle(searchValue, allParams));\n }\n \n // area only\n if (areaFilters.length) {\n return this.memoize(argsString, this.filterArea(areaFilters, allParams));\n }\n\n // type only\n if (typeFilters.length) {\n return this.memoize(argsString, this.filterType(typeFilters, allParams));\n }\n }", "function searchFilter(key) {\n let predicate = new Predicate('cardContent', 'Contains', key, true);\n predicate = predicate.or('cardImage.title', 'Contains', key, true).or('header_title', 'Contains', key, true).or('header_subtitle', 'Contains', key, true);\n data = new DataManager(cardBook).executeLocal(new Query().where(predicate));\n destroyAllCard();\n cardRendering(data);\n }", "function all() {\n return dictionary.slice();\n}", "function removeFilter(key) {\r\n delete(activeFilterList[key]);\r\n applyFilterList();\r\n }", "function get_filtered_types() {\n\t\n\tvar filters = [ 'locales' , 'skyshard' , 'lorebook' , 'boss' , 'treasure' ];\n\t$( '#marker-filters :checked' ).each( function() {\n\t\tfor( i = filters.length; i >= 0; i-- ) {\n\t\t\tif ( $(this).val() == filters[i] )\tfilters.splice( i , 1 );\n\t\t}\n });\n\t return filters;\n}", "function getSelectedFilters() {\n var selectedFilters = [];\n $('.logic-checkbox').each(function (index, value) {\n if (value.checked) { selectedFilters.push(value.id.split(\"-logic-checkbox\")[0]); }\n });\n return selectedFilters;\n}", "function filterAll() {\n emptyDatasets();\n filters[dimensionName] = members;\n return dimensionObj;\n }", "filterSupplierWithKey(key, suppliers) {\n\t\tkey = key.replace(/ +/g, '');\n\t\tlet filteredSuppliers = suppliers.filter(supplier => {\n\t\t\tlet supplierInfo = supplier.tedarikciAdi + supplier.ilAdi + supplier.ilceAdi + supplier.telNo;\n\t\t\tsupplierInfo = supplierInfo.replace(/ +/g, '');\n\t\t\treturn supplierInfo.toLowerCase().includes(key.toLowerCase());\n\t\t});\n\t\treturn filteredSuppliers;\n\t}", "function ListFilter(type, key, default_value, params)\n {\n var filter = this;\n filter.isolated = false;\n filter.getValue = getValue;\n filter.setValue = setValue;\n filter.hasDefaultValue = hasDefaultValue;\n init();\n\n ///////////\n\n /**\n * Initialize ListFilter.\n */\n function init()\n {\n if(typeof params === 'undefined' || params === undefined)\n {\n params = {};\n }\n filter.type = type;\n\n // KEYS\n filter.key = key;\n filter.static = !!params.static ? params.static : false;\n filter.query_key = params.query_key ? params.query_key : filter.key;\n\n // VALUES\n filter.default_value = default_value;\n if(params.value)\n {\n if(params.value === 'fromStateParams')\n {\n filter.setValue($stateParams[key] ? $stateParams[key] : default_value);\n }\n else\n {\n filter.setValue(params.value);\n }\n }\n else\n {\n filter.setValue(default_value);\n }\n\n // PARAMS\n filter.force_bool = !!params.force_bool;\n }\n\n /**\n * Get the computed value (null if default)\n * @returns {*}\n */\n function getValue()\n {\n if(hasDefaultValue())\n {\n return null;\n }\n if(typeof filter.value === 'boolean')\n {\n return filter.value ? 'True' : 'False';\n }\n return filter.value;\n }\n\n /**\n * Set the value.\n * @param value\n */\n function setValue(value)\n {\n if(filter.force_bool)\n {\n filter.value = !!value;\n }\n filter.value = value;\n }\n\n function hasDefaultValue()\n {\n return filter.value === filter.default_value;\n }\n }", "function FilterKeyExtractor(agent) {\n this.agent = agent;\n \n this.filterKeys = {};\n this.sampleNum = 0;\n}", "function parseFilters() {\n\t\t\tvar filter_regex = /^bind\\((.*)\\)$/,\n\t\t\t\tfilter, matches, selector, val, timestamp, $inp, type;\n\n\t\t\t// Empty filters\n\t\t\tparsedFilters = {};\n\n\t\t\tfor (var i = 0, filter_count = filters.length; i < filter_count; i++) {\n\t\t\t\tfilter = filters[i];\n\t\t\t\tif (filter_regex.test(filter[2])) {\n\t\t\t\t\tmatches = filter_regex.exec(filter[2]);\n\t\t\t\t\tif (matches.length == 2) {\n\t\t\t\t\t\tselector = '[name=\"'+matches[1]+'\"]';\n\t\t\t\t\t\t$inp = $formFilter.find('input'+selector+', select'+selector).eq(0);\n\t\t\t\t\t\ttype = $inp.attr('type');\n\t\t\t\t\t\tval = $inp.val();\n\n\t\t\t\t\t\t// If field has been initialized with datepicker, change value to unix timestamp\n\t\t\t\t\t\t// TODO: Can this be better somehow?\n\t\t\t\t\t\tif (val && $inp.hasClass('hasDatepicker')) {\n\t\t\t\t\t\t\ttimestamp = $.datepicker.parseDate('dd-mm-yy', val);\n\t\t\t\t\t\t\t// Convert to unix timestamp, adjusting to UTC timezone\n\t\t\t\t\t\t\tval = (timestamp.getTimezoneOffset() * -60) + (timestamp.getTime() / 1000);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Use filter, unless it's an unchecked checkbox input or value is identical to placeholder\n\t\t\t\t\t\tif (val && val != $inp.attr('placeholder') && (type != 'checkbox' || $inp.is(':checked'))) {\n\t\t\t\t\t\t\tparsedFilters[filter[0]] = val;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tparsedFilters[filter[0]] = filter[2];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn parsedFilters;\n\t\t}", "handleOnChange(event) {\n const { appliedFilters: appliedFiltersList } = this.state;\n const result = CommonHelper.getSelectedFilters(event, appliedFiltersList);\n this.setState({ appliedFilters: [...result] }, this.handleOnChangeFilters);\n }", "getEntitiesByState(state){\n let result = this.getAllEntitiesWithState().filter(e => e.state.getState() === state);//e: entity e.state: StateComponent\n if(result)\n return result;\n else\n return [];\n }", "function checkAll(qnodeId, propertyKey) {\n const check = isPropFiltered(filterKeys[qnodeId][propertyKey]);\n Object.keys(filterKeys[qnodeId][propertyKey]).forEach((propertyValue) => {\n filterKeys[qnodeId][propertyKey][propertyValue][0] = check;\n });\n const newFilterKeys = _.cloneDeep(filterKeys);\n setFilterKeys(newFilterKeys);\n updateFilter(newFilterKeys);\n }", "function filterParam(field) {\n var key = field[0],\n value = field[1],\n namespace = key.replace(/\\[\\]$/, '').replace(/\\[/, ' ').replace(/\\]/, '');\n \n filters = new Hash(filters);\n \n if (filters.keys().include(key)) return [key, applyFilter(filters.get(key), value)];\n \n var match;\n filters.each(function (pair) {\n if (namespace.match('\\\\s' + pair.key + '$')) {\n match = [key, applyFilter(pair.value, value)];\n throw $break;\n }\n });\n \n filters = filters.toObject();\n return match || field;\n }", "function filterStateRegistry(registry) {\n const storeModules = {};\n registry.forEach((value, key) => {\n if (value instanceof EntityStore) {\n return;\n }\n\n storeModules[key] = value;\n });\n\n return storeModules;\n }", "activeMonthFilters (state, { monthsFiltersToShow }) {\n return monthsFiltersToShow.filter(filter => filter.active)\n }", "function all(filter, type) {\n switch (type) {\n case \"make\":\n return cars.filter(function (car) {\n return car.make === filter;\n });\n break;\n case \"price\":\n // code block\n break;\n case \"year\":\n\n default:\n // code block\n }\n}", "async getFilterChoices(filter) {\n const object = await Params.objectProps(filter.for_object);\n if ((object.name in mbtaApiObjectPaths) && (filter.json_path)) {\n const response = await fetch(mbtaApiObjectPaths[object.name]);\n const json = await response.json();\n const internalValues = getUniqueValues(json, filter.json_path);\n const choices = await mapFilterValuesToNames(filter, internalValues);\n return choices.sort(getFilterSortFunction(filter));\n } else {\n return [];\n }\n }", "function getAll(filter) {\n const requestOptions = {\n method: \"GET\",\n headers: authHeader.get(),\n credentials: \"include\"\n };\n\n //case filter type status ==> http://slackcart.com/api/v1/workflows/?status=<status_id>\n //case filter type kind ==> http://slackcart.com/api/v1/workflows/?kind=<kind_id>\n //case filter type multi ==> http://slackcart.com/api/v1/workflows/?answer=<field_tag>__<operator>__<value>\n //case filter type multi ==> http://slackcart.com/api/v1/workflows/?stepgroupdef=<stepgroup_id>\n\n let filters = store.getState().workflowFilters,\n filterParams = getFilterParams(filters),\n url = baseUrl + \"workflows-list/\";\n\n url += filterParams;\n\n if (filter) {\n const params = pageUrl(filter);\n url += params;\n }\n return fetch(url, requestOptions).then(handleResponse);\n}", "function filteringStates(members) {\n var filteredArray = [];\n // Value are the letters of the State\n var selectedValue = document.getElementById(\"dropDownMenu\").value;\n\n if (selectedValue == \"ALL\") {\n createTable(members);\n } else {\n for (var i = 0; i < members.length; i++) {\n if (selectedValue.includes(members[i].state)) {\n filteredArray.push(members[i]);\n }\n }\n createTable(filteredArray);\n }\n}", "function filterTable() {\n\n filteredData = tableData\n\n// Loop through all of the filters and keep any data that\n// matches the filter values\n Object.entries(filters).forEach(([key,value]) => {\n filteredData = filteredData.filter(x => x[key] === value)\n console.log(key,value)\n })\n\n// Finally, rebuild the table using the filtered data\n buildTable(filteredData)\n\n console.log(filteredData)\n}", "function updateFilters(){\r\n\tif (event.keyCode != 13) return;\r\n\t\r\n\tvar keys = document.getElementById(\"pattern_input\").value;\r\n\tkeys = keys.replace(' ', '');\r\n\tkeys = keys.split(',');\r\n\t\r\n\tkeys.forEach(function(key){\r\n\t\tvar regex = buildRegex(key);\r\n\t\tfilterStack.push(function(d){ return d.RAW.match(regex)==null });\r\n\t})\r\n\t\r\n\tupdateViews();\r\n}", "function familyFilter() {\n return func;\n\n ////////////////\n\n function func(items, filters) {\n \tvar filtered = [];\n\t\t\tangular.forEach(items, function(item) {\n\t\t \t\tif(filters.indexOf(item.config.family) > -1 || filters.length === 0) {\n\t\t\t\t \tfiltered.push(item);\n\t\t \t\t}\n\t\t\t});\n\t\t\treturn filtered;\n }\n }", "function get_filter_values()\r\n{\r\n\tvar elems = $('#filter input,select')\r\n\tif(!elems.length)\r\n\t\treturn '' // page has no filters\r\n\r\n\tvar vals = {}\r\n\tfor(var i = 0; i < elems.length; i++)\r\n\t{\r\n\t\tvar e = elems[i]\r\n\t\tvar id = $(e).prop('id')\r\n\t\t\r\n\t\tif(!id.startsWith(core_context.content + '-filter-'))\r\n\t\t\tcontinue\r\n\r\n\t\tvar val = get_input_value(id)\r\n\t\tvar val_cookie = $.cookie(id)\r\n\t\t\r\n\t\t//~ if(val_cookie !== undefined && val_cookie != '')\r\n\t\t\t//~ val = val_cookie;\r\n\t\t\r\n\t\tvals[id] = val\r\n\t\t$.cookie(id, val);\r\n\t\t\r\n\t}\r\n\r\n\treturn vals\r\n}", "function fillFilters() {\n let filterContainer = $(\".filter-container\");\n\n for (let filterKey in filters) {\n let domFilter = $(filterContainer).find(`[name=\"${filterKey}\"]`);\n domFilter.eq(0).val(filters[filterKey]);\n }\n\n for (let filterKey in enabledFilters) {\n if (enabledFilters[filterKey])\n $(filterContainer).find(`input[name=\"${filterKey}\"]`).prop('checked', true);\n }\n }", "getFilteredItems(query){\r\n return this.source.filter((item) =>item[this.getOptionLabel].toLowerCase().startsWith(query.toLowerCase(), 0) && !item.invisible);\r\n }", "getKeys() {\n this.logger.trace(\"Retrieving all cache keys\");\n // read cache\n const cache = this.getCache();\n return [...Object.keys(cache)];\n }", "function resFilter(resourceKey) {\n return resource.get(resourceKey);\n }", "function get_filters() {\n let ele = $(\".search-filters .search-filter-selected\").get();\n filter_results = ele.map((x) => $(x).text().toLowerCase());\n modal_filters = make_modal_body_filters(filters, filter_results);\n update_search(filter_results);\n}", "async applyFilter(key, filter) {\n switch (key) {\n case 'playerClass':\n await this._applyPlayerClassFilter(filter);\n break;\n case 'cardSet':\n await this._applyCardSetFilter(filter);\n break;\n case 'type':\n await this._applyTypeFilter(filter);\n break;\n case 'faction':\n await this._applyFactionFilter(filter);\n break;\n case 'rarity':\n await this._applyRarityFilter(filter);\n break;\n case 'race':\n await this._applyRaceFilter(filter);\n break;\n default:\n return -1;\n }\n\n /* after apply filter save info from cache and calls done */\n localStorage.setItem('HearthstoneDeckBuilderCallsDone', JSON.stringify(this._callsDone));\n localStorage.setItem(\n 'HearthstoneDeckBuilderCardsNoImageCache',\n JSON.stringify(this._cardsNoImageCache)\n );\n localStorage.setItem('HearthstoneDeckBuilderCardsCache', JSON.stringify(this._cardsCache));\n\n return this._cardsShown;\n }", "function getOnlyFromChannelsGetter(valProp) {\n return function(metric, filtersState) {\n let channelsArr;\n\n if (filters.hasNoActiveState(filtersState.channels)) {\n /* No channel filter, get all channels */\n channelsArr = filters.getAvailableFilterStates(filtersState.channels);\n } else {\n /* Filtered by channel, get only active channel */\n channelsArr = [filters.getActiveState(filtersState.channels)];\n }\n\n let data = dataResolvers.addChannelValues(channelsArr, metric, valProp, 'sum');\n\n return data\n };\n}", "get filterOptions() { // list state for filter\n let filterOptions = [\n 'All Orders',\n 'Waiting',\n 'Confirmed',\n 'Cancelled',\n ];\n if (!this.env.pos.tables) {\n return filterOptions\n } else {\n this.env.pos.tables.forEach(t => filterOptions.push(t.name))\n return filterOptions\n }\n }", "filterBuilderFilter() {\n const that = this,\n filterSettings = that.filterBuilder.value,\n caseSensitive = that.context.filterType === 'string' ? that.caseSensitive.checked : false,\n filterResult = { filters: [] };\n\n function recursion(currentContext, collection) {\n const filterObject = new JQX.Utilities.FilterGroup(),\n operator = currentContext[1];\n\n collection.logicalOperator = operator;\n\n for (let i = 0; i < currentContext.length; i++) {\n if (i === 1) {\n continue;\n }\n\n const node = currentContext[i];\n\n if (Array.isArray(node)) {\n if (Array.isArray(node[0])) {\n const subCollection = { filters: [] };\n\n collection.filters.push(subCollection);\n recursion(node, subCollection);\n }\n else {\n filterObject.addFilter(operator, that.createFilterBuilderFilter(filterObject, node, caseSensitive));\n }\n }\n }\n\n if (filterObject.filters.length > 0) {\n collection.filters.push(filterObject);\n }\n }\n\n recursion(filterSettings, filterResult);\n that.filterBuilderObject = filterResult;\n that.cachedFilter = {\n filterBuilder: JSON.parse(JSON.stringify(that.filterBuilder.value), function (key, value) {\n return /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})Z$/.test(value) ? new Date(value) : value;\n }),\n caseSensitive: caseSensitive\n };\n }", "function sendFilterState(builder) {\n const dashboard = tableau.extensions.dashboardContent.dashboard;\n\n let filters = dashboard.worksheets.map(function(worksheet) {\n return worksheet.getFiltersAsync();\n });\n\n function collectFilterData(filtersForWorksheet) {\n return filtersForWorksheet.map(function (filter) {\n return Object.assign({}, {\n fieldName: filter.fieldName,\n worksheetName: filter.worksheetName,\n }, getFilterValues(filter));\n });\n }\n\n console.log(\"[FFF] START Sending filter state\");\n\n return Promise.all(filters)\n .then(allFilters => allFilters.map(collectFilterData))\n .then(function(data) {\n console.log(\"[FFF] COLLECTED filter state\");\n return dispatchEvent(builder, KIND_FILTER_STATE, {\n filterState: data\n });\n })\n }", "tableFiltering() {\n return {\n source: '',\n filters: {},\n filtersOrder: [],\n name: '',\n state: false,\n show: false,\n showOptions: true,\n date: {\n state: false,\n start: null,\n end: null,\n },\n search: {\n state: false,\n string: null,\n target: [],\n },\n searches: {},\n keys: [],\n selected: [],\n backup: [],\n\t\t};\n }", "function loadSavedFilters(chat, filter_name) {\n let vals = GM_listValues();\n for (let i=0; i < vals.length; i++) {\n let key = vals[i];\n let value = GM_getValue(key);\n if (value == '') {continue;}\n if (key.indexOf(filter_name) == -1) {continue;}\n addSavedFilter(filter_name, key, value);\n }\n}", "function visibilityFilter() {\n var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : SHOW_ALL;\n var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var type = action.type,\n filter = action.filter;\n\n switch (type) {\n case _actions.SET_VISIBILITY_FILTER:\n return filter;\n default:\n return state;\n }\n}", "function getFilter() {\n var filters = listToArray(RTG_VCF_RECORD.getFilters());\n filters.add = addFilter;\n return filters;\n }", "getActiveFilters() {\n let currentFilters = document.querySelectorAll('.active');\n let filtersSelected = [];\n\n currentFilters.forEach(function (currentFilter) {\n filtersSelected.push(currentFilter.getAttribute(\"data-filter\"));\n });\n\n return filtersSelected;\n }", "async getProductsByKeyWord(keyWord) {\n return await this.get(`/producto/GetfiltersByKeyWord?keyWord=${keyWord}`);\n }", "function filterAll() {\n for (var i = 0, l = items.length; i < l; ++i) {\n filterItem(items[i], mapping[items[i].id])\n }\n }", "async getHistory(ctx, key) {\n let iterator = await ctx.stub.getHistoryForKey(key);\n let result = [];\n let res = await iterator.next();\n while (!res.done) {\n if (res.value) {\n console.info(`found state update with value: ${res.value.value.toString('utf8')}`);\n const obj = JSON.parse(res.value.value.toString('utf8'));\n result.push(obj);\n }\n res = await iterator.next();\n }\n await iterator.close();\n return result; \n }" ]
[ "0.6328111", "0.5901546", "0.58349544", "0.58121383", "0.5690221", "0.5685676", "0.56763643", "0.56332403", "0.5598371", "0.55732536", "0.5545668", "0.55348384", "0.5534282", "0.55137384", "0.5483862", "0.54693913", "0.5461851", "0.54310584", "0.539737", "0.5390439", "0.5369593", "0.5369593", "0.53491455", "0.5343588", "0.53275377", "0.5326171", "0.529773", "0.52785635", "0.5275179", "0.5275011", "0.5272512", "0.52518743", "0.5244964", "0.5212294", "0.521077", "0.5205963", "0.52017754", "0.51912355", "0.51392156", "0.5117744", "0.5117744", "0.5114373", "0.5109839", "0.51009643", "0.5100326", "0.5094812", "0.5076317", "0.5069204", "0.50671804", "0.506681", "0.50645524", "0.5060719", "0.5051268", "0.5042043", "0.5038387", "0.50368947", "0.5025704", "0.5024302", "0.501094", "0.5005908", "0.49986744", "0.4997768", "0.49966043", "0.4995992", "0.49928716", "0.49896663", "0.4986084", "0.49851722", "0.49792033", "0.49650156", "0.49620205", "0.4961934", "0.4959807", "0.49550405", "0.4943433", "0.4937501", "0.49360096", "0.49318922", "0.49314958", "0.49228328", "0.4921678", "0.49188766", "0.49165225", "0.49122605", "0.49115264", "0.49090785", "0.4898392", "0.48983747", "0.4891069", "0.48714843", "0.48651668", "0.48646975", "0.48642263", "0.48593953", "0.48538518", "0.4847519", "0.48474112", "0.48467326", "0.48451853", "0.48392245" ]
0.58016527
4
Here, we are providing callbacks with dispatching functions.
onYearChange(year) { dispatch({ type: 'SET_YEAR', year, }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_dispatch(msg) {\n var i = msg.post || 0, action = msg.action;\n this.callback = i;\n var callbacks = this.callbacks[i] || [];\n for (var j = 0, m = callbacks.length; j < m; j++) {\n if (callbacks[j].hasOwnProperty(action)) {\n callbacks[j][action].call(this,msg.data);\n break;\n }\n }\n }", "dispatch() {\r\n }", "function Dispatch(f) { f(); }", "dispatch(action, parameters) {\n const callbacks = this.events[action];\n\n if (this.disable) {\n return;\n }\n\n if (!callbacks) {\n throw new Error();\n }\n\n for(var index = 0; index < callbacks.length; index++) {\n callbacks[index].apply(this, [this, parameters]);\n }\n }", "function callback(){}", "function handleCb(key, payload) {\n if (key && callbacks[key])\n callbacks[key](payload);\n }", "registerCallbacks(dispatch) {\n this.webview.addEventListener('load-commit', event => {\n if (event.isMainFrame) {\n dispatch(notifyStartLoading(this.tile_id, event.url));\n }\n });\n\n this.webview.addEventListener(\n 'did-finish-load',\n () => dispatch(notifyEndLoading(this.tile_id))\n );\n\n this.webview.addEventListener('did-fail-load', event => {\n if (event.errorCode) {\n console.log(`Failed loading: ${event.validatedUrl}: ${event.errorDescription}`);\n }\n });\n\n this.webview.addEventListener(\n 'close',\n () => dispatch(closeTile(this.tile_id))\n );\n }", "function dispatchEvent(eventName) \n\t\t{\n\t\t\t// Create an event object to send the callback\n\t\t\tvar evt = {};\n\n\t\t\tif (callbacks.hasOwnProperty(eventName)) \n\t\t\t{\n\t\t\t\tvar myCallbacks = callbacks[eventName];\n\t\t\t\tfor (var i = 0; i < myCallbacks.length; ++i)\n\t\t\t\t{\n\t\t\t\t\t// Call the attached function with an event object parameter\n\t\t\t\t\tmyCallbacks[i](evt);\n\t\t\t\t}\n\t\t\t}\n\t\t}", "onDispatchComplete(cb){\n this.onDispatchCompleteCbs.push(cb);\n }", "function Dispatch() {\n\tthis.watchers = new Array();\n\tthis.isLoading = false;\n\n\t// Listeners\n\tthis.listener = {\n\t\tonadd:\t\t[],\n\t\tonremove:\t[],\n\t\tonstart:\t[],\n\t\tonstop:\t\t[],\n\t\tonchange:\t[]\n\t};\n}", "function callback() {}", "function callback() {}", "function callback() {}", "function callback() {}", "function callback() {}", "function makeOrderEventHandler(dispatch){\n\t\n}", "dispatcher(){ return this.dispatch.bind(this); }", "function dispatch () {\n\t\teach(routes, function (route, uri) {\n\t\t\tvar callback = route[0];\n\t\t\tvar pattern = route[1];\n\t\t\tvar params = route[2];\n\t\t\tvar match = location.match(pattern);\n\n\t\t\t// we have a match\n\t\t\tif (match != null) {\n\t\t\t\t// create params object to pass to callback\n\t\t\t\t// i.e {user: 'simple', id: '1234'}\n\t\t\t\tvar data = match.slice(1, match.length);\n\n\t\t\t\tvar args = data.reduce(function (previousValue, currentValue, index) {\n\t\t\t\t\t\t// if this is the first value, create variables store\n\t\t\t\t\t\tif (previousValue == null) {\n\t\t\t\t\t\t\tpreviousValue = {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// name: value\n\t\t\t\t\t\t// i.e user: 'simple'\n\t\t\t\t\t\t// `vars` contains the keys for the variables\n\t\t\t\t\t\tpreviousValue[params[index]] = currentValue;\n\n\t\t\t\t\t\treturn previousValue;\n\n\t\t\t\t\t\t// null --> first value\n\t\t\t\t\t}, null); \n\n\t\t\t\tcallback(args, uri);\n\t\t\t}\n\t\t});\n\t}", "_constructCallbacks() {\n\t\tthis._contract.on(\"PriceSent\", this._receivePrice.bind(this));\n\n\t\tthis._contract.on(\"InvoiceSent\", this._receiveInvoice.bind(this));\n\t}", "function _dispatchUpdateCallbacks(){\n App.broadcast(ON_UPDATE_EVENT,App.Modules.GPS);\n }", "_dispatch(name, detail = {}) {\n this.utils.dispatchEvent(name, {\n detail\n });\n }", "runCallbacks(event, data, requestInfo, additionalData) {\n let callbacksToRun = this.callbacks[event];\n\n if (callbacksToRun) {\n for (let callback of callbacksToRun) {\n callback(data, requestInfo, additionalData);\n }\n }\n }", "setupCallbacks() {\n var key, fn;\n var callbacks = {\n 'initialize': 'onInitialize',\n 'change': 'onChange',\n 'item_add': 'onItemAdd',\n 'item_remove': 'onItemRemove',\n 'clear': 'onClear',\n 'option_add': 'onOptionAdd',\n 'option_remove': 'onOptionRemove',\n 'option_clear': 'onOptionClear',\n 'optgroup_add': 'onOptionGroupAdd',\n 'optgroup_remove': 'onOptionGroupRemove',\n 'optgroup_clear': 'onOptionGroupClear',\n 'dropdown_open': 'onDropdownOpen',\n 'dropdown_close': 'onDropdownClose',\n 'type': 'onType',\n 'load': 'onLoad',\n 'focus': 'onFocus',\n 'blur': 'onBlur'\n };\n\n for (key in callbacks) {\n fn = this.settings[callbacks[key]];\n if (fn) this.on(key, fn);\n }\n }", "__onDispatch(type,data) {\n console.log(type,data);\n }", "registerCallbacks(callbacks) {\n for (var eventType in callbacks) {\n this.on(eventType, callbacks[eventType]);\n }\n }", "hookListeners(dispatchEvents, callback) {\n debug('hookListeners()');\n return this.hookListenersImpl(dispatchEvents, callback);\n }", "StoreAndDispatch() {\n\n }", "_onDispatch(eventName, handler) {\n const boundHandler = handler.bind(this);\n this.on(eventName, (...args) => {\n console.log('dispatch:', eventName, ...args);\n boundHandler(...args);\n });\n }", "function DispatchCall(callback, thisArg) { callback.call(thisArg); }", "dispatch(data) {\n this._receiveListener(data);\n }", "updateDispatchers() {\n const { onSuccess, onError, onRequest } = this.options;\n\n const {\n invalidateResource,\n prepopulateResource,\n dispatchRequest\n } = bindActionCreators(actions, this.store.dispatch);\n\n // TODO no need to update these two\n this.invalidateResource = invalidateResource;\n this.prepopulateResource = prepopulateResource;\n\n // wrapping in a function returning a normal promise\n this.dispatchRequest = (definition) => {\n const promise = new Promise((resolve, reject) => {\n dispatchRequest(definition, {\n onSuccess: extendFunction(onSuccess, resolve),\n onError: extendFunction(onError, reject)\n });\n });\n onRequest && onRequest(promise);\n return promise;\n };\n }", "on(typenames, callback) {\n if (arguments.length < 2) {\n return this.dispatch.on(typenames);\n }\n\n this.dispatch.on(typenames, callback);\n return this;\n }", "dispatch(invocation) {\n const finish = function finish(err) {\n for (var _len = arguments.length, results = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n results[_key - 1] = arguments[_key];\n }\n\n const serialized = [err != null ? { message: err.message } : null];\n\n if (results && results.length) {\n serialized.push.apply(serialized, results);\n }\n\n invocation.callback(invocation, JSON.stringify(serialized));\n };\n\n const parameters = JSON.parse(invocation.args);\n\n // console.log(invocation.name + '(' + JSON.stringify(parameters) + ')');\n\n if (invocation.name === 'httpRequest') {\n return this.httpRequest(...parameters, finish);\n } else if (invocation.name === 'log') {\n this.log(...parameters);\n return finish(null);\n } else if (invocation.name === 'error') {\n this.error(...parameters);\n return finish(null);\n }\n\n return finish(null);\n }", "function executeCallbacks(){\n\t\t\t\t\t\tcallbacks[lib].forEach(function(cb) {\n\t\t\t\t\t\t\tcb();\n\t\t\t\t\t\t});\n\t\t\t\t\t\tloading[lib].status = 1;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}", "publish() {\n _callbacks.forEach(callback => callback());\n }", "function callbackDriver() {\n cb();\n }", "function performer(cb) {\n cb();\n }", "function Dispatch3(a, b) { a(); b(); }", "__invokeOnDispatch(type,payload) {\n this.__changed = false;\n this.__onDispatch(type,payload);\n if (this.__changed) {\n this.__emitter.emit(this.__changeEvent);\n }\n }", "dispatch(eventName) {\n\t\t// Only call if a method with the event name exists\n\t\tif (this[eventName]) {\n\t\t\tthis[eventName]();\n\t\t}\n\t}", "function executeDispatchesInOrder(event,cb){forEachEventDispatch(event,cb);event._dispatchListeners = null;event._dispatchIDs = null;}", "static performCallbacks(callbacks) {\n // This is my method of getting all the arguments except for the list of callbacks\n const args = Array.prototype.slice.call(arguments, 1);\n callbacks.forEach((callback) => {\n // To use the arguments I have to use the apply method of the function\n callback(...args);\n });\n }", "selfAssignHandlerFunctions() {\n this.request = this.api.request.bind(this.api);\n this.addRateLimitService = this.api.addRateLimitService.bind(this.api);\n this.addRequestService = this.api.addRequestService.bind(this.api);\n }", "function executeDispatchesInOrder(event,cb){forEachEventDispatch(event,cb);event._dispatchListeners=null;event._dispatchIDs=null;}", "on(typenames, callback) {\n if (!this.dispatch) { // Lazy construct the dispatcher.\n this.dispatch = d3.dispatch(...this.events);\n }\n\n if (callback) {\n this.dispatch.on(typenames, callback);\n return this;\n }\n\n return this.dispatch.on(typenames);\n }", "dispatchAsync() {\r\n this._dispatch(true, this, arguments);\r\n }", "_postProcessing() {\n // None yet...\n }", "function Dispatch2(f, arg) { f(arg); }", "register_callbacks() {\n\t\tthis.$user_list\n\t\t\t.parents( '.collapse' )\n\t\t\t.on( 'shown.bs.collapse hidden.bs.collapse', event => this.user_list_collapse_handler(event) );\n\n\t\t$( document ).on( 'keydown', event => this.key_press_handler(event) );\n\t\t$( '.cancel_auth:not(.alert .cancel_auth)' ).on( 'click', event => this.cancel_authentication(event) );\n\n\t\t$( '.submit_passwd' ).on( 'click', event => this.submit_password(event) );\n\t\t$( '[data-i18n=\"debug_log\"]' ).on( 'click', event => this.show_log_handler(event) );\n\n\t\tlightdm.show_prompt.connect( (prompt, type) => this.show_prompt(prompt, type) );\n\t\tlightdm.show_message.connect( (msg, type) => this.show_message(msg, type) );\n\n\t\twindow.start_authentication = event => this.start_authentication(event);\n\t\twindow.cancel_authentication = event => this.cancel_authentication(event);\n\n\t\tlightdm.authentication_complete.connect( () => this.authentication_complete() );\n\t\tlightdm.autologin_timer_expired.connect( event => this.cancel_authentication(event) );\n\t}", "function userinfo_dispatcher_routines() {\n\n\n}", "function dispatchRequest(request, response)\n{\n try {\n //Dispatch\n dispatcher.dispatch(request, response);\n }\n catch (e) {\n console.log(e);\n }\n}", "__onDispatch (action) {\n switch(action.type) {\n\n case ADD_TODO:\n this.addTodo(action.id, action.text);\n this.__emitChange();\n break;\n\n case REMOVE_TODO:\n this.removeTodo(action.id);\n this.__emitChange();\n break;\n\n case TOGGLE_TODO:\n this.toggleTodo(action.id);\n this.__emitChange();\n break;\n }\n }", "function Dispatcher() {\n this._callbacks = [];\n this._recovers = [];\n\n }", "function callback(action) {\n if (req.readyState === 4) {\n if (req.status === 200) {\n if (action === \"findUser\") {\n processSearchResults(req.responseXML);\n } else if (action === \"addNote\") {\n refreshCurrentNotes();\n } else if (action===\"getNote\") {\n changeNote(req.responseXML);\n } else if (action===\"getHistory\") {\n changeArea(req.responseXML);\n } else if (action===\"getNotes\") {\n changeArea(req.responseXML);\n } else if (action===\"getPersonalNotes\") {\n changeArea(req.responseXML);\n } else if (action===\"disable\") {\n historyViewImg.trigger(\"click\");\n } else if (action===\"resetNotifications\") {\n $(\"#personalBar\").children().first().trigger(\"click\");\n } else if (action===\"findUserInfo\") {\n updateUserInfo(req.responseXML);\n } else if (action===\"findUserInfoSelf\") {\n updateUserInfo(req.responseXML, sessionStorage.getItem(\"loggedInUser\"));\n }\n }\n }\n }", "function callCallbacks() {\n console.log('CALLING require() CALLBACKS');\n while(require.pendingCallbacks.length > 0) {\n let cb = require.pendingCallbacks.shift();\n // Call the callback with argument being the\n // content.\n assert(require.content[cb.path] !== undefined,\n 'require.content[\"' + cb.path + '\"] is not defined');\n cb.callback(require.content[cb.path]);\n }\n }", "function EventDispatcher() {}", "function EventDispatcher() {}", "handleEvent() {}", "handleEvent() {}", "adoptedCallback() { }", "static _handle_action_complete_triggers() {\n\n // run queued trigger functions\n while (!Actor._action_complete_trigger_queue.is_empty())\n Actor._action_complete_trigger_queue.out()();\n }", "runCallbacks(){\n if(this.state == 'FULLFILLED') {\n this.thenCbs.forEach(thenCb => {\n thenCb(this.value);// notifies all our thenable callbacks of our fulfilled value\n })\n this.thenCbs = [];\n }\n }", "_onUpdate() {\n const args = [this.x, this.y];\n this.moveHandlers.forEach((callback) => callback(...args));\n }", "function forEachEventDispatch(event,cb){var dispatchListeners=event._dispatchListeners;var dispatchIDs=event._dispatchIDs;if(true){validateEventDispatches(event);}if(Array.isArray(dispatchListeners)){for(var i=0;i < dispatchListeners.length;i++) {if(event.isPropagationStopped()){break;} // Listeners and IDs are two parallel arrays that are always in sync.\n\tcb(event,dispatchListeners[i],dispatchIDs[i]);}}else if(dispatchListeners){cb(event,dispatchListeners,dispatchIDs);}}", "_onTasksDone() {\n // meant to be implemented by subclass if needed\n }", "_bindEventListenerCallbacks() {\n this._onClickBound = this._onClick.bind(this);\n this._onScrollBound = this._onScroll.bind(this);\n this._onResizeBound = this._onResize.bind(this);\n this._onVisibleBound = this._onVisible.bind(this);\n this._onMutateBound = this._onMutate.bind(this);\n }", "onComplete() {// Do nothing, this is defined for flow if extended classes implement this function\n }", "function mockCallBack() {\n}", "handleActions(action) {\n // it is check by a switch and will have a type that id it\n switch(action.type) {\n // call a function\n case 'GET_ALL': {\n this.getAll();\n }\n }\n }", "detail(...args) {\n callback(...args);\n }", "bindCallbacks() {\n this.socket.onopen = (event) => this.onopen(event);\n this.socket.onmessage = (event) => this.onmmessage(event);\n this.socket.onclose = (event) => this.onclose(event);\n this.socket.onerror = (event) => this.onerror(event);\n }", "function method_callback (request_id,rslt,e) {\n\tif(rslt == null) {\n\t return;\n\t}\n\n\tif(typeof (global_request_registry[request_id]) != 'undefined') {\t\n\t widget = global_request_registry[request_id][0];\n\t method_name = global_request_registry[request_id][1];\n\t widget[method_name](rslt);\n\t}\n}", "function _callback(err, data) { _call(callback, err, data); }", "on(data) {\n switch (data.type) {\n case ACTION_TYPES.CHANGE_GRAMMAR:\n this.onGrammar(data.grammar);\n break;\n case ACTION_TYPES.MOVE_CURSOR:\n this.onCursorMoved(data.cursor, data.user);\n break;\n case ACTION_TYPES.HIGHLIGHT:\n this.onHighlight(data.newRange, data.userId);\n break;\n case ACTION_TYPES.CHANGE_FILE:\n this.onChange(data.path, data.buffer);\n break;\n default:\n }\n }", "notify(noti, type, callback = function () {}) {\n switch (type) {\n case 'success':\n this.props.onDispatchNotification(success(noti));\n break;\n case 'info':\n this.props.onDispatchNotification(info(noti));\n break;\n case 'warning':\n this.props.onDispatchNotification(warning(noti));\n break;\n case 'error':\n this.props.onDispatchNotification(error(noti));\n break;\n default:\n console.log('ERROR IN CALLING this.notify()');\n }\n callback();\n}", "function sendDispatchRequest(n, m, a, v, c, callback, uniqueDispatchKey) {\n if (uniqueDispatchKey === void 0) {\n uniqueDispatchKey = undefined;\n }\n // Here we are going to add each of the callbacks values as a key to our callback object.\n // Since the shim will only identify the response with the value passed in our callbacks argument we must use each of these to \n // key our callback storage.\n if (callback) {\n if (uniqueDispatchKey == undefined) {\n var keys = Object.keys(c);\n for (var i = 0; i < keys.length; i++) {\n var val = c[keys[i]];\n callbacks[val] = callback;\n }\n } else {\n callbacks[uniqueDispatchKey.toString()] = callback;\n if (a['Parameters']) {\n a['Parameters']['uniqueDispatchKey'] = uniqueDispatchKey;\n }\n }\n }\n var message = buildDispatchMessage(dispatchKey, n, m, JSON.stringify(a), v, JSON.stringify(c));\n window.parent.postMessage(message, '*');\n }", "function doCallbacks(ag, msg) {\n\t\tfor (var i=0; i<Eden.Agent.importQueue[path].length; i++) {\n\t\t\tEden.Agent.importQueue[path][i](ag, msg);\n\t\t}\n\t\tEden.Agent.importQueue[path] = undefined;\n\t}", "componentDidMount(){\n this.props.dispatch({ type: 'GET_EVENT_INFO' })\n this.props.dispatch({ type: 'GET_VIDEOS_ADMIN' })\n this.props.dispatch({ type: 'GET_ENTIRE_GOAL_INFO' })\n }", "function registerCallbackForActuators() {\n registerCallbackRGBScreen();\n registerCallbackVibration();\n registerCallbackImage();\n registerCallbackVideo();\n registerCallbackAudio();\n}", "runCallbacks(callbacks, args) {\r\n for (let i = 0; i < callbacks.length; i++) {\r\n if (typeof callbacks[i] !== 'function') continue;\r\n callbacks[i].apply(null, args);\r\n }\r\n }", "function DispatchApply(callback, thisArg) { callback.apply(thisArg); }", "onSuccess() {}", "onDispatch(action) {\n this.dispatchStack.push(action);\n\n if (this.options.dispatch instanceof Function) {\n this.options.dispatch(action);\n }\n }", "function acc_handler() {}", "function exec_callback(id) { /// Execute callback\n if (!callbacks[id])\n return;\n callbacks[id].call();\n}", "function _fireReadyEventCallbacks() {\n _callbacks.ready.forEach(function(callback) {\n callback();\n });\n }", "ServerCallback() {\n\n }", "setCallbacks() {\n const that = this;\n // Declare the Interactive Canvas action callbacks.\n const callbacks = {\n onUpdate(data) {\n that.commands[data.state ? data.state.toUpperCase() : 'DEFAULT'](data);\n },\n };\n // Called by the Interactive Canvas web app once web app has loaded to\n // register callbacks.\n this.canvas.ready(callbacks);\n }", "function callback() {\n\n}", "function callback(){\n handlePortfolioAnchor()\n handleAboutAnchor()\n}", "handle() {}", "adoptedCallback() {\n\n }", "actions(dispatcher, context) {\n return {\n addTodo(newTodo) {\n dispatcher.dispatch(new Action(\"ADD_TODO_LOADING\"))\n dispatcher.dispatch(new Action(\"ADD_TODO_SUCCESS\", {\n newTodo\n }))\n },\n displayTodoDone() {\n dispatcher.dispatch(new Action(\"DISPLAY_TODO_DONE\"))\n\n },\n displayTodoNotDone() {\n dispatcher.dispatch(new Action(\"DISPLAY_TODO_NOT_DONE\"))\n\n },\n displayAllTodos() {\n dispatcher.dispatch(new Action(\"DISPLAY_ALL_TODO\"))\n }\n }\n }", "function constructCallbackDispatcher(callback) {\n if (callback == null) {\n return function (response) {\n console.warn(\"Ignoring response \" + JSON.stringify(response));\n };\n } else if (callback === \"ignore\") {\n // Ignore the return value\n return function () {\n };\n }\n var callbackArray = $.isArray(callback) ? callback : [ callback ];\n return function (response, idx) {\n callbackArray[idx % callbackArray.length](response, idx);\n }\n }", "adoptedCallback() {}", "adoptedCallback() {}", "_registerHandlers(target, becameInvalid, becameValid) {\n this.on('becameInvalid', target, becameInvalid);\n this.on('becameValid', target, becameValid);\n }", "createDelegates() {\n // this.onMove = this.onMove.bind(this);\n // this.onMoveComplete = this.onMoved.bind(this);\n this.completeInitialization = this.completeInitialization.bind(this);\n this.onBoundsChanging = this.onBoundsChanging.bind(this);\n this.onBoundsChanged = this.onBoundsChanged.bind(this);\n this.onBoundsUpdate = this.onBoundsUpdate.bind(this);\n this.onMoved = this.onMoved.bind(this);\n this.onClosed = this.onClosed.bind(this);\n this.onFocused = this.onFocused.bind(this);\n this.onMinimized = this.onMinimized.bind(this);\n this.onRestored = this.onRestored.bind(this);\n this.onGroupChanged = this.onGroupChanged.bind(this);\n }", "function dispatch(packet) {\n\n }", "function assignCallbacks() {\n $('[class*=\"dlg-callback-\"]').each(function() {\n var control = $(this).context;\n\n // If an onclick attribute is already defined for the element,\n // don't attach a new one.\n // This is the case when the developer wants to call their custom\n // callback, that e.g. sends some form data too.\n // REVIEW: Should perhaps also detect event listeners here?\n if (control.getAttribute('onclick')) return;\n\n var action = control.className.match(/dlg-callback-(\\S+)/)[1];\n var func = sketchup[action];\n if (typeof func === 'function') {\n console.log('Assign SU callback \\''+action+'\\' to control \\''+control+'\\'.')\n // Wrap callback in anonymous method to prevent event from being sent\n // as parameter. This seemed to cause infinite loop as it froze the\n // dialog.\n // TODO: Maybe send hash of data in all named fields? If so, document\n // how to get vars into fields in the first palce.\n $(control).click( { func: func }, function(e) { func() });\n } else {\n console.warn('Missing SU callback \\''+action+'\\'.');\n }\n });\n }", "function assess() {\n\t\t\tvar args = Array.prototype.slice.call(arguments);\n\t\t\tif (args[0]) handleError(args[0]);\n\t\t\telse if (callback) callback.apply(null, args);\n\t\t}" ]
[ "0.69337356", "0.68187547", "0.6443289", "0.63594806", "0.63036895", "0.6225387", "0.61851853", "0.61549896", "0.6128388", "0.6116177", "0.6063215", "0.6063215", "0.6063215", "0.6063215", "0.6063215", "0.60455024", "0.6032874", "0.59899586", "0.5964031", "0.5958332", "0.5948069", "0.59053826", "0.58893", "0.5861277", "0.5861146", "0.58000183", "0.5785216", "0.5778702", "0.57735664", "0.5769605", "0.5748409", "0.5745654", "0.57286376", "0.5695882", "0.5676017", "0.5670384", "0.5669324", "0.56436324", "0.5617836", "0.5615047", "0.56019735", "0.55930233", "0.5563349", "0.5555132", "0.55496275", "0.5546331", "0.5527299", "0.55226874", "0.5509143", "0.5499268", "0.5482582", "0.54555243", "0.54504925", "0.54499555", "0.54462045", "0.54441816", "0.54441816", "0.5443319", "0.5443319", "0.54351705", "0.5427021", "0.54207635", "0.5416171", "0.5406477", "0.54046714", "0.5396564", "0.539454", "0.5388773", "0.5368368", "0.5362049", "0.53585845", "0.535604", "0.53483933", "0.53429276", "0.5339354", "0.5338535", "0.5336006", "0.53293383", "0.5327797", "0.53162956", "0.531433", "0.530081", "0.52961606", "0.5295929", "0.5292713", "0.52836293", "0.52817035", "0.5263211", "0.5258688", "0.5256897", "0.5240277", "0.52381337", "0.52246374", "0.52207917", "0.5214233", "0.5214233", "0.5211386", "0.5209644", "0.52018493", "0.5198567", "0.51975477" ]
0.0
-1
destruction de la session
function detruireSession() { /* il faut detruire la session : copier coller de php.net... / La session est deja initialisee / Detruit toutes les variables de session */ $_SESSION = array(); /* Si vous voulez detruire completement la session, effacez egalement / le cookie de session. / cela detruira la session et pas seulement les donnees de session !*/ if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000, '/'); } /* Finalement, on detruit la session. session_destroy(); / on termine par la redirection*/ header("Location: index.php"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function sessionCleanup() {\n\n\t}", "function destroy() {\n devlog.channel('iscSessionStorageHelper').debug( 'iscSessionStorageHelper.destroy');\n $window.sessionStorage.removeItem('loginResponse');\n $window.sessionStorage.removeItem('sessionTimeoutCounter');\n $window.sessionStorage.removeItem('showTimedOutAlert');\n $window.sessionStorage.removeItem('config');\n }", "logout() {\n // destroy the session\n localStorage.removeItem('session');\n }", "clearSession() {\n this._clearSessionInStorage();\n\n this._session = {};\n }", "function _destroy() {\n token = undefined;\n authStore.destroy();\n }", "logout() {\n this._userId = null\n this._userToken = null\n this._userUsername = null\n\n sessionStorage.clear()\n }", "detach() {\n if (this._page) {\n Pup.disconnect(this._page);\n this._page = null;\n }\n if (this.session) {\n this.session.close();\n this.session = null;\n }\n }", "function deleteSession() {\n\tsessionStorage.clear();\n}", "function destroy(){}", "function logout() {\n\n if ( checkProtocol('ws') || SERVERLESS ) return;\n\n if ( SESSION.id ) {\n\n // XHR\n send({ action: 'remove', data: SESSION.id }, function(){\n\n // beforeunload callback\n if ( QUEUE.length ) {\n\n delete SESSION.id;\n\n executeQueue( QUEUE );\n }\n });\n\n } else {\n\n executeQueue( QUEUE );\n }\n }", "logout() {\n // remove authentication credentials\n this.credentials = null;\n }", "function destroy(){\n\t\t// TODO\n\t}", "static clearSession() {\n localStorage.removeItem(KEY.ACCESS_TOKEN);\n localStorage.removeItem(KEY.ID_TOKEN);\n localStorage.removeItem(KEY.EXPIRES_AT);\n }", "destroy () {\n super.destroy()\n this.share = null\n if (this.connector != null) {\n if (this.connector.destroy != null) {\n this.connector.destroy()\n } else {\n this.connector.disconnect()\n }\n }\n if (this.persistence !== null) {\n this.persistence.deinit(this)\n this.persistence = null\n }\n this.os = null\n this.ds = null\n this.ss = null\n }", "logout() {\n this.account.sid = null;\n this.account.token = null;\n this.account.save();\n this.account = null;\n this.cb.onLogoutSuccess();\n }", "destroy () {\n super.destroy();\n this.share = null;\n if (this.connector != null) {\n if (this.connector.destroy != null) {\n this.connector.destroy();\n } else {\n this.connector.disconnect();\n }\n }\n if (this.persistence !== null) {\n this.persistence.deinit(this);\n this.persistence = null;\n }\n this.os = null;\n this.ds = null;\n this.ss = null;\n }", "logout(id) {\n if (this.sessions[id]) {\n delete this.sessions[id];\n }\n }", "doLogout() {\n this.user = null;\n }", "function deleteSession() {\n localStorage.clear();\n}", "function logout(){\n localStorage.removeItem(localStorageSessionName);\n setSession('', '');\n }", "sessionCLose() {\n localStorage.removeItem(\"user\");\n }", "logout() {\n this.Storage.unstore('isLoggedIn');\n this.Storage.unstore('token');\n }", "destroy () {\n this._cache = undefined;\n }", "function endSession(id) {\n\tdelete sessions[id];\n\tdelete remotes[id];\n\tclearTimeout(timers[id]);\n\tdelete timers[id];\n}", "function logout() {\n svc.token = null;\n svc.identity = null;\n delete $window.localStorage['authToken']; \n }", "function logout() {\n sessionStorage.removeItem('user')\n sessionStorage.removeItem('isLogged')\n}", "logout() {\n this.setAccessToken(null);\n this.user = null;\n }", "end() {\n this.session.close();\n }", "function destroy () {\n\t\t// TODO\n\t}", "function destroy() {\n asps.autoLogout.remove();\n $log.debug(\"AutoLogout removed from DOM\");\n }", "reset() {\n console.log(\"session cleared\");\n localStorage.removeItem(this.getStorageKey());\n }", "destroy () {\n\n this._setState(PortalService.STATE.DESTROYED);\n\n this._routes = undefined;\n this._http = undefined;\n this._authenticators = undefined;\n this.DEFAULT_AUTHENTICATOR = undefined;\n\n nrLog.trace(`${PortalService.getAppName()} destroyed`);\n\n }", "deletePlayerSession() {\n sessionStorage.removeItem(PLAYER_ID)\n sessionStorage.removeItem(PLAYER_NAME)\n }", "logout() {\r\n this.authenticated = false;\r\n localStorage.removeItem(\"islogedin\");\r\n localStorage.removeItem(\"token\");\r\n localStorage.removeItem(\"user\");\r\n }", "static logout() {\n AuthService.clearSession();\n clearTimeout(tokenRenewalTimeout);\n }", "clear() {\n this.user = '';\n this.data = '';\n this.admin = false;\n ls.remove('session');\n }", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "destroy() {}", "unload() {}", "function logout() {\n sessionStorage.clear(); \n}", "logout() {\n return __awaiter(this, void 0, void 0, function* () {\n this.store = new SessionStore();\n });\n }", "destroy() {\n this.personalInfoCollection = null;\n this.leucineAllowance = null;\n this.calorieGoal = null;\n }", "function destroy(){\r\n }", "function destroy(){\r\n }", "endSession() {\r\n this.endScript();\r\n this.cycler.endSession();\r\n }", "function logOut(){\n checkConnection();\n $(\".popover-backdrop.backdrop-in\").css(\"visibility\",\"hidden\");\n $(\".popover.modal-in\").css(\"display\",\"none\"); \n window.localStorage.removeItem(\"session_uid\"); \n window.localStorage.removeItem(\"session_fname\"); \n window.localStorage.removeItem(\"session_lname\"); \n window.localStorage.removeItem(\"session_uname\");\n window.localStorage.removeItem(\"session_ulevel\");\n window.localStorage.removeItem(\"session_department\");\n window.localStorage.removeItem(\"session_mobile\");\n window.localStorage.removeItem(\"session_email\"); \n window.localStorage.removeItem(\"session_loc\");\n window.localStorage.removeItem(\"session_dp\"); \n mainView.router.navigate('/');\n //app.panel.close();\n //app.panel.destroy(); \n}", "destroy() {\n this._$window.localStorage.removeItem(this._AppConstants.jwtKey);\n }", "function clearSession() {\n sessionStore.clear();\n }", "function stop() {\n Stories.remove( {} );\n sessions();\n}", "static logout() {\n localStorage.removeItem('auth_token');\n localStorage.removeItem('email');\n localStorage.removeItem('userid');\n localStorage.removeItem('username');\n }", "function logout() {\n tokenStore['igtoken'] = undefined;\n }", "function logout() {\n setCookie('code', '', 0);\n setCookie('session', '', undefined, isDev ? '/dev/' : undefined);\n session = null;\n guilds = {};\n statGroups = {};\n user = {};\n fuse = null;\n memberFuse = null;\n if (guildList) guildList.remove();\n if (socket) {\n socket.emit('logout');\n socket.close();\n socket = null;\n }\n loginButton.innerHTML = '<span>Login</span>';\n loginButton.setAttribute('onclick', 'login()');\n setView('login');\n mainBody.innerHTML = '';\n }", "sclear() {\n sessionStorage.clear()\n }", "function logoff(){\r\n\toStorage.clear();\r\n\toLocalStorage.put(\"AllAlerts\", null);\r\n\tsetCookie(\"sessionObject\", \"\", -1);\r\n\tdb.delete();\r\n\tlocation.reload();\r\n}", "logout() {\n // Remove the HTTP header that include the JWT token\n delete axios.defaults.headers.common['Authorization'];\n // Delete the token from our session\n sessionStorage.removeItem('token');\n this.token = null;\n }", "destroy() {\n if (this._isRunning) this.pause(false); // Going to destroy -> no idle timeout.\n this.removeAllPlayers();\n this._playerManager.destroy();\n delete this._hub;\n delete this._timeIdleId;\n delete this._gameId;\n delete this._jobId;\n delete this._connection;\n delete this._kind;\n delete this._refreshRate;\n delete this._isRunning;\n }", "async delete() {\n\t\tawait this.logger.deleteSession(this.name);\n\t}", "function logout() {\n setCurrentUser(null);\n setToken(null);\n }", "clearSession() {\n this.withMixpanel(() => {\n // Clears entire session\n // This should be called only on LOGOUT and not in mid-session.\n if (mixpanel.cookie && mixpanel.cookie.clear) {\n mixpanel.cookie.clear();\n this._sessionInitialized = false;\n }\n });\n }", "destroySessionRecorder() {\n const recorder = this.get('sessionRecorder');\n if (recorder) {\n if (!(this.get('isDestroyed') || this.get('isDestroying'))) {\n this.send('setTimeEvent', 'destroyingRecorder');\n }\n recorder.destroy();\n }\n }", "_destroy() {}", "deleteSession(){\n if (localStorage.getItem(\"user\") === null) {\n \n }\n else\n localStorage.removeItem(\"user\");\n localStorage.removeItem(\"roleid\");\n\n }", "static logout() {\n AsyncStorage.removeItem('token');\n AsyncStorage.removeItem('currentVehicle');\n AsyncStorage.removeItem('userId');\n }", "function _clear() {\n $window.sessionStorage.clear();\n }", "destroy () {\n debug('destroying Recurly instance', this.id);\n this.off();\n if (this.bus) {\n this.bus.send('destroy');\n this.bus.destroy();\n }\n if (this.fraud) {\n this.fraud.destroy();\n }\n if (this.reporter) {\n this.reporter.destroy();\n delete this.reporter;\n }\n }", "destroy() {\r\n this.off();\r\n }", "logout(request,response){\n request.session.destroy();\n response.clearCookie('userID');\n response.clearCookie('userName');\n response.clearCookie('expiration');\n response.json(true);\n }", "function logout() {\n $window.sessionStorage['userInfo'] = null;\n $http.defaults.headers.common['X-TOKEN'] = null; // jshint ignore:line\n userInfo = null;\n }", "logout() {\n localStorage.removeItem('email');\n localStorage.removeItem(\"id_token\");\n localStorage.removeItem(\"expires_at\");\n localStorage.removeItem('name');\n localStorage.removeItem('productId');\n localStorage.removeItem('productName');\n }", "logout() {\n localStorage.removeItem('token');\n request.unset('Authorization');\n }", "deleteSessionToken() {\n store.delete(this.SESSION_TOKEN_STORAGE_KEY);\n }", "logout(){\n // clear bearer auth tokens to reset to state before login\n this.token = null;\n Cookies.remove(process.env.API_TOKEN_KEY);\n }", "function logout() {\n setToken(null);\n setCurrentUser(null);\n }", "logout() { Backend.auth.logout(); }", "logout() {\n Backend.logout();\n }", "end() {\n store.commit(SESSION_CLEAR);\n }", "onDestroy() {}", "function logout() {\n sessionStorage.removeItem('id');\n sessionStorage.removeItem('token');\n sessionStorage.removeItem('registerUser');\n setIsLoggedIn(false);\n }", "destroy() {\n removeAddedEvents();\n if (mc) {\n mc.destroy();\n }\n mc = null;\n instance = null;\n settings = null;\n }", "function logout() {\n JoblyApi.token = null;\n setCurrentUser(null);\n localStorage.removeItem(\"token\");\n localStorage.removeItem(\"currentUser\");\n }", "function onSubscriptionEnded() {\n session = null;\n }", "destroy(){\n log.silly('Session.destroy:', `Session ${this.name}`);\n let deleted = 0;\n let ret = 1;\n\n for(let stage of this.get_stages()){\n // dump(stage, 1);\n\n if(stage.status === 'RETRYING'){\n log.silly('Session.end:', `${this.name}:`,\n `stage: ${stage.origin}:`,\n `Stage retrying, not removing`);\n ret = 0;\n continue;\n }\n\n // status is CONNECTED, DISCONNECTED, or END\n log.silly('Session.destroy:', `${this.name}:`,\n `Stage: \"${stage.origin}\"/${stage.status}:`,\n `Ending stage`);\n let stream = stage.stream;\n try{\n if(stage.on_disc){\n // // log.info('end:', stream.listenerCount(\"end\"));\n // stream.removeListener(\"end\", stage.on_disc[\"end\"]);\n // // log.info('end:', stream.listenerCount(\"end\"));\n\n // log.info('close:', stream.listenerCount(\"close\"));\n stream.removeListener(\"close\", stage.on_disc[\"close\"]);\n // log.info('close:', stream.listenerCount(\"close\"));\n\n // log.info('error:', stream.listenerCount(\"error\"));\n stream.removeListener(\"error\", stage.on_disc[\"error\"]);\n // log.info('error:', stream.listenerCount(\"error\"));\n }\n if(stage.status !== 'END' && stream){\n stream.end();\n // stream.destroy();\n deleted++;\n }\n } catch(err){\n log.info(`Session.destroy: ${this.name}: Could not terminate stage:`,\n `\"${stage.origin}\"/${stage.status}:`, dumper(err, 3));\n }\n\n stage.status = 'END';\n }\n\n log.verbose('Session.destroy:', `${this.name}:`,\n `deleted ${deleted} streams`);\n this.status = 'DESTROYED';\n\n this.events.push({ event: 'DESTROY',\n timestamp: new Date().toISOString(),\n message: \"Session destroyed\",\n content: ''});\n\n if(this.track){\n log.silly('Session.destroy:', `${this.name}:`,\n `Tracking session for ${this.track} seconds`);\n setTimeout(() => this.emit('destroy'), this.track * 1000);\n } else {\n this.emit('destroy');\n }\n\n // return OK if no stage is retrying\n return ret;\n }", "signOut() {\n this._authData = {};\n window.localStorage.removeItem(this._authDataKey);\n }", "destroy () {}", "removeAllSessions() {\n if (this._connection) {\n this._connection.remove_all_sessions();\n }\n }", "unload () {\n this.#timers.off()\n this.#display.off()\n this.#logFile.off()\n }", "clear() {\n this.sessionAttributes = {};\n this.incrementSessionId();\n }", "clearSession() {\n this.engineWorker.postMessage({\n type: \"clear-session\",\n });\n return this;\n }", "destroy() {\n //TODO this.\n }", "clear() {\n sessionStorage.clear()\n localStorage.clear()\n }", "destroy() { }", "destroy() { }" ]
[ "0.76232225", "0.7553529", "0.7224527", "0.7035157", "0.70255184", "0.7019585", "0.6997646", "0.68235904", "0.67810684", "0.675823", "0.67419165", "0.6737653", "0.672311", "0.67098373", "0.6701298", "0.6682128", "0.6676892", "0.6673964", "0.66620404", "0.66323125", "0.6617079", "0.65992236", "0.65932506", "0.65891725", "0.65877956", "0.65691006", "0.6562523", "0.65293014", "0.65149844", "0.6509684", "0.65095747", "0.6509519", "0.6472334", "0.6446648", "0.64275086", "0.6423274", "0.64200455", "0.64200455", "0.64200455", "0.64200455", "0.64200455", "0.64200455", "0.64200455", "0.64200455", "0.64200455", "0.64200455", "0.64200455", "0.6419078", "0.6404569", "0.6398059", "0.63856894", "0.6375621", "0.6375621", "0.6373947", "0.6370125", "0.63577247", "0.63556725", "0.63532436", "0.63518536", "0.63402957", "0.63370365", "0.63255876", "0.6318787", "0.6317735", "0.63157666", "0.63117814", "0.6307354", "0.63071305", "0.6306686", "0.6295794", "0.6287421", "0.6284343", "0.62772423", "0.62713087", "0.6269123", "0.6258198", "0.62507707", "0.62477666", "0.6243099", "0.6239256", "0.6238071", "0.6237532", "0.6228846", "0.62267095", "0.6223888", "0.6216588", "0.6209951", "0.61960626", "0.6195563", "0.6189192", "0.6183845", "0.6178449", "0.61772174", "0.61692", "0.61673677", "0.6166111", "0.616491", "0.61642194", "0.6163269", "0.61616975", "0.61616975" ]
0.0
-1
another way to write a component, call it function
function NoMatch(){ return( <div> No Match Found </div> ) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function FunctionalComponent() {}", "function Component() { }", "getFromComponent(componentName, funcName, args=undefined){\n return this.#components.get(componentName)[funcName](args);\n }", "function SomeComponent() {}", "message(componentName, funcName, args){\n this.#components.get(componentName)[funcName](args);\n }", "function FunComponent()\n{\n return <h1>This is my Functional Component</h1>;\n \n}", "function UserComponent(){\n console.log('User component')\n}", "function render(comp) {\n // here comp will be the entire fn component code eg.\n // comp ƒ Counter() {\n // const [count, setCount] = TinyHooks.useState(0);\n // const [time, setTime] = TinyHooks.useState(new Date());\n\n // // This could should run on each function call/render\n // TinyHooks.useEffect…\n const instance = comp(); // invoking (executing) the function\n // here instance is a object with a render method. eg.\n // Object\n // render: () => { root.innerHTML = view; }\n // __proto__: Object\n instance.render();\n // in the next render the key counter can start from 0 again\n sequence = undefined;\n return instance;\n }", "function component() {\n var element = document.createElement('div');\n var btn = document.createElement('button');\n var br = document.createElement('br');\n\n btn.innerHTML = 'clikcME';\n element.innerHTML = _.join(['Hello', 'webpack'], ' ');\n element.appendChild(br);\n element.appendChild(btn);\n // btn.onclick = Print.bind(null,'click');\n /*element.classList.add('test');\n btn.innerHTML = 'clickMe';\n\n element.appendChild(btn);*/\n\n return element;\n}", "doHandle(component) {}", "function component() {\n let element = document.createElement('div');\n\n let btn = document.createElement('button');\n\n element.innerHTML = _.join(['Hello', 'webpack125' +\n ',,'\n ], ' ');\n\n btn.innerHTML = 'Click me and check the console!';\n btn.onclick = printMe;\n\n\n element.appendChild(btn);\n createArgumentsTest({ xqr: 1 }, 2, 3);\n\n // let lion = new Lion({name:'lion'});\n return element;\n}", "function MyComponent() {\r\n return <div>Hello</div>;\r\n}", "function component(domElement) {\n this.domElement=domElement;\n this.initialize=function() {\n console.log('init');\n };\n this.render=function(){\n console.log('render');\n }\n}", "cs (...args) {\n return MVC.ComponentJS(...args)\n }", "function IntroToFuncComp() {\n\treturn <Demo></Demo>;\n}", "render() { // it is a function ==> render: function() {}\n return (<h1>Hello World!!!!!!!</h1>);\n }", "function SampleComponent() {\n return <h1>Hello World</h1>;\n}", "function New({firstName} ) {\n return <p>Hello from another component {firstName}<br/>\n <h1>check this out</h1>\n <img src='../public/rose.jpeg' alt='pic' title='anms pic' />\n <ol>\n <li>new.js</li>\n <li>first try</li>\n <li> second try </li>\n </ol> </p>\n}", "function PratoDoDiaComponent() {\n }", "function App(){\n return <div><NumberDescriber number=\"1\" event={(text) => alert(text)}>\n Hello , I am a Functional Component !!!\n </NumberDescriber>\n </div>\n}", "function component() {\n const element = document.createElement('div');\n element.innerHTML = _.join(['A1', 'B1'], ' ')\n const button = document.createElement('button');\n // element.onclick = Print.bind(null, 'hello hello');\n return element;\n}", "static define() {\n Akili.component('component', Component);\n }", "function component() {\n var element = document.createElement('div');\n // Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的\n element.innerHTML = 'Hello';\n element.classList.add('hello');\n $('.box').append('--addd');\n return element;\n}", "function MyFunctionalComponent() {\n return <input />;\n}", "mountComponent(/* instance, ... */) { }", "function componentWrapper(type) {\n return function () {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n args.unshift(type);\n this.component.apply(this, args);\n };\n }", "function hi () {\n return <div> hi </div>\n \n}", "function Component() {\n return this; // this is needed in Edge !!!\n } // Component is lazily setup because it needs", "function FunctionComponent(props) {\n return <h1>hello, {props.name}</h1>\n}", "render(){\n const testValue = `All the names ${this.state.input}`\n return(\n <test value ={testValue} name={this.state.name} /> //How to render components from other files. value gives testValue as a PROP \n );\n }", "function Component(module, name, type){\n\t\n this.import = {\n module: module,\n name: name\n };\n \n this.action = function(){\n \talert(\"I'm defined to do \"+type+\" actions\");\n };\n}", "function createComponent(comp, onChange) {\n let creator = function() {\n console.warn(\"Unknown component type: \" + comp.type);\n return <div hidden=\"true\" />\n }\n switch(comp.type) {\n case constants.DESCRIPTION: {\n creator = createDescription;\n break;\n }\n case constants.NOTIFICATION: {\n creator = createNotification;\n break;\n }\n case constants.DOCUMENT: {\n creator = createDocument;\n break;\n }\n case constants.TASK: {\n creator = createTask;\n break;\n }\n }\n return creator(comp, onChange);\n}", "render(){\n //esto es lo que te devuelve esta funcion\n return <div></div>;\n }", "function genComponent(componentName, el, state) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return \"_c(\" + componentName + \",\" + genData$2(el, state) + (children ? \",\" + children : '') + \")\";\n }", "render2D(params, key) {\n throw new Error(\"User needs to provide method for component definition, look at examples\");\n }", "function genComponent(componentName, el, state) {\n\t var children = el.inlineTemplate ? null : genChildren(el, state, true);\n\t return \"_c(\" + componentName + \",\" + genData$2(el, state) + (children ? \",\" + children : '') + \")\";\n\t}", "function genComponent(componentName, el, state) {\n\t var children = el.inlineTemplate ? null : genChildren(el, state, true);\n\t return \"_c(\" + componentName + \",\" + genData$2(el, state) + (children ? \",\" + children : '') + \")\";\n\t}", "function genComponent(componentName, el, state) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return \"_c(\" + componentName + \",\" + genData$2(el, state) + (children ? \",\" + children : '') + \")\";\n }", "function component(html) {\n return `\n class MyComponent extends Component {\n __html__ = \\`${html}\\`\n }\n `\n}", "render() {\n return (\n /*\n 2) MAKING AN INTERACTIVE COMPONENT: \n\n Let’s fill the Square component with an “X” when we click it.\n First, change the button tag that is returned from the Square\n component’s render() function:\n */\n <button className=\"square\" onClick={function() {alert('click')}}>\n {this.props.value}\n </button>\n );\n }", "function component() {\n const element = document.createElement('div');\n const btn = document.createElement('button');\n \n element.innerHTML = __WEBPACK_IMPORTED_MODULE_0_lodash___default.a.join(['Hello', 'webpack'], ' ');\n // element.classList.add('hello');\n\n // const myIcon = new Image();\n // myIcon.src = Icon;\n\n // element.appendChild( myIcon );\n\n // console.log(Data);\n btn.innerHTML = 'Click me and check the console!';\n btn.onclick = __WEBPACK_IMPORTED_MODULE_1__print_js__[\"a\" /* default */];\n\n element.appendChild(btn);\n\n return element;\n}", "render() {\n const { name, code } = this.props\n return (\n <div>\n <h1>This is a Class Components</h1>\n <p>I am {name}, and I love {code}</p>\n </div>\n )\n }", "insertComponent(name) {\n // console.log('insert component into text', name);\n }", "function Example(){\n const example = 'Hello Function Component!';\n return <h1>{example}</h1>;\n}", "function clientCode(component) {\n // ...\n console.log(\"RESULT: \" + component.operation());\n // ...\n}", "function Button(){\n return <button>test</button>\n}", "function component() {\n var element = document.createElement('div');\n // var btn = document.createElement('button');\n var input = document.createElement('input');\n\n element.innerHTML = __WEBPACK_IMPORTED_MODULE_0_lodash___default.a.join(['H22osfsdss', 'w22ebpack'], ' ');\n // btn.innerHTML = 'print Me';\n // btn.onclick = printMe;\n // element.appendChild(btn);\n element.appendChild(input);\n\n return element;\n}", "function genComponent(componentName, el, state) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return \"_c(\" + componentName + \",\" + genData$2(el, state) + (children ? \",\" + children : '') + \")\";\n}", "function genComponent(componentName, el, state) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return \"_c(\" + componentName + \",\" + genData$2(el, state) + (children ? \",\" + children : '') + \")\";\n}", "function genComponent(componentName, el, state) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return \"_c(\" + componentName + \",\" + genData$2(el, state) + (children ? \",\" + children : '') + \")\";\n}", "function genComponent(componentName, el, state) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return \"_c(\" + componentName + \",\" + genData$2(el, state) + (children ? \",\" + children : '') + \")\";\n}", "static get component() {\n return Component;\n }", "GetComponents() {}", "GetComponents() {}", "GetComponents() {}", "GetComponents() {}", "createComponent(obj){\n\t\t\tvar comp = new Component(obj.selector, obj.template, obj.ctrlFunc);\n\t\t\tthis[componentSymbol].push({\n\t\t\t\tname: obj.name,\n\t\t\t\tcomponent: comp\n\t\t\t});\n\t\t\treturn comp;\n\t\t}", "render() {\n return <div>{this.toRender()}</div>;\n }", "function FunctionalComponentSyntax(props) {\n return <div>Hello World!</div>;\n}", "function getComponentConstructor ( ractive, name ) {\n\t \tvar instance = findInstance( 'components', ractive, name );\n\t \tvar Component;\n\n\t \tif ( instance ) {\n\t \t\tComponent = instance.components[ name ];\n\n\t \t\t// best test we have for not Ractive.extend\n\t \t\tif ( !Component._Parent ) {\n\t \t\t\t// function option, execute and store for reset\n\t \t\t\tvar fn = Component.bind( instance );\n\t \t\t\tfn.isOwner = instance.components.hasOwnProperty( name );\n\t \t\t\tComponent = fn();\n\n\t \t\t\tif ( !Component ) {\n\t \t\t\t\twarnIfDebug( noRegistryFunctionReturn, name, 'component', 'component', { ractive: ractive });\n\t \t\t\t\treturn;\n\t \t\t\t}\n\n\t \t\t\tif ( typeof Component === 'string' ) {\n\t \t\t\t\t// allow string lookup\n\t \t\t\t\tComponent = getComponentConstructor( ractive, Component );\n\t \t\t\t}\n\n\t \t\t\tComponent._fn = fn;\n\t \t\t\tinstance.components[ name ] = Component;\n\t \t\t}\n\t \t}\n\n\t \treturn Component;\n\t }", "execute(){\n\t\tvar component;\n\n\t\tfor (component in this.components){\n\t\t\tthis.components[component]();\n\t\t}\n\t}", "function FuncComp(props) {\n\tvar nameID = \"name\" + props.id;\n\tvar typeID = \"type\" + props.id;\n\tvar opID = \"op\" + props.id;\n\tswitch(props.type) {\n\t\tcase funcBody:\n\t\t\treturn (<div \n\t\t\t\t\t\tclassName=\"compContainer\"\n\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + props.x + 'px, ' + props.y + 'px)'}}>\n\t\t\t\t\t\t<img \n\t\t\t\t\t\t\tkey={props.id} \n\t\t\t\t\t\t\tclassName=\"fBody\" \n\t\t\t\t\t\t\tid={props.id}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0}}\n\t\t\t\t\t\t\tdraggable=\"true\" \t\t\t\t\t\t\n\t\t\t\t\t\t\tonDragStart={(event) => {drag(event)}}\n\t\t\t\t\t\t\talt=\"Test draggable\" \n\t\t\t\t\t\t\tsrc=\"./functionBody.png\" />\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={nameID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + 50 + 'px, ' + 20 + 'px)'}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: props.name}}></div>\n\t\t\t\t\t</div>);\n\t\tcase funcRec:\n\t\t\treturn (<div \n\t\t\t\t\t\tclassName=\"compContainer\"\n\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + props.x + 'px, ' + props.y + 'px)'}}>\n\t\t\t\t\t\t<img \n\t\t\t\t\t\t\tkey={props.id} \n\t\t\t\t\t\t\tclassName=\"fBody\" \n\t\t\t\t\t\t\tid={props.id}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0}}\n\t\t\t\t\t\t\tdraggable=\"true\" \t\t\t\t\t\t\n\t\t\t\t\t\t\tonDragStart={(event) => {drag(event)}}\n\t\t\t\t\t\t\talt=\"Test draggable\" \n\t\t\t\t\t\t\tsrc=\"./recFunctionBody.png\" />\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={nameID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + 50 + 'px, ' + 20 + 'px)'}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: props.name}}></div>\n\t\t\t\t\t</div>);\n\t\tcase funcOp:\n\t\t\treturn (<div \n\t\t\t\t\t\tclassName=\"compContainer\"\n\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + props.x + 'px, ' + props.y + 'px)'}}>\n\t\t\t\t\t\t<img \n\t\t\t\t\t\t\tkey={props.id} \n\t\t\t\t\t\t\tclassName=\"opfBody\" \n\t\t\t\t\t\t\tid={props.id}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0}}\n\t\t\t\t\t\t\tdraggable=\"true\" \t\t\t\t\t\t\n\t\t\t\t\t\t\tonDragStart={(event) => {drag(event)}}\n\t\t\t\t\t\t\talt=\"Test draggable\" \n\t\t\t\t\t\t\tsrc=\"./opFunctionBody2.png\" />\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={nameID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + 50 + 'px, ' + 20 + 'px)'}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: props.name}}></div>\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={opID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, fontSize:\"100%\", transform: 'translate(' + 130 + 'px, ' + 90 + 'px)'}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: \"(\" + props.op +\")\"}}></div>\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={typeID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + 180 + 'px, ' + 150 + 'px)'}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: props.valueType}}></div>\n\t\t\t\t\t</div>);\n\t\tcase funcExp:\n\t\t\treturn (<div \n\t\t\t\t\t\tclassName=\"compContainer\"\n\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + props.x + 'px, ' + props.y + 'px)'}}>\n\t\t\t\t\t\t<img \n\t\t\t\t\t\t\tkey={props.id} \n\t\t\t\t\t\t\tclassName=\"fExp\" \n\t\t\t\t\t\t\tid={props.id}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0}}\n\t\t\t\t\t\t\tdraggable=\"true\" \t\t\t\t\t\t\n\t\t\t\t\t\t\tonDragStart={(event) => {drag(event)}}\n\t\t\t\t\t\t\talt=\"Test draggable\" \n\t\t\t\t\t\t\tsrc=\"./expression.png\" />\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={nameID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + 3 + 'px, ' + 10 + 'px)'}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: props.name}}></div>\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={typeID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + 15 + 'px, ' + 10 + 'px)'}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: props.valueType}}></div>\n\t\t\t\t\t</div>);\n\t\tcase funcNExp:\n\t\t\treturn (<div \n\t\t\t\t\t\tclassName=\"compContainer\"\n\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + props.x + 'px, ' + props.y + 'px)'}}>\n\t\t\t\t\t\t<img \n\t\t\t\t\t\t\tkey={props.id} \n\t\t\t\t\t\t\tclassName=\"fNExp\" \n\t\t\t\t\t\t\tid={props.id}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0}}\n\t\t\t\t\t\t\tdraggable=\"true\" \t\t\t\t\t\t\n\t\t\t\t\t\t\tonDragStart={(event) => {drag(event)}}\n\t\t\t\t\t\t\talt=\"Test draggable\" \n\t\t\t\t\t\t\tsrc=\"./nameExpression.png\" />\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={nameID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + 3 + 'px, ' + 10 + 'px)'}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: props.name}}></div>\n\t\t\t\t\t\t<div \n\t\t\t\t\t\t\tclassName=\"txtComp\"\n\t\t\t\t\t\t\tid={typeID}\n\t\t\t\t\t\t\tstyle={{position:\"absolute\", top:0, left:0, transform: 'translate(' + 44 + 'px, ' + 10 + 'px)', fontSize:\"60%\"}}\n\t\t\t\t\t\t\tdangerouslySetInnerHTML={{__html: props.valueType}}></div>\n\t\t\t\t\t</div>);\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\t\n}", "compose() {\n this.id += 1\n this.componentName = this.createComponentName()\n this.createComponentFile()\n }", "function genComponent (\n\t componentName,\n\t el,\n\t state\n\t) {\n\t var children = el.inlineTemplate ? null : genChildren(el, state, true);\n\t return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n\t}", "function MyComponent() {\n return (\n <div>\n <p>This is my functional component.</p>\n </div>\n );\n}", "function genComponent (\n componentName,\n el,\n state\n ) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n }", "function genComponent (\n componentName,\n el,\n state\n ) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n }", "function genComponent (\n componentName,\n el,\n state\n ) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n }", "function component() {\n var element = document.createElement('pre');\n\n element.innerHTML = [\n 'Hello webpack!',\n '5 cubed is equal to ' + cube(5)\n ].join('\\n\\n');\n\n return element;\n}", "render(createElement/*(TYPE, props, children, rawcontent)*/,components){\n\t\treturn \"Input.render should be implemented\"\n\t}", "function render() {\r\n\r\n}", "function render() {\r\n\r\n}", "function genComponent (\r\n componentName,\r\n el,\r\n state\r\n) {\r\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\r\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\r\n}", "broadcast(funcName, args){\n for(let {name,component} of this.#components){\n if(typeof component[funcName] === \"function\"){\n component[funcName](args);\n }\n }\n }", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}", "function genComponent (\n componentName,\n el,\n state\n) {\n var children = el.inlineTemplate ? null : genChildren(el, state, true);\n return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}" ]
[ "0.737132", "0.7364122", "0.71303815", "0.70566297", "0.69755214", "0.6674257", "0.6328816", "0.6289747", "0.6275815", "0.6270926", "0.62676793", "0.62541646", "0.62524074", "0.6234294", "0.6202065", "0.6195937", "0.6191933", "0.618333", "0.61314565", "0.61071986", "0.6092048", "0.60856247", "0.60483295", "0.6038442", "0.60149306", "0.5977039", "0.59666073", "0.59533113", "0.593617", "0.5930678", "0.59300196", "0.59269536", "0.5923539", "0.59159774", "0.590904", "0.5899531", "0.5899531", "0.5871355", "0.5867337", "0.58480835", "0.58455205", "0.5840681", "0.5837746", "0.5832268", "0.5829687", "0.58287543", "0.58284193", "0.5815432", "0.5815432", "0.5815432", "0.5815432", "0.5813146", "0.5804206", "0.5804206", "0.5804206", "0.5804206", "0.58009124", "0.57991993", "0.57931453", "0.5778855", "0.5778528", "0.5770606", "0.575873", "0.57456434", "0.5743126", "0.57383126", "0.57383126", "0.57383126", "0.573485", "0.5723286", "0.5718034", "0.5718034", "0.5714426", "0.5709213", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186", "0.57072186" ]
0.0
-1
TODO: inline implementation into single call site
function onCHANNEL_OPEN(self, info) { // The server is trying to open a channel with us, this is usually when // we asked the server to forward us connections on some port and now they // are asking us to accept/deny an incoming connection on their side let localChan = -1; let reason; const accept = () => { const chanInfo = { type: info.type, incoming: { id: localChan, window: MAX_WINDOW, packetSize: PACKET_SIZE, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; const stream = new Channel(self, chanInfo); self._chanMgr.update(localChan, stream); self._protocol.channelOpenConfirm(info.sender, localChan, MAX_WINDOW, PACKET_SIZE); return stream; }; const reject = () => { if (reason === undefined) { if (localChan === -1) reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; } if (localChan !== -1) self._chanMgr.remove(localChan); self._protocol.channelOpenFail(info.sender, reason, ''); }; const reserveChannel = () => { localChan = self._chanMgr.add(); if (localChan === -1) { reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of incoming channel open: ' + 'no channels available' ); } } return (localChan !== -1); }; const data = info.data; switch (info.type) { case 'forwarded-tcpip': { const val = self._forwarding[`${data.destIP}:${data.destPort}`]; if (val !== undefined && reserveChannel()) { if (data.destPort === 0) data.destPort = val; self.emit('tcp connection', data, accept, reject); return; } break; } case '[email protected]': if (self._forwardingUnix[data.socketPath] !== undefined && reserveChannel()) { self.emit('unix connection', data, accept, reject); return; } break; case '[email protected]': if (self._agentFwdEnabled && typeof self._agent.getStream === 'function' && reserveChannel()) { self._agent.getStream((err, stream) => { if (err) return reject(); const upstream = accept(); upstream.pipe(stream).pipe(upstream); }); return; } break; case 'x11': if (self._acceptX11 !== 0 && reserveChannel()) { self.emit('x11', data, accept, reject); return; } break; default: // Automatically reject any unsupported channel open requests reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of unsupported incoming channel open ' + `type: ${info.type}` ); } } if (reason === undefined) { reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; if (self.config.debug) { self.config.debug( 'Client: Automatic rejection of unexpected incoming channel open for: ' + info.type ); } } reject(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private public function m246() {}", "private internal function m248() {}", "transient private protected internal function m182() {}", "protected internal function m252() {}", "transient protected internal function m189() {}", "static private internal function m121() {}", "transient private internal function m185() {}", "transient final protected internal function m174() {}", "static transient final private internal function m43() {}", "obtain(){}", "static transient final protected internal function m47() {}", "static private protected internal function m118() {}", "transient private protected public internal function m181() {}", "static transient final protected public internal function m46() {}", "static final private internal function m106() {}", "transient final private protected internal function m167() {}", "function _____SHARED_functions_____(){}", "static transient final private protected internal function m40() {}", "static transient private protected internal function m55() {}", "transient final private internal function m170() {}", "__previnit(){}", "apply () {}", "static transient private protected public internal function m54() {}", "transient private public function m183() {}", "static transient final protected function m44() {}", "static protected internal function m125() {}", "static private protected public internal function m117() {}", "function fm(){}", "static transient private public function m56() {}", "static transient private internal function m58() {}", "transient final private protected public internal function m166() {}", "static final private protected internal function m103() {}", "static first(context) {\n throw new Error(\"TODO: Method not implemented\");\n }", "function AeUtil() {}", "function ea(){}", "static transient final private public function m41() {}", "static method(){}", "function DWRUtil() { }", "function miFuncion (){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "function r(){}", "static transform() {}", "static final protected internal function m110() {}", "static final private protected public internal function m102() {}", "function Utils() {}", "function Utils() {}", "static async method(){}", "function oi(){}", "function __func(){}", "static final private public function m104() {}", "function Helper() {}", "function Adaptor() {}", "getResult() {}", "function __it() {}", "function miFuncion(){}", "function miFuncion(){}", "function miFuncion(){}", "static transient final private protected public internal function m39() {}", "function Alerter() {}", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }", "compilable(_locator) {\n throw new Error('Method not implemented.');\n }", "prepare() {}", "function ba(){}", "function ba(){}", "function ba(){}", "function ba(){}", "function Util() {}", "function dummy(){}", "function dummy(){}", "function dummy(){}", "transient final private public function m168() {}", "static transient final private protected public function m38() {}", "function wa(){}", "function customHandling() { }", "function Scdr() {\r\n}", "function Utils(){}", "method() {\n throw new Error('Not implemented');\n }", "function r() {}", "function r() {}", "function r() {}", "function Common() {}", "function fn() {\n\t\t }", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "initialize() {}", "static private public function m119() {}" ]
[ "0.6862103", "0.65810156", "0.64286816", "0.6407269", "0.6366164", "0.6211606", "0.6190751", "0.61487025", "0.60363835", "0.60345316", "0.59641826", "0.58858234", "0.58616424", "0.58480537", "0.5800668", "0.5785152", "0.5777472", "0.5710852", "0.57090497", "0.56764054", "0.56616265", "0.56576866", "0.5525069", "0.55011326", "0.5494689", "0.54925567", "0.5444847", "0.54293907", "0.5418555", "0.54047006", "0.53877467", "0.5366518", "0.5349276", "0.53416526", "0.53220713", "0.53079945", "0.5297709", "0.5294957", "0.5289203", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.52657396", "0.5261458", "0.52555156", "0.5251652", "0.5223007", "0.5223007", "0.5214072", "0.5204177", "0.52039385", "0.51914346", "0.51902145", "0.5181726", "0.5174848", "0.5168697", "0.5168548", "0.5168548", "0.5168548", "0.5140403", "0.51263624", "0.5107093", "0.5107093", "0.5107093", "0.50965744", "0.5094646", "0.5094646", "0.5094646", "0.5094646", "0.5087624", "0.50578284", "0.50578284", "0.50578284", "0.5055807", "0.5053299", "0.50401556", "0.50122046", "0.5010358", "0.5007954", "0.49994022", "0.49744424", "0.49744424", "0.49744424", "0.49669957", "0.49635208", "0.4959845", "0.4959845", "0.4959845", "0.4959845", "0.4959845", "0.4959845", "0.49570748" ]
0.0
-1
This function starts a new game with the users chosen settings (Timer, Difficulty and Theme)
function startNewGame() { // Select game board difficulty let grid; if (id("easy-diff").checked) { grid = easy[0]; } else if (id("medium-diff").checked) { grid = medium[0]; } else if (id("hard-diff").checked) { grid = hard[0]; } else if (id("hardcore-diff").checked) { grid = hardcore[0]; } // Set number of lives to five and enable selection of squares and numbers lives = 5; noSelect = false; id("lives").textContent = "Remaining Lives: 5"; // Create game board based on difficulty createGrid(grid); // Start the timer startTimer(); // Assigns theme based on select if (id("theme-1").checked){ // Remove unwanted themes from list and adds light theme // Body qs("body").classList.remove("dark"); qs("body").classList.remove("coffee"); qs("body").classList.remove("unicorn"); qs("body").classList.add("light"); // Header qs("header").classList.remove("dark"); qs("header").classList.remove("coffee"); qs("header").classList.remove("unicorn"); qs("header").classList.add("light"); // Footer qs("footer").classList.remove("dark"); qs("footer").classList.remove("coffee"); qs("footer").classList.remove("unicorn"); qs("footer").classList.add("light"); } else if (id("theme-2").checked) { // Remove unwanted themes from list and adds dark theme // Body qs("body").classList.remove("light"); qs("body").classList.remove("coffee"); qs("body").classList.remove("unicorn"); qs("body").classList.add("dark"); // Header qs("header").classList.remove("light"); qs("header").classList.remove("coffee"); qs("header").classList.remove("unicorn"); qs("header").classList.add("dark"); // Footer qs("footer").classList.remove("light"); qs("footer").classList.remove("coffee"); qs("footer").classList.remove("unicorn"); qs("footer").classList.add("dark"); } else if (id("theme-3").checked) { // Remove unwanted themes from list and adds coffee theme // Body qs("body").classList.remove("light"); qs("body").classList.remove("dark"); qs("body").classList.remove("unicorn"); qs("body").classList.add("coffee"); // Header qs("header").classList.remove("light"); qs("header").classList.remove("dark"); qs("header").classList.remove("unicorn"); qs("header").classList.add("coffee"); // Footer qs("footer").classList.remove("light"); qs("footer").classList.remove("dark"); qs("footer").classList.remove("unicorn"); qs("footer").classList.add("coffee"); } else if (id("theme-4").checked) { // Remove unwanted themes from list and adds unicorn theme // Body qs("body").classList.remove("light"); qs("body").classList.remove("dark"); qs("body").classList.remove("coffee"); qs("body").classList.add("unicorn"); // Header qs("header").classList.remove("light"); qs("header").classList.remove("dark"); qs("header").classList.remove("coffee"); qs("header").classList.add("unicorn"); // Footer qs("footer").classList.remove("light"); qs("footer").classList.remove("dark"); qs("footer").classList.remove("coffee"); qs("footer").classList.add("unicorn"); } // Show the number selector id("number-selector").classList.remove("hidden"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function startNewGame() {\n // Possible speeds\n var speeds = {\n 0: 60,\n 200: 77,\n 500: 120,\n 800: 300\n };\n\n // Getting speed based on difficulty\n var speed = difficulty.options[difficulty.selectedIndex].value;\n\n var moleTimer = new Timer({\n seconds: speeds[speed],\n speed: speed,\n onTime: function() {\n if (!gameEnded) {\n renderMole();\n }\n }\n });\n\n // Start timer.\n gameTimer.start();\n moleTimer.start();\n\n // New game\n gameEnded = false;\n }", "function startGame(){\n hideContent();\n unhideContent();\n assignButtonColours();\n generateDiffuseOrder();\n clearInterval(interval);\n setlevel();\n countdown(localStorage.getItem(\"theTime\"));\n listeningForClick();\n}", "function startGame() {\n hitCount = 0\n\n if (isSettingsInitialized) {\n console.log('Settings initialized')\n loadSettings()\n }\n\n togglePanel(panel.PREGAME)\n generateLayout()\n\n maxSpawns = Math.floor(maxTime / spawnRate)\n remainingSpawns = maxSpawns\n\n for (let s = 0; s < maxSpawns; s++) {\n spawnTimeouts.push(setTimeout(spawnYagoo, spawnRate * s))\n }\n\n startTimer(msToSec(maxTime), document.getElementById('timer-text'))\n}", "function startGame() {\n if(gameState.gameDifficulty === 'easy')\n {\n easyMode();\n } \n if(gameState.gameDifficulty ==='normal'){\n normalMode();\n }\n\n if(gameState.gameDifficulty ==='hard'){\n hardMode();\n }\n\n}", "function startNewGame(){\n\t\tclearTimeout(intervalVar);\n\t\tcurWin.set({\n\t\t\tcurrentWin: -1\n\t\t});\n\n\t\tplayerOneRef.update({\n\t\t\tchoice: \"undefined\"\n\t\t});\n\n\t\tplayerTwoRef.update({\n\t\t\tchoice: \"undefined\"\n\t\t});\t\t\n\n\t\tturnRef.set({\n\t\t\tturn: 1\n\t\t});\n\t}", "function StartNewGame() {\n\tsnowStorm.stop();\n\tsnowStorm.freeze();\n\n\tvar params = {\n\t\tchosen: \"riley\"\n\t};\n\n\t_gameObj = new Game();\n\t_gameObj.SetupCanvas(params);\n\t$j(window).resize(function () {\n\t\t_gameObj.SetupCanvas(params);\n\t});\n\n\t$j.mobile.changePage($j('#game'));\n}", "function startGame(){\n getDictionary();\n var state = $.deparam.fragment();\n options.variant = state.variant || options.variant;\n makeGameBoard();\n loadState();\n }", "function startGame() {\n\t\tstatus.show();\n\t\tinsertStatusLife();\n\t\tsetLife(100);\n\t\tsetDayPast(1);\n\t}", "function startNewGame() {\n // Clears the wave generation timeout\n clearInterval(info.timeout);\n // Hides the modal if displayed\n if(divs.modal_div.style.display != \"none\") {\n divs.modal_div.style.display = \"none\";\n }\n // Resets the score, level and lives\n info.score = 0;\n info.level = 1;\n info.lives = 3;\n // Starts the wave\n startWave();\n}", "function startGame(){\r\n let difficulty = $('input[name=difficulty]:checked').val()\r\n $('input[name=\"difficulty\"]').prop('checked', false)\r\n $('.game-settings-container').css('display', 'none')\r\n if(difficulty !== 'Good Luck'){\r\n bugFunction = setInterval(createbug, gameSpeed.spawnTime)\r\n }\r\n createbug()\r\n timerFunction = setInterval(updateTimer,1000)\r\n}", "function newGame() {\n level = 1;\n lives = 3;\n levelKey = 0;\n levelHeart = 0;\n time = 0;\n startTimer();\n}", "function startGame(mapName = 'galaxy'){\n toggleMenu(currentMenu);\n if (showStats)\n $('#statsOutput').show();\n $('#ammoBarsContainer').show();\n scene.stopTheme();\n scene.createBackground(mapName);\n if (firstTime) {\n firstTime = false;\n createGUI(true);\n render();\n } else {\n requestAnimationFrame(render);\n }\n}", "function newGame(gameMode) {\n seriesPlayed = 1;\n gameIsStarted = true;\n gameHasEnded = false;\n isReady = false;\n $('#instructionsContent').text(\"Clique quand la couleur change\");\n $('#actionButton').text(\"START\");\n\n console.log(\"New Game starting.\")\n\n}", "function startGame(){\n var valid = setGame()\n if (valid){\n var elem = document.getElementById(\"alert\");\n elem.innerHTML = `Welcome to the memory game. Change to desired settings and press start to play.`\n elem.style.color = \"black\";\n new MatchGrid( input.width, input.height, input.columns, input.rows, input.timeLimit, input.theme)\n }\n else {\n clearInterval(interval)\n disableGame()\n }\n}", "function startGame(player1Name, player2Name, difficultySetting) {\n window.scoreboard = new Scoreboard(player1Name, player2Name, difficultySetting); \n window.gameboard = new Gameboard(difficultySetting); \n window.clickToPlay = new ClickToPlay(player1Name, player2Name, difficultySetting);\n $('#grid-container-body').removeClass('hide');\n setTimeout(hideWelcomeModal, 500);\n }", "function startGame(){\n countdown();\n question();\n solution();\n }", "function newGame() {\n if (DEBUG) console.log('inside newGame(), calling clearGame() to clean things up...');\n clearGame();\n if (DEBUG) console.log('about to wait a bit before starting the next game...');\n delayOperation = window.setTimeout(function(){ initGame(); }, millisecondOperationDelay);\n }", "function startNewGame(p_type){\n\t hideLockoutLayerAtStart();\n\t // send state immediately for static\n\t //$(\"#lockout\").css({\"background\": \"transparent\"});\n\t \n\t _currVars.myVars.myType = p_type;\n\t sendState();\n }", "startGame() {\n //@todo: have this number set to the difficulty, easy = 3, normal = 6, hard = 9\n StateActions.onStart(5, 5, this.state.difficulty);\n StateStore.setGameState(1);\n this.gameState();\n }", "function newGame() {\n\t// Das Spielfeld leeren\n\tctx.clearRect(0,0, canvasWidth, canvasHeight);\n\t\n\t// Wenn der Timer widererwarten noch laufen sollte, dann muss er angehalten werden\n\tif(time.Enable){\n\t\ttime.Stop();\n\t}\n\t\n\t// Timer zurücksetzen\n\tseconds = 0;\n\t$('span#timer').html(seconds);\n\t\n\talive = true;\n\t// Baue das Spielfeld\n\tarrayBuild();\n\t// Zeichne die Anzahl der Minen\n\t$('span#mines').html(exsistingMines);\n\t\n\t// Den Schwierigkeitsgrad des Statistikdiv setzen\n\t$('#difficulty4statistics').val($('#difficulty').val());\n\t\n\trepaint();\n}", "function newGame() {\n //Reseta a score\n score = 0;\n scoreText = 0;\n //Inicia\n if (!firsTime) {\n gameState = gameStates.ready;\n }\n //Reseta o game over\n gameOver = false;\n pause = false;\n //Tempo\n time = 10;\n //Cria o level\n createLevel();\n }", "function startNewGame() {\n const newGame = new GameLoop();\n newGame.startGame(true);\n}", "function startGame() {\n logger.log('Staring a new game');\n // Hide any dialog that might have started this game\n $('.modal').modal('hide');\n\n // Reset the board\n board.init();\n\n // Init the scores\n level = 1;\n score = 0;\n totalShapesDropped = 1;\n delay = 500; // 1/2 sec\n updateUserProgress();\n\n // Init the shapes\n FallingShape = previewShape;\n previewShape = dropNewShape();\n\n // Reset game state\n drawPreview();\n pauseDetected = false;\n isPaused = false;\n isGameStarted = true;\n isStopped = false;\n\n // Update the button if this is the first game\n $('#newGameButton').text(\"New Game\");\n\n // Start dropping blocks\n advance();\n }", "function startGame() {\n hideStart();\n hideSaveScoreForm();\n resetFinalScore();\n clearCurrentQuestion();\n resetUserScore();\n displayCurrentQuestion();\n startTimer();\n}", "function startGame() {\n\t\tvar game = document.getElementById(\"game-area\");\n\t\ttimeStart();\t\t\t\t\n\t}", "function startGame() { }", "function startGame() {\n\t\n\t// fill the question div with new random question\n\tgenerateQuestion();\n\t\n\t// start the timer\n\tmoveProgressBar();\n}", "function GameStart() {\n\tGenerateCharacter();\n\tCreateTileGrid();\n\tCreateGraphicsGrid();\n\tCreateNoteGrid();\n\tGenerateDungeon();\n\tRoundTimer();\n}", "function startGame () {\n if (!gameStarted) { // ensure setInterval only fires once\n setInterval(countdown, 1000)\n generateList() // start game generates first order, subsequent order generated by serve\n setTimeout(gameOver, 90000) // cause endGameOverlay DOM\n }\n gameStarted = true\n removeStartScreen() //remove instructions\n createBoard() //create title and bottom burger in playArea\n }", "function startNewGame() {\n setGoal();\n updateDisplay();\n randomlizeCrystals();\n storeCrystals();\n}", "function startNewGame() {\n\t\tif (userRoundScore > randomScore) {\n\t\t\tlosses++;\n\t\t\talert(\"Math is hard... You Lost. Try again!\");\n\t\t\tinitializeVariables();\n\t\t}\n\n\t\tif (userRoundScore == randomScore) {\n\t\t\twins++;\n\t\t\tinitializeVariables();\n\t\t\talert(\"Szechuan Sauce For All! You Win!\");\n\t\t}\n\t}", "function newGame(){\n reset ();\n correct = 0;\n incorrect =0;\n unanswered = 0;\n time = 10;\n intervalId;\n clockRunning = false;\n clicked = false;\n\n}", "function newGame() {\n userScore = 0;\n gameStart();\n }", "function newGame () {\n if (timer != null) {\n clearInterval(timer);\n }\n turn = false;\n timer = null;\n difficulty = difficultyTemp;\n multiplayer = multiplayerTemp;\n document.getElementById('player').innerHTML = '1';\n p1Score = 0;\n p2Score = 0;\n updateScore(0);\n deck = getDeck();\n board = dealBoard();\n cards = ['', '', ''];\n setUINewGame();\n displayBoard();\n timerStart();\n}", "function startGame() {\n if(!presence.ballIsSpawned) {\n fill(start.color.c, start.color.saturation, start.color.brightness);\n stroke(start.color.c, start.color.saturation, start.color.brightness)\n if((windowWidth < 600) && (windowHeight < 600)) {\n textSize(20);\n text(\"PRESS ENTER TO START GAME\", windowWidth/4.2, windowHeight/2.5);\n textSize(15);\n text(\"(First to 7 Wins)\", windowWidth * 0.41, windowHeight * 0.47);\n }\n if((windowWidth > 601) && (windowHeight > 601)) {\n textSize(30)\n text(\"PRESS ENTER TO START GAME\", windowWidth * 0.35, windowHeight/2.5);\n textSize(20);\n text(\"(First to 7 Wins)\", start.textX + start.textX * 0.265, windowHeight * 0.44);\n }\n if(mode == 'single'){\n if((windowWidth > 601) && (windowHeight > 601)){\n text(\"Mode: \" + mode, windowWidth * 0.9, windowHeight * 0.08);\n textSize(18);\n text(\"USE ARROWS TO MOVE\", start.textX + start.textX * 0.2, windowHeight * 0.48);\n textSize(14);\n text(\"PRESS SHIFT FOR TWO PLAYER\", start.textX + start.textX * 0.2, windowHeight * 0.52);\n }\n if((windowWidth < 600) && (windowHeight < 600)){\n text(\"Mode: \" + mode, windowWidth * 0.8, windowHeight * 0.08);\n textSize(14);\n text(\"USE ARROWS TO MOVE\", start.textX + start.textX * 0.01, start.textY + start.textY * 0.04);\n textSize(12);\n text(\"PRESS SHIFT FOR TWO PLAYER\", windowWidth * 0.35, start.textY + start.textY * 0.16);\n defaultBallSpeed = 4;\n }\n }\n if(mode == 'two'){\n if((windowWidth > 601) && (windowHeight > 601)) {\n textSize(20);\n text(\"Mode: \" + mode, windowWidth * 0.9, windowHeight * 0.08)\n textSize(18);\n text(\"USE Q, A, P, L TO MOVE\", windowWidth * 0.43, windowHeight * 0.48);\n textSize(14);\n text(\"PRESS SHIFT FOR ONE PLAYER\", start.textX + start.textX * 0.2, windowHeight * 0.52);\n }\n }\n \n start.color.c += 1;\n if(start.color.c > 359) {\n start.color.c = 0;\n }\n }\n }", "function prepareNewGame(){\n client.prepareNewGame('Phat3lfstone', 'red', GameSettings.create());\n}", "prepAndStartNewGame() {\n this.resetPlayers(Player.TOWN);\n this.assignRoles(this.options.numMafia, this.options.numCops, this.options.numDoctors);\n this.updateRoleCounts();\n this.gameState = MAFIA_TIME;\n }", "startNewGame() {\n this.currentRound = 0;\n this.monsterHealth = 100;\n this.playerHealth = 100;\n this.playerCanAttack = true;\n this.winner = null;\n this.logMsg = [];\n }", "function startNewGame() {\n arrayPlayCardTravaux = arrayCardTravaux.slice();\n melangeArray(arrayPlayCardTravaux);\n \n arrayPlayCardPlan1 = arrayCardPlan1.slice();\n melangeArray(arrayPlayCardPlan1);\n \n arrayPlayCardPlan2 = arrayCardPlan2.slice();\n melangeArray(arrayPlayCardPlan2);\n \n arrayPlayCardPlan3 = arrayCardPlan3.slice();\n melangeArray(arrayPlayCardPlan3);\n\n startBtnElt.style.display = 'none';\n soloBtnElt.style.display = 'block';\n \n affichageCardsTravaux();\n affichageCardsPlan();\n affichageNumberCard();\n setInterval(chronoRunVar, 1000);\n}", "function startGame() {\n shuffleDeckEn(); //shuffles the english cards deck on load\n shuffleDeckFrench(); //shuffles the french cards deck on load\n shuffleDeckItalian(); //shuffles the italian cards deck on load\n turns = [];\n matchedPairs = [];\n secondsLeft = 60;\n }", "function startGame() {\n incrementGameStep({ gameId, gameData });\n }", "function startNewGame(p_type, p_attemptsAllowed, p_feedbackType, p_isOpenResponse){\n\t\n\t // modify this to handle infinity -- ie make it 2000\n\t _currVars.myVars.attemptsAllowed = p_attemptsAllowed;\n\t\n\t \t_currVars.myVars.feedbackSetup = p_feedbackType;\n\t\n\t _currVars.myVars.myType = p_type;\n\t\n\t\t\n\t isCurrentDeviceMobile();\n\n\t captureAnswerDataAtStart();\n\t\n\t attachClickHandlersToAnswerDivs();\n\t\n\t if(p_isOpenResponse === \"true\"){\n\t\t_currVars.myVars.myType = \"openresponse\";\n\t\t_currVars.myVars.allowCheckbuttonInteraction = false;\n\t\thideLockoutLayerAtStart();\n\t\tsendState();\n\t\treturn;\t\t\n\t }\n\t\n\t if(_currVars.myVars.myType === \"assessment\"){\n\t\t//alert(\"i am an asessment\");\n\t\t_currVars.myVars.allowCheckbuttonInteraction = false;\n\t\thideLockoutLayerAtStart();\n\t\treturn;\n\t\t\n\t }\n\t\n\t _currVars.myVars.allowCheckbuttonInteraction = true;\n\t\n\t //show check answer button as inactive\n\t _myDispatcher.setCheckButtonToInactive();\n\t\n\t hideLockoutLayerAtStart();\n\n\t sendState();\n }", "runGame() {\r\n HangmanUtils.displayGameOptions();\r\n let gameOption = input.questionInt(\">> \");\r\n let game = new Game(this.sourceFileName, this.recordsFileName, this.maxScore);\r\n switch (gameOption) {\r\n case 1:\r\n game.opOneRoundIndependent();\r\n break;\r\n case 2:\r\n game.opOneGameplay();\r\n break;\r\n case 3:\r\n game.opContinuousGameplays();\r\n break;\r\n case 4:\r\n break;\r\n default:\r\n console.log(\"\\nPlease only enter 1, 2, 3 or 4!\");\r\n input.question(\"\\nPress \\\"Enter\\\" to proceed...\");\r\n }\r\n }", "function start(data) {\n startGameTimer();\n}", "function startGame() {\r\n countUp = 0;\r\n setTimeout(endGame, 120000);\r\n startTimer();\r\n cancelTimer = false;\r\n triggerCrime();\r\n}", "function newGame() {\r\n if (is5x5) {\r\n startUp()\r\n constructMaze(5, 5);\r\n Texture().initialize(150);\r\n }\r\n else if (is10x10) {\r\n startUp()\r\n constructMaze(10, 10);\r\n Texture().initialize(75);\r\n }\r\n else if (is15x15) {\r\n startUp()\r\n constructMaze(15, 15);\r\n Texture().initialize(50);\r\n }\r\n else if (is20x20) {\r\n startUp()\r\n constructMaze(20, 20);\r\n Texture().initialize(37.5);\r\n }\r\n else {\r\n console.log(\"Please select a maze size to start.\")\r\n }\r\n }", "function startGame() {\n water = 0;\n corn = 2;\n beans = 2;\n squash = 2;\n month = 1;\n gameOver = false;\n \n initGameBoard();\n playGame();\n}", "function playGame(){\n createTimer();\n juego.resetScore();\n juego.resetCorrectLabel();\n juego.setStatePlaying(true);\n disablePlayButton();\n juego.updateExpression();\n enableSendResultButton();\n resetClasses();\n}", "function startGame() {\n\tinitGame();\n\tsetInterval(updateGame, 90);\n}", "function updateGame(settings) {\n spawnCharacters(redGroup, 'teamRed', settings.teamRed.count);\n spawnCharacters(blueGroup, 'teamBlue', settings.teamBlue.count);\n }", "function startNewGame() {\n if (!document.fullscreenElement) { p.wrapper.requestFullscreen(); }\n p.loadingWidth = 0;\n p.matrix = [];\n p.ready = false;\n p.timeOfStart = 0;\n p.timeOfEnd = 0;\n clearTimeout(p.timeOut1);\n clearTimeout(p.timeOut2);\n\n createMatrix();\n if (p.startGame) { startTimer(); }\n }", "function NewGame() {\n\t// Your code goes here for starting a game\n\tprint(\"Complete this method in Singleplayer.js\");\n}", "function gameStart() {\n gameStarted = true;\n let pSelected = userChoice;\n let hSelected = houseSelection();\n gameRule(pSelected, hSelected);\n}", "function startGame() {\n\t\t\tvm.gameStarted = true;\n\t\t\tMastermind.startGame();\n\t\t\tcurrentAttempt = 1;\n\t\t\tactivateAttemptRow();\n\t\t}", "function startGame(){\n if(!gameStarted){\n gameStarted = true;\n startGame1 = true;\n $scoreP1.text(0);\n timeUp = false;\n p1Score = 0;\n highlight();\n countdown();\n setTimeout(() => {\n timeUp = true;\n $player1PopUp.css('display', 'block');\n $p1ScoreDisplay.text(p1Score);\n },15000);\n }\n }", "function newGame() {\n rebuildDeck(shapes);\n resetOpenCards();\n resetMoves();\n resetMatchCount();\n timer.reset();\n}", "function startGame() {\n setVars();\n clearInterval(wordAnimation); // Stop animations on how-to page\n getTopics();\n displayTopicChoice();\n $(\".try-again\").addClass(\"d-none\"); // Remove try again button\n $(\".menu1\").addClass(\"d-none\");\n $(\".menu2\").removeClass(\"d-none\");\n $(\".skip-question-btn\").css(\"background-color\", \"#054a91\"); // Reset Skip Button\n $(\"#message-icon\").text(\" \"); // Get rid of lives icon\n}", "function newGame() {\n /* This uses a callback function as all of the other processes are dependant on the configuration information. */\n GAME.loadConfig(function() {\n GAME.loadSVGFiles(); // This will also begin to draw the starting room when complete. //\n GAME.createMaze();\n GAME.prepareCanvas(); // Draws a blank canvas in preparation for rooms. //\n PLAYER.setRandomRoom(); // Assign the player to a random room. //\n });\n}", "function newGame(){\n //On remet les scores à 0\n score = 0;\n globalScore = [0,0,0];\n player = 1;\n playing = true;\n \n $('#global-score-1').text('0');\n $('#global-score-2').text('0');\n $('#round-score-1').text('0');\n $('#round-score-2').text('0');\n \n $('#player1-title').text('PLAYER 1');\n $('#player2-title').text('PLAYER 2');\n \n $('#player2').removeClass('active');\n $('#player1').removeClass('active').addClass('active');\n \n $('#roll-dice').show();\n $('#hold').show();\n }", "function gameStart(){\n\t\t\tshuffleCards();\n\t\t\ttime = 0;\n\t\t\tstarttime = Date.now();\n\t\t\ttimer = setInterval(function(){\n\t\t\t\ttime++;\n\t\t\t\t$(\".info .timer .sec\").text(time);\n\t\t\t}, 1000);\n\t\t}", "function startGame(freshGame = false) {\n if (freshGame) initState()\n loop()\n}", "function startGame()\n{\n //Call to the Instruction Screen UI function that generates the UI for the Instruction Screen\n createInstructionScreenUI();\n\n //Cal to create Instruction function that loads the level data from the gameLevels and append the required texts onto the UI elements\n createLevelInstruction();\n}", "function startGame() {\n showGuessesRemaining();\n showWins();\n}", "launchGame() {\n this.grid.generate()\n this.grid.generateWalls()\n this.grid.generateWeapon('axe', this.grid.giveRandomCase())\n this.grid.generateWeapon('pickaxe', this.grid.giveRandomCase())\n this.grid.generateWeapon('sword', this.grid.giveRandomCase())\n this.grid.generateWeapon('rod', this.grid.giveRandomCase())\n \n this.shears = new Weapon('shears', 10)\n this.sword = new Weapon('sword', 20)\n this.axe = new Weapon('axe', 30)\n this.pickaxe = new Weapon('pickaxe', 40)\n this.rod = new Weapon('rod', 50)\n\n var position_player1 = -1\n var position_player2 = -1\n\n do {\n position_player1 = this.grid.generatePlayer('1')\n this.player1.setPosition(position_player1)\n } while (position_player1 == -1)\n\n do {\n position_player2 = this.grid.generatePlayer('2')\n this.player2.setPosition(position_player2)\n } while (position_player2 == -1 || this.grid.isNextToPlayer(position_player2))\n\n this.game_status = $('#game_status')\n this.game_status.html('Recherche d\\'armes pour les deux joueurs...')\n }", "function startGame() {\n pacSoundId = setInterval(pacSound, 650)\n countUpid = setInterval(countUp, 1000)\n ghostMoveIdOne = setInterval(function(){\n chooseAndMove(ghostOne)\n }, ghostTimePerMove)\n ghostMoveIdTwo = setInterval(function(){\n chooseAndMove(ghostTwo)\n }, ghostTimePerMove)\n ghostMoveIdThree = setInterval(function(){\n chooseAndMove(ghostThree)\n }, ghostTimePerMove)\n ghostMoveIdFour = setInterval(function(){\n chooseAndMove(ghostFour)\n }, ghostTimePerMove)\n }", "function startGame() {\n\n\t\tvar gss = new Game(win.canvas);\n\n\t\t// shared zone used to share resources.\n gss.set('keyboard', new KeyboardInput());\n gss.set('loader', loader);\n\n\t\tgss.start();\n\t}", "function startGame() {\n\tsetup();\n\tmainLoop();\n}", "function initGameMode() {\n characters = {\n \"leia\": {\n name: \"leia\",\n attackPower: 8,\n healthPoints: 120,\n counterAttackPower: 15,\n },\n\n \"vader\": {\n name: \"vader\",\n attackPower: 14,\n healthPoints: 100,\n counterAttackPower: 5,\n },\n\n \"trooper\": {\n name: \"trooper\",\n attackPower: 8,\n healthPoints: 150,\n counterAttackPower: 20,\n },\n\n \"kylo\": {\n name: \"kylo\",\n attackPower: 7,\n healthPoints: 180,\n counterAttackPower: 20,\n }\n };\n fightRound = 1;\n var $container = $(\"#characters\");\n $container.html(\"\");\n $(\"#pickOpponentChar\").html(\"\").prepend(\"<div class='pick'>Pick opponent</div>\");\n $(\"#opponentChar\").html(\"\").prepend(\"<div class='pick'>Opponent</div>\");\n\n var c = characters[\"leia\"];\n addCharacter($container, c.name, c.attackPower, c.healthPoints, c.counterAttackPower, \"leia2.jpg\");\n c = characters[\"vader\"];\n addCharacter($container, c.name, c.attackPower, c.healthPoints, c.counterAttackPower, \"vader2.jpg\");\n c = characters[\"trooper\"];\n addCharacter($container, c.name, c.attackPower, c.healthPoints, c.counterAttackPower, \"trooper.jpg\");\n c = characters[\"kylo\"];\n addCharacter($container, c.name, c.attackPower, c.healthPoints, c.counterAttackPower, \"kylo.jpg\");\n $(\"#restart\").hide();\n gameMode = \"not-started\";\n $(\"#characters\").prepend(\"<div class='pick'>Pick character</div>\");\n $(\".pick\").css(\"font-family\", 'Open Sans Condensed', 'sans-serif');\n //needs to disappear after user player is picked & change to say player\n\n $(\".pick\").css(\"font-family\", 'Open Sans Condensed', 'sans-serif');\n //needs to disappear when opponent is picked, but reappear when a second opponent needs to be picked\n\n $(\".pick\").css(\"font-family\", 'Open Sans Condensed', 'sans-serif');\n }", "function startGame() {\n if (isGameRunning) return;\n isGameRunning = true;\n hideAllMenus();\n setupScore();\n updateScoreDisplay();\n shootBulletsRandomlyLoop();\n}", "function newGame() {\n // If congrats message have not been cleared\n clearTimeout(displayTimeout);\n hideGameCompleted();\n\n // Reset data to initial state\n initData();\n\n // Shuffle and reset cards to a new game\n initCardShuffle();\n }", "function startGame() {\n //hide the deal button\n hideDealButton();\n //show the player and dealer's card interface\n showCards();\n //deal the player's cards\n getPlayerCards();\n //after brief pause, show hit and stay buttons\n setTimeout(displayHitAndStayButtons, 2000);\n }", "function startGame() {\n init();\n}", "function startGame(){\n startScene.visible = false;\n helpScene.visible = false;\n gameOverScene.visible = false;\n gameScene.visible = true;\n\n //Reset starting variables\n //startTime = new Date;\n time = 0;\n slowTime = 10000; //in milliseconds\n player.x = 640;\n player.y = 360;\n activated = false;\n spawnTime = 0;\n createCircles(5);\n updateTime(time);\n updateSlow(slowTime);\n\n paused = false;\n}", "startGame (data) {\n if (THIS.gameIsSet == false) {\n GameWindow.displayMessage('Welcome to RiKS World!')\n }\n var ms = 2000\n this.clearTimeoutDisplay()\n THIS.timeoutDisplay = setTimeout(function () {\n GameWindow.clearDisplayMessage()\n console.log(\n 'localstorage id = ' +\n localStorage.myId +\n ', activeplayerid = ' +\n THIS.view.currentPlayer\n )\n\n GameWindow.displayCurrentPlayer()\n if (THIS.gameIsSet == false) {\n if (localStorage.getItem('myId') == THIS.view.currentPlayer) {\n GameWindow.displayMessage('Click on a territory to claim it !')\n } else {\n GameWindow.displayMessage(\n THIS.getActivePlayerName() + ' is choosing a territory !'\n )\n }\n } else {\n if (localStorage.getItem('myId') == THIS.view.currentPlayer) {\n GameWindow.displayMessage('Put 1 unit on one of your territories !')\n } else {\n GameWindow.displayMessage(\n THIS.getActivePlayerName() + ' is reinforcing a territory !'\n )\n }\n }\n console.log('free territories = ' + THIS.getFreeTerritoriesNumber())\n }, ms)\n /**\n * from now players claim territories turn by turn on map\n * using dbclick on territory, until no more free territories left\n */\n }", "function startGame() {\n setTimeRemaining(starting_time)\n setShouldStart(true)\n setText(\"\")\n textboxRef.current.disabled = false\n textboxRef.current.focus()\n }", "function startGame() {\n pairMovieWithSounds();\n randomSounds(movie);\n addPhraseToDisplay();\n keyboardSetup();\n}", "function startNewGame(text){\n\n\t//console.log('start new game!');\n\n\ttext.destroy();\n\n\t//not very elegant but it does the job\n\tvar playerName = prompt(\"What's your name?\", \"Cloud\");\n\n\t//store player name in cache to be shown on in-game HUD\n\tlocalStorage.setItem(\"playerName\", playerName);\n\n\tthis.game.state.start('Game');\n}", "function startGame(){\n \t\tGameJam.sound.play('start');\n \t\tGameJam.sound.play('run');\n\t\t\n\t\t// Put items in the map\n\t\titemsToObstacles(true);\n\n\t\t// Create the prisoner path\n\t\tGameJam.movePrisoner();\n\n\t\t// Reset items, we dont want the user to be able to drag and drop them\n \t\tGameJam.items = [];\n \t\t\n \t\tfor (var item in GameJam.levels[GameJam.currentLevel].items) {\n \t\t\tGameJam.levels[GameJam.currentLevel].items[item].count = GameJam.levels[GameJam.currentLevel].items[item].countStart;\n \t\t}\n\n\t\t// Reset prisoner speed\n\t\tGameJam.prisoner[0].sprite.speed = 5;\n\n\t\t// Reset game time\n\t\tGameJam.tileCounter = 0;\n\t\tGameJam.timer.className = 'show';\n\t\tdocument.getElementById('obstacles').className = 'hide';\n\t\tdocument.getElementById('slider').className = 'hide';\n\t\tdocument.getElementById('start-button-wrapper').className = 'hide';\n\n\t\t// Game has started\n\t\tGameJam.gameStarted = true;\n\n\t\tGameJam.gameEnded = false;\n\n\t\tdocument.getElementById('static-canvas').className = 'started';\n\n\t\tconsole.log('-- Game started');\n\t}", "function startGame() {\n //startGame function will... reset stats in case coming from results page\n right = 0;\n wrong = 0;\n not = 0;\n counter = 90;\n //hide welcome div\n $(\"#welcome-page\").toggle();\n //show questions div\n $(\"#questions-page\").toggle();\n //start setTimeInterval\n timer = setInterval(countDown, 1000)\n }", "function newGame() {\n // Reset score\n score = 0;\n \n // Set the gamestate to ready\n gamestate = gamestates.ready;\n \n // Reset game over\n //gameover = false;\n $(\"#player1\").block();\n hod = 2;\n \n // Create the level\n createLevel();\n \n // Find initial clusters and moves\n findMoves();\n findClusters(); \n playerchange(hod);\n \n }", "function startGame(){\n\tif (playerArray.length == 0){\n\t\tgameOn = false;\n\t\talert(\"You must input a player name and click 'New Player' first!\");\n\t}\n\telse{\n\tgameOn = true;\n\t//user started the game. Save the time. Save the time + 30 seconds.\n\tgameStart = Date.now();\n\tgameEnd = Date.now() + 30000;\n\t//start the interval\n\ttimerInterval = setInterval(updateTimer, 1000);\n\tcurrentScore = 0;\n\tdocument.getElementById('currentScore').innerHTML = 0;\n\t}\n}", "function startGame(){\n initialiseGame();\n}", "function start_episode(){\n update_episode_number();\n if(parameter_dict['episode_number']<8){\n app = new Space_App(parameter_dict['n_targets'], parameter_dict['n_distractors'],\n parameter_dict['target_color'], parameter_dict['distractor_color'],\n window_width, window_height, parameter_dict['radius_min'], parameter_dict['radius_max'],\n parameter_dict['speed_min'], parameter_dict['speed_max'], hover_color, fish_left_img,\n fish_right_img, img_width, img_height);\n app.change_to_same_color();\n // check whether the timer could be incorporate to app!\n timer(app, 2000, 2000, 5000);\n }else{\n quit_game();\n }\n}", "function startBattle(e){\n\t\t\t\t// Only start if league and cup are selected\n\t\t\t\tvar val = $(\".league-cup-select option:selected\").val();\n\n\t\t\t\tif(val == \"\"){\n\t\t\t\t\tmodalWindow(\"Select League\", $(\"<p>Please select a league or cup.</p>\"));\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\n\t\t\t\tvar teams = [\n\t\t\t\t\t multiSelectors[0].getPokemonList(),\n\t\t\t\t\t multiSelectors[1].getPokemonList()\n\t\t\t\t\t];\n\t\t\t\tvar difficulty = $(\".difficulty-select option:selected\").val();\n\n\t\t\t\tif((teams[0].length < partySize)||((teamSelectMethod == \"manual\")&&(teams[1].length < partySize))){\n\t\t\t\t\tmodalWindow(\"Select Teams\", $(\"<p>Please select a full team.</p>\"));\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tif((teamSelectMethod == \"featured\")&&(! featuredTeam)){\n\t\t\t\t\tmodalWindow(\"Featured Team\", $(\"<p>Please select a featured team to fight.</p>\"));\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tvar autotapOverride = $(\".autotap-toggle\").hasClass(\"on\");\n\t\t\t\tvar switchTime = parseInt($(\".switch-time-select option:selected\").val());\n\n\t\t\t\tconsole.log(switchTime);\n\n\t\t\t\t// Set the round number to 0 for tournament mode\n\t\t\t\troundNumber = 0;\n\n\t\t\t\tvar props = {\n\t\t\t\t\tteams: teams,\n\t\t\t\t\tmode: mode,\n\t\t\t\t\tdifficulty: difficulty,\n\t\t\t\t\tteamSelectMethod: teamSelectMethod,\n\t\t\t\t\tpartySize: partySize,\n\t\t\t\t\tleague: battle.getCP(),\n\t\t\t\t\tcup: battle.getCup().name,\n\t\t\t\t\tfeaturedTeam: featuredTeam,\n\t\t\t\t\tautotapOverride:autotapOverride,\n\t\t\t\t\tswitchTime: switchTime,\n\t\t\t\t\tcustomTeamPool: []\n\t\t\t\t\t};\n\n\t\t\t\t// Reset roster selection for tournament mode\n\t\t\t\tif(mode == \"tournament\"){\n\t\t\t\t\tcurrentTeamIndex = 0;\n\t\t\t\t\tcurrentTeam = [];\n\t\t\t\t}\n\n\t\t\t\t// Set custom team pool\n\n\t\t\t\tif(teamSelectMethod == \"custom\"){\n\t\t\t\t\tprops.customTeamPool = JSON.parse($(\"textarea.team-import\").val());\n\t\t\t\t}\n\n\t\t\t\thandler.initBattle(props);\n\t\t\t}", "start() {\n\t\tplaySound( 'lvls' );\n\t\tgame.loading = true;\n\n\t\t// the game noticibly lags while setting the terrain, so this makes it look like a loading\n\t\t// black screen for 100 ms whenever it is loaded\n\t\tsetTimeout( () => {\n\t\t\tpause_name = '';\n\n\t\t\t//I think this maybe saved like 8 bytes over just saying game.loading, game.started... etc\n\t\t\tObject.assign( game, {\n\t\t\t\tloading: 0,\n\t\t\t\tstarted: 1,\n\t\t\t\tpaused: 0,\n\t\t\t\tscrolling: 1,\n\t\t\t\tlvln: 1,\n\t\t\t\ta: [],\n\t\t\t\tspawns: [],\n\t\t\t\tpl: new Player(),\n\t\t\t\tscore: 0,\n\t\t\t\tsmult: 1,\n\t\t\t\tspfr: 0,\n\t\t\t\ttss: TSS,\n\t\t\t\ti: null\n\t\t\t} );\n\t\t\tgame.createObjects();\n\t\t\tgame.camToLvl( game.lvln );\n\t\t\tgame.fade( true );\n\t\t}, 100 );\n\t}", "function startGame() {\n timerStat = true;\n showGamePanel();\n runTimer();\n displayImage();\n}", "function startGame(g_ctx){\n main.GameState = 1;\n levelTransition.levelIndex = -1;\n}", "function startGame() {\n\t// Move all characters back to Select Char Div\n\tfor (var i = 1; i < 5; i++) {\n\t\tchar = $(\"#char\" + [i]);\n\t\t$(\"#select-char-div\").append(char);\n\t}\n\n\t// Reset character formatting\n\t$(\".select-char\")\n\t\t.addClass(\"btn-light\")\n\t\t.removeClass(\"btn-success btn-primary btn-danger\")\n\t\t.removeAttr(\"disabled style\");\n\n\t// Reset all character stats\n\thero = \"\";\n\theroID = \"\";\n\theroStats = {};\n\n\tenemy = \"\";\n\tremEnemies = 0;\n\tenemyID = \"\";\n\n\tdefender = \"\";\n\tdefenderID = \"\";\n\tdefenderStats = {};\n\n\tfor (var i = 1; i < 5; i++) {\n\t\tchar = (\"char\" + [i]);\n\t\tchars[char].hp = chars[char].origHP;\n\t\tchars[char].ap = chars[char].origAP;\n\t\t$(\"#char\" + [i] + \"-hp\").html(chars[char].origHP);\n\t}\n\n\t// Starting instructions\n\t$(\"#instructions\").html(\"Select a character to begin.\")\n\n\t// Disable Attack button\n\t$(\".attack\").hide();\n\n\t// Hide Fight description\n\t$(\"#fight-desc\").hide();\n\n\t// Disable Restart button\n\t$(\"#restart\").hide();\n}", "function startGame() {\n gameState.active = true;\n resetBoard();\n gameState.resetBoard();\n\n var activePlayer = rollForTurn();\n \n // Game has started: enable/disable control buttons accordingly.\n btnDisable(document.getElementById('btnStart'));\n btnEnable(document.getElementById('btnStop'));\n\n var showPlayer = document.getElementById('showPlayer');\n showPlayer.innerHTML = activePlayer;\n showPlayer.style.color = (activePlayer === \"Player 1\") ? \"blue\" : \"red\";\n // The above line, doing anything more would require a pretty sizeable refactor.\n // I guess I could name \"Player 1\" with a constant.\n}", "function startGame(playerCount) {\r\n\t\r\n\tGC.initalizeGame(playerCount);\r\n\t\r\n\tUI.setConsoleHTML(\"The game is ready to begin! There will be a total of \" + GC.playerCount + \" players.<br />Click to begin!\");\r\n\tUI.clearControls();\r\n\tUI.addControl(\"begin\",\"button\",\"Begin\",\"takeTurn()\");\r\n\t\r\n\tGC.drawPlayersOnBoard();\r\n}", "function gameCreate() {\n // get the level from url\n setLevel();\n GameNumber.updateNumLevels(document);\n GameNumber.setNextLevel(document);\n\n // set the game tutorial text\n GameHelp.setHelpText(GameNumber.currGame, document);\n\n // initialize tile selector\n tileDisplay = new TileDisplay(document);\n\n // Initialize board object\n board = new Board(PIXI, app, tileDisplay);\n\n // Initialize selector object\n selector = new Selector(graphics, app);\n\n // create the rulesets\n ruleSet = GameNumber.getRuleset();\n generateRulesetDisplay(ruleSet.accepting_rule, true);\n generateRulesetDisplay(ruleSet.rules, false);\n\n // init game ticker\n app.ticker.add(delta => gameLoop(delta));\n \n}", "function runGame () {\n var settings = [pickLanguage(), pickDifficulty()];\n var score = 0;\n var currentWord = generateWord(settings).toUpperCase().split('');\n\n localStorage.clear();\n \n writeLettersToDOM(currentWord);\n shuffleLetters();\n resetHeader();\n\n saveSettings('currentWord', currentWord);\n saveSettings('localSettings', settings);\n saveSettings('currentGameScore', score);\n\n var mainGameInterval = setInterval(function() {\n if (checkForWin() === true) {\n clearInterval(mainGameInterval);\n winGame();\n }\n }, 1000);\n\n}", "function start_episode(){\n if(parameter_dict['episode_number']<8){\n app = new App(parameter_dict['n_targets'], parameter_dict['n_distractors'],\n parameter_dict['target_color'], parameter_dict['distractor_color'],\n window_width, window_height, parameter_dict['radius_min'], parameter_dict['radius_max'],\n parameter_dict['speed_min'], parameter_dict['speed_max'], hover_color);\n app.change_to_same_color();\n // check whether the timer could be incorporate to app!\n timer(app, 2000, 2000, 5000);\n }else{\n quit_game();\n }\n}", "function startGame(){\n\tif(!$.editor.enable){\n\t\tfor(n=0;n<levels_arr.length;n++){\n\t\t\t$.stage[n].visible = false;\n\t\t}\n\t\t$.stage[gameData.levelNum].visible = true;\n\t}\n\t\n\tgameData.planes = [];\n\tgameData.runway = [];\n\tgameData.types = [];\n\tgameData.typeCount = 0;\n\tgameData.countPlane = 0;\n\tgameData.totalPlane = levels_arr[gameData.levelNum].level.total;\n\tgameData.speed = levels_arr[gameData.levelNum].level.speed;\n\tgameData.nextPlaneTimer = levels_arr[gameData.levelNum].level.planTimer;\n\tgameData.stageComplete = false;\n\t\n\tplayerData.score = playerData.displayScore = 0;\n\tplayerData.total = 0;\n\tupdateStatus();\n\t\n\tfor(var n=0;n<levels_arr[gameData.levelNum].runway.length;n++){\n\t\tcreateRunway(false, levels_arr[gameData.levelNum].runway[n].type, levels_arr[gameData.levelNum].runway[n].x, levels_arr[gameData.levelNum].runway[n].y, levels_arr[gameData.levelNum].runway[n].rotation);\n\t\t\n\t\tfor(var t=0;t<levels_arr[gameData.levelNum].runway[n].planes.length;t++){\n\t\t\tgameData.types.push(levels_arr[gameData.levelNum].runway[n].planes[t]);\t\t\n\t\t}\n\t}\n\t\n\tgameData.types = unique(gameData.types);\n\tshuffle(gameData.types);\n\t\n\tTweenMax.ticker.useRAF(false);\n\tTweenMax.lagSmoothing(0);\n\n\titemBoom.visible = false;\n\tcompleteContainer.visible = false;\n\t\n\tif(gameData.tutorial){\n\t\tgameData.tutorial = false;\n\t\ttoggleTutorial(true);\n\t}else{\n\t\tstartPlaneTimer(0);\n\t\tgameData.paused = false;\n\t}\n}", "function initGame(){\n gamemode = document.getElementById(\"mode\").checked;\n \n fadeForm(\"user\");\n showForm(\"boats\");\n \n unlockMap(turn);\n \n player1 = new user(document.user.name.value);\n player1.setGrid();\n \n turnInfo(player1.name);\n bindGrid(turn);\n}", "startGame () {\n game.state.start('ticTac')\n }", "function startGame() {\n\taudio.play();\n\tif(!(popup.classList.contains('cache'))){\n\t\tpopup.classList.add('cache');\n\t}\n\trandompresident();\n\twindow.setInterval(function a(){\n\t\tif(mich > 0){\n\t\t\tmich--\n\t\t\ttemps.textContent= mich}}, 1000);\n\tscoreBoard.textContent = 0;\n\ttimeUp = false;\n\tscore = 0;\n\tsortietrou();\n\tsetTimeout(function time(){\n\t\ttimeUp = true;\n\t\tpopup.classList.remove('cache');\n\t\taudio.pause();\n\t},15000)\n\tvar mich = 15;\n}", "function initialiseGame(){\n\n\t/* ------------------\n\t\tRESET GAME OBJECT\n\t--------------------*/\n\tgame = new Game();\n\n\t/* ------------------\n\t\tCONTEXT SETTINGS\n\t--------------------*/\n\tvar fgCanv = document.getElementById('canvas');\n\tvar fgCtx = fgCanv.getContext('2d');\n\tfgCtx.translate(0.5, 0.5);\n\tclearCanvas(fgCtx);\n\n\tvar bgCanv = document.getElementById('bgCanvas');\n\tvar bgCtx = bgCanv.getContext('2d');\n\tbgCtx.translate(0.5, 0.5);\n\tclearCanvas(bgCtx);\n\n\t//WHY HERE? game.restart();\n\t//towers = enemies = bullets = [];\n\n\tlevelSetup();\n\n\t/* ------------------\n\t\tSCREEN VARIABLES\n\t--------------------*/\n\n\t//var level_data = levelMaps[game.level];\n\t//level = new Level(fgCtx, level_data.rows, level_data.columns, level_data.grid, level_data.start, level_data.end);\n\n\t//level.path = plotPath(level.grid, level.start, level.end);\n\t//if (level.path.length == 0){\n\t//\tconsole.log('Path error');\n\t\t//resetGame();\n\t//}\n\t//console.log(level);\n\n\t//resizeCanvas();\n\n\t// Check for cookie\n\tvar cookieName = 'privacyOptOut=';\n\n\t// Check document cookies for this flag\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(cookieName) == 0){\n\t\t\tvar cookieVal = c.substring(cookieName.length,c.length);\n\t\t}\n }\n\n\t// If cookie value found and true\n\tif (cookieVal === true){\n\t\tshowModal(\"Privacy Flag\", 0);\n\t}else{\n\t\tshowModal(\"Privacy Opt-Out\",0);\n\t}\n\n\t//showModal(\"Introduction\",0);\n\n\t/* ------------------\n\t\tEVENT LISTENERS\n\t--------------------*/\n\tfgCanv.addEventListener('touchstart', function(event){touchCanvas(event);});//,false );\n\tfgCanv.addEventListener('click', function(event){mouseCanvas(event);});//,false); //stopHover();},false );\n\n\t // Trying to work out what the fuck happens when the window is minimized - enemies seem to vanish off the canvas! :-/\n\t//focus = 1;\n\t//window.addEventListener('visibilitychange', function(){ focus *= -1; if (focus){ console.log(enemies); } });\n\n\tmainLoopRequest = window.requestAnimationFrame(mainLoop);\n\n}", "function startTheGame() {\n if (opponentReady) {\n startNewRound();\n }\n }", "function run () {\n var $canvasBox;\n \n $('#newGameLink').removeAttr('disabled'); // can click new game link\n\n if (m.debug > m.NODEBUG) { console.log('screens.gameScreen.run'); }\n \n if (needsInit) {\n \n // disable mouse events on canvas and halt the game loop when we return to the menu\n $('#gameMenuLink')\n .click( function (event) {\n m.playtouch.unhookMouseEvents();\n m.Model.stopGameNow();\n m.Audio.beQuiet();\n m.screens.showScreen('menuScreen');\n });\n \n // shuffle and deal if we ask nicely\n $('#newGameLink')\n .click( function (event) {\n // disallow double-clicks, also disabled in the model while dealing\n if ( $(this).attr('disabled') === 'disabled' ) { return false; } \n $(this).attr('disabled', 'disabled'); \n // if you start a new game before winning, give 'em the not impressed face\n if (m.Settings.getPlaySounds() && !hasWon) {\n m.Sounds.playSoundFor(m.Sounds.QUIT);\n }\n \n // now we play\n setTimeout( function() {\n m.Model.stopGameNow();\n m.screens.showScreen('gameScreen');\n }, m.Settings.Delays.Quit);\n return false;\n });\n \n }\n needsInit = false;\n \n // start the game animation loop\n m.gameloop.setLoopFunction(m.view.refreshDisplay);\n \n // start a new game\n m.view.newGame($('#gameViewBox'));\n \n // hook up event handling\n m.playtouch.hookMouseEvents(); \n\n // resize the game pane if needed after a short delay\n $(window)\n .resize(function (event) {\n setTimeout( function () {\n mikeycell.view.setMetrics();\n }, 500);\n });\n\n }" ]
[ "0.73494184", "0.72415197", "0.7241255", "0.7128199", "0.70512295", "0.70036256", "0.69970423", "0.6982174", "0.6955063", "0.68771404", "0.68770766", "0.6812864", "0.6778389", "0.6776338", "0.677211", "0.6748761", "0.67425144", "0.6733717", "0.67281985", "0.6726751", "0.6690416", "0.6686673", "0.6673683", "0.66553736", "0.6648545", "0.66368616", "0.6633997", "0.6627438", "0.661468", "0.66013765", "0.6588685", "0.6583235", "0.6544193", "0.65382594", "0.65218925", "0.651631", "0.6515456", "0.6502082", "0.64857185", "0.64840084", "0.6458311", "0.6432127", "0.6417695", "0.63949853", "0.6387508", "0.638548", "0.6377391", "0.6372682", "0.63545376", "0.6344442", "0.6341101", "0.6337827", "0.6336674", "0.63350534", "0.6324317", "0.6323898", "0.63157564", "0.6309278", "0.63015026", "0.63003945", "0.6300307", "0.6288711", "0.62821215", "0.6281376", "0.627696", "0.6273296", "0.62727356", "0.6272405", "0.62498105", "0.62495697", "0.6249303", "0.62491006", "0.6249019", "0.62444997", "0.6240405", "0.62343496", "0.623433", "0.62302905", "0.6229545", "0.62204653", "0.6217161", "0.6214293", "0.62111914", "0.6209731", "0.6200198", "0.6197148", "0.6186525", "0.61814207", "0.617912", "0.6178232", "0.61779726", "0.61768466", "0.61750954", "0.6175036", "0.61664134", "0.6166028", "0.61645997", "0.61640173", "0.61628705", "0.61500067" ]
0.6845081
11
This function starts the game timer with the selected time duration
function startTimer() { // Set time remaining based on selection if (id("time-3").checked) { timeLeft = 180; } else if (id("time-5").checked) { timeLeft = 300; } else { timeLeft = 600; } // Set the timer for first second id("timer").textContent = timeConvert(timeLeft); // Timer to update every second timer = setInterval(function() { timeLeft --; // If time runs out, end the game if (timeLeft === 0) { gameOver(); } id("timer").textContent = timeConvert(timeLeft); }, 1000); // function runs every 1000 ms }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function startTimer(duration, display) {\n let timer = duration,\n minutes,\n seconds\n\n let updateTimer = () => {\n minutes = parseInt(timer / 60, 10)\n seconds = parseInt(timer % 60, 10)\n\n minutes = minutes < 10 ? '0' + minutes : minutes\n seconds = seconds < 10 ? '0' + seconds : seconds\n\n if (seconds < 0) seconds = 0\n\n display.textContent = minutes + ':' + seconds\n }\n\n clearTimer()\n updateTimer()\n\n remainingTime = duration\n\n timerInterval = setInterval(() => {\n updateTimer()\n\n if (--timer < 0) {\n endGame()\n }\n --remainingTime\n }, 1000)\n}", "function startTimer(duration, display) {\n let timer = duration, minutes, seconds;\n\n let start=setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n if (foodeaten){\n foodeaten=false;\n timer=seconds=seconds+10;\n }\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n if (--timer < 0 ||checkdead) {\n storeScore(score);\n showScreen(3);\n timeattack = 0;\n clearInterval(start);\n display.textContent=\"starting..\";\n dead.play();\n }\n }, 1000);\n\n }", "function startTimer(duration) {\n var display = document.querySelector('#time');\n var timer = duration,\n minutes, seconds;\n setInterval(function() {\n minutes = parseInt(timer / 60, 10)\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.innerText = minutes + \":\" + seconds;\n\n if (--timer < 0) { //when the timer is 0 run the code\n timer = duration;\n RunForestRun();\n }\n }, 1000);\n}", "function startTimer(duration) {\n\tvar start = Date.now(), diff, minutes, seconds;\n\tfunction timer() {\n\t\tdiff = duration - (((Date.now() - start) / 1000) | 0);\n\t\tminutes = (diff / 60) | 0;\n\t\tseconds = (diff % 60) | 0;\n\t\t// minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n\t\ttimerTextElement.innerHTML = minutes + \":\" + seconds;\n\n if (diff <= 0) {\n\t minutes = (duration / 60) | 0;\n\t\t\tseconds = (duration % 60) | 0;\n\t\t\t// minutes = minutes < 10 ? \"0\" + minutes : minutes;\n\t seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\t\t\ttimerTextElement.innerHTML = minutes + \":\" + seconds;\n\t\t\tendRound(false);\n \treturn;\n }\n }\n // we don't want to wait a full second before the timer starts\n timer();\n time = setInterval(timer, 1000);\n}", "function startTimer(duration, display) {\n let timer = duration, minutes, seconds;\n timer.id=timer\n count = setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n // minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.innerText = minutes + \":\" + seconds;\n\n if (--timer < 0) {\n showAllAnswers(\"Time ran out!\")\n }\n }, 1000);\n }", "function startTimer(duration, display) {\n var timer = duration,\n minutes,\n seconds;\n let c = setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n\n if (--timer < 0) {\n display_alert(\"Time's Up!!!\");\n clearInterval(c);\n }\n }, 1000);\n }", "function startTimer() {\n\tgameData.timer = setInterval(timerData.timeCounter, 1000);\n}", "function startTimer(duration, display) {\r\n var timer = duration, minutes, seconds;\r\n setInterval(function () {\r\n minutes = parseInt(timer / 60, 10);\r\n seconds = parseInt(timer % 60, 10);\r\n\r\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\r\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\r\n\r\n display.textContent = \"Time Left: \" + minutes + \":\" + seconds;\r\n\r\n if (--timer < 0) {\r\n timer = duration;\r\n }\r\n }, 1000);\r\n}", "function startTimer(duration, display) {\n var timer = duration,\n minutes,\n seconds;\n setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n\n if (--timer < 0) {\n window.alert(\"Game Over Press Enter to Start\");\n currentScore=0;\n score.innerText = currentScore;\n timer = duration;\n }\n }, 1000);\n}", "function startTimer(duration, display){\n\n\tvar timer = duration, minutes, seconds;\n\n\tconsole.log(duration)\n\n\tt = setInterval(function(){\n\n\t\ttimer--;\n\n\t\tminutes = parseInt(timer / 60, 10);\n\t\tseconds = parseInt(timer % 60, 10);\n\n\t\tif(minutes < 10){\n\t\t\tminutes = \"0\" + minutes;\n\t\t} else {\n\t\t\tminutes = minutes;\n\t\t}\n\n\t\tif(seconds < 10){\n\t\t\tseconds = \"0\" + seconds;\n\t\t} else {\n\t\t\tseconds = seconds;\n\t\t}\n\n\t\tdisplay.text(minutes + \":\" + seconds);\n\n\t\tif (timer > 0) {\n timer--;\n } else {\n \tclearInterval(t);\n \tresetTime();\n }\t\t\n\n\t}, 1000);\n}", "function timerStart(){\n heatGenerate();\n dsec++;\n totalTime++;\n if(dsec == 10) {\n dsec = 0;\n sec++;\n if(sec == 60) {\n sec = 0;\n min++;\n }\n }\n \n if(totalTime % GAME_SPAWN_TIME == 0) {\n spawnRandomGame();\n }\n \n if(difficulty < MAX_DIFFICULTY && totalTime % DIFF_INCREASE == 0) {\n difficulty++;\n }\n \n timer.innerHTML = pad(min) + \" : \" + pad(sec) + \" : \" + dsec;\n\n\n if(min == TIME_GOAL){\n ironManAction();\n }\n}", "function startTimer(){\n\n // ParseInt to only get whole number\n const seconds = parseInt(this.dataset.time);\n timer(seconds);\n}", "function startNewGame() {\n // Possible speeds\n var speeds = {\n 0: 60,\n 200: 77,\n 500: 120,\n 800: 300\n };\n\n // Getting speed based on difficulty\n var speed = difficulty.options[difficulty.selectedIndex].value;\n\n var moleTimer = new Timer({\n seconds: speeds[speed],\n speed: speed,\n onTime: function() {\n if (!gameEnded) {\n renderMole();\n }\n }\n });\n\n // Start timer.\n gameTimer.start();\n moleTimer.start();\n\n // New game\n gameEnded = false;\n }", "function startTime() {\n if (!gameInProgress) {\n intervalId = setInterval(countdown, 1000);\n gameInProgress = true;\n };\n}", "function setTime() {\n //increments timer\n ++totalSeconds;\n //temporarily stops timer at 5 seconds for my sanity\n if (totalSeconds === 59) {\n totalMinutes += 1;\n totalSeconds = 0;\n }\n\n //stops timer when game is won\n if (gameWon === true) {\n return;\n }\n //calls function to display timer in DOM\n domTimer();\n }", "startCountdown() {\n this.setGameValues();\n this.timerStart = new Date().getTime();\n this.countdownInterval = setInterval(this.updateTime, 1000);\n }", "function startTimer(duration, display) {\n let timer = duration, minutes, seconds;\n setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n\n if (--timer < 0) {\n timer = 0;\n\n }\n }, 1000);\n}", "function setGameTime() {\r\n if (test) { console.log(\"--- setGameTime ---\"); }\r\n if (test) { console.log(\"gameDuration \" + gameDuration); }\r\n clearInterval(gameInterval);\r\n gameSeconds = gameDuration;\r\n}", "function startTimer(duration, display) {\n let timer = duration;\n\n // must use whatever is on the left side of the assignment\n // statement for setInterval for clearInterval argument\n timerId = setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? '0' + minutes : minutes;\n seconds = seconds < 10 ? '0' + seconds : seconds;\n\n if (!clockNotRunning) {\n display.textContent = minutes + ':' + seconds;\n }\n\n if (--timer < 0) {\n timer = duration;\n }\n\n let diffTime, diffMinutes, diffSeconds;\n let currentTime = minutes * 60 + seconds;\n diffTime = 120 - currentTime;\n\n }, 1000);\n}", "function startTimer(duration, display) {\r\n var timer = duration, minutes, seconds;\r\n setInterval(function () {\r\n minutes = parseInt(timer / 60, 10);\r\n seconds = parseInt(timer % 60, 10);\r\n\r\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\r\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\r\n\r\n display.textContent = minutes + \":\" + seconds;\r\n\r\n if (--timer < 0) {\r\n timer = duration;\r\n }\r\n }, 1000);\r\n}", "function startTimer(duration, display) {\n var timer = duration, minutes, seconds;\n setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n\n if (--timer < 0) {\n timer = 0;\n }\n }, 1000);\n}", "function startTimer() {\n if (stoptime) {\n stoptime = false;\n runClock();\n }\n}", "function startGameTimer(){\n var timer = setInterval(() => {\n console.log(GMvariables.timerSecs);\n $(\"#timer\").text(GMvariables.timerSecs);\n if(GMvariables.timerSecs == 0){\n $(\"#timer\").text(\"Go\");\n clearInterval(timer);\n setTimeout(() => {\n $(\"#timer\").css(\"display\", \"none\");\n reset();\n changePositionOfElement();\n headerUpdater();\n }, 1000);\n }\n GMvariables.timerSecs -= 1;\n }, 1000);\n \n}", "function startTimer(duration, display) {\n var timer = duration, minutes, seconds;\n setInterval(function () {\n minutes = parseInt(timer / 60, 10)\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n\n if (--timer < 0) {\n timer = duration;\n }\n }, 1000);\n}", "function startGame() {\n timer = setInterval(start, timerCd) \n}", "function startTimer(duration, display) {\n var timer = duration, minutes, seconds;\n\n setInterval(function () {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n\n if (--timer < 0) {\n timer = duration;\n }\n }, 1000);\n}", "function startTimer() {\n\n\t\t$(\"#timer\").text(\"Time remaining: \" + timeRemaining + \"s\")\n\t\t\n\t\tquizInterval = setInterval(function() {\n\n\t\t\ttimeRemaining -= 1;\n\t\t\t$(\"#timer\").text(\"Time remaining: \" + timeRemaining + \"s\");\n\t\t\t\n\t\t\tif (timeRemaining <= -1) {\n\t\t\t\ttimeRemaining = 0;\n\t\t\t\tclearInterval(quizInterval);\n\t\t\t\t$(\"#timer\").text(\"Time remaining: 0s\");\n\t\t\t\tendPhase(\"timeUp\");\n\t\t\t\tsounds.timeUp();\n\t\t\t}\n\n\t\t}, 1000);\n\n\t}", "function startTimer(duration, display) {\n\tdisplay.html(formatTime(duration));\n\tvar loop = setInterval(function () {\n\t\tdisplay.html(formatTime(duration));\n\t\tif (--duration < 0) {\n\t\t\tclearInterval(loop);\n\t\t}\n\t}, 1000);\n}", "function startTime() {\n setTimer();\n}", "function startTimer(duration, display) {\n $(\"#timerText\").removeClass(\"flash\").css(\"color\", \"lightgreen\"); // set default non-flashing class and text color to lightgreen\n let timer = duration, minutes, seconds;\n intervalID = setInterval(function() {\n minutes = parseInt(timer / 60, 10);\n seconds = parseInt(timer % 60, 10);\n if (minutes === 0 && seconds <= 45) {\n $(\"#timerText\").css(\"color\", \"#ffff00\"); // at 45 seconds set the timer text color to yellow\n }\n if (minutes === 0 && seconds <= 30) {\n $(\"#timerText\").css(\"color\", \"#ffa500\"); // at 30 seconds set the timer text color to orange\n }\n if (minutes === 0 && seconds <= 20) {\n $(\"#timerText\").css(\"color\", \"#ff0000\"); // at 20 seconds set the timer text color to red\n }\n if (minutes === 0 && seconds <= 10) {\n $(\"#timerText\").addClass(\"flash\"); // at 10 seconds make the the timer flash between red and white\n }\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n display.text(minutes + \":\" + seconds);\n if (--timer < 0) { // actions to take if timer runs out\n gamesPlayed++;\n fadeMusic();\n $(\".gameOverModal\").addClass(\"showModal\");\n clearInterval(intervalID);\n playGameEndSoundEffect();\n }\n }, 1000);\n}", "timer() {\r\n // Check first if its not running, Note that we set it to null\r\n if (typeof (this.interval) === 'number')\r\n return;\r\n\r\n // Timestamp in millisecond\r\n const now = Date.now();\r\n // Seconds when the test duration is done (60 seconds) converted to millisecond\r\n const done = now + this.duration * 1000;\r\n // Display the timer before interval run\r\n _timer.innerHTML = `${this.duration}<span class=\"small\">s</span>`;\r\n // Set interval\r\n this.interval = setInterval(() => {\r\n // Get seconds left. Note that we ran Date.now() again to update the time\r\n const secondsLeft = Math.round((done - Date.now()) / 1000);\r\n // Display the timer in DOM again \r\n _timer.innerHTML = `${secondsLeft}<span class=\"small\">s</span>`;\r\n // Stop when reach 0 and call finish function\r\n if (secondsLeft === 0) {\r\n this.stop();\r\n this.finish();\r\n }\r\n }, 1000);\r\n }", "function startTimer(){\n $scope.timeRemaining = $scope.levels.timeDuration;\n $scope.timerId = $interval(function() {\n if ($scope.timeRemaining > 0) {\n updateTilesRemaining(); // update remaining tiles\n $scope.timeRemaining = $scope.timeRemaining - 1000;\n if($scope.tilesRemaining.length == 0){\n $scope.stopGame(\"win\");\n }\n } else {\n $scope.stopGame(\"loose\");\n }\n }, 1000);\n }", "_startTimer () {\n // Clear previous intervalID and set time-limit for current interval\n clearInterval(this._intervalID)\n\n this._intervalID = setInterval(() => {\n this._time += (this._updateTime / 1000)\n this._timeArea.textContent = `Time: ${this._cropTime(this._time, this._dec)} s`\n }, this._updateTime)\n }", "function startTimer() {\n if (timeLeft == 0) {\n gameEnded();\n } else {\n gameOn = true;\n setTimeout(printTime, 1000);\n }\n}", "function startTimer() {\n currentTime = 0;\n timeoutStore = setInterval(updateTimer, timeIncrementInMs);\n }", "function startTimer() {\n setTimeout(function () {\n //when game is stopped timer from previous game shouldn't infere\n if (!pausedGame) timerDone = true;\n }, 10000);\n}", "function startTimer() {\n clearInterval(countdownTimer);\n timeRemaining = timerLength[activeRoundNumber-1];\n postMessageToDisplay({\"message\":\"timerStarted\", \"seconds\":timeRemaining});\n if (timeRemaining == 0) {\n document.getElementById(\"game-timer-cell\").innerHTML = `Unlimited time`;\n return\n }\n document.getElementById(\"game-timer-cell\").innerHTML = `<strong>${timeRemaining}</strong> seconds left`;\n countdownTimer = setInterval(function() {\n timeRemaining -= 1;\n document.getElementById(\"game-timer-cell\").innerHTML = `<strong>${timeRemaining}</strong> seconds left`;\n if (timeRemaining < 0) {\n clearInterval(countdownTimer);\n document.getElementById(\"game-timer-cell\").innerHTML = \"<strong>OUT OF TIME</strong>\";\n postMessageToDisplay({\"message\":\"outOfTime\"});\n }\n }, 1000);\n}", "function gameStart(){\n\t\t\tshuffleCards();\n\t\t\ttime = 0;\n\t\t\tstarttime = Date.now();\n\t\t\ttimer = setInterval(function(){\n\t\t\t\ttime++;\n\t\t\t\t$(\".info .timer .sec\").text(time);\n\t\t\t}, 1000);\n\t\t}", "function startTimer() {\n setTime();\n if (totalSeconds > 0) {\n setInterval(function() {\n secondsElapsed++;\n renderTime();\n }, 1000);\n } \n }", "function startTimer() {\n p.timeOut1 = setTimeout(() => {\n p.ready = true;\n p.timeOfStart = p.millis();\n p.timeOut2 = setTimeout(() => {\n p.ready = false;\n p.timeOfEnd = p.millis();\n const success = false;\n const time = ((p.timeOfEnd - p.timeOfStart) / 1000).toFixed(3);\n p.props.generateResult(success, time);\n }, p.props.gameTime * 1000);\n }, p.props.startTime * 1000);\n }", "function start(data) {\n startGameTimer();\n}", "function startTimer(_timer){\n _timer.start({\n countdown: true,\n startValues: {\n seconds: 30\n }\n });\n }", "function timer(){\n\tif(!start){\n\t\ttime+=1\n\t\tminutes = (Math.floor(time/60) < 10) ? '0' + Math.floor(time/60).toString() : Math.floor(time/60).toString()\n \tseconds = (time % 60 < 10) ? '0' + (time % 60).toString() : (time % 60).toString();\n\t}\n\t\n\t}", "_startTimer() {\n let interval = this.config[\"appear\"][\"interval\"]\n let variation = this.config[\"appear\"][\"interval_variation\"]\n let seconds = interval + Math.round(Math.random() * variation)\n\n util.log(\"power-up\", \"next in \" + seconds + \" seconds\")\n this.timer = this.game.time.events.add(Phaser.Timer.SECOND * seconds, this._addPowerup, this);\n }", "function startTime(){\n clearInterval(timer);\n timer = setInterval(displayTime, 1000);\n }", "function startGame() {\n var select = document.getElementById(\"time\");\n var value = select.options[select.selectedIndex].value;\n console.log(value); // en\n var duration = value; // 10 seconds\n hide(startBtn);\n score = -1;\n score2 = -1;\n ended = false;\n // we get start time\n startTime = new Date().getTime();\n\n // we create a timer with the setInterval method\n var timerId = setInterval(function () {\n var total = (new Date().getTime() - startTime) / (value * 100);\n // console.log(total);\n // console.log(new Date().getTime() - startTime)\n console.log(new Date().getTime() - startTime)\n\n // while total lower than duration, we update timer and the clicks by seconds\n if ((new Date().getTime() - startTime) < (duration * 1000)) {\n timerTxt.textContent = ((new Date().getTime() - startTime)/ 1000).toFixed(3);\n clicksTxt.textContent = (score / total).toFixed(2);\n clicksTxt2.textContent = (score2 / total).toFixed(2);\n } else {\n // otherwise, game is ended, we clear interval and we set game as ended\n ended = true;\n clearInterval(timerId);\n // we call the end game method\n endGame();\n }\n }, 1);\n}", "function timer() {\n\t\t//get elapsed time, comes as milliseconds\n\t\tlet timeElapsed = Date.now() - timerStart;\n\n\t\tif (timeElapsed >= QUIZDURATION) {\n\t\t\tendQuiz();\n\t\t\treturn;\n\t\t}\n\t\t//convert to seconds\n\t\tlet remaining = (QUIZDURATION - timeElapsed) / 1000;\n\t\tlet h = parseInt(remaining / 3600); //divide to get hours\n\t\tlet m = parseInt( (remaining % 3600) / 60); //divide remainder to get minutes\n\t\tlet s = parseInt( (remaining % 3600) % 60); //divide that remainder to get seconds\n\n\t\t//put on page\n\t\tlet textString = padTimer(h) + \":\" + padTimer(m) + \":\" + padTimer(s);\n\t\ttimeDisplay.innerText = textString;\n\t}", "function startGameTimer() {\n clearInterval(gameClock);\n gameClock = setInterval(gameTimer, 1000);\n}", "function startTimer() {\n if (totalSeconds > 0) {\n interval = setInterval(function() {\n secondsElapsed++;\n renderTime();\n }, 1000);\n } else {\n endGame();\n }\n}", "function startTimer() {\n timeLeft = startingTime;\n \n timeInterval = setInterval(function() {\n timerBox.textContent = Math.floor(timeLeft/60)+\":\"+ formatTime(timeLeft%60);\n timeLeft--;\n \n if (timeLeft === 0) {\n timerBox.textContent = \"\";\n loadEnd();\n clearInterval(timeInterval);\n }\n \n }, 1000);\n }", "function runTimer() {\n currentTime =\n leadingZero(timer[0]) +\n \":\" +\n leadingZero(timer[1]) +\n \":\" +\n leadingZero(timer[2]);\n theTimer.innerHTML = currentTime;\n timer[3]++;\n\n timer[0] = Math.floor(timer[3] / 100 / 60);\n timer[1] = Math.floor(timer[3] / 100 - timer[0] * 60);\n timer[2] = Math.floor(timer[3] - timer[1] * 100 - timer[0] * 6000);\n}", "function startTimer(seconds) {\n console.log(\"starting timer\");\n if (!clockRunning){\n clockInterval = setInterval(function () {\n $(\"#clock\").html(seconds);\n seconds--;\n \n //If we run out of time give one penalty and display the answer. \n //Check if the game needs to end or continue to next question\n if (seconds <= 0) {\n clear();\n triviagame.wrong++;\n displayAnswer(correctText, \"outoftime\");\n \n if (index < triviagame.questionsArray.length) {\n setTimeout(displayQuestions, 2000);\n }\n else {\n setTimeout(displayAnswer(correctText, \"end\"), 2000);\n }\n }\n }, 1000);\n clockRunning = true;\n }\n \n}", "function startTimer() {\n timerInterval = setInterval(() => {\n timePassed = timePassed += 1;\n timeLeft = TIME_LIMIT - timePassed;\n document.getElementById(\"base-timer-label\").innerHTML = formatTime(\n timeLeft\n );\n\n if (timeLeft <= 0) {\n onTimesUp();\n }\n }, 1000);\n}", "function startGame() {\n startTime = new Date().getTime();\n\n // Update the time every 1 second\n timeIntervalId = setInterval(function () {\n // Get current time\n let currentTime = new Date().getTime();\n\n // have the startTime begin at 0\n let totalTime = currentTime - startTime;\n\n // Time calculations for days, hours, minutes and seconds\n let days = Math.floor(totalTime / (1000 * 60 * 60 * 24));\n let hours = Math.floor((totalTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));\n let minutes = Math.floor((totalTime % (1000 * 60 * 60)) / (1000 * 60));\n let seconds = Math.floor((totalTime % (1000 * 60)) / 1000);\n\n // Output the result in an element with id=\"timer\"\n $(\"#timer\").html(days + \"d \" + hours + \"h \"\n + minutes + \"m \" + seconds + \"s \");\n\n //creates a variable with final time for modal and adds it to the HTML\n timeElapsed = days + \"d \" + hours + \"h \" + minutes + \"m \" + seconds + \"s \";\n document.getElementById(\"timeCompleted\").innerHTML = timeElapsed;\n }, 1000);\n}", "function startTimer(){\n setTimeout(setIntervals, 300);\n setTimeout(rail_lights, 3000);\n setTimeout(getAudio, 3300);\n setTimeout(empty_window, 9000);\n}", "function countDownStart() {\n if (timer == 0) {\n that.gameLoop = setInterval(that.update, interval);\n that.status = State.RUN;\n }\n else {\n drawElements();\n that.gameArea.paintTimer(that.contex, timer);\n timer--;\n setTimeout(countDownStart, 1500);\n }\n \n }", "function runTimer() {\r\n let currentTime =\r\n leadingZero(timer[0]) +\r\n \":\" +\r\n leadingZero(timer[1]) +\r\n \":\" +\r\n leadingZero(timer[2]);\r\n\r\n theTimer.innerHTML = currentTime;\r\n timer[3]++;\r\n\r\n timer[0] = Math.floor(timer[3] / 100 / 60);\r\n timer[1] = Math.floor(timer[3] / 100 - timer[0] * 60);\r\n timer[2] = Math.floor(timer[3] - timer[1] * 100 - timer[0] * 6000);\r\n}", "function startChallengeTimer() {\n // Set the global 'challengeRunning' variable state to on\n showPrompt();\n if (timerState === TIMER_STATES.PAUSED) {\n disableStartButton();\n }\n\n timerState = TIMER_STATES.ACTIVE;\n unSelectAllTimerButtons();\n\n // Get the selected time, turn it into a date object\n let challengeLengthMinutes = $('#timer .minutes').text();\n let challengeLengthSeconds = $('#timer .seconds').text();\n\n // Fast timer for dev purposes\n // let challengeLengthMinutes = 0;\n // let challengeLengthSeconds = 3;\n\n // start the timer based on what's already on the clock\n let challengeLength = new Date( Date.parse( new Date() ) + ( 1 * 1 * challengeLengthMinutes * 60 * 1000 ) + ( 1 * 1 * challengeLengthSeconds * 1000 ) );\n\n // If the challenge is 60m or greater, subtract a second so that the minutes doesn't show '00' in the first second\n if( challengeLengthMinutes >= 60 ) {\n challengeLength.setSeconds( challengeLength.getSeconds() - 1 );\n }\n\n // Call the start timer function\n initializeClock('timer', challengeLength);\n\n // Get the time remaining\n function getTimeRemaining(endtime) {\n let total = Date.parse(endtime) - Date.parse(new Date());\n let seconds = Math.floor((total / 1000) % 60);\n let minutes = Math.floor((total / 1000 / 60) % 60);\n return {\n total,\n minutes,\n seconds\n };\n }\n\n // Function to start the clock\n function initializeClock(id, endtime) {\n clearAllIntervals();\n $('.workoutman--animated').show();\n $('.workoutman--still').hide();\n\n let clock = document.getElementById(id);\n let minutesEl = clock.querySelector('.minutes');\n let secondsEl = clock.querySelector('.seconds');\n\n function updateClock() {\n let t = getTimeRemaining(endtime);\n minutesEl.innerHTML = ('0' + t.minutes).slice(-2);\n secondsEl.innerHTML = ('0' + t.seconds).slice(-2);\n\n if (t.total <= 0) {\n window.clearInterval(timeInterval);\n // $('.timesup').removeClass('hide');\n // $('.illo--animated').hide();\n // $('.illo--still').show();\n showOutOfTime();\n }\n }\n updateClock();\n let timeInterval = setInterval(updateClock, 1000);\n activeIntervals.push(timeInterval)\n }\n}", "function startTimer() {\n totalSeconds = quizObj.length * 10;\n clearInterval(interval); \n setTime();\n}", "function startTimer() {\n runTime = setInterval(() => {\n displayTime();\n time++;\n }, 1000);\n\n}", "function startGame() {\n // console.log('Clicked')\n var startTime = new Date(),\n endTime = new Date(),\n seconds = (endTime - startTime) / 1000\n console.log() \n }", "function startTime() {\n var timerInterval = setInterval(function() {\n secondsLeft--;\n cornerTimer.text(\"Time: \" + secondsLeft);\n \n if(secondsLeft <= 0) {\n clearInterval(timerInterval);\n allDone();\n }\n \n }, 1000);\n }", "function timer() {\n\t\tvar d = new Date();\n\t\tvar time = Math.round(GAME_DURATION - (d.getTime() - startTime) / 1000);\n\t\tdocument.getElementById(\"timer\").innerHTML = \"Time remaining: \" + time;\n\t\tif (time <= 0) {\n\t\t\tendGame();\n\t\t}\n\t}", "function startTime() {\n //setInterval method calls a function or evaluates an expression at specified intervals (milliseconds)\n interval = setInterval(function () {\n timer.innerHTML = minute + \" mins \" + second + \" secs\";\n second++;\n if (second === 60) {\n minute++;\n second = 0;\n }\n if (minute === 60) {\n hour++;\n console.log(\"This game should NOT take an hour!\");\n minute = 0;\n }\n }, 1000);\n}", "function startTimer() {\n timerInterval = setInterval(function() {\n timeRemaining--\n $timer.text(timeRemaining)\n if (timeRemaining === 0) {\n endQuiz()\n }\n }, 1000)\n }", "function startGame() {\r\n countUp = 0;\r\n setTimeout(endGame, 120000);\r\n startTimer();\r\n cancelTimer = false;\r\n triggerCrime();\r\n}", "function startTimer() {\n timerId = setInterval(() => {\n time++;\n displayTime();\n }, 1000);\n}", "function startTimer() {\n\n var timeInterval = setInterval(function () {\n timerEl.textContent = \"Time: \" + timeLeft;\n timeLeft--;\n\n if (timeLeft === -1) {\n clearInterval(timeInterval);\n gameOver();\n }\n\n }, 1000);\n\n initialize();\n}", "function startTimer(duration, display) {\n var timer = duration, minutes, seconds;\n setInterval(function () {\n minutes = parseInt(timer / 60, 10)\n seconds = parseInt(timer % 60, 10);\n\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.text(minutes + \":\" + seconds);\n\n if (--timer < 0) {\n timer = alert(\"Great job! You're done\");\n }\n }, 1000);\n}", "function timerStart() {\n timer = setInterval(function tick(){\n timeInSeconds++;\n updateTimerDisplay(timeInSeconds);\n }, 1000);\n}", "function startTimer() {\n\tconst seconds = parseInt(this.dataset.time); //grab data attr value\n\ttimer(seconds); //set value to timer fn\n}", "function timerStart() {\n interval = setInterval(function() {\n seconds++;\n timer.innerHTML = minutes + ' min(s) ' + seconds + ' secs(s)';\n if (seconds === 60) {\n minutes++;\n seconds = 0;\n }\n if (minutes === 60) {\n hours++;\n minutes = 0;\n }\n }, timerDelay);\n}", "function startTimer() {\n var startTimer = setInterval(() => {\n if (timer > 0) {\n timerEl.textContent = \"Time: \" + timer;\n timer--;\n } else if (timer === 0) {\n clearInterval(startTimer);\n endQuiz();\n } else if (timer < 0) {\n clearInterval(startTimer);\n timer = 0;\n timerEl.textContent = \"Time: \" + timer;\n endQuiz();\n }\n }, 1000);\n runQuestions();\n}", "function timer(time){\n var display = document.querySelector('#time');\n var timer = time;\n //Prevents the spamming of Start game\n clearInterval(interval)\n interval = setInterval(function() {\n minutes = parseInt(timer / 60, 10)\n seconds = parseInt(timer % 60, 10);\n minutes = minutes < 10 ? \"0\" + minutes : minutes;\n seconds = seconds < 10 ? \"0\" + seconds : seconds;\n\n display.textContent = minutes + \":\" + seconds;\n //Checks pause status every second\n if (!pause){\n --timer;\n //Game lost\n if (timer < 0) {\n var x = document.getElementsByClassName(\"time-box\");\n x[0].style.background = \"#F2403F\";\n gameStatus(\"lose\")\n disableGame();\n clearInterval(interval);\n on();\n clearInterval(interval);\n }\n }\n }, 1000);\n}", "function timerStart(){\n\t\n\t\t\n\t}", "function startTimer() {\n timeCounter = setTimeout(addTime, 1000);\n timerStatus = true;\n }", "function runTimer(){\n \n let currentTime = leadingZero(timer[0]) + \":\" + leadingZero(timer[1]) + \":\" + leadingZero(timer[2]);\n \n theTimer.innerHTML = currentTime;\n \n timer[3]++;\n \n //.floor means no decimals\n // convertion to min/sec/10 milli\n timer[0]=Math.floor((timer[3]/100)/60);\n timer[1]=Math.floor((timer[3]/100)-(timer[0]*60)); \n timer[2]=Math.floor((timer[3])-(timer[1]*100)-timer[0]*6000);\n \n}", "function startTimer() {\n /* The \"interval\" variable here using \"setInterval()\" begins the recurring increment of the\n secondsElapsed variable which is used to check if the time is up */\n interval = setInterval(function () {\n secondsElapsed--;\n // So renderTime() is called here once every second.\n renderTime();\n }, 1000);\n}", "function timerola (){\n\tsetInterval(startGame,1000/60);\n}", "function timeStart() {\n\ttime = setInterval(buildTime, 1000);\n}", "function startTimer() {\n $(\"#timer\").text(\"Time Remaining: \" + timeRemaining);\n // count down by 1 second\n time = setInterval(countDown, 100);\n // hides the start button so start can't be pressed again\n $(\"#start-screen\").empty();\n // calls function to display trivia\n displayQuestions();\n }", "function stopwatch() {\n\tgameTime++;\n\titemTimer.innerText = gameTime /100;\n\t//statement to stop the game when time is too long\n\tif (gameTime == 9999) { // set max. time value (100 = 1 [s])\n\t\ttoStopWatch();\n\t\tmodalToLong();\n\t} else {\n\t\t\n\t}\n}", "function timestart() {\n clearInterval(intervalId);\n\n var time = 60;\n var intervalId;\n intervalId = setInterval(timeDown, 1000);\n function timeDown() {\n time--;\n $(\".time\").html(\"<h2>Time remaining: \" + time + \"</h2>\");\n\n if (time === 0) {\n showResults(questions);\n clearInterval(intervalId);\n\n }\n\n }\n}", "function startGame() {\n timerStat = true;\n showGamePanel();\n runTimer();\n displayImage();\n}", "function startTimer(){\n // check timer is on or off\n if(stopTime === true){\n stopTime = false;\n // this function will start the timer\n currentTime();\n }\n}", "function startTimer(timeInseconds) {\r\n seconds = timeInseconds;\r\n countDown();\r\n timer = setInterval(countDown, 1000);\r\n }", "function startTimer() {\n resetTimers(); \n game_timer = setTimeout ( \"endTimer()\", maximum_time);\n update_timer = setInterval(\"updateTimerBox(1000)\", 1000); //update every 1 second\n}", "function startTimer() {\n setTime();\n\n // We only want to start the timer if totalSeconds is > 0\n if (totalSeconds > 0) {\n /* The \"interval\" variable here using \"setInterval()\" begins the recurring increment of the\n secondsElapsed variable which is used to check if the time is up */\n interval = setInterval(function() {\n secondsElapsed++;\n\n // So renderTime() is called here once every second.\n renderTime();\n }, 1000);\n } else {\n alert(\"Minutes of work/rest must be greater than 0.\")\n }\n}", "function timerSetup() {\n // MINIGAME 1: 35sec\n if (minigame1) {\n timer = 35;\n }\n // MINIGAME 2: 5sec\n else if (minigame2) {\n timer = 5;\n }\n}", "function startTimer(duration, timerContainer) {\n timerContainer.style.display = 'block';\n let timer = duration;\n let minutes, seconds;\n\n setInterval(function() {\n //added parseInt javascript method to timer\n minutes = parseInt(timer / 60);\n seconds = parseInt(timer % 60);\n\n //formatting time and minutes in 00:00 format, checking if/else condition\n\n minutes = minutes < 10 ? '0' + minutes : minutes;\n seconds = seconds < 10 ? '0' + seconds : seconds;\n\n timerContainer.textContent = `Time left ${minutes}:${seconds}`;\n\n // decrease time\n timer--;\n if (timer < 0) {\n timerContainer.style.display = 'none';\n // Jump to final screen with scores\n resetContainer.innerHTML = `<h1>Game is over</h1><h3>Your total score is: ${quiz.score} out of 20 questions.</h3> <button id ='reset' onclick='window.location.href=\"index.html\"'>Reset Game</button><br>\n <h3 id='button'><a href='https://generalassemb.ly/' target='_blank'>Learn More</a></h3>`;\n answerContainer.style.display = 'none';\n resetContainer.style.display = 'block';\n }\n }, 1000);\n}", "function setTime() {\n var timerInterval = setInterval(function() {\n secondsLeft--;\n timeEl.textContent = secondsLeft + \" seconds left.\";\n if (secondsLeft === 0) {\n stopGame ();\n } \n }, 1000);\n\t }", "function startTimer() {\n if(timerStart == true) {\n seconds++;\n\n if(seconds == 60) {\n minutes++;\n seconds = 0;\n }\n if(minutes == 60) {\n hours++;\n minutes = 0;\n }\n\n if(minutes >= 1 && minutes < 2) {\n timer.style.color = \"orange\";\n }\n else if(minutes >= 2) {\n timer.style.color = \"red\";\n }\n else {\n timer.style.color = \"green\";\n }\n\n timer.textContent = hours + \":\" + minutes + \":\" + seconds;\n\n setTimeout(startTimer,1000);\n }\n}", "function startClock(){\n\tt = getTime();\n\tsetNum(\"sec2\" ,t[\"s2\"]);\n\tsetNum(\"sec1\" ,t[\"s1\"]);\n\tsetNum(\"min2\" ,t[\"m2\"]);\n\tsetNum(\"min1\" ,t[\"m1\"]);\n\tsetNum(\"hours2\" ,t[\"h2\"]);\n\tsetNum(\"hours1\" ,t[\"h1\"]);\n\tupdateTimer = setTimeout(\"updateClock()\",5000)\n\t //console.debug(\"called startClock\");\n\tclock();\n}", "function setTime() {\n var secondsLeft = 3600;\n var timerInterval = setInterval(function() {\n secondsLeft--; \n if(secondsLeft === 0) {\n clearInterval(timerInterval);\n setTime();\n }\n timeManagement();\n colorCoding()\n\n }, 1000);\n \n }", "function startTimer() {\r\n if (!isPaused){\r\n currentSeconds = workMinutesInput.value * 60;\r\n }\r\n isPaused = false;\r\n interval = setInterval(function(){\r\n currentSeconds--;\r\n let timeLeft = calculateTime(currentSeconds);\r\n minutesDisplay.textContent = Math.floor(timeLeft.minutes);\r\n secondsDisplay.textContent = Math.floor(timeLeft.seconds);\r\n }, 1000)\r\n}", "function handleStartGame() {\n console.log(\"Start Game clicked...!\");\n\n //------- Timer ------- //\n\n // Start Timer\n startTimer(0);\n}", "function startTime() {\n\ttime = setInterval(() => {\n\t\tseconds = seconds + 1;\n\t\tif (seconds == 59) {\n\t\t\tseconds = 0;\n\t\t\tmin = min + 1;\n\t\t}\n\t\tif (min == 60) {\n\t\t\tmin = 0;\n\t\t\thour = hour + 1;\n\t\t}\n\t\ttimeSpace.innerHTML = \"h\" + hour + \":\" + min + \"m : \" + seconds + \"s\";\n\t\t// to Show time\n\t}, 1000)\n}", "function timer() {\n\t\t--secs;\n\t\tmins = (secs < 0) ? --mins : mins;\n\t\tif (mins < 0) {\n\t\t\tstop();\n\t\t\tmins += 1;\n\t\t\taudio.play();\n\t\t}\n\t\tsecs = (secs < 0) ? 59 : secs;\n\t\tsecs = (secs < 10) ? '0' + secs : secs;\n\t\t$('#timer').html(mins + ':' + secs);\n\t\tdisplayTime = mins + ':' + secs;\n\t}", "function startGame()\n{\n \nbuttonStart.disabled = 'disabled';\nisPlaying = true;\nrenderScore();\n\ntimer = setInterval(clock,1000);// 1000 duration counting time\n}", "function startGame(){\n countStartGame = 30;\n correctAnswers = 0;\n wrongAnswers = 0;\n unanswered = 0;\n\n if (!timerRunning){ \n intervalId = setInterval(timer, 1000);\n timerRunning = true;\n }\n timer();\n console.log(\"game startiiing\");\n \n}" ]
[ "0.76168585", "0.75543934", "0.73781145", "0.73288554", "0.72690344", "0.7131463", "0.71276635", "0.7034538", "0.7034284", "0.7030517", "0.69974965", "0.69954294", "0.6990467", "0.6970833", "0.6970506", "0.6967031", "0.6959388", "0.6955698", "0.69466543", "0.6930948", "0.69168866", "0.69121516", "0.69058484", "0.6875302", "0.68593556", "0.6841822", "0.6839341", "0.6832215", "0.6831492", "0.68281025", "0.68178797", "0.68085134", "0.6806653", "0.68061495", "0.6798145", "0.6780697", "0.67611927", "0.6756958", "0.6744976", "0.6736918", "0.67363316", "0.6726291", "0.6722571", "0.6720838", "0.67140007", "0.6708353", "0.6704125", "0.6694747", "0.66944885", "0.66859454", "0.66599387", "0.6657349", "0.66493523", "0.6642043", "0.664036", "0.6631001", "0.6629776", "0.6628459", "0.662757", "0.661914", "0.6617433", "0.6616308", "0.6612437", "0.65975064", "0.6586582", "0.6586163", "0.6576387", "0.6574925", "0.6574845", "0.65721077", "0.65656245", "0.65594375", "0.65532637", "0.65520847", "0.6551402", "0.65327233", "0.65321475", "0.65297943", "0.6527224", "0.65266436", "0.6525191", "0.6523896", "0.6521987", "0.650755", "0.6505457", "0.65042806", "0.65038174", "0.6503393", "0.65014637", "0.65010136", "0.6498784", "0.64978385", "0.6497774", "0.6494036", "0.6478637", "0.64761996", "0.64760405", "0.64730203", "0.64712375", "0.64684415" ]
0.70791966
7
This function converts the time to a format of mm:ss as a string
function timeConvert(time) { // Define minutes as 60 seconds or less let minutes = Math.floor(time / 60); // Display "0" infront of number of minutes if minutes is less than 10 if (minutes < 10) { minutes = "0" + minutes; } // Define seconds as remainder of 60 seconds let seconds = time % 60; // Display "0" infront of number of seconds if seconds is less than 10 if (seconds < 10) { seconds = "0" + seconds; } return minutes + ":" + seconds; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function toMMSSFormat(time){\n var sec, min;\n\n sec = parseInt((time % 60), 10);\n sec = formatTime(sec);\n\n min = parseInt((time / 60), 10);\n min = formatTime(min);\n\n return min +\":\"+ sec;\n }", "function timeToString(time) {\n let diffInHrs = time / 3600000;\n let hh = Math.floor(diffInHrs);\n \n let diffInMin = (diffInHrs - hh) * 60;\n let mm = Math.floor(diffInMin);\n \n let diffInSec = (diffInMin - mm) * 60;\n let ss = Math.floor(diffInSec);\n \n let diffInMs = (diffInSec - ss) * 100;\n let ms = Math.floor(diffInMs);\n \n let formattedMM = mm.toString().padStart(2, \"0\");\n let formattedSS = ss.toString().padStart(2, \"0\");\n let formattedMS = ms.toString().padStart(2, \"0\");\n \n return `${formattedMM}:${formattedSS}:${formattedMS}`;\n}", "function formatTime(time) {\n // The largest round integer less than or equal to the result of time divided being by 60.\n const minutes = Math.floor(time / 60);\n // Seconds are the remainder of the time divided by 60 (modulus operator)\n let seconds = time % 60;\n // If the value of seconds is less than 10, then display seconds with a leading zero\n if (seconds < 10) {\n seconds = `0${seconds}`;\n }\n // The output in MM:SS format\n return `${minutes}:${seconds}`;\n}", "function formattedTime(time) {\n let mins = 0;\n let seconds = 0;\n mins = Math.floor(time/60)\n seconds = time%60\n if (String(mins).length<2) mins=\"0\"+String(mins)\n if (String(seconds).length<2) seconds=\"0\"+String(seconds)\n return `${mins}:${seconds}`\n}", "function formatTime(time) {\n const minutes = Math.floor(time / 60);\n let seconds = time % 60;\n \n if (seconds < 10) {\n seconds = `0${seconds}`;\n }\n \n return `${minutes}:${seconds}`;\n}", "formatTime(time) {\n var sec_num = parseInt(time, 10);\n var hours = Math.floor(sec_num / 3600);\n var minutes = Math.floor((sec_num - (hours * 3600)) / 60);\n var seconds = sec_num - (hours * 3600) - (minutes * 60);\n\n if (hours < 10) { hours = \"0\" + hours; }\n if (seconds < 10) { seconds = \"0\" + seconds; }\n return (hours < 1 ? '' : hours + ':') + (minutes < 1 ? '0:' : minutes + ':') + seconds;\n }", "function timeToString (time) {\r\n let diffInHrs = time / 3600000;\r\n let hh = Math.floor(diffInHrs);\r\n\r\n let diffInMin = (diffInHrs - hh) * 60;\r\n let mm = Math.floor(diffInMin);\r\n\r\n let diffInSec = (diffInMin - mm) * 60;\r\n let ss = Math.floor(diffInSec);\r\n\r\n let diffInMs = (diffInSec - ss) * 100;\r\n let ms = Math.floor(diffInMs);\r\n\r\n let formatHH = formatToTwoDigits(hh);\r\n let formatMM = formatToTwoDigits(mm);\r\n let formatSS = formatToTwoDigits(ss);\r\n let formatMS = formatToTwoDigits(ms)\r\n return `${formatMM}:${formatSS}:${formatMS}`;\r\n }", "function timeString(time) {\n let diffInHrs = time / 3600000;\n let hh = Math.floor(diffInHrs);\n let diffInMin = (diffInHrs - hh) * 60;\n let mm = Math.floor(diffInMin);\n let diffInSec = (diffInMin - mm) * 60;\n let ss = Math.floor(diffInSec);\n let formattedHH = hh.toString().padStart(2, \"0\");\n let formattedMM = mm.toString().padStart(2, \"0\");\n let formattedSS = ss.toString().padStart(2, \"0\");\n return `${formattedHH}:${formattedMM}:${formattedSS}`;\n}", "function timeToString(t) {\n var s = t.hours + \":\" + t.mins + \" \";\n s += t.isAM ? \"AM\" : \"PM\";\n return s;\n }", "function format_time(t) {\n var mins = Math.floor(t / 60);\n var secs = Math.floor(t) % 60;\n var out = \"\";\n \n if (secs < 10)\n out = mins + \":0\" + secs;\n else\n out = mins + \":\" + secs; \n \n return out; \n}", "function formatTime(time) {\n const minutes = Math.floor(time / 60);\n let seconds = time % 60;\n\n if (seconds < 10) {\n seconds = `0${seconds}`;\n }\n\n return `${minutes}:${seconds}`;\n}", "function timeFormat() {\n return setTwoDigit(timer.min) + \":\" + setTwoDigit(timer.sec) + \":\" + setTwoDigit(timer.millisecond);\n}", "function timeToString(time) {\n let diffInHrs = time / 3600000;\n let hh = Math.floor(diffInHrs);\n\n let diffInMin = (diffInHrs - hh) * 60;\n let mm = Math.floor(diffInMin);\n\n let diffInSec = (diffInMin - mm) * 60;\n let ss = Math.floor(diffInSec);\n\n let diffInMs = (diffInSec - ss) * 100;\n let ms = Math.floor(diffInMs);\n\n let formattedMM = mm.toString().padStart(2, \"0\");\n let formattedSS = ss.toString().padStart(2, \"0\");\n let formattedMS = ms.toString().padStart(2, \"0\");\n\n return `${formattedMM}:${formattedSS}:${formattedMS}`;\n}", "function formatTime(time){\n\ttime = Math.round(time);\n\n\tvar minutes = Math.floor(time / 60),\n\t\tseconds = time - minutes * 60;\n\n\tseconds = seconds < 10 ? '0' + seconds : seconds;\n\n\treturn minutes + \":\" + seconds;\n}", "function timeConversion(time) {\n let minutes = Math.floor(time/60);\n if(minutes < 10) minutes = \"0\" + minutes;\n let seconds = time % 60;\n if(seconds < 10) seconds = \"0\" + seconds;\n return minutes + \":\" + seconds;\n}", "function timeToString(time) {\n let diffInHrs = time / 3600000;\n let hh = Math.floor(diffInHrs);\n let diffInMin = (diffInHrs - hh) * 60;\n let mm = Math.floor(diffInMin);\n let diffInSec = (diffInMin - mm) * 60;\n let ss = Math.floor(diffInSec);\n let diffInMs = (diffInSec - ss) * 100;\n let ms = Math.floor(diffInMs);\n let formattedHH = hh.toString().padStart(2, \"0\");\n let formattedMM = mm.toString().padStart(2, \"0\");\n let formattedSS = ss.toString().padStart(2, \"0\");\n let formattedMS = ms.toString().padStart(2, \"0\");\n return `${formattedHH}:${formattedMM}:${formattedSS}:${formattedMS}`;\n}", "function convertTime(time) {\n\n \t\tvar time = time.toString();\n\t\tstrArray = time.split(\"\");\n\t\tnewString = \"\";\n\t\tfor (var i = 0; i < strArray.length; i++) {\n\t\t\tif ( i === strArray.length - 2) {\n\t\t\t\tnewString += \":\";\n\t\t\t}\n\t\t\tnewString += strArray[i]\n\t\t};\n\n\t\treturn newString;\n\t}", "function convertTimeString(time) {\n var hours = Number(time.match(/^(\\d+)/)[1]);\n var minutes = Number(time.match(/:(\\d+)/)[1]);\n var AMPM = time.match(/\\s(.*)$/)[1];\n if (AMPM == \"PM\" && hours < 12)\n hours = hours + 12;\n if (AMPM == \"AM\" && hours == 12)\n hours = hours - 12;\n var sHours = hours.toString();\n var sMinutes = minutes.toString();\n if (hours < 10)\n sHours = \"0\" + sHours;\n if (minutes < 10)\n sMinutes = \"0\" + sMinutes;\n return (sHours + ':' + sMinutes + ':00');\n}", "function displayTime(time) {\n const minutes = Math.floor(time / 60);\n let seconds = Math.floor(time % 60);\n seconds = seconds < 10 ? `0${seconds}` : seconds;\n return `${minutes}:${seconds}`;\n}", "function displayTime(time) {\n let minutes = Math.floor(time / 60);\n let seconds = Math.floor(time % 60);\n minutes = minutes > 9 ? minutes : `0${minutes}`;\n seconds = seconds > 9 ? seconds : `0${seconds}`;\n return `${minutes}:${seconds}`;\n}", "function format_time_output(time) {\n var h = 0; \n var m = 0;\n var s = 0;\n var ms = 0;\n var formated_time;\n\n h = Math.floor( time / (60 * 60 * 1000) );\n time = time % (60 * 60 * 1000);\n m = Math.floor( time / (60 * 1000) );\n time = time % (60 * 1000);\n s = Math.floor( time / 1000 );\n ms = time % 1000;\n\n newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms,3);\n return newTime;\n}", "function timeformat(time) {\r\n\t//calculate the time in hours, minutes and seconds\r\n\tmin = time / 60000;\r\n\tsec = min % 1;\r\n\tmin -= sec;\r\n\tsec *= 60;\r\n\tremainder = sec % 1;\r\n\tsec -= remainder;\r\n\tif( min < 10 ) { min = \"0\" + min; }\r\n\tif( sec < 10 ) { sec = \"0\" + sec; }\r\n\tformattedtime = min + \":\" + sec;\r\n\treturn formattedtime;\r\n}", "function formatTime(time) {\n if (time == -1) { return \"N/A\" }\n time = +time;\n let cs = time % 1000;\n let s = time % (1000 * 60) - cs;\n let m = time - s - cs;\n\n // Since the values returned above is suffixed\n // we have to divide afterwards\n cs = Math.floor(cs / 10);\n s = Math.floor(s / 1000);\n m = Math.floor(m / (1000 * 60));\n\n return (m > 0 ? m + \":\" : \"\") + (s < 10 && m > 0 ? \"0\" + s : s) + \".\" + (cs < 10 ? \"0\" + cs : cs);\n}", "function fancyTimeFormat(time)\n{ \n // Hours, minutes and seconds\n var hrs =Math.floor(time / 3600);\n var mins = Math.floor((time % 3600) / 60);\n var secs = time % 60;\n\n // Output like \"1:01\" or \"4:03:59\" or \"123:03:59\"\n var ret = \"\";\n\n if (hrs > 0) {\n ret += \"\" + hrs + \":\" + (mins < 10 ? \"0\" : \"\");\n }\n\n ret += \"\" + mins + \":\" + (secs < 10 ? \"0\" : \"\");\n ret += \"\" + secs;\n return ret;\n}", "function timeConverter(t) {\n var minutes = Math.floor(t / 60);\n var seconds = t - (minutes * 60);\n \n if (seconds < 10) {\n seconds = \"0\" + seconds;\n }\n \n if (minutes === 0) {\n minutes = \"00\";\n }\n \n else if (minutes < 10) {\n minutes = \"0\" + minutes;\n }\n \n return minutes + \":\" + seconds;\n }", "function formatTime() {\n\n // get whole minutes\n var minutes = Math.floor(timer / 60);\n\n // get remaining seconds\n var seconds = timer % 60;\n\n // add leading \"0\"s\n if (seconds < 10) {\n seconds = \"0\" + seconds;\n }\n\n return minutes + \":\" + seconds;\n}", "_displayTime(time) {\n const minutes = Math.floor(time / 60);\n let seconds = Math.floor(time % 60);\n seconds = seconds > 9 ? seconds : `0${seconds}`;\n return `${minutes}:${seconds}`;\n }", "function timeConverter(t) {\n var minutes = Math.floor(t / 60);\n var seconds = t - (minutes * 60);\n if (seconds < 10) {\n seconds = \"0\" + seconds;\n }\n if (minutes === 0) {\n minutes = \"00\";\n }\n else if (minutes < 10) {\n minutes = \"0\" + minutes;\n }\n return minutes + \":\" + seconds;\n }", "function timestr(time, full) {\r\n time = parseInt (time);\r\n var m = [];\r\n var t = time;\r\n if (t < 61)\r\n return t + 's';\r\n if (t > 86400){\r\n m.push (parseInt(t/86400)); \r\n m.push ('d ');\r\n t %= 86400;\r\n } \r\n if (t>3600 || time>3600){\r\n m.push (parseInt(t/3600)); \r\n m.push ('h ');\r\n t %= 3600;\r\n } \r\n m.push (parseInt(t/60)); \r\n m.push ('m');\r\n if (full || time<=3600 ){\r\n m.push (' ');\r\n m.push (t%60);\r\n m.push ('s'); \r\n }\r\n return m.join ('');\r\n}", "function formatTime (t) {\n if (isNaN(t)) return ('');\n var m = Math.floor(t/60/1000),\n s = Math.floor(t/1000 - m * 60);\n\n return m + ':' + (s > 9 ? s : '0' + s);\n}", "function timestr(time, full) {\r\n time = parseInt (time);\r\n var m = [];\r\n var t = time;\r\n if (t < 61)\r\n return t + 's';\r\n if (t > 86400){\r\n m.push (parseInt(t/86400));\r\n m.push ('d ');\r\n t %= 86400;\r\n } \r\n if (t>3600 || time>3600){\r\n m.push (parseInt(t/3600));\r\n m.push ('h ');\r\n t %= 3600;\r\n } \r\n m.push (parseInt(t/60));\r\n m.push ('m');\r\n if (full || time<=3600 ){\r\n m.push (' ');\r\n m.push (t%60);\r\n m.push ('s'); \r\n }\r\n return m.join ('');\r\n}", "function timeConverter(t) {\n\n var minutes = Math.floor(t / 60);\n var seconds = t - (minutes * 60);\n\n if (seconds < 10) {\n seconds = \"0\" + seconds;\n }\n\n if (minutes === 0) {\n minutes = \"00\";\n\n } else if (minutes < 10) {\n minutes = \"0\" + minutes;\n }\n\n return minutes + \":\" + seconds;\n }", "function _timeFormat(sec) {\n\t\t\tstr = \"00:00\";\n\t\t\tif (sec > 0) {\n\t\t\t\tstr = Math.floor(sec / 60) < 10 ? \"0\" + Math.floor(sec / 60) + \":\" : Math.floor(sec / 60) + \":\";\n\t\t\t\tstr += Math.floor(sec % 60) < 10 ? \"0\" + Math.floor(sec % 60) : Math.floor(sec % 60);\n\t\t\t}\n\t\t\treturn str;\n\t\t}", "timeFormatter (time) {\n var timeArr = time.split('T');\n var finalTime = timeArr[1].slice(0,2) + ':' + timeArr[1].slice(2,4);\n return finalTime;\n }", "function fancyTimeFormat(time)\r\n\t\t{ \r\n \t\tvar hrs = ~~(time / 3600);\r\n \t\tvar mins = ~~((time % 3600) / 60);\r\n \t\tvar secs = time % 60;\r\n\t\t\tvar ret = \"\";\r\n \t\tif (hrs > 0) {\r\n \tret += \"\" + hrs + \":\" + (mins < 10 ? \"0\" : \"\");\r\n \t\t}\r\n \t\tret += \"\" + mins + \":\" + (secs < 10 ? \"0\" : \"\");\r\n \t\tret += \"\" + secs;\r\n \t\treturn ret;\r\n\t\t}", "function formatTime(time) {\n let seconds = time % 60;\n if (seconds < 10) {\n seconds = \"0\" + seconds.toString();\n }\n let minutes = Math.floor(time / 60);\n if (minutes < 10) {\n minutes = \"0\" + minutes.toString();\n }\n let hours = Math.floor(time / 3600);\n return hours.toString() + \":\" + minutes + \":\" + seconds;\n}", "function timeFormatter (time) {\n\tvar timeArr = time.split('T');\n\tvar finalTime = timeArr[1].slice(0,2) + ':' + timeArr[1].slice(2,4);\n\treturn finalTime;\n}", "function formatTime(time) {\n const secconds = parseInt(time % 60);\n const minute = parseInt(time / 60);\n\n return (minute < 10 ? '0' : '') + minute + (secconds < 10 ? ':0' : ':') + secconds;\n}", "function converTime(t){\n t = Number(t); //cast to number\n if (t > 0 && t < 12){\n return t + ':00 am'\n } else if(t === 0) {\n return \"12:00 am\"\n } else if(t === 12) {\n return '12:00 pm'\n } else if(t > 12){\n return (t-12) + ':00 pm'\n }\n }", "function timeConverter(t) {\n var minutes = Math.floor(t / 60);\n var seconds = t - (minutes * 60);\n\n if (seconds < 10) {\n seconds = \"0\" + seconds;\n }\n\n if (minutes === 0) {\n minutes = \"00\";\n }\n else if (minutes < 10) {\n minutes = \"0\" + minutes;\n }\n\n return minutes + \":\" + seconds;\n}", "function toTimeString(time) {\n var date = new Date(time);\n var hours = date.getHours();\n if(hours < 10) hours = \"0\" + hours;\n var minutes = date.getMinutes();\n if(minutes < 10) minutes = \"0\" + minutes;\n return hours + \":\" + minutes;\n}", "function timeConverter(t) {\n\n var minutes = Math.floor(t/60);\n var seconds = t - (minutes*60);\n\n if (seconds < 10) {\n seconds = \"0\" + seconds;\n }\n\n if (minutes === 0) {\n minutes = \"00\";\n }\n\n else if (minutes < 10) {\n minutes = \"0\" + minutes;\n }\n\n return minutes + \":\" + seconds; \n}", "function formatTime(time) {\n // converts the time in hours\n var hours = Math.floor(time / (1000 * 60 * 60));\n // converts the time to minutes\n var minutes = Math.floor(time / (1000 * 60)) % 60;\n // converts the time to seconds\n var seconds = Math.floor(time / 1000) % 60;\n\n // formatting for seconds\n if (seconds < 10) {\n seconds = \"0\" + seconds;\n }\n seconds = \":\" + seconds\n\n // formatting for hours\n if (hours == 0) {\n hours = \"\";\n } else {\n hours += \":\";\n }\n\n // formatting for minutes\n if (minutes == 0) {\n minutes = \"\";\n }\n // returns the final result as a string\n return hours + minutes + seconds;\n}", "function timeFormatString() {\n return is24HourTime() ? 'HH:mm' : 'hh:mm a';\n}", "displayTime(time) {\n\n // let minutes = parseInt(this.state.currentTime / 60);\n // let seconds = parseInt(this.state.currentTime % 60);\n let minutes = Math.floor(time / 60);\n let seconds = Math.floor(time % 60);\n //need to make it 0:00\n if (seconds < 10) {\n seconds = '0' + seconds;\n }\n return `${minutes}:${seconds}`\n }", "function timeToString(time) {\n let diffInHrs = time / 3600000;\n let hh = Math.floor(diffInHrs);\n\n let diffInMin = (diffInHrs - hh) * 60;\n let mm = Math.floor(diffInMin);\n\n let diffInSec = (diffInMin - mm) * 60;\n let ss = Math.floor(diffInSec);\n\n let diffInMs = (diffInSec - ss) * 100;\n let ms = Math.floor(diffInMs);\n\n let formattedHH = hh.toString().padStart(2, '0');\n let formattedMM = mm.toString().padStart(2, '0');\n let formattedSS = ss.toString().padStart(2, '0');\n let formattedMS = ms.toString().padStart(2, '0');\n\n return (\n 'Timer ' + `${formattedHH}:${formattedMM}:${formattedSS}:${formattedMS}`\n );\n}", "function formatTime(time) {\n if (time > 9) {\n return time;\n } else {\n return \"0\" + time;\n }\n }", "_toHHMMSS(ms) {\n return new Date(ms).toISOString().slice(11, -1);\n // console.log( time(1234567890) ); // \"06:56:07.890\"\n }", "function formatTime(val) {\n var a = new Number(val.substring(0,val.indexOf(\":\")));\n if (a > 12) {\n a -= 12;\n }\n var b = val.substring(val.indexOf(\":\"),val.length);\n return a + b;\n}", "function getNewTimeDisplay(time){\n if(isNaN(time))\n return \"00:00\";\n time=parseInt(time)\n var minutes = Math.floor( time / 60 );\n var seconds = time % 60;\n minutes = minutes < 10 ? '0' + minutes : minutes;\n seconds = seconds < 10 ? '0' + seconds : seconds;\n if (minutes==\"NaN\" && seconds==\"NaN\"){\n return \"00:00\";\n }\n return minutes + \":\" + seconds; \n}", "function formatTime(time) {\n var hour = time.substr(0, 2);\n var minute = time.substr(3, 2);\n var ret;\n\n if (hour == 0) {\n ret = \"12:\" + minute + \"am\";\n }\n else if (hour == 12) {\n ret = hour + \":\" + minute + \"pm\";\n }\n else if (hour > 12) {\n hour -= 12;\n ret = hour + \":\" + minute + \"pm\";\n } else {\n ret = hour * 1 + \":\" + minute + \"am\";\n }\n if (hour < 10) {\n ret = \"&nbsp;\" + ret;\n }\n return ret;\n }", "function formatTime (time) {\n const hours = Math.floor(time / 3600)\n let mins = Math.floor((time - hours * 3600) / 60)\n let secs = Math.floor(time - (hours * 3600) - (mins * 60))\n\n if (secs < 10) secs = '0' + secs\n\n if (hours > 0) {\n if (mins < 10) mins = '0' + mins\n return hours + ':' + mins + ':' + secs\n } else {\n return mins + ':' + secs\n }\n}", "function getTime(time) {\n var minute = Math.floor(time / 60);\n var second = Math.floor(time % 60);\n if (minute < 10) {\n minute = \"0\" + minute;\n }\n\n if (second < 10) {\n second = \"0\" + second;\n }\n\n return minute + \":\" + second;\n }", "function getTimeString(time) {\n let result = ''\n let format = time.split('.')[0].split(':')\n let hour = parseInt(format[0], 10)\n let meridiem = (hour / 12) >= 1 ? 'PM' : 'AM'\n\n result += hour % 12 === 0 ? 12 : hour % 12\n result += ':'\n result += format[1]\n\n return result + ' ' + meridiem\n}", "function time_string(ms) {\n let secs = Math.floor(ms / 1000)\n ms = ms - (secs * 1000)\n let mins = Math.floor(secs / 60)\n secs = secs - (mins * 60)\n return mins.toString() + ' m ' + secs.toString() + ' s ' + ms.toString() + ' ms' \n}", "function timeToText(time) {\n var timeArr = time.split(':');\n var hour = timeArr[0];\n var mins = ':' + timeArr[1].toString();\n if (mins == ':00') {\n mins='';\n }\n if (hour < 12) {\n return `${parseInt(hour).toString()}${mins}am`;\n }\n else if (hour == 12) {\n return `12${mins}pm`;\n }\n else {\n normal_hour = parseInt(hour) - 12\n return `${normal_hour.toString()}${mins}pm`;\n }\n}", "formatTime(time) {\n time = parseInt(time, 10);\n if (time < 10) return '0' + time;\n return time;\n }", "function timeConvert(num) { \n if (num < 60) {\n return \"0:\" + String(num);\n }\n else {\n return String(Math.floor(num / 60)) + \":\" + String(num % 60); \n } \n}", "function timeFormat(time) {\n return time < 10 ? \"0\"+time : time;\n }", "function timeSetFormat(time){\r\n let tempArr = time.split(\":\");\r\n for(var i=0; i<tempArr.length; i++){\r\n tempArr[i] = +tempArr[i];\r\n }\r\n tempArr = roundTime(tempArr);\r\n\r\n //reformat by adding starting 0's\r\n if(tempArr[1] == '0'){\r\n tempArr[1] = '00';\r\n }\r\n if(tempArr[0] < 10){\r\n tempArr[0] = '0' + tempArr[0];\r\n }\r\n\r\n tempArr = tempArr.join(':');\r\n return tempArr;\r\n}", "formatTime(time) {\r\n var timeString = \"\";\r\n if (time < 1200) {\r\n time = time / 100.00;\r\n if (time % 1 === 0) {\r\n timeString = time + \".00 AM\";\r\n } else {\r\n timeString = time + \"0 AM\";\r\n }\r\n } else if (time === 1200) {\r\n time = time / 100.00;\r\n if (time % 1 === 0) {\r\n timeString = time + \".00 PM\";\r\n } else {\r\n timeString = time + \"0 PM\";\r\n }\r\n } else {\r\n time = (time - 1200) / 100.00;\r\n if (time % 1 === 0) {\r\n timeString = time + \".00 PM\";\r\n } else {\r\n timeString = time + \"0 PM\";\r\n }\r\n }\r\n return timeString;\r\n }", "function convertTime(time) {\n var ampm = 'am'\n var hrs = parseInt(Number(time/4));\n \tvar min = Math.round((Number(time/4)-hrs) * 60);\n if (hrs > 12) {\n ampm = 'pm';\n hrs = hrs - 12;\n }\n if (min == 0) {\n min = '00';\n }\n \n return hrs + ':' + min + ampm;\n }", "function timeConversion(s) {\n\tlet hh = s.slice(0, 2)\n\tlet mm = s.slice(3, 5)\n\tlet ss = s.slice(6, 8)\n\n\tif (s.slice(8, 10) === 'PM') {\n\t\tif (hh === '12') return `${hh}:${mm}:${ss}`\n\t\treturn `${+hh + 12}:${mm}:${ss}`\n\t}\n\tif (s.slice(8, 10) === 'AM') {\n\t\tif (hh === '12') return `00:${mm}:${ss}`\n\t\treturn `${hh}:${mm}:${ss}`\n\t}\n}", "function format_time(time){\n\tvar h,m,s;\n\th=(time/360)|0;time%=360;\n\tm=(time/60)|0;time%=60;\n\ts=time|0;\n\t\n\treturn (h?h+\":\": \"\")+(m>=10?m: \"0\"+m)+\":\"+(s>=10?s: \"0\"+s);\n}", "formatTime(n) {\n if ((n + '').length > 2) {\n\treturn n;\n }\n const padding = new Array(2).join('0');\n return (padding + n).slice(-2);\n }", "function formatTime(){\r\n var response = \"\",\r\n hours = 0,\r\n mins = 0,\r\n secs = time;\r\n\r\n while (secs >= 60){\r\n secs -= 60;\r\n mins += 1;\r\n }\r\n\r\n while (mins >= 60){\r\n mins -= 60;\r\n hours += 1;\r\n }\r\n\r\n if (secs == 0) {\r\n secs = \"\";\r\n } else if (secs == 1) {\r\n secs += \" second\";\r\n } else if (secs > 1) {\r\n secs += \" seconds\";\r\n }\r\n\r\n if (mins == 0) {\r\n mins = \"\";\r\n } else if (mins == 1) {\r\n mins += \" minute\";\r\n } else if (mins > 1) {\r\n mins += \" minutes\";\r\n }\r\n\r\n if (hours == 0) {\r\n hours = \"\";\r\n } else if (hours == 1) {\r\n hours += \" hour\";\r\n } else if (hours > 1) {\r\n hours += \" hours\";\r\n }\r\n\r\n if (hours != \"\"){\r\n response += hours + \" \";\r\n }\r\n\r\n if (mins != \"\"){\r\n response += mins + \" \";\r\n }\r\n\r\n if (secs != \"\"){\r\n response += secs;\r\n }\r\n\r\n return response;\r\n }", "function getTimeStr(time) {\n\t\tvar d = new Date(START_OF_DAY + (time * 1000 * 60)),\n\t\t\thours = d.getHours(),\n\t\t\tmins = d.getMinutes(),\n\t\t\tamPM = getAMPM(hours);\n\n\t\thours = hours > 12 ? hours - 12 : hours || 12;\n\t\tmins = mins ? ':' + (mins < 10 ? '0' + mins : mins) : '';\n\n\t\treturn hours + mins + ' ' + amPM;\n\t}", "function timeFormat(timeInFormat){\n var mSeconds = Math.floor((timeInFormat%(1000)));\n var seconds = Math.floor((timeInFormat%(1000*60))/1000);\n var minute = Math.floor((timeInFormat % (1000 * 60 * 60)) / (1000 * 60));\n return `${minute}:${seconds}:${mSeconds}`;\n}", "function formatTime(s) {\n var i = 2;\n var a = new Array();\n do {\n a.push(s.substring(0, i));\n } while((s = s.substring(i, s.length)) != \"\");\n return a.join(':');\n }", "function convertMsToString(time) {\n\t// Create a Date object with that time as the milliseconds\n\tvar d = new Date(0,0,0,0,0,0,time);\n\tvar hours = d.getHours();\n\tvar hoursStr = hours.toString();\n\tvar minutes = d.getMinutes();\n\tvar minutesStr = minutes.toString();\n\tvar am_pm = 'AM';\n\n\t// Change from 24-hr clock time to 12-hr clock time\n\tif (hours === 12) {\n\t\tam_pm = 'PM';\n\t} else if (hours > 12) {\n\t\thours = hours % 12;\n\t\tam_pm = 'PM';\n\t\thoursStr = hours.toString();\n\t} else if (hours === 0) {\n\t\thoursStr = '12';\n\t}\n\t// Add the '0' before the minutes if less than 10 minutes\n\tif (minutes < 10) {\n\t\tminutesStr = '0' + minutesStr;\n\t}\n\n\t// Create the string in the proper format HH:MM(AM/PM)\n\tvar dateString = hoursStr + ':' + minutesStr + am_pm;\n\treturn dateString;\n}", "function convTime(time) {\n // var for am/pm\n var amPm;\n // split hours and mins\n var timesplit = time.split(\":\");\n\n // if hours > 12 then do conversion\n if (timesplit[0] > 12) {\n timesplit[0] = timesplit[0]-12;\n amPm=\"pm\";\n }\n else {\n if (timesplit[0] === \"12\") {\n amPm=\"pm\";\n }\n else {\n amPm=\"am\";\n }\n }\n\n // if minutes > 10 then insert a 0\n if (timesplit[1] < 10) {\n timesplit[1] = \"0\"+timesplit[1];\n }\n\n // return the string with am/pm added\n return (timesplit[0]+ \":\" + timesplit[1] + \" \" + amPm);\n\n}", "function converNumToTimeString (num) {\n var sec_num = parseInt(num, 10); // don't forget the second param\n var hours = Math.floor(sec_num / 3600);\n var minutes = Math.floor((sec_num - (hours * 3600)) / 60);\n var seconds = sec_num - (hours * 3600) - (minutes * 60);\n\n if (hours < 10) {hours = \"0\" + hours;}\n if (minutes < 10) {minutes = \"0\" + minutes;}\n if (seconds < 10) {seconds = \"0\" + seconds;}\n return hours + ':' + minutes + ':' + seconds;\n}", "function formatTime(time){\r\n //Incoming Time format hh:mm:ss\r\n splitTime = time.split(\":\");\r\n hour = splitTime[0];\r\n minute = splitTime[1];\r\n\r\n //Determine if the hour is AM or PM\r\n if (hour > 12){\r\n amPM = \"PM\";\r\n hour = hour - 12;\r\n }else{\r\n amPM = \"AM\";\r\n }\r\n\r\n //return time in hh:mm AM/PM\r\n return hour +\":\" + minute + \" \" + amPM;\r\n}", "function getTimeStr(time,hideSeconds){ // was int2timestr\n\t// returns like \"1d 12:30:42\"\n\tvar str,help;\n\tif(time<0){ time *= -1; }\n\tif (hideSeconds) {\n\t\tstr = timeFormatHM;\n\t} else {\n\t\tstr = timeFormatHMS;\n\t\thelp = time%60;\n\t\tstr = str.replace(\"sec\",((help<10)?\"0\":\"\")+Math.floor(help));\n\t}\n\ttime=time/60;\n\thelp = time%60;\n\tstr = str.replace(\"min\",((help<10)?\"0\":\"\")+Math.floor(help));\n\ttime=time/60;\n\thelp = time%24;\n\tstr = str.replace(\"hour\",((help<10)?\"0\":\"\")+Math.floor(help));\n\ttime=time/24;\n\tif (time>=1){ str=Math.floor(time)+\"d&nbsp;\"+str; }\n\treturn str;\n}", "function formatTimeString(h, m, s) {\n m = checkTime(m);\n s = checkTime(s);\n\n return h + \":\" + m + \":\" + s;\n}", "function timestr(time, full) {\r\n time = parseInt (time);\r\n var m = [];\r\n var t = time;\r\n if (t < 61)\r\n return t + 'sn.';\r\n if (t > 86400){\r\n m.push (parseInt(t/86400));\r\n m.push ('Gün');\r\n t %= 86400;\r\n } \r\n if (t>3600 || time>3600){\r\n m.push (parseInt(t/3600));\r\n m.push ('Saat ');\r\n t %= 3600;\r\n } \r\n m.push (parseInt(t/60));\r\n m.push ('Dk.');\r\n if (full || time<=3600 ){\r\n m.push (' ');\r\n m.push (t%60);\r\n m.push ('sn.'); \r\n }\r\n return m.join ('');\r\n}", "function fancyTimeFormat(time) {\n var hrs= ~~(time/3600);\n var min= ~~((time%3600)/60);\n var sec= time%60;\n var ret=\"\";\n if(hrs>0)\n {\n ret+=\"\"+hrs+\":\"+(min<10?\":\":\"\");\n }\n ret+=\"\"+min+\":\"+(sec<10?\"0\":\"\");\n ret+=\"\"+sec;\n return ret;\n}", "function reFormatTime(time) {\n const ampm = time.substr(-2, 2);\n let formattedTime;\n let formattedHour;\n const colon = time.indexOf(':');\n\n if (ampm === 'PM') {\n formattedHour = time.substr(0, 2);\n\n if (formattedHour == '12') { formattedHour = 12; } else { formattedHour = 12 + parseInt(time.substr(0, 2)); }\n\n formattedTime = `${formattedHour + time.substr(colon, 3)}:00`;\n } else {\n formattedHour = parseInt(time.substr(0, 2));\n if (formattedHour < 10) {\n formattedHour = `0${formattedHour}`;\n }\n if (formattedHour == 12) {\n formattedHour = '00';\n }\n formattedTime = `${formattedHour + time.substr(colon, 3)}:00`;\n }\n return formattedTime;\n }", "function TIME_FORMAT(time) {\n var sec_num = parseInt(time, 10); // don't forget the second param\n var hours = Math.floor(sec_num / 3600);\n var minutes = Math.floor((sec_num - (hours * 3600)) / 60);\n var seconds = sec_num - (hours * 3600) - (minutes * 60);\n\n if (hours < 10) {hours = \"0\"+hours;}\n if (minutes < 10) {minutes = \"0\"+minutes;}\n if (seconds < 10) {seconds = \"0\"+seconds;}\n \n if(time==Infinity || isNaN(time)){\n return '--';\n } else {\n return minutes+':'+seconds;\n }\n}", "function timeFormat(seconds){\n var m = Math.floor(seconds/60)<10 ? \"0\"+Math.floor(seconds/60) : Math.floor(seconds/60);\n var s = Math.floor(seconds-(m*60))<10 ? \"0\"+Math.floor(seconds-(m*60)) : Math.floor(seconds-(m*60));\n return m+\":\"+s;\n}", "function toMilitaryTime(time) {\n var timeParse = time.split(\" \");\n var half = timeParse[1]\n var timeParse2 = timeParse[0].split(\":\");\n var milTime = \"{0}:{1}\";\n var hour = parseInt(timeParse2[0]);\n if (hour >= 24)\n hour = 0 \n if (half == 'PM') {\n if (hour != 12)\n hour += 12 \n }\n else {\n if (hour == 12)\n hour = 0 \n }\n return milTime.format(hour, timeParse2[1])\n}", "function formatTime(time) {\n if (time < 10) {\n time = \"0\" + time;\n }\n return time;\n }", "function formatTime(tm) {\r\n\tvar str = (Math.floor(tm / 1000)).toString(10);\r\n\tvar d = Math.floor((tm % 1000) / 100);\r\n\treturn str + \".\" + d;\r\n}", "function formatTime(time) {\r\n return time < 10 ? `0${time}` : time;\r\n}", "function formatTime(time) {\n var hr = Math.floor(time / 60), //Important to use math.floor with hours\n min = Math.round(time % 60);\n\n if (hr < 1 && min < 1) {\n return \"\";\n }\n else if (hr < 1) {\n return min + \" minute(s)\";\n }\n\n return hr + \" hour(s) \" + min + \" minute(s)\";\n}", "function format_time(secs)\n{\n\tvar min = Math.floor(secs / 60);\n\tvar sec = secs % 60;\n\t\n\tif (sec < 10)\n\t\tsec = \"0\" + sec;\n\t\n\treturn min + \":\" + sec;\n}", "function parseTime(time) {\n var st = '';\n var h = 0,\n m = 0,\n s = 0;\n if (time > 3600) {\n h = Math.floor(time / 3600);\n time -= 3600 * h;\n st += h + ':';\n }\n if (time > 60) {\n m = Math.floor(time / 60);\n time -= 60 * m;\n st += m + ':';\n } else {\n st += '0:';\n }\n s = Math.floor(time);\n st += s;\n return st;\n }", "function ConvertTimeformat(format) {\n\tvar time = format;\n\tvar hours = Number(time.match(/^(\\d+)/)[1]);\n\tvar minutes = Number(time.match(/:(\\d+)/)[1]);\n\tvar AMPM = time.match(/\\s(.*)$/)[1];\n\tif (AMPM == \"PM\" && hours < 12) hours = hours + 12;\n\tif (AMPM == \"AM\" && hours == 12) hours = hours - 12;\n\tvar sHours = hours.toString();\n\tvar sMinutes = minutes.toString();\n\tif (hours < 10) sHours = \"0\" + sHours;\n\tif (minutes < 10) sMinutes = \"0\" + sMinutes;\n\treturn (sHours + \":\" + sMinutes + \":00\");\n}", "function timeConvert(num) {\n var n = num;\n var hours = n / 60;\n var rhours = Math.floor(hours);\n var minutes = (hours - rhours) * 60;\n var rminutes = Math.round(minutes);\n return rhours + \":\" + rminutes;\n}", "function toHHMMSS(prmTime) {\n var reste = prmTime;\n var result='';\n \n var nbJours = Math.floor(reste / (3600 * 24));\n reste -= nbJours * 24 * 3600;\n \n var nbHours = Math.floor(reste / 3600);\n\treste -= nbHours * 3600;\n \n\tvar nbMinutes = Math.floor(reste/60);\n\treste -= nbMinutes * 60;\n \n\tvar nbSeconds=reste;\n \n\tif (nbJours > 0)\n\t\tresult = result + nbJours + 'j ';\n \n\tif (nbHours>0)\n\t\tresult = result + nbHours + 'h ';\n \n\tif (nbMinutes>0)\n\t\tresult = result + nbMinutes + 'min ';\n \n\tif (nbSeconds>0)\n\t\tresult = result + nbSeconds + 's ';\n \n\treturn result;\n}", "function formatTime(time){\n\t\tvar formatted = {\n\t\t\tminute:time.getMinutes(),\n\t\t\thour:time.getHours(),\n\t\t\tampm:'AM',\n\t\t\ttimeString:''\n\t\t};\n\t\tif (formatted.hour > 11){\n\t\t\tformatted.ampm = 'PM';\n\t\t}\n\t\tif (formatted.hour > 12){\n\t\t\tformatted.hour -= 12;\n\t\t}\n\t\tif (formatted.minute < 10){\n\t\t\tformatted.minute = '0'+formatted.minute;\n\t\t}\n\t\tformatted.timeString = formatted.hour + ':'+formatted.minute + ' ' + formatted.ampm;\n\t\treturn formatted;\n\t}", "formatTime(time) {\n return (time < 10) ? `0${time}` : time;\n }", "function timeConvert(n) {\n\t\t\t\t\t\t\tvar num = n;\n\t\t\t\t\t\t\tvar hours = (num / 60);\n\t\t\t\t\t\t\tvar rhours = Math.floor(hours);\n\t\t\t\t\t\t\tvar minutes = (hours - rhours) * 60;\n\t\t\t\t\t\t\tvar rminutes = Math.round(minutes);\n\t\t\t\t\t\t\treturn rhours + \"hour \" + rminutes + \" mins\";\n\t\t\t\t\t\t}", "function formatTime(time) {\r\n if ( time < 10 ) {\r\n return '0' + time;\r\n }\r\n return time;\r\n}", "function prettyDate2(time) {\n var date = new Date(parseInt(time));\n var localeSpecificTime = date.toLocaleTimeString();\n return localeSpecificTime.replace(/:\\d+ /, ' ');\n }", "function formatTime(d){\n\treturn d.toTimeString().split(' ')[0];\n}", "function toTimeFormat(num) {\n const hours = Math.floor(num / 3600);\n const minutes = (num % 3600) / 60;\n return hours + \":\" + minutes;\n }", "function timerToString(time) {\n let differenceInHours = time / 3600000;\n let hour = Math.floor(differenceInHours);\n \n let differenceInMinutes = (differenceInHours - hour) * 60;\n let minute = Math.floor(differenceInMinutes);\n \n let differenceInSeconds = (differenceInMinutes - minute) * 60;\n let second = Math.floor(differenceInSeconds);\n \n let differenceInMilliseconds = (differenceInSeconds - second) * 100;\n let millisecond = Math.floor(differenceInMilliseconds);\n \n // Here we will format and pad the timer:\n let MINUTE = minute.toString().padStart(2, \"0\");\n let SECOND = second.toString().padStart(2, \"0\");\n let MILLISECOND = millisecond.toString().padStart(2, \"0\");\n \n return `${MINUTE}:${SECOND}:${MILLISECOND}`;\n}", "function formatTime(t) {\n return padZeros(t.getHours(), 2) + ':' + padZeros(t.getMinutes(), 2) + ':' + padZeros(t.getSeconds(), 2);\n}", "function format_time( time_in_seconds ) {\n\n var hours, minutes, seconds\n\n // calculate hours\n hours = Math.floor( time_in_seconds / 3600 );\n\n // calculate minutes\n minutes = Math.floor( time_in_seconds / 60 );\n if ( hours > 0 ) {\n minutes = minutes % 60;\n }\n\n // calculate seconds\n seconds = Math.floor( time_in_seconds % 60 );\n\n // generate minutes part\n if ( !isNaN( minutes ) ) {\n minutes = ( minutes >= 10 )? minutes : \"0\" + minutes;\n } else {\n minutes = \"--\";\n }\n \n\n // generate seconds part\n if ( !isNaN( seconds ) ) {\n seconds = ( seconds >= 10 )? seconds : \"0\" + seconds;\n } else {\n seconds = \"--\";\n }\n \n\n return ( hours > 0 )? hours + \":\" + minutes + \":\" + seconds : minutes + \":\" + seconds;\n\n}" ]
[ "0.7927201", "0.79084516", "0.7874276", "0.7854004", "0.7851414", "0.78483313", "0.7812436", "0.7809364", "0.78092253", "0.78032494", "0.78020144", "0.7799904", "0.7793222", "0.7761326", "0.7726641", "0.7699753", "0.76643515", "0.766226", "0.7640788", "0.7626631", "0.761478", "0.7585659", "0.75657654", "0.75582254", "0.75396377", "0.753508", "0.7533744", "0.7533155", "0.75306493", "0.752721", "0.752315", "0.75165117", "0.7512872", "0.7499554", "0.7482395", "0.74787265", "0.7477166", "0.74767315", "0.74735737", "0.746597", "0.7464959", "0.74607515", "0.74569494", "0.7453995", "0.74368536", "0.74250215", "0.74226844", "0.74162006", "0.741609", "0.7415174", "0.7414944", "0.7411399", "0.741092", "0.74001735", "0.73935187", "0.7391056", "0.7378165", "0.7367129", "0.7352776", "0.7338354", "0.73336476", "0.7283136", "0.7281853", "0.7281837", "0.7279406", "0.7274548", "0.72640824", "0.72624725", "0.7251957", "0.7248322", "0.7244253", "0.72313297", "0.72240657", "0.7222147", "0.7208701", "0.7208374", "0.7205082", "0.7201441", "0.7190186", "0.718635", "0.716861", "0.7161877", "0.7152589", "0.71513367", "0.7150321", "0.7144073", "0.71400696", "0.7138685", "0.71375906", "0.71335524", "0.71314496", "0.712708", "0.7125086", "0.71220094", "0.7120596", "0.7116165", "0.71136755", "0.7107471", "0.7102792", "0.70988643" ]
0.7876833
2
This function creates the game board for the game
function createGrid(grid) { // The game board and all variables are cleared clearPrevGrid(); // Increment the ids of the squares as they are created let idNumber = 0; // This creates 81 squares to fill the 9x9 grid of the game board for (let i = 0; i < 81; i++) { // This creates a new paragraph element let square = document.createElement("p"); // Checks the pre-defined game boards based on difficulty, to see if the squares should have numbers or be empty if (grid.charAt(i) != "-") { // Assign the correct number to the squares square.textContent = grid.charAt(i); } else { // Add event listener to each blank square square.addEventListener("click", function() { // If noSelect is not disabled if (!noSelect) { // If the square is already selected if (square.classList.contains("selected")) { // Deselect the square selected square.classList.remove("selected"); selectedSquare = null; } else { // Deselect all other squares selected for (let i = 0; i < 81; i++) { qsa(".square")[i].classList.remove("selected"); } // Select square and update selectedSquare variable square.classList.add("selected"); selectedSquare = square; updateSquare(); } } }); } // Assign an id to each square square.id = idNumber; // Increment the id for each square made idNumber ++; // // Add "square" class to each square created square.classList.add("square"); // Adding in a thicker bottom border on these lines to define the game board sections if ((square.id > 17 && square.id < 27) || (square.id > 44 && square.id < 54)) { square.classList.add("bottomBorder"); } // Adding in a thicker border on these right of these lines to define the game board sections (Selects the 3rd and 6th square in each row) if ((square.id + 1) % 9 == 3 || (square.id + 1) % 9 == 6) { square.classList.add("rightBorder"); } // Add square to the game board id("grid").appendChild(square); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function create_game_board(){\n update_number_of_players();\n create_player_areas();\n // create new game\n game_instance.deal_cards();\n \n render_cards();\n apply_card_event_handlers();\n \n game_instance.determine_winners();\n // determine_winners();\n // show_best_hands(); //for diagnostics\n }", "function createBoard(){\n\tdocument.body.style.setProperty('--size', size);\n\tdocument.body.style.setProperty('--grid-size', size+1);\n\n\tvar th = document.createElement('div');\n\tth.className = \"content head\";\n\tth.innerHTML = \"\";\n\tth.id = \"header\"\n\tdom.gameBoard.appendChild(th);\n\t//initialize alphabetical headers\n\tfor (var row = 0; row < size; row++) {\n\t\tvar letter = (row+10).toString(36);\n\t\tvar th = document.createElement('div');\n\t\tth.className = \"content head\";\n\t\tth.innerHTML = letter;\n\t\tth.id = \"header\"\n\t\tdom.gameBoard.appendChild(th);\n\t}\n\n\tfor(var i = 0; i < size; i++){\n\t\tvar th = document.createElement('div');\n\t\tth.className = \"content head\";\n\t\tth.innerHTML = i+1;\n\t\tth.id = \"header\"\n\t\tdom.gameBoard.appendChild(th);\n\n\t\tfor(var x = 1; x <= size; x++){\n\t\t\tvar cell = document.createElement(\"div\");\n\t\t\tcell.classList.add(\"content\");\n\n\t\t\t//logic for borders\n\t\t\tif (x == size){\n\t\t\t\tcell.classList.add(\"child-with-border\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcell.classList.add(\"child\");\n\t\t\t}\n\t\t\tif (i == size-1){\n\t\t\t\tcell.classList.add(\"child-edge\");\n\t\t\t}\n\t\t\tvar num = (i * (size) + x).toString();\n\t\t\tcell.id = \"cell\"+num;\n\t\t\tdom.gameBoard.appendChild(cell);\n\t\t}\n\t}\n}", "function createBoard() {\n\tconst board = document.querySelector('.game');\n\tconst rows = document.createElement('tr');\n\n\t//Create the head row\n\trows.setAttribute('id', 'HeaderRow');\n\trows.classList.add('row');\n\trows.addEventListener('click', (e) => {\n\t\tgamePlay(e);\n\t});\n\n\t//Create the header column and append to header row\n\tfor (let col = 0; col < WIDTH; col++) {\n\t\tconst cols = document.createElement('td');\n\t\tcols.setAttribute('id', `c${col}`);\n\t\tcols.classList.add('colHead');\n\t\trows.append(cols);\n\t}\n\n\t// Append to board\n\tboard.append(rows);\n\n\t//Create the remaining boards\n\tfor (let myRow = 0; myRow < HEIGHT; myRow++) {\n\t\tconst row = document.createElement('tr');\n\t\tfor (let myCol = 0; myCol < WIDTH; myCol++) {\n\t\t\tconst cols = document.createElement('td');\n\t\t\tcols.setAttribute('id', `r${myRow}c${myCol}`);\n\t\t\tcols.dataset.row = myRow;\n\t\t\tcols.dataset.col = myCol;\n\t\t\tcols.classList.add('col');\n\t\t\trow.append(cols);\n\t\t}\n\t\tboard.append(row);\n\t}\n}", "function createBoard(){\n\tdocument.body.style.setProperty('--size', size);//set\n\tdocument.body.style.setProperty('--grid-size', size+1);//set\n\n\tvar th = document.createElement('div');\n\tth.className = \"content head\";\n\tth.innerHTML = \"\";\n\tth.id = \"header\"\n\tdom.gameBoard.appendChild(th);\n\t//initialize alphabetical headers\n\tfor (var row = 0; row < size; row++) {\n\t\tvar letter = (row+10).toString(36);\n\t\tvar th = document.createElement('div');\n\t\tth.className = \"content head\";\n\t\tth.innerHTML = letter;\n\t\tth.id = \"header\"\n\t\tdom.gameBoard.appendChild(th);\n\t}\n\n\tfor(var i = 0; i < size; i++){\n\t\tvar th = document.createElement('div');\n\t\tth.className = \"content head\";\n\t\tth.innerHTML = i+1;\n\t\tth.id = \"header\"\n\t\tdom.gameBoard.appendChild(th);\n\n\t\tfor(var x = 1; x <= size; x++){\n\t\t\tvar cell = document.createElement(\"div\");\n\t\t\tcell.classList.add(\"content\");\n\t\t\t//logic for borderes\n\t\t\tif (x == size){\n\t\t\t\tcell.classList.add(\"child-with-border\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcell.classList.add(\"child\");\n\t\t\t}\n\t\t\tif (i == size-1){\n\t\t\t\tcell.classList.add(\"child-edge\");\n\t\t\t}\n\t\t\tvar num = (i * (size) + x).toString();\n\t\t\tcell.id = \"cell\"+num;\n\t\t\tdom.gameBoard.appendChild(cell);\n\t\t}\n\t}\n}", "function createBoard() {\n\t// clear previous board and saved word\n\tclearPreviousBoard(letterSpaces);\n\tclearPreviousBoard(guessRemaining);\n\t// reset image to blank board\n\tmanImage.setAttribute('src', `images/hangman7.png`);\n\t// reset the incorrectGuess to 6\n\tincorrectGuess = 6;\n\t// create guesses remaining\n\tfor (let i = 0; i < incorrectGuess; i++) {\n\t\tconst divElement = document.createElement('div');\n\t\tdivElement.classList.add('show-circle');\n\t\tdivElement.setAttribute('id', [i + 1]);\n\t\tguessRemaining.appendChild(divElement);\n\t}\n\n\t// loop through letters array and create divs for all of them\n\tfor (let i = 0; i < letters.length; i++) {\n\t\tconst divElement = document.createElement('div');\n\t\tdivElement.innerText = letters[i];\n\t\tdivElement.classList.add('letter-button');\n\t\tdivElement.setAttribute('id', letters[i]);\n\t\tletterSpaces.appendChild(divElement);\n\t}\n}", "function createBoard() {\n\tfor (let i = 0; i < layout.length; i++) {\n\t\tconst square = document.createElement('div')\n\t\tgrid.appendChild(square)\n\t\tsquares.push(square)\n\n\t\t//add layout to the board\n\t\t//we want to check what is on the board on every position :\n\t\tif (layout[i] === 0) {\n\t\t\tsquares[i].classList.add('pac-dot')\n\t\t} else if (layout[i] === 1) {\n\t\t\tsquares[i].classList.add('wall')\n\t\t} else if (layout[i] === 2) {\n\t\t\tsquares[i].classList.add('ghost-lair')\n\t\t} else if (layout[i] === 3) {\n\t\t\tsquares[i].classList.add('power-pellet')\n\t\t}\n\t}\n}", "function makeBoard() {\n // Game mechanics code -- to keep track of the game state\n for (let row = 0; row < HEIGHT; row++) {\n let currentRow = [];\n for (let columns = 0; columns < WIDTH; columns++) {\n currentRow.push(null);\n }\n board.push(currentRow);\n }\n}", "createBoard() {\n\t\tfor (let i = 0; i < 6; i++) {\n\t\t\tfor (let j = 0; j < 6; j++) {\n\t\t\t\tlet tile = new MyTile(this.scene, this);\n\t\t\t\tlet pieceSize = 0.395 + 0.005;\n\t\t\t\ttile.addTransformation(['translation', -3 * pieceSize + pieceSize * j, -3 * pieceSize + pieceSize * i, 0]);\n\t\t\t\tthis.tiles.push(tile);\n\t\t\t}\n\t\t}\n\t\tfor (let i = 0; i < 8; i++) {\n\t\t\tthis.whitePieces.push(new MyPieceWhite(this.scene, 'whitePiece'));\n\t\t\tthis.blackPieces.push(new MyPieceBlack(this.scene, 'blackPiece'));\n\t\t}\n\t}", "function createGame() {\n const rowClassNames = ['topRow', 'middleRow', 'bottomRow'];\n const cellClassNames = ['LeftCell', 'CenterCell', 'RightCell'];\n const rowLength = rowClassNames.length;\n const columnLength = cellClassNames.length;\n const gameBoardContainer = document.querySelector('.gameBoardContainer');\n toggleHideElement('.inputs');\n toggleHideElement('.avatarOptions');\n toggleHideElement('.startBtn');\n for (let gridX = 0; gridX < rowLength; gridX++) {\n let row = document.createElement('div');\n row.classList.add(rowClassNames[gridX]);\n gameBoardContainer.appendChild(row);\n for (let gridY = 0; gridY < columnLength; gridY++) {\n let cell = document.createElement('div');\n let cellName = rowClassNames[gridX] + cellClassNames[gridY];\n cell.classList.add(cellName);\n cell.onclick = () => placePlayerMarker(cell);\n row.appendChild(cell);\n }\n }\n updatePlayer(playerOne);\n updatePlayer(playerTwo);\n updateAnnouncementBoard();\n}", "function createBoard() {\n for (let i=0; i < width*width; i++) {\n square = document.createElement('div')\n square.innerHTML = 0\n gridDisplay.appendChild(square)\n squares.push(square)\n }\n generate()\n generate()\n }", "function createBoard() \n{\n\tvar grid = $('#grid');\n\t\n\tfor(var row = 0; row < boardSize; row++) \n\t{\n\t\tvar rowDiv = $('<div class=\"row\"></div>');\n\n\t\tfor(var col = 0; col < boardSize; col++)\n\t\t{\n\t\t\trowDiv.append('<div id=\"s' + row + col + '\" class=\"col square\" row=\"' + row + '\" col=\"' + col + '\"><div class=\"square-interior\"><p></p></div></div>');\n\t\t}\n\n\t\tgrid.append(rowDiv);\n\t}\n\n\t//Spawn a square somewhere to start off the game\n\tspawnTile();\n}", "function createBoard() {\r\n for(let i=0;i<width*width;i++)\r\n {\r\n square = document.createElement('div')\r\n square.innerHTML = 0\r\n gridDisplay.appendChild(square)\r\n squares.push(square)\r\n }\r\n generate()\r\n generate()\r\n\r\n\r\n }", "function buildBoard(){\n\n\t\tvar boardSize = (GAME.board.width * defaultTile.tileSize) + 200; //padding\n\n\t\t//$gamearea.style.maxWidth = (boardSize + 20) +'px'; //extra space for scroll bar\n\t\t$map.style.height = boardSize +'px';\n\t\t$map.style.width = boardSize +'px';\n\t\t\n\t\t//Build our board! //0 or 1 based?\n\t\tfor(var w = 0; w < GAME.board.width; w++){\n\t\t\tGAME.board.tiles[w] = [];\n\t\t\tGAME.NPCs[w] = [];\n\t\t\tfor(var h = 0; h < GAME.board.height; h++){\t\n\n\t\t\t\t//Put our tile into our state board\n\t\t\t\tGAME.board.tiles[w][h] = createTile(w,h);\n\t\t\t\t\n\t\t\t\t//Creating a bunch of random GAME.NPCs\n\t\t\t\tif( (w + h) % 10 == 0){\n\t\t\t\t\tGAME.NPCs[w][h] = createNPC(w,h);\n\t\t\t\t}\n\n\t\t\t\t//tileHolder.appendChild(board.tiles[w][h].element);\n\t\t\t}\n\t\t}\n\n\t\tdisplayBoard(GAME.board);\n\t\tdisplayNPCs(GAME.NPCs);\n\n\t\t//we need to build our graph array AFTER npcs have been added so we know if the tiles are passable\n\t\tbuildGraphArray();\n\t}", "function createBoard() {\n var board = {squares:[]};\n\n for (var x = 0; x < 8; x++) {\n for (var y = 0; y < 8; y++) {\n var asquare = square({x:x, y:y});\n if (asquare.position.y === 0 || asquare.position.y === 1 || asquare.position.y === 6 || asquare.position.y === 7) {\n var colour = (asquare.position.y === 0 || asquare.position.y === 1) ? \"red\" : \"black\";\n asquare.piece = new pieces.Piece({side:colour, position:asquare.position});\n }\n board['squares'][board['squares'].length] = asquare;\n }\n }\n board.id = createGameCheck(board);\n board.asJson = function () {\n var json = [];\n board.squares.forEach(function (sq, inx) {\n json[json.length] = sq.asJson();\n });\n return json;\n\n };\n return board;\n }", "function createBoard() {\n window.board = new Board(4, 13);\n createCards();\n window.board.placeCards();\n}", "makeBoardOnScreen(){\n // Here we'll create a new Group\n for (var i=0; i < game.n; i++) {\n for (var j=0; j < game.n; j ++) {\n //initialize 2D array board to be empty strings\n for (var k=0; k < game.n; k++) {\n for (var l=0; l < game.n; l++) {\n //create square\n var square = game.addSprite(game.startingX + i*game.squareSize*3 + k*game.squareSize, game.startingY + j * game.squareSize*3 + l*game.squareSize, 'square');\n //allow square to respond to input\n square.inputEnabled = true\n //indices used for the 4D array\n square.bigXindex = i\n square.bigYindex = j\n square.littleXindex = k\n square.littleYindex = l\n //make have placePiece be called when a square is clicked\n square.events.onInputDown.add(game.placePiece, game)\n }\n }\n }\n }\n game.drawLines()\n }", "function makeBoard() {\n\t// TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n\t//loop over HEIGHT (6) times to signify the 6 rows\n\tfor (let i = 0; i < HEIGHT; i++) {\n\t\t//create an empty array\n\t\tlet arr = [];\n\t\t//push the empty array into the empty \"board\" array\n\t\tboard.push(arr);\n\t\t//loop over WIDTH times (7) to create the length of each row\n\t\tfor (let i = 0; i < WIDTH; i++) {\n\t\t\t//push \"null\" into each \"arr\" array\n\t\t\tarr.push(null);\n\t\t}\n\t}\n}", "function makeBoard() {\n for (let y = 0; y < HEIGHT; y++) {\n board.push(Array.from({ length: WIDTH }));\n }\n makeHtmlBoard();\n}", "function createBoard(rows, columns) {\n for (let i = 0; i < rows; i++) {\n board.push([]);\n for (let j = 0; j < columns; j++) {\n if (i === 0 || i === rows - 1 || j === 0 || j === columns - 1) {\n board[i][j] = [\n { type: 'wall', visual: '#', position: { row: i, column: j } },\n ];\n } else {\n board[i][j] = [\n { type: 'grass', visual: '.', position: { row: i, column: j } },\n ];\n }\n }\n }\n}", "function createBoard() {\n for (let i = 0; i < width * width; i++) {\n //every time it loops we want to create a div\n //using .createElement\n const square = document.createElement('div');\n //we want to make the divs draggable. so we just use the\n //setAttribute function and set draggable to true\n square.setAttribute('draggable', true);\n //we also want to use setAttribute to give each square a unique ID\n square.setAttribute('id', i);\n //set a random number based on the candy colors length and a whole number\n let randomColor = Math.floor(Math.random() * candyColors.length);\n //set that color background for the square at this index\n square.style.backgroundImage = candyColors[randomColor];\n //next we add that div to the grid with appendChild\n grid.appendChild(square);\n //we also want to store these squares into an array\n squares.push(square);\n }\n }", "function boardCreate() {\n let board = [\n [' ', ' ', ' '],\n [' ', ' ', ' '],\n [' ', ' ', ' '],\n ];\n\n return board;\n}", "function makeBoard() {\n\t// TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tboard.push(Array.from({ length: WIDTH }));\n\t}\n}", "function makeBoard() {\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tconst row = [];\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\trow.push(null);\n\t\t}\n\t\tboard.push(row);\n\t}\n}", "create_board() {\n console.log(\"creating board\")\n const $board = $(this.selector)\n for (let i = 0; i < this.row; i++) {\n let $row = $('<div>').addClass('row')\n for (let j = 0; j < this.col; j++) {\n let $col = $('<div>').addClass('col empty').attr('row', i).attr('col', j)\n $row.append($col)\n }\n $board.append($row)\n }\n }", "function makeBoard() {\n\tfor (let row = 0; row < HEIGHT; row++) {\n\t\tlet c = [];\n\t\tboard.push(c);\n\t\tfor (let col = 0; col < WIDTH; col++) {\n\t\t\tc.push(null);\n\t\t}\n\t}\n}", "generateBoard() {\n for (let i = 0; i < this.rows; i++) {\n let row = [];\n for (let i = 0; i < this.cols; i++) row.push(new Tile(0, false));\n this.tiles.push(row);\n }\n this.setMines();\n }", "function createBoard() {\n for (let i = 0; i < width * width; i++) {\n const square = document.createElement(\"div\");\n //put this child into the gird\n grid.appendChild(square);\n squares.push(square);\n\n // Assigning a random colour to each div\n let randomColor = Math.floor(Math.random() * coloursOfCancy.length);\n square.style.backgroundImage = coloursOfCancy[randomColor];\n\n //To drag each square and give unique ID to each cell so we can see which square is actually moved.\n square.setAttribute(\"draggable\", \"true\");\n square.setAttribute(\"id\", i);\n }\n }", "function createHTMLBoard() {\n $board.innerHTML = '';\n $board.applyClassToTile = applyClassToTile;\n\n const coords = new Coords();\n\n let $row;\n for (let i = 0; i < coords.length; i++) {\n // create a new row div at the start of each row\n if (coords[i] % 10 === 1) {\n $row = document.createElement('div');\n $row.className = 'row board-row';\n }\n\n // append either a tile to the row\n const $tile = document.createElement('div');\n $tile.className = 'tile';\n $tile.id = coords[i];\n $row.append($tile);\n\n // append the row to the board at the end of each row\n if (coords[i] % 10 === 8) {\n $board.append($row);\n }\n }\n}", "function makeBoard() {\n //Make an empty array for board propert cells\n board.cells = [];\n for (let rowNum = 0; rowNum < gridSize; rowNum++) {\n for (let colNum = 0; colNum < gridSize; colNum++) {\n board.cells.push({\n row: rowNum,\n col: colNum,\n isMine: Math.round(Math.random() >= 0.7),\n isMarked: false,\n hidden: true,\n });\n }\n }\n}", "function makeBoard() {\n // TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n const arr = [];\n for (let i = 0; i < WIDTH; i++) {\n arr[i] = null;\n }\n for (let i = 0; i < HEIGHT; i++) {\n board[i] = [...arr];\n }\n}", "function createBoard() {\n // How big can each square be?\n // Add 2 to allow for one square's worth of padding on either side\n var squareWidth = Math.round(window.innerWidth / (totalCols + 2));\n console.log(\"width: \" + squareWidth);\n var squareHeight = Math.round(window.innerHeight / (totalRows + 2));\n console.log(\"height: \" + squareHeight);\n\n // Choose the smaller of the two dimensions so both height and width\n // will fit in the viewport and still be a square\n var bestDimension = Math.min(squareWidth, squareHeight);\n console.log(\"Squares should be: \" + bestDimension);\n\n\n // store the board div in a variable\n var gameBoardDiv = $(\"#board\");\n\n // loop to print rows of squares\n for (var rowNum = 1; rowNum <= totalRows; rowNum++) {\n // Create a new row\n var rowOfSquares = $(\"<div>\");\n // give the row the class of \"row\" (for Bootstrap)\n rowOfSquares.addClass(\"row justify-content-center\");\n // add the row to the gameboard\n gameBoardDiv.append(rowOfSquares);\n\n // loop to print the squares in each row\n for (var colNum = 1; colNum <= totalCols; colNum++) {\n // create an empty element to be a square on the board\n var square = $(\"<span>\");\n // give the square its row number as data\n square.data(\"row\", rowNum);\n // give the square its column number as data\n square.data(\"col\", colNum);\n // set the width and height of the square\n square.width(bestDimension);\n square.height(bestDimension);\n // give the square the class of \"square\" to make it inline-block\n square.addClass(\"square\");\n // display the square's row and column info\n // square.html(`Row ${rowNum}<br>Col ${colNum}`); //don't need\n // make the square run a function when clicked\n square.click(humanPlayerTurn);\n // color of the squares\n square.css(\"background-color\", \"grey\");\n\n // add the square to the current row\n rowOfSquares.append(square);\n }\n }\n }", "function makeBoard() { // creates in-memory board to track board movements\n for(let y = 0; y < HEIGHT; y++){\n board.push([])\n for(let x = 0; x < WIDTH; x++){\n board[y].push(null)\n }\n }\n}", "function buildBoard(){\n\t \t\tvar mineCount = 0;\n\t \t\tfor (var i = 0; i < ROWS; i+=1) {\n\t\t\t\tfor (var j = 0; j < COLS; j+=1) {\n\t\t\t\t\tvar x_shift = Math.floor(0.5*start) + i*stepW;\n\t\t\t\t\tvar y_shift = Math.floor(0.5*start) + j*stepH;\n\t\t\t\t\tvar circleCol = randomColorGenerator(x_shift,y_shift);\n\t\t\t\t\tvar invertedCol = getInvertedColors(circleCol);\n\t\t\t\t\tvar myCircle = new Path.Circle(new Point(x_shift+circleSize,y_shift+circleSize),circleSize).fillColor = circleCol;\n\t\t\t\t\t//initialise space object\n\n\n\t\t\t\t\tvar spaceObj = {\n\t\t\t\t\t\t\t\t\tindex: n, \n\t\t\t\t\t\t\t\t\tcolor: circleCol,\n\t\t\t\t\t\t\t\t\toutline: invertedCol,\n\t\t\t\t\t\t\t\t\tcircleRef: myCircle,\n\t\t\t\t\t\t\t\t\tpos_x: 0, pos_y: 0, \n\t\t\t\t\t\t\t\t\tholdsMine: 0, \n\t\t\t\t\t\t\t\t\tadjacentNeighbours: 0, \n\t\t\t\t\t\t\t\t\tclicked: false,\n\t\t\t\t\t\t\t\t\tflagged: false,\n\t\t\t\t\t\t\t\t\tneighbourIndexList: []\n\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\tspaceObj.pos_x = x_shift+circleSize;\n\t\t\t\t\tspaceObj.pos_y = y_shift+circleSize;\n\t\t\t\t\tspaceObj.holdsMine = assignMine();\n\n\t\t\t\t\tif(spaceObj.holdsMine){\n\t\t\t\t\t\tmineCount++;\n\t\t\t\t\t}\n\n\t\t\t\t\tspaces.push(spaceObj);\n\t\t\t\t\tn++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tplayerStats.totalMines = mineCount;\n\t\t\tplayerStats.flags = mineCount;\n\t \t}", "function createBoard() {\n let html = ``,\n color = \"black\";\n for (i = 1; i < 9; i++) {\n if (i % 2) {\n color = \"white\";\n } else {\n color = \"black\";\n }\n for (j = 1; j < 9; j++) {\n html += `<div id=${i},${j} class='board ${color}' ></div>`;\n if (color == \"black\") {\n color = \"white\";\n } else {\n color = \"black\";\n }\n }\n }\n document.getElementById(\"root\").innerHTML = html;\n}", "function createBoard() {\n const board = document.getElementById(\"board\");\n\n for (let y = 0; y < NROWS; y++) {\n const row = document.createElement(\"tr\");\n for (let x = 0; x < NCOLS; x++) {\n const cell = document.createElement(\"td\");\n cell.id = y + \"-\" + x;\n row.appendChild(cell);\n }\n board.appendChild(row);\n }\n}", "function makeBoard() {\n\t// TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n\tfor (let i = 0; i < HEIGHT; i++) {\n\t\tboard.push([]);\n\t\tfor (let j = 0; j < WIDTH; j++) {\n\t\t\tboard[i].push(null);\n\t\t}\n\t}\n}", "createGameBoard() {\n function tileClickHandler() {\n const row = parseInt(this.id.split('_')[1][0], 10);\n const col = parseInt(this.id.split('_')[1][1], 10);\n if (!player.getCurrentTurn() || !game) {\n alert('Its not your turn!');\n return;\n }\n\n if ($(this).prop('disabled')) {\n alert('This tile has already been played on!');\n return;\n }\n // Update board after your turn.\n game.playTurn(this);\n game.updateBoard(player.getPlayerType(), row, col, this.id);\n\n player.setCurrentTurn(false);\n player.updatePlaysArr(1 << ((row * 3) + col));\n\n game.checkWinner();\n }\n for (let i = 0; i < 3; i++) {\n this.board.push(['', '', '']);\n for (let j = 0; j < 3; j++) {\n $(`#button_${i}${j}`).on('click', tileClickHandler);\n }\n }\n }", "function createBoard() {\r\n // We'll use a for loop to iterate through all the elemtents of the layout array:\r\n for (let i = 0; i < layout.length; i++) {\r\n // For each element we create a square:\r\n const square = document.createElement('div')\r\n // Append the square to our grid:\r\n grid.appendChild(square)\r\n // And push the square to our squares array:\r\n squares.push(square)\r\n\r\n // Now we color each square depending on its number, by adding the corresponding class:\r\n if (layout[i] === 0) {\r\n squares[i].classList.add('pac-dot')\r\n } else if (layout[i] === 1) {\r\n squares[i].classList.add('wall')\r\n } else if (layout[i] === 2) {\r\n squares[i].classList.add('ghost-lair')\r\n } else if (layout[i] === 3) {\r\n squares[i].classList.add('power-pellet')\r\n }\r\n }\r\n}", "function buildBoard() {\n\t// DONE: Create the Matrix 10 * 12\n\tvar board = [];\n\tfor(var i = 0; i< ROWS; i++) {\n\t\tboard[i] = [];\n\t\tfor(var j = 0; j< COLS; j++) {\n\t\t\t// DONE: Put FLOOR everywhere and WALL at edges\n\t\t\tvar cell = {type: FLOOR, gameElement: null};\n\t\t\tif(i === 0 || j === 0 || i === ROWS - 1 || j === COLS -1 ) {\n\t\t\t\tcell.type = WALL;\n\t\t\t}\n\t\t\tboard[i][j] = cell;\n\t\t}\n\t}\n\t\n\t// DONE: Place the gamer\n\tboard[gGamerPos.i][gGamerPos.j].gameElement = GAMER;\n\t\n\tfor (var i = 0; i < gWindowsPos.length; i++) {\n\t\tvar currWindow = gWindowsPos[i].pos;\n\t\tboard[currWindow.i][currWindow.j].type = FLOOR;\n\t}\n\n\t// console.log(board);\n\treturn board;\n}", "function makeBoard() {\n\tfor (let h = 0; h < HEIGHT; h++) {\n\t\t//outer loop will allow us to build 7 rows (WIDTH) for every iteration through the column (HEIGHT)\n\t\tlet rowArray = []; //initialize an interal array\n\t\tfor (let w = 0; w < WIDTH; w++) {\n\t\t\trowArray[w] = 0; //increment the array each time through the loop\n\t\t}\n\t\tboard.push(rowArray); //finish by pushing the newly made array into the board array\n\t}\n}", "function createBoard() {\n debug(\"createBoard\");\n shuffle(cardList);\n cardList.forEach(function(i) {\n newCard = document.createElement('li');\n newIcon = document.createElement('i');\n deck = document.querySelector('.deck');\n \n newCard.setAttribute(\"class\", \"card\");\n newIcon.setAttribute(\"class\", i);\n deck.appendChild(newCard);\n deck.lastChild.appendChild(newIcon);\n })\n evtListener(); \n }", "function makeHtmlBoard() {\n\t// TODO: get \"htmlBoard\" variable from the item in HTML w/ID of \"board\"\n\tconst newBoard = document.querySelector('#board');\n\n\t// TODO: add comment for this code\n\t// this part will create the header or first row where the token will be displayed and each column, and will add an Id, class and eventlistener\n\tconst top = document.createElement('tr');\n\ttop.setAttribute('id', 'column-top');\n\ttop.addEventListener('click', handleClick);\n\ttop.classList.add('p1');\n\n\tfor (let x = 0; x < WIDTH; x++) {\n\t\tconst headCell = document.createElement('td');\n\t\theadCell.setAttribute('id', x);\n\t\ttop.append(headCell);\n\t}\n\tnewBoard.append(top);\n\n\t// TODO: add comment for this code\n\t// this part will create the chart of the game with 6 rows and 7 columns and the value of each cell represented by [y-x]\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tconst row = document.createElement('tr');\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst cell = document.createElement('td');\n\t\t\tcell.classList.add('item');\n\t\t\tcell.setAttribute('id', `${y}-${x}`);\n\t\t\trow.append(cell);\n\t\t}\n\t\tnewBoard.append(row);\n\t}\n}", "function makeHtmlBoard() {\n\t// TODO: get \"htmlBoard\" variable from the item in HTML w/ID of \"board\"\n\tconst htmlBoard = document.querySelector('#board');\n\n\t// TODO: create row at the top (which players drop in pieces)\n\tconst top = document.createElement('tr');\n\ttop.setAttribute('id', 'column-top');\n\ttop.addEventListener('click', handleClick);\n\n\t// TODO: create individual cells for the row at the top (which players drop in pieces)\n\tfor (let x = 0; x < WIDTH; x++) {\n\t\tconst headCell = document.createElement('td');\n\t\theadCell.setAttribute('id', x);\n\t\ttop.append(headCell);\n\t}\n\thtmlBoard.append(top);\n\n\t// TODO: create individual cells for the rest of the board (where the game is played on)\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tconst row = document.createElement('tr');\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst cell = document.createElement('td');\n\t\t\tcell.setAttribute('id', `${y}-${x}`);\n\t\t\trow.append(cell);\n\t\t}\n\t\thtmlBoard.append(row);\n\t}\n}", "function makeBoard() {\n // TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n for (let i = 1; i <= HEIGHT; i++) {\n board.push(Array.from({ length: WIDTH }));\n }\n}", "function makeBoard() {\n \n // loops through starting at Y grid position 0-0,pushing to the board array each coordinate for x at y, 6X7\n for (let y = 0; y < HEIGHT; y++) {\n board.push(Array.from({length: WIDTH}));\n }\n}", "function buildBoard(size){\n\t\t\t$(\"#board\").append( $(\"<table id='boardId'>\").addClass(\"boardTable\") );\n\t\t\tfor (i = 0; i < size; ++i) {\n\t\t\t\t$(\".boardTable\").append( $(\"<tr>\").addClass(\"boardRow\") );\n\t\t\t\tfor (j = 0; j < size; ++j) {\n\t\t\t\t\t$(\".boardRow:last\").append( $(\"<td>\").addClass(\"boardCell\").data(\"column\",j)\n\t\t\t\t\t.click(function() {\n var __this = this;\n\t\t\t\t\t\tif(turn==0) {\n if (firstMove) {\n persistNewGame(function(err,game){\n if (err) {\n Materialize.toast('Sorry, something went wrong with creating the new game.', 4000);\n }\n firstMove = false;\n gameId = game.id;\n playColumn(jQuery.data(__this,\"column\"));\n });\n } else {\n playColumn(jQuery.data(__this,\"column\"));\n }\n }\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t}\n\t\t}", "_createBoard() {\n let map = this.map = this._createHexagonMap();\n\n for (let q in map) {\n for (let r in map[q]) {\n this._createSprite(map[q][r]);\n }\n }\n }", "setupGameBoard()\n {\n this.gameBoard.innerHTML = \"\";\n let newStyle = \"grid-template-columns: repeat(\" + this.xSize + \", 1fr); grid-template-rows: repeat(\" + this.ySize + \", 1fr);\";\n this.gameBoard.setAttribute(\"style\", newStyle);\n\n for (let row = 0; row < this.ySize; row++)\n {\n for (let col = 0; col < this.xSize; col++)\n {\n let newTile = document.createElement(\"div\");\n if (((col+row) % 2) == 0)\n {\n newTile.className = \"tile\";\n }\n else\n {\n newTile.className = \"tile odd\";\n }\n\n newTile.setAttribute(\"data-x\", col);\n newTile.setAttribute(\"data-y\", row);\n \n let tileStyle = \"grid-row: \" + (row+1) + \"; grid-column: \" + (col+1) + \";\";\n newTile.setAttribute(\"style\", tileStyle);\n\n this.gameState[col][row].tile = newTile;\n this.gameBoard.appendChild(newTile);\n }\n \n }\n\n this.setUpTileListeners();\n }", "function createGameBoards() {\r\n for (i=0; i < 10; i++) {\r\n playerCoordinateEl.push([]);\r\n opponentCoordinateEl.push([]);\r\n for (j=0; j < 10; j++) {\r\n playerCoordinateEl[i][j] = document.createElement('div');\r\n opponentCoordinateEl[i][j] = document.createElement('div');\r\n playerCoordinateEl[i][j].id = `p-r${i}c${j}`;\r\n opponentCoordinateEl[i][j].id = `o-r${i}c${j}`;\r\n playerBoardEl.appendChild(playerCoordinateEl[i][j]);\r\n opponentBoardEl.appendChild(opponentCoordinateEl[i][j]);\r\n }\r\n }\r\n}", "function setupGame() {\n const boardElement = document.getElementById('board')\n\n for (let y = 0; y < boardHeight; ++y) {\n const row = []\n for (let x = 0; x < boardWidth; ++x) {\n const cell = {}\n\n // Create a <div></div> and store it in the cell object\n cell.element = document.createElement('div')\n\n // Add it to the board\n boardElement.appendChild(cell.element)\n\n // Add to list of all\n row.push(cell)\n }\n\n // Add this row to the board\n board.push(row)\n }\n\n startGame()\n\n // Start the game loop (it will call itself with timeout)\n gameLoop()\n }", "function _makeGrid () {\n let board = [];\n for (let i = 0; i < 8; i++) {\n let row = [];\n for (let j = 0; j < 8; j++) {\n row.push(null);\n }\n board.push(row);\n }\n let whites = [[3, 3], [4, 4]];\n let blacks = [[4, 3], [3, 4]];\n whites.forEach(coordinates => {\n let piece = new Piece(\"white\");\n board[coordinates[0]][coordinates[1]] = piece;\n });\n blacks.forEach(coordinates => {\n let piece = new Piece(\"black\");\n board[coordinates[0]][coordinates[1]] = piece;\n });\n return board;\n}", "function setupBoard() {\n\tif (boardRows !== difficulty) {\n\t\tboard.innerHTML = \"\";\n\t\tboardRows = difficulty;\n\t\tfor (let i = 0; i <= difficulty; i++) {\n\t\t\tconst rowDiv = document.createElement('div');\n\t\t\trowDiv.className = 'row';\n\t\t\tfor (let i=0; i < 3; i++) {\n\t\t\t\tconst squareBorder = document.createElement('div');\n\t\t\t\tsquareBorder.className = 'square-border';\n\t\t\t\tconst squareInner = document.createElement('div');\n\t\t\t\tsquareInner.className = 'square';\n\t\t\t\tsquareBorder.appendChild(squareInner);\n\t\t\t\trowDiv.appendChild(squareBorder);\n\t\t\t}\n\t\t\tboard.appendChild(rowDiv);\n\t\t}\n\n\t\tsquareDivs = document.querySelectorAll('.square');\n\t\tsquareBorders = document.querySelectorAll('.square-border');\n\t\taddBoardListeners();\n\t}\n}", "function buildBoard() {\r\n var boardLength = gCurrLevel.boardSize\r\n var board = [];\r\n for (var i = 0; i < boardLength; i++) {\r\n board[i] = [];\r\n for (var j = 0; j < boardLength; j++) {\r\n var cell = {\r\n type: EMPTY,\r\n minesAroundCount: 0,\r\n isShown: false,\r\n isMine: false,\r\n isMarked: false,\r\n isCanClick: true\r\n }\r\n board[i][j] = cell;\r\n }\r\n }\r\n return board;\r\n}", "function makeHtmlBoard() {\n // DONE - TODO: get \"board\" variable from the item in HTML w/ID of \"board\"\n let board = document.getElementById('board');\n if (board === null) {\n return;\n }\n\n // TODO: add comment for this code\n // creates top row with id x\n var top = document.createElement(\"tr\");\n top.setAttribute(\"id\", \"column-top\");\n top.addEventListener(\"click\", handleClick);\n\n for (var x = 0; x < WIDTH; x++) {\n var headCell = document.createElement(\"td\");\n headCell.setAttribute(\"id\", x);\n top.append(headCell);\n }\n board.append(top);\n\n // TODO: add comment for this code\n // creates rows below top row w/ id = 'y-x' for coordinates on board\n for (var y = 0; y < HEIGHT; y++) {\n const row = document.createElement(\"tr\");\n for (var x = 0; x < WIDTH; x++) {\n const cell = document.createElement(\"td\");\n cell.setAttribute(\"id\", `${y}-${x}`);\n row.append(cell);\n }\n board.append(row);\n }\n}", "function drawGame() {\n var x, y;\n var gameTable = '<table class=\"game-board\">';\n\n // The higher rows get added to the table first\n for (y = board.BOARD_HEIGHT - 1; y > -1; y--) {\n // Generate each row\n gameTable += '<tr>';\n for (x = 0; x < board.BOARD_WIDTH; x++) {\n gameTable += '<td class=\"' + board.space[x][y] + '\">&nbsp;</td>';\n }\n gameTable += '</tr>';\n }\n gameTable += '</table>';\n // Leave in plain js rather than jquery for efficiency\n document.getElementById(\"game\").innerHTML = gameTable;\n }", "makeBoard() {\n // Initialize the board to be an empty array\n this.board = [];\n // For loop to create the board's empty elements using the values of height and width\n for (let y = 0; y < this.height; y++) {\n this.board.push(Array.from({ length: this.width }));\n }\n }", "function _makeBoard(){\n var board = document.createElement('div');\n board.classList.add('board')\n\n var roundsContainer = document.createElement('div');\n roundsContainer.classList.add('rounds-container');\n\n var scoreContainer = _makeScoreContainer();\n\n board.append(roundsContainer, scoreContainer.scoreContainer);\n return {\n board:board,\n roundsContainer: roundsContainer,\n ... scoreContainer\n }\n}", "function createBoard(grid, squares) {\n for (let i = 0; i < nbSquares * nbSquares; i++) {\n const square = document.createElement('div');\n square.dataset.id = i; // we give each square an id\n grid.appendChild(square);\n squares.push(square);\n }\n }", "function createBoard() {\n for (let i = 0; i < numSquaresY; i++) {\n board[i] = [];\n for (let j = 0; j < numSquaresX; j++) {\n board[i][j] = new Square(i, j, j * xIncrement, i * yIncrement + headerHeight);\n }\n }\n}", "function makeHtmlBoard() {\n\tlet htmlBoard = document.getElementById('board');\n\n\t// Creates a row with the id of column-top\n\t// Inside of the row creates cells with the id according to the lenght of WIDTH and it adds to the column-top\n\tlet top = document.createElement('tr');\n\ttop.setAttribute('id', 'column-top');\n\ttop.addEventListener('click', handleClick);\n\n\tfor (let x = 0; x < WIDTH; x++) {\n\t\tlet headCell = document.createElement('td');\n\t\theadCell.setAttribute('id', x);\n\t\tlet arrow = document.createElement('img');\n\t\tarrow.setAttribute('src', `arrow.png`);\n\t\tarrow.setAttribute('id', x);\n\t\theadCell.appendChild(arrow);\n\t\ttop.append(headCell);\n\t}\n\thtmlBoard.append(top);\n\n\t// Creates rows and cell according to lenght of WIDTH and HEIGHT\n\t// For each cell, an ID is given according to its location\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tconst row = document.createElement('tr');\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst cell = document.createElement('td');\n\t\t\tcell.setAttribute('id', `${y}-${x}`);\n\t\t\trow.append(cell);\n\t\t}\n\t\thtmlBoard.append(row);\n\t}\n}", "function makeHtmlBoard() {\n // TODO: get \"htmlBoard\" variable from the item in HTML w/ID of \"board\"\n const htmlBoard = document.querySelector(\"#board\");\n \n // TODO: add comment for this code\n // creates a top row for clicking the game pieces with id \n // adding event handler\n const top = document.createElement(\"tr\");\n top.setAttribute(\"id\", \"column-top\");\n top.addEventListener(\"click\", handleClick);\n // creating td/cells for each column in the top row\n // set id for each cell\n for (let x = 0; x < WIDTH; x++) {\n const headCell = document.createElement(\"td\");\n headCell.setAttribute(\"id\", x);\n top.append(headCell);\n }\n htmlBoard.append(top);\n\n // TODO: add comment for this code\n // creating new rows and adding cells below the top row\n // setting an id for each cell\n // append cell to row\n for (let y = 0; y < HEIGHT; y++) {\n const row = document.createElement(\"tr\");\n for (let x = 0; x < WIDTH; x++) {\n const cell = document.createElement(\"td\");\n cell.setAttribute(\"id\", `${y}-${x}`);\n row.append(cell);\n }\n htmlBoard.append(row);\n }\n}", "function createBoard() {\n var board = [];\n for (var i = 0; i < gCurrLevel.size; i++) {\n board.push([])\n for (var j = 0; j < gCurrLevel.size; j++) {\n board[i][j] = {\n minesAroundCount: 0,\n isShown: false,\n isMine: false,\n isMarked: false,\n emptyNeighborsCount: null\n };\n }\n }\n return board;\n}", "function makeBoard() {\n // set \"board\" to empty HEIGHT x WIDTH matrix array\n board = [...Array(height)].map(arr => [...Array(width)].map(e => ''));\n}", "function makeBoard() {\n clearBoard();\n bombsFlagged = 0;\n cellsOpen = 0;\n updateNumBombs();\n // Now place the bombs on the board\n bombsToPlace = maxNumBombs;\n while (bombsToPlace != 0) {\n placeBombRandomLoc();\n bombsToPlace--; } }", "function makeHtmlBoard() {\n let htmlBoard = document.getElementById('board');\n htmlBoard.innerHTML = '';\n // This code blocks creates a top row assigns it an id of \"column-top\" and assigns a click handler to it\n // Then the code creates a series of cells with an id that corresponds to the column count (left to right)\n let top = document.createElement(\"tr\");\n top.setAttribute(\"id\", \"column-top\");\n top.addEventListener(\"click\", handleClick);\n\n\n for (let x = 0; x < WIDTH; x++) {\n let headCell = document.createElement(\"td\");\n headCell.setAttribute(\"id\", x);\n top.append(headCell);\n }\n htmlBoard.append(top);\n\n // This code creates the rest of the game board. The area that game pieces are placed in\n for (let y = 1; y <= HEIGHT; y++) {\n const row = document.createElement(\"tr\");\n for (let x = 0; x < WIDTH; x++) {\n const cell = document.createElement(\"td\");\n cell.setAttribute(\"id\", `${x}-${HEIGHT - y}`);\n row.append(cell);\n }\n htmlBoard.append(row);\n }\n}", "function createBoard(tilePairs) {\n var gameBoard = $('#game-board');\n var row = $(document.createElement('div'));\n var img;\n _.forEach(tilePairs, function(tile, elementIndex) {\n if (elementIndex > 0 && 0 == (elementIndex % 4)) {\n gameBoard.append(row);\n row = $(document.createElement('div'));\n }\n img = $(document.createElement('img'));\n img.attr({\n src: 'img/tile-back.png',\n alt: 'tile ' + tile.tileNum\n });\n img.data('tile', tile);\n row.append(img);\n });\n gameBoard.append(row);\n}", "function buildBoard(Rows, Cols) {\n var board = [];\n for (var i = 0; i < Rows; i++) {\n board[i] = [];\n for (var j = 0; j < Cols; j++) {\n board[i][j] = {\n isBomb: false,\n coord: {i, j},\n numOfBombsAround: 0,\n isShown: false,\n isFlaged: false,\n textContent: '',\n };\n }\n }\n return board;\n}", "function makeHtmlBoard() {\n\n let htmlBoard = document.getElementById('board');\n\n // Creates row for user interface to handle which column player selects to drop game piece.\n var top = document.createElement(\"tr\");\n top.setAttribute(\"id\", \"column-top\");\n top.addEventListener(\"click\", handleClick);\n\n var clearButton = document.getElementById(\"reset-button\").addEventListener(\"click\", resetBoard);\n\n // Creates column for user interface to handle which column player selects to drop game piece.\n for (var x = 0; x < WIDTH; x++) {\n var headCell = document.createElement(\"td\");\n headCell.setAttribute(\"id\", x);\n top.append(headCell);\n }\n htmlBoard.append(top);\n\n // dynamically creates the main part of html board\n // uses HEIGHT to create table rows\n // uses WIDTH to create table cells for each row\n for (var y = 0; y < HEIGHT; y++) {\n\n let currRow = document.createElement(\"tr\");\n for (var x = 0; x < WIDTH; x++) {\n let currCell = document.createElement(\"td\");\n currCell.id = `${y}-${x}`\n currRow.append(currCell);\n }\n htmlBoard.append(currRow);\n }\n}", "function createGameBoard() {\n // ForEach method called on trueCardArr adds each card into the deck, returning the entire deck at the end\n\ttrueCardArr.forEach(function(card) {\n return deck.innerHTML += card;\n });\n\treturn deck;\n}", "createGameBoard() {\n function tileClickHandler() {\n let row, col;\n \n row = game.getRowFromTile(this.id);\n col = game.getColFromTile(this.id);\n\n //If is not your turn\n if (!player.getCurrentTurn() || !game) {\n alert('Its not your turn!');\n return;\n }\n\n //In gomoku first move for blacks have to be in the middle tile\n if(game.moves == 0 && !(row == 7 && col == 7)){\n alert('You have to put pawn in the middle of grid!');\n return;\n }\n //In gomoku second move for blacks have to be beyond 5x5 grid in the middle\n else if(game.moves == 2 && (row >= 5 && row <= 9 && col >= 5 && col <= 9)){\n alert('You have to put pawn beyond 5x5 grid in the middle!');\n return;\n }\n //If tile has been already played\n else{\n if ($(this).prop('disabled')) {\n alert('This tile has already been played on!');\n return;\n }\n\n //Update board after player turn.\n game.playTurn(this);\n game.updateBoard(player.getPlayerColor(), row, col, this.id);\n\n //Check if player win\n game.checkWinner();\n \n player.setCurrentTurn(false);\n }\n } \n $('#color').css(\"background-color\", `${player.getPlayerColor()}`);\n game.createTiles(tileClickHandler);\n if(player.getPlayerColor() != \"white\" && this.moves == 0){\n game.setTimer();\n }else{\n $(\".center\").prop(`disabled`, true);\n }\n }", "function createBoard() {\n var board = [\n []\n ];\n\n for (let row = 0; row < 7; row++) {\n let tempArr = [];\n for (let col = 0; col < 7; col++) {\n tempArr[col] = \"_\";\n }\n board[row] = tempArr;\n }\n return board;\n}", "function initBoards() {\n let boardIds = [\"playerboard\", \"enemyboard\"]\n let rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];\n // init grey spaces\n for (let boardId of boardIds) {\n let board = document.getElementById(boardId);\n let id = boardId[0];\n for (let row of rows) {\n for (let col = 0; col < 10; col++) {\n let div = document.createElement(\"div\");\n div.id = `${id}${row}${col}`;\n div.className = \"opaque\";\n if (boardId === \"enemyboard\") {\n div.onclick = () => handleBoardClick(div.id);\n }\n board.appendChild(div);\n }\n }\n }\n}", "function makeBoard () {\n // Done TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n //Setting 'board' to empty height x width creates a 2d array\n //that has a height of 6 rows by a width of 7 columns\n //set variable y (columns) to zero; y iterates thru columns until false\n for (let y = 0; y < HEIGHT; y++) {\n //calling board[y] = empty array;\n board[y] = [];\n for (let x = 0; x < WIDTH; x++) {\n //creates an empty/undefined array\n board[y][x] = null;\n }\n }\n}", "function makeBoard() {\n // TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n //2d array to generate the BOARD H x W\n for (let i = 0; i < HEIGHT; i++) {\n let rows = [];\n for (let j = 0; j < WIDTH; j++) {\n rows.push(undefined);\n }\n BOARD.push(rows);\n } \n console.log(BOARD);\n}", "function buildBoard() {\n var size = gLevel.size\n var board = [];\n for (var i = 0; i < size; i++) {\n var row = [];\n for (let j = 0; j < size; j++) {\n var cell = {\n minesAroundCount: 0,\n isShown: false,\n isMine: false,\n isUsedLife: false,\n isMarked: false,\n }\n row.push(cell)\n }\n board.push(row)\n }\n return board;\n}", "function createBoardArr(){\n for(var i = tileAmt; i >= 1; i--){\n for(var j = 1; j <= tileAmt; j++){\n const tmpObj = new Object;\n tmpObj.val = \"tile\";\n tmpObj.empty = true;\n tmpObj.x = i;\n tmpObj.y = String.fromCharCode(64+j);\n tmpObj.tileLocation = tmpObj.x + tmpObj.y;\n if(i % 2 == 0){\n if(j % 2 == 0){ tmpObj.color = \"dark\";}\n else{ tmpObj.color = \"light\";}\n }else{\n if(j % 2 !== 0){ tmpObj.color = \"dark\";}\n else{ tmpObj.color = \"light\";}\n }\n if(tmpObj.color == \"dark\"){tmpObj.legalPlay = true;}\n else{tmpObj.legalPlay = false;}\n boardArr.push(tmpObj);\n }\n }\n}", "function makeHtmlBoard() {\n // TODO: get \"htmlBoard\" variable from the item in HTML w/ID of \"board\"\n let htmlBoard = document.getElementById(\"board\");\n // TODO: add comment for this code\n // create table row in HTML with ID of \"column-top\" and adding event listener of \"click\"\n let top = document.createElement(\"tr\");\n top.setAttribute(\"id\", \"column-top\");\n top.addEventListener(\"click\", handleClick);\n // adding divs to row at top of board with an id of the x-coordinate\n for (let x = 0; x < WIDTH; x++) {\n let headCell = document.createElement(\"td\");\n\n headCell.setAttribute(\"id\", x);\n top.append(headCell);\n }\n // adding top row to board\n htmlBoard.append(top);\n\n // TODO: add comment for this code\n // creating playable space with coodinate IDs (y-x) for each cell... (0,0) in top left\n for (let y = 0; y < HEIGHT; y++) {\n let row = document.createElement(\"tr\");\n \n for (let x = 0; x < WIDTH; x++) {\n let cell = document.createElement(\"td\");\n \n cell.setAttribute(\"id\", `${y}-${x}`);\n row.append(cell);\n }\n htmlBoard.append(row);\n }\n}", "function boardSetup() {\n\n\tclearBoard();\n\t$('#game_info').show();\n\t// add tie break track\n\t$('#tie_break_track').append(\n\t\t$('<span/>').text('Tie Break:')\n\t);\n\tfor (i = 0; i < numPlayers; i ++) {\n\t\tvar c = tieBreak[i];\n\t\t$('#tie_break_track').append(\n\t\t\t$('<div/>')\n\t\t\t\t.addClass('tie_break_token')\n\t\t\t\t.css('background-color', playerColors[c])\n\t\t\t\t.text(Number(i+1))\n\t\t\t\t.attr('title', players[c].username)\n\t\t);\n\t\t// distribute starting resources depending on tie break order\n\t\tplayers[c].money += (startingMoney + Math.floor(i/2));\n\t\tplayers[c].numRibbons += i%2;\n\t}\n\n\t// add status bar\n\tvar $statusBar = $('<div/>').addClass('status_bar')\n\t\t.append(\n\t\t\t$('<span/>').addClass('status_bar--turn'),\n\t\t\t$('<span/>').addClass('status_bar--phase'),\n\t\t\t$('<span/>').addClass('status_bar--text')\n\t\t);\n\n\t$('#status_bar').append($statusBar);\n\n\t// add opponents' boards on the top\n\tfor (i = 0; i < numPlayers; i ++)\n\t\tif (myID != i) {\n\t\t\tvar $board = $('<div/>')\n\t\t\t\t\t.addClass('player_board')\n\t\t\t\t\t.css('background-color', playerColors[i])\n\t\t\t\t\t.val(i);\n\t\t\tvar $vase = $('<div/>').addClass('player_vase').addClass('player_vase--opponent');\n\n\t\t\tfor (j = 0; j < 3; j ++)\n\t\t\t\t$($vase).append(\n\t\t\t\t\t$('<img/>').attr('src', 'img/empty_vase.png')\n\t\t\t\t\t\t.addClass('icon--small empty_vase')\n\t\t\t\t);\n\n\t\t\tvar $upperBoard = $('<div/>').append(\n\t\t\t\t// name \n\t\t\t\t$('<span/>').text(players[i].username)\n\t\t\t\t\t.addClass('player_name'), \n\t\t\t\t// money\n\t\t\t\t$('<img/>').attr('src','img/money_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].money)\n\t\t\t\t\t.addClass('player_money'),\n\t\t\t\t// score\n\t\t\t\t$('<img/>').attr('src','img/score_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].score)\n\t\t\t\t\t.addClass('player_score'),\n\t\t\t\t// time\n\t\t\t\t$('<img/>').attr('src','img/time_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].time)\n\t\t\t\t\t.addClass('player_time'),\n\t\t\t\t$('<br>'),\n\t\t\t\t$vase\n\t\t\t);\n\n\t\t\tvar $lowerBoard = $('<div/>').append(\n\t\t\t\t// ribbons\n\t\t\t\t$('<img/>').attr('src','img/ribbon_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].numRibbons)\n\t\t\t\t\t.addClass('player_ribbon'),\n\t\t\t\t// action cubes\n\t\t\t\t$('<img/>').attr('src','img/action_cube_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].actionCubes)\n\t\t\t\t\t.addClass('player_action_cube'),\n\t\t\t\t// number of played cards\n\t\t\t\t$('<img/>').attr('src','img/played_cards_icon.png')\n\t\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(0)\n\t\t\t\t\t.addClass('player_number_played_cards'),\n\t\t\t\t\n\t\t\t\t$('<br>')\n\t\t\t);\n\n\t\t\tfor (j = 1; j < 4; j ++) {\n\t\t\t\tvar starColor = players[i].bonus[j-1] + 1;\n\t\t\t\t$lowerBoard.append(\n\t\t\t\t\t$('<img/>').attr('src', 'img/bonus_icon' + j + '.png')\n\t\t\t\t\t\t.addClass('icon--small')\n\t\t\t\t\t\t.css('background-color', shopColors[starColor]),\n\t\t\t\t\t$('<span/>').text(0)\n\t\t\t\t\t\t.addClass('bonus_star')\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t$($board).append(\n\t\t\t\t$upperBoard,\n\t\t\t\t$lowerBoard\n\t\t\t);\n\t\t\t$($lowerBoard).css({\n\t\t\t\t\t'background-color': playerColors[i],\n\t\t\t\t\t'z-index': 0\n\t\t\t\t})\n\t\t\t\t.addClass('lower_opponent_board')\n\t\t\t\t.hide();\n\n\t\t\t$('#opponent_board_area').append($board);\n\t\t\tplayers[i].addBoard($board);\n\t\t}\n\n\t\t$('#opponent_board_area').append(\n\t\t\t$('<button/>').text('More')\n\t\t\t\t.addClass('button button--expand_opponent_board')\n\t\t);\n\t// add info to your board at the bottom of the screen\n\t$('#my_board').css('background-color', playerColors[myID])\n\t\t.val(myID);\n\n\t$('#my_name .player_name').text(myusername);\n\n\t// starting resources\n\t$('#my_money .player_money').text(players[myID].money);\n\t$('#my_score .player_score').text(0);\n\t$('#my_ribbon .player_ribbon').text(players[myID].numRibbons);\t\n\t$('#my_action_cube .player_action_cube').text(0);\n\n\t// time_track\n\t$('#my_time_track').append(\n\t\t$('<img/>').attr('src','img/time_track0.png')\n\t\t\t.addClass('time_track_image')\n\t)\n\n\t// the rest\n\t$('#my_number_played_cards span').text(0);\n\t\n\tfor (i = 1; i < 4; i ++) {\n\t\tvar starColor = players[myID].bonus[i-1] + 1;\n\t\t$('#bonus_icon' + i).css('background-color', shopColors[starColor])\n\t\t\t.append(\n\t\t\t\t$('<img/>').attr('src', 'img/bonus_icon' + i + '.png')\n\t\t\t\t\t.addClass('icon')\n\t\t\t\t\t.attr('title', bonusTypeString[i-1])\n\t\t\t);\n\t\t\n\t\t$('#my_bonus' + i).css('background-color', shopColors[starColor])\n\t\t\t.append(\n\t\t\t\t$('<span/>').text(0)\n\t\t\t\t\t.addClass('bonus_star'),\n\t\t\t\t$('<img/>').attr('src', 'img/star_icon' + starColor + '.png')\n\t\t\t\t\t.addClass('icon--small')\n\t\t\t);\n\n\t\t$('#my_vase').append(\n\t\t\t$('<img/>').attr('src', 'img/empty_vase.png')\n\t\t\t\t.addClass('empty_vase')\n\t\t);\n\t}\n\n\t// add tool tokens and popup area that shows all tools with all levels\n\tshops = [[],[],[],[],[],[]];\n\tfor (i = 0; i < 6; i ++)\n\t\tshops[5].push(\n\t\t\tnew toolToken(i)\n\t\t);\n\t\t\n\t$('#tool_lookup').append(\n\t\t$('<button/>').text('Close')\n\t\t\t.addClass('button--expand_tool')\n\t);\n\n\tfor (i = 0; i < 3; i ++ ) {\n\t\t$('#tool_lookup').append(\n\t\t\t$('<br>'),\n\t\t\t$('<span/>').text('level ' + i).css('color', 'white')\n\t\t);\n\t\t$('#tool_lookup').append($('<br>'));\n\t\tfor (j = 0; j < 6; j ++) {\n\t\t\t$('#tool_lookup').append(\n\t\t\t\t$(\"<img/>\")\n\t\t\t\t\t.attr('src', 'img/tool' + j + 'lv' + i + '.jpg' )\n\t\t\t\t\t.addClass('tool--large')\n\t\t\t\t\t.val(i)\n\t\t\t);\n\t\t}\n\t}\n\n\t // add as many achievements as the number of players\n\t$('#achievement_area').empty();\n\t$('#achievement_area--large').empty();\n\t$('#achievement_area').append(\n\t\t$('<span/>').text('Achievements'),\n\t\t$('<br>'),\n\t\t$('<button/>').text('Expand')\n\t\t\t.addClass('button button--expand_achievement')\n\t\t\t.css({'position':'absolute','top':'0'})\n\t);\n\n\tfor (i = 0; i < achievements.length; i ++) {\n\t\tvar type = achievements[i].type;\n\t\tvar $accard = \n\t\t$('#achievement_area').append(\n\t\t\t$('<img/>').attr('src','img/achievement' + type + '.png')\n\t\t\t\t.addClass('achievement_card')\n\t\t\t\t.data({\n\t\t\t\t\ttype: type,\n\t\t\t\t\tindex: i\n\t\t\t\t}),\n\t\t\t$('<span/>').addClass('achievement_claimer_token')\n\t\t);\n\n\t\t$('#achievement_area--large').append(\n\t\t\t$('<img/>').attr('src','img/achievement' + type + '.png')\n\t\t\t\t.addClass('achievement_card--large')\n\t\t\t\t.data({\n\t\t\t\t\ttype: type,\n\t\t\t\t\tindex: i\n\t\t\t\t})\n\t\t);\n\t}\n\n\t$('#achievement_area--large').append(\n\t\t$('<button/>').text('Close')\n\t\t\t.addClass('button button--expand_achievement')\n\t);\n\n\t// initialize board component\n\tplayers[myID].addBoard(\n\t\t$('#my_board')\n\t);\n}", "makeHtmlBoard() {\n // select the HTML element table and set the inner HTML of that table to be blank\n const board = document.getElementById('board');\n board.innerHTML = '';\n\n // make column tops (clickable area for adding a piece to that column). These have to be separate from actual playable squares.\n const top = document.createElement('tr');\n top.setAttribute('id', 'column-top');\n\n //Store a reference to the handleClick bound function so that we can remove the event listener correctly later. \n this.handleGameClick = this.handleClick.bind(this);\n\n // Adding the event listener to the top of the board\n top.addEventListener('click', this.handleGameClick);\n\n for (let x = 0; x < this.width; x++) {\n const headCell = document.createElement('td');\n headCell.setAttribute('id', x);\n top.append(headCell);\n }\n\n board.append(top);\n\n // make main part of board\n for (let y = 0; y < this.height; y++) {\n const row = document.createElement('tr');\n\n for (let x = 0; x < this.width; x++) {\n const cell = document.createElement('td');\n cell.setAttribute('id', `${y}-${x}`);\n row.append(cell);\n }\n\n board.append(row);\n }\n }", "function makeBoard() {\n // TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n while (board.length < HEIGHT){\n let row = [];\n for (let i = 1; i <= WIDTH; i++){\n row.push(null);\n }\n board.push(row);\n }\n}", "function createBoard(grid, squares, width)\n {\n for (let i = 0; i < width * width; i++) // We have a 10x10 board so overall we have 100 places on the board\n {\n const square = document.createElement('div') // create a new board place\n\n square.dataset.id = i // Add an id identifier to the created board place\n\n grid.appendChild(square) // Add the div of the new board place to the input board\n\n squares.push(square) // Add the created place to the input board places array\n }\n }", "function createBoard() {\n shuffledCards = shuffle(cardList);\n shuffledCardsHTML = cardList.map(function(card) {\n return generateCardHTML(card)\n });\n deck.innerHTML = shuffledCardsHTML.join('');\n}", "function createBoard(){\n for(let i=0; i<width*width; i++){\n const square = document.createElement('div');\n square.setAttribute('id', i);\n grid.appendChild(square);\n squares.push(square);\n }\n}", "function CreateGame(y, x, nBombs){\n\tif(BoardState != undefined){\n\t\treturn;\n\t}\n\tvar div = document.getElementById(\"minesweeper\");\n\tvar minesweeper = document.createElement(\"TABLE\");\n\twidth = 0;\n\theight = 0;\n\tfor (var i = x - 1; i >= 0; i--) {\n\t\tvar row = document.createElement(\"TR\");\n\t\tfor (var f = y - 1; f >= 0; f--) {\n\t\t\tvar col = document.createElement(\"TD\");\n\t\t\tcol.innerHTML = '<img src=\"images/HiddenSquare.png\" class=\"square\" height=30 width=30 onclick=\"buttonclick(this);\" xVal=\"' + width + '\" yVal= \"' + height + '\" id=\"' + width.toString() + 'h' + height.toString() + 'w\">';\n\t\t\trow.appendChild(col);\n\t\t\twidth++;\n\t\t}\n\t\tminesweeper.appendChild(row);\n\t\theight++;\n\t\twidth = 0;\n\t};\n\tdocument.getElementById(\"minesweeper\").appendChild(minesweeper);\n\tvar flag = document.createElement(\"BUTTON\");\n\tflag.setAttribute(\"onclick\",\"changeFlag();\");\n\tflag.innerHTML = \"Togge Flag\";\n\tdocument.getElementById(\"minesweeper\").appendChild(flag);\n\n\tBoardState = Board(new WyJS.Integer(y), new WyJS.Integer(x));\n\tinitialiseBoard(nBombs);\n}", "initBoard() {\r\n // Generate a new row\r\n const newRow = (rowNum) => {\r\n const row = document.createElement('div');\r\n row.classList.add('row');\r\n row.classList.add('row-' + rowNum);\r\n console.log(\"row:\"+ row);\r\n return row;\r\n }\r\n // Generate a new column\r\n const newCol = (colNum) => {\r\n const col = document.createElement('div');\r\n col.classList.add('col');\r\n col.classList.add('col-' + colNum);\r\n console.log(\"col:\"+ col);\r\n return col;\r\n }\r\n\r\n // For each number of rows make a new row element and fill with columns\r\n for (let r = 0; r < SnakeGame.NUM_ROWS; r++) {\r\n\r\n const row = newRow(r);\r\n const boardCellsRow = [];\r\n\r\n // For each number of columns make a new column element and add to the row\r\n for (let c = 0; c < SnakeGame.NUM_COLS; c++) {\r\n\r\n const col = newCol(c);\r\n row.appendChild(col);\r\n boardCellsRow.push(col);\r\n\r\n }\r\n\r\n this.board.appendChild(row);\r\n this.boardCells.push(boardCellsRow);\r\n\r\n }\r\n\r\n }", "function buildBoard(){\n for(var i = 0; i < boardArr.length; i++){\n const deTile = document.createElement('div');\n deTile.classList = \"allTile \" + boardArr[i].color+'Tile';\n deTile.id = boardArr[i].tileLocation + \"Tile\";\n boardApp.appendChild(deTile);\n }\n}", "function makeHtmlBoard() {\n\t// make column tops (clickable area for adding a piece to that column)\n\tconst headRow = document.createElement('tr');\n\theadRow.setAttribute('id', 'head-row'); // 'column-top' === 'head-row'!\n\theadRow.addEventListener('click', handleClick); // eventListener and handleClick!\n\n\tfor (let x = 0; x < WIDTH; x++) {\n\t\tconst headCell = document.createElement('th');\n\t\theadCell.setAttribute('id', x);\n\t\theadRow.append(headCell);\n\t}\n\tconst htmlBoard = document.getElementById('board');\n\thtmlBoard.append(headRow);\n\n\t// make main part of board\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tconst row = document.createElement('tr');\n\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst cell = document.createElement('td');\n\t\t\tcell.setAttribute('id', `${y}-${x}`);\n\t\t\trow.append(cell);\n\t\t}\n\t\thtmlBoard.append(row);\n\t}\n}", "function buildBoard(){\n container = document.createElement(\"div\");\n container.classList.add(\"grid-container\");\n\n for(i=0; i < dims; i++){\n for(j = 0; j < dims; j++){\n let temp = makeGridEle(boardSize);\n container.appendChild(temp);\n }\n let br = document.createElement(\"br\");\n container.appendChild(br);\n }\n\n document.body.appendChild(container);\n}", "function makeHtmlBoard() {\n\t// TODO: get \"htmlBoard\" variable from the item in HTML w/ID of \"board\"\n\tconst htmlBoard = document.querySelector('#board');\n\n\t// TODO: add comment for this code\n\t//creates the top row, sets its attributes to give it CSS properties\n\tlet top = document.createElement('tr');\n\ttop.setAttribute('id', 'column-top');\n\n\t//when a player clicks in the top row, the handleClick function will run\n\ttop.addEventListener('click', handleClick);\n\n\t//loop over WIDTH (7) times\n\tfor (let x = 0; x < WIDTH; x++) {\n\t\t//create a td (table data/cell)\n\t\tlet headCell = document.createElement('td');\n\t\t//add the attribute to signify it as the head cell\n\t\theadCell.setAttribute('id', x);\n\t\t//append it to the top row\n\t\ttop.append(headCell);\n\t}\n\t//append the top row to the HTML board\n\thtmlBoard.append(top);\n\n\t// TODO: add comment for this code\n\t// loop over HEIGHT times, which is 6\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\t//create a row each time\n\t\tconst row = document.createElement('tr');\n\t\t//loop over WIDTH times, 7\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\t//create a cell for each row\n\t\t\tconst cell = document.createElement('td');\n\t\t\t//set its attribute based on its position\n\t\t\tcell.setAttribute('id', `${y}-${x}`);\n\t\t\t//append it to the row\n\t\t\trow.append(cell);\n\t\t}\n\t\t//append all the rows to the gameboard\n\t\thtmlBoard.append(row);\n\t}\n\n\t//select the top row\n\tlet topTr = document.querySelector('tr');\n\n\t//show color of current player when hovering over top row\n\t//check if currPlayer is Player 1, use e.target to change each cell in top row as you hover\n\ttopTr.addEventListener('mouseover', (e) => {\n\t\tlet target = e.target;\n\t\tif (currPlayer === 1) {\n\t\t\ttarget.style.backgroundColor = 'red';\n\t\t} else {\n\t\t\ttarget.style.backgroundColor = 'gold';\n\t\t}\n\t});\n\t//have the color go back to blue when done hovering so that it doesn't stay red or gold\n\ttopTr.addEventListener('mouseout', (e) => {\n\t\tlet target = e.target;\n\t\ttarget.style.backgroundColor = 'rgba(0, 41, 203, 0.954)';\n\t});\n}", "function createGame(frame){ // creates the game area by looping on the createTile function\n for(var i = 0; i < GAME_SIZE; i++)\n frame.appendChild(createTile());\n}", "function makeBoard() {\r\n for (let y = 0; y < HEIGHT; y++) {\r\n board.push(Array.from({ length: WIDTH }));\r\n }\r\n}", "function makeHtmlBoard() {\n let htmlBoard = document.getElementById(\"board\");\n\n // create top row that listens for player click\n // click represents col where game piece will be placed\n let top = document.createElement(\"tr\");\n top.setAttribute(\"id\", \"column-top\");\n top.addEventListener(\"click\", handleClick);\n\n // create individual col cells up to max WIDTH and then append to top row\n for (let col = 0; col < WIDTH; col++) {\n let headCell = document.createElement(\"td\");\n headCell.setAttribute(\"id\", col);\n top.append(headCell);\n }\n // also append top row to game board\n htmlBoard.append(top);\n\n // dynamically creates the main part of html board\n // uses HEIGHT to create table rows\n // uses WIDTH to create table cells for each row\n for (let row = 0; row < HEIGHT; row++) {\n let gameRow = document.createElement(\"tr\");\n\n for (let col = 0; col < WIDTH; col++) {\n let gameCell = document.createElement(\"td\");\n\n gameCell.setAttribute(\"id\", `${row}-${col}`);\n // you'll use this later, so make sure you use y-x\n\n gameRow.append(gameCell);\n\n }\n htmlBoard.append(gameRow);\n\n }\n\n // add event listener for undo button which may be hidden initially\n let undo = document.querySelector(\".undo\");\n undo.addEventListener(\"click\", takeBackMostRecentMove);\n}", "initBoard() {\n\n // Generate a new row\n const newRow = (rowNum) => {\n const row = document.createElement('div');\n row.classList.add('row');\n row.classList.add('row-' + rowNum);\n return row;\n }\n // Generate a new column\n const newCol = (colNum) => {\n const col = document.createElement('div');\n col.classList.add('col');\n col.classList.add('col-' + colNum);\n return col;\n }\n\n // For each number of rows make a new row element and fill with columns\n for (let r = 0; r < SnakeGame.NUM_ROWS; r++) {\n\n const row = newRow(r);\n const boardCellsRow = [];\n\n // For each number of columns make a new column element and add to the row\n for (let c = 0; c < SnakeGame.NUM_COLS; c++) {\n\n const col = newCol(c);\n row.appendChild(col);\n boardCellsRow.push(col);\n\n }\n\n this.board.appendChild(row);\n this.boardCells.push(boardCellsRow);\n\n }\n\n }", "function generateGameBoard() {\n let xCoords = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];\n let yCoords = [1, 2, 3, 4, 5, 6, 7, 8];\n let gameBoard = {};\n\n xCoords.forEach((xCoord) => {\n yCoords.forEach((yCoord) => {\n let square = {\n state: {\n occupied: false,\n color: null,\n piece: null\n }\n }\n\n let squareName = xCoord + yCoord;\n gameBoard[squareName] = square;\n });\n });\n\n let populatedBoard = populateBoard(gameBoard);\n\n return populatedBoard;\n}", "makeBoard() {\n let board = [];\n for(let row = 0; row < this.height; row++ ){\n let newRow = [];\n for(let column = 0; column <this.width; column++){\n newRow.push(0);\n }\n board.push(newRow);\n }\n return board;\n }", "function makeBoard() {\n // DONE - TODO: set \"board\" to empty HEIGHT x WIDTH matrix array\n\n board = []\n\n for (let y = 0; y < HEIGHT; y++) {\n let row = []\n for (let x = 0; x < WIDTH; x++) {\n row.push(null)\n }\n board.push(row)\n }\n\n}", "function initBoard(game) {\n for (var i = 0; i < COLUMN; i++) {\n game.board[i] = new Array(ROW);\n for(var y=0; y < ROW; y++){\n // genere des tiles aleatoire dans tour le tableau\n generateTile(game, new Coord(i, y));\n }\n }\n\n destroyTiles(game);\n\n for (i = 0; i < COLUMN; i++) {\n for(y=0; y < ROW; y++){\n drawTile(game.board[i][y]);\n }\n }\n\n}", "function makeBoard() {\n // making our H X W grid\n for (let row = 0; row < HEIGHT; row++) {\n board.push([]);\n \n // can use Array.fill instead\n for (let col = 0; col < WIDTH; col++) {\n board[row].push(null);\n }\n }\n\n return board;\n}", "function makeHtmlBoard() {\n // get \"htmlBoard\" variable from the item in HTML w/ID of \"board\"\n let htmlBoard = document.getElementById('board')\n // create a table row for the top of the board, give it an id, and add a click event handler\n let top = document.createElement(\"tr\");\n top.setAttribute(\"id\", \"column-top\");\n top.addEventListener(\"click\", handleClick);\n for (var x = 0; x < WIDTH; x++) {\n let headCell = document.createElement(\"td\");\n headCell.setAttribute(\"id\", x);\n top.append(headCell);\n }\n htmlBoard.append(top);\n\n // set the board height and width dynamically, adding ids based off their position\n for (var y = 0; y < HEIGHT; y++) {\n const row = document.createElement(\"tr\");\n for (var x = 0; x < WIDTH; x++) {\n const cell = document.createElement(\"td\");\n cell.setAttribute(\"id\", `${y}-${x}`);\n row.append(cell);\n }\n htmlBoard.append(row);\n }\n}", "buildBoard() {\n // As the ids are declared explicitly, this class is tied to this specific HTML doc\n $(\"#game-board\").empty()\n $(\"#variable-title\").append($(\"<button>\").addClass(\"btn btn-danger\").attr(\"id\", \"end-button\").text(\"End Game\"));\n for (let i = 1; i <= this.board.length; i++) {\n let box = $(\"<div>\").addClass(\"board-box\").attr(\"id\", `box-${i}`).attr(\"data-index\", i - 1);\n let play = $(\"<h1>\").addClass(\"play center\").text(this.board[i - 1]);\n box.append(play);\n $(\"#game-board\").append(box)\n }\n }" ]
[ "0.8567491", "0.82497925", "0.81799", "0.8129172", "0.8061828", "0.8031286", "0.8020527", "0.79634976", "0.7946054", "0.7884545", "0.7865835", "0.78648", "0.7855752", "0.7853354", "0.78226095", "0.7761402", "0.7740199", "0.77289814", "0.769943", "0.7694575", "0.7680842", "0.7679357", "0.7648224", "0.7614822", "0.76043934", "0.75975704", "0.759277", "0.75776255", "0.75637424", "0.7541681", "0.75400597", "0.7530854", "0.75096834", "0.7505989", "0.74981976", "0.74960256", "0.7491754", "0.7488118", "0.74847084", "0.7469933", "0.7460193", "0.7457684", "0.74518514", "0.7444563", "0.7432129", "0.7424399", "0.74229556", "0.7394465", "0.7392636", "0.73908776", "0.7388167", "0.7376408", "0.737591", "0.73712796", "0.7371003", "0.734905", "0.7344658", "0.73207134", "0.7316352", "0.7315853", "0.73157185", "0.7314426", "0.7313993", "0.731204", "0.7310734", "0.7309517", "0.73032033", "0.7303025", "0.7299111", "0.7296185", "0.7294338", "0.7292512", "0.7289974", "0.7289561", "0.7289383", "0.7265613", "0.7262917", "0.7262036", "0.7257481", "0.72556156", "0.7250214", "0.7247637", "0.7239825", "0.7227746", "0.72110456", "0.7208536", "0.72084093", "0.72079283", "0.7190875", "0.7187699", "0.7179484", "0.7178059", "0.7173091", "0.716903", "0.7159013", "0.7155612", "0.7150307", "0.7148543", "0.7143504", "0.71421075" ]
0.71622854
94
This function assigns the chosen number to a square if correct, or removes a life if incorrect
function updateSquare() { // If a square and a number are both selected if (selectedSquare && selectedNumber) { // Assign the chosen number to the chosen square selectedSquare.textContent = selectedNumber.textContent; // If the number matches the number in the solution key if (checkIfCorrect(selectedSquare)){ // Deselect the selected square and number selector selectedSquare.classList.remove("selected"); selectedNumber.classList.remove("selected"); // Clear any selected variables selectedNumber = null; selectedSquare = null; // Check if the game board is completed if (checkGridComplete()) { gameOver(); } } else { // Check if the number does not match the solution key // Disallow selecting new numbers for half a second noSelect = true; // Turn the selected square dark with red text selectedSquare.classList.add("incorrect"); // Run after half a second setTimeout(function() { // Take 1 from lives lives --; // If user runs out of lives if (lives === 0) { gameOver(); } else { // If there are lives remaining // Update the remaining lives section with current lives id("lives").textContent = "Remaining Lives: " + lives; // Allow number and square selection noSelect = false; } // Restore square and number color and remove selected from both selectedSquare.classList.remove("incorrect"); selectedSquare.classList.remove("selected"); selectedNumber.classList.remove("selected"); // Clear the text in tiles and selected variables selectedSquare.textContent = ""; selectedSquare = null; selectedNumber = null; }, 500); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function pickSquare() {\n if (gameover || this.innerHTML !== '') return; \n this.innerHTML = selectTurn.value;\n if (selectTurn.value == 'X') {\n selectTurn.value = 'O';\n } else {\n selectTurn.value = 'X';\n }\n checkWin();\n }", "function randomSquare() {\n // clearing all squares first to be sure there are no moles\n square.forEach(moleClass => {\n moleClass.classList.remove('mole')\n })\n // getting our random number using math.floor to make sure its always under 9\n let randomNum = square[Math.floor(Math.random() * 9)];\n randomNum.classList.add('mole');\n\n // storing the position id of the mole so that we can check if the user clicks on it\n molePoisiton = randomNum.id;\n}", "function easySpot() {\n let randomNumber = Math.random();\n if (randomNumber < 0.11 && origBoard[0] != 'O' && origBoard[0] != 'X') {\n return 0;\n } if (randomNumber < 0.22 && origBoard[1] != 'O' && origBoard[1] != 'X') {\n return 1;\n } if (randomNumber < 0.33 && origBoard[2] != 'O' && origBoard[2] != 'X') {\n return 2;\n } if (randomNumber < 0.44 && origBoard[3] != 'O' && origBoard[3] != 'X') {\n return 3;\n } if (randomNumber < 0.55 && origBoard[4] != 'O' && origBoard[4] != 'X') {\n return 4;\n } if (randomNumber < 0.66 && origBoard[5] != 'O' && origBoard[5] != 'X') {\n return 5;\n } if (randomNumber < 0.77 && origBoard[6] != 'O' && origBoard[6] != 'X') {\n return 6;\n } if (randomNumber < 0.88 && origBoard[7] != 'O' && origBoard[7] != 'X') {\n return 7;\n } if (randomNumber < 0.99 && origBoard[8] != 'O' && origBoard[8] != 'X') {\n return 8;\n } else {\n let availSpots = emptySquares();\n console.log(availSpots);\n return availSpots[0];\n }\n}", "function newSize(){\n\n var size = prompt(\"Enter a new size! Size MUST be than 2 and less than 50.\");\n\n if((size < 50) && (size > 2)){\n current_size = size;\n clearSquare();\n } else {\n alert(\"Oops! You entered a size too big. Please try again!\");\n newSize();\n }\n}", "function computerSquareHard(squareArray){\n //Declare variable for upcoming beast slaying\n let activateTheBeast;\n\n //Do we activate THE BEAST? If not activated we'll continue in hard mode\n if (beastMode){\n activateTheBeast = activateBeast();\n } else {\n activateTheBeast = 0;\n }\n if (activateTheBeast === 0){\n\n //If meets criteria choose hard else computerSquareEasy(squareArray)\n //Check if 2 or more squares are available, else computerSquareEasy(squareArray)\n if (squareArray.length > 1){\n\n //Elegible Squares are:\n let eligibleNumsArray = [[1,2],[2,3],[1,3],[4,5],[5,6],[4,6],\n [7,8],[8,9],[7,9],[1,4],[4,7],[1,7],\n [2,5],[5,8],[2,8],[3,6],[6,9],[3,9],\n [1,5],[5,9],[1,9],[3,5],[5,7],[3,7]];\n\n //Declare array for player's squares\n let playerArray = [];\n\n //Squares with active O will be added to player's squares array\n for (let i = 1; i <= 9; i++) {\n if (document.getElementById(`square-${i}`).innerHTML === \"O\"){\n playerArray.push(i);\n }\n }\n //Declare the variable to return\n let cSquare = computerSquareEasy(squareArray);\n\n //Loop through the winning squares to check against player squares\n for (let i = 0; i < eligibleNumsArray.length; i++) {\n\n //Checks if player squares match with elegible squares\n if (eligibleNumsArray[i].every((val) => playerArray.includes(val))) {\n \n let arrStr = eligibleNumsArray[i].toString();\n\n //Check if there's free squares next to the eligible lines\n if (arrStr === \"1,2\" && squareFree(3)){\n cSquare = 3;\n } else if (arrStr === \"2,3\" && squareFree(1)){\n cSquare = 1;\n } else if (arrStr === \"1,3\" && squareFree(2)){\n cSquare = 2;\n } else if (arrStr === \"4,5\" && squareFree(6)){\n cSquare = 6;\n } else if (arrStr === \"5,6\" && squareFree(4)){\n cSquare = 4;\n } else if (arrStr === \"4,6\" && squareFree(5)){\n cSquare = 5;\n } else if (arrStr === \"7,8\" && squareFree(9)){\n cSquare = 9;\n } else if (arrStr === \"8,9\" && squareFree(7)){\n cSquare = 7;\n } else if (arrStr === \"7,9\" && squareFree(8)){\n cSquare = 8;\n } else if (arrStr === \"1,4\" && squareFree(7)){\n cSquare = 7;\n } else if (arrStr === \"4,7\" && squareFree(1)){\n cSquare = 1;\n } else if (arrStr === \"1,7\" && squareFree(4)){\n cSquare = 4;\n } else if (arrStr === \"2,5\" && squareFree(8)){\n cSquare = 8;\n } else if (arrStr === \"5,8\" && squareFree(2)){\n cSquare = 2;\n } else if (arrStr === \"2,8\" && squareFree(5)){\n cSquare = 5;\n } else if (arrStr === \"3,6\" && squareFree(9)){\n cSquare = 9;\n } else if (arrStr === \"6,9\" && squareFree(3)){\n cSquare = 3;\n } else if (arrStr === \"3,9\" && squareFree(6)){\n cSquare = 6;\n } else if (arrStr === \"1,5\" && squareFree(9)){\n cSquare = 9;\n } else if (arrStr === \"5,9\" && squareFree(1)){\n cSquare = 1;\n } else if (arrStr === \"1,9\" && squareFree(5)){\n cSquare = 5;\n } else if (arrStr === \"3,5\" && squareFree(7)){\n cSquare = 7;\n } else if (arrStr === \"5,7\" && squareFree(3)){\n cSquare = 3;\n } else if (arrStr === \"3,7\" && squareFree(5)){\n cSquare = 5;\n }\n }\n }\n //Return the square\n return cSquare;\n } else {\n //Less than 2 squares left so just do the easy logic\n return computerSquareEasy(squareArray);\n }\n } else {\n //Return THE BEAST's choice of number\n return activateTheBeast;\n }\n}", "function setSquares(n){\n getSwapSquares();\n if (swapSquares.includes(n)){\n for (var row = 0; row < listSquares.length; row++) {\n for (var col = 0; col < listSquares.length; col++) {\n if (listSquares[row][col] === 0) {\n listSquares[row][col] = n;\n } else if (listSquares[row][col] === n) {\n listSquares[row][col] = 0;\n }\n }\n }\n moveSquares();\n }\n}", "function clearSqr () {\n //function that clears all squares\n const clearSqr = document.getElementsByClassName('square')\n for (let i = clearSqr.length-1; i>=0; i--) {\n clearSqr[i].remove();\n }\n //function that creates new squares\n let sqrNum = prompt('Enter number of squares between 4-64')\n let newNum = Math.pow(sqrNum,2)\n for (let i=0; i<newNum; i++){\n createSquare()\n\n//gives square a color whwn mouse enters a square \nlet columns = container.style.setProperty('grid-template-columns', 'repeat(' + sqrNum + ', 1fr)');\nlet rows = container.style.setProperty('grid-template-rows', 'repeat(' + sqrNum + ', 1fr)');\n };\n changeColor()\n}", "function collision(number,pieceNumber){\r\n\tvar pieceToRemove=gameBoardArray[number-1].childNodes[0];\r\n \tif(gameBoardArray[number-1].childElementCount!==0 && !number==20){ //allow collision with star\r\n\t\tgameBoardArray[0].appendChild(pieceToRemove);\r\n\t\tswitch(pieceNumber){\r\n\t\tcase 1:\r\n\t\t\tpiece1.reset();\r\n\t\t\tbreak;\r\n\t\tcase 2:\r\n\t\t\tpiece2.reset();\r\n\t\t\tbreak;\r\n\t\tcase 3:\r\n\t\t\tpiece3.reset();\r\n\t\t\tbreak;\r\n\t\tcase 4:\r\n\t\t\tpiece4.reset();\r\n\t\t\tbreak;\r\n\t}\r\n\t}\r\n}", "function computerTurn() {\n //Double check it's computer's turn\n if (document.getElementById(\"game-turn\").innerHTML === \"Computer's\") {\n //Find a free square\n //Declare array for squares\n let squareArray = [];\n\n //Squares with active O or X will not be added to the array\n //Loop through squares from 1-9.\n for (let i = 1; i <= 9; i++) {\n if (document.getElementById(`square-${i}`).innerHTML === ''){\n squareArray.push(i);\n }\n }\n //Check if all squares are full or not\n if (squareArray.length < 1 && !winner) {\n //If no winner, reset game and increment draw-score\n setTimeout(() => {resetSquares();}, 1000);\n setScoreboard(false);\n\n //Show draw colour\n drawAnimation();\n\n //Draw message\n modalBox(\"Draw\");\n } else {\n //Assign a free square based on difficulty level\n let chosenSquare = (hardMode) ? computerSquareHard(squareArray) : computerSquareEasy(squareArray);\n\n //Wait 0.75 seconds then add X to the square\n setTimeout(() => {setSquare(chosenSquare, \"X\");}, 750);\n }\n } else {\n console.log(\"Error, It's not the computer's turn?\");\n }\n}", "function GameLogic() {\n 'use strict';\n var chosenSquare;\n chosenSquare = parseInt(this.id, 10);\n \n if (this.classList.contains('free')) {\n this.classList.remove('free');\n\n if (playerTurn % 2 === 0) {\n this.classList.add('blue');\n playerOne.push(chosenSquare);\n } else {\n this.classList.add('red');\n playerTwo.push(chosenSquare);\n }\n \n playerTurn += 1;\n chosenSquare = 0;\n }\n \n if (playerTurn >= 5) {\n declareWinner();\n }\n}", "function newSize(number) { \n let squareAll = document.querySelectorAll(\".square1\");\n squareAll.forEach(function(square1) {\n square1.remove();\n })\n makeGrid(number);\n }", "function activateBeast(){\n //Elegible Squares are:\n let eligibleNumsArray = [[1,2],[2,3],[1,3],[4,5],[5,6],[4,6],\n [7,8],[8,9],[7,9],[1,4],[4,7],[1,7],\n [2,5],[5,8],[2,8],[3,6],[6,9],[3,9],\n [1,5],[5,9],[1,9],[3,5],[5,7],[3,7]];\n\n //Declare array for computer's squares\n let computerArray = [];\n\n //Squares with active X will be added to computer's squares array\n for (let i = 1; i <= 9; i++) {\n if (document.getElementById(`square-${i}`).innerHTML === \"X\"){\n computerArray.push(i);\n }\n }\n //Declare the variable with default value to return\n let cSquare = 0;\n\n //Loop through the winning squares to check against computer's squares\n for (let i = 0; i < eligibleNumsArray.length; i++) {\n\n //Checks if computer's squares match with elegible squares\n if (eligibleNumsArray[i].every((val) => computerArray.includes(val))) {\n let arrStr = eligibleNumsArray[i].toString();\n \n //Check if there's free squares next to the eligible lines\n if (arrStr === \"1,2\" && squareFree(3)){\n cSquare = 3;\n } else if (arrStr === \"2,3\" && squareFree(1)){\n cSquare = 1;\n } else if (arrStr === \"1,3\" && squareFree(2)){\n cSquare = 2;\n } else if (arrStr === \"4,5\" && squareFree(6)){\n cSquare = 6;\n } else if (arrStr === \"5,6\" && squareFree(4)){\n cSquare = 4;\n } else if (arrStr === \"4,6\" && squareFree(5)){\n cSquare = 5;\n } else if (arrStr === \"7,8\" && squareFree(9)){\n cSquare = 9;\n } else if (arrStr === \"8,9\" && squareFree(7)){\n cSquare = 7;\n } else if (arrStr === \"7,9\" && squareFree(8)){\n cSquare = 8;\n } else if (arrStr === \"1,4\" && squareFree(7)){\n cSquare = 7;\n } else if (arrStr === \"4,7\" && squareFree(1)){\n cSquare = 1;\n } else if (arrStr === \"1,7\" && squareFree(4)){\n cSquare = 4;\n } else if (arrStr === \"2,5\" && squareFree(8)){\n cSquare = 8;\n } else if (arrStr === \"5,8\" && squareFree(2)){\n cSquare = 2;\n } else if (arrStr === \"2,8\" && squareFree(5)){\n cSquare = 5;\n } else if (arrStr === \"3,6\" && squareFree(9)){\n cSquare = 9;\n } else if (arrStr === \"6,9\" && squareFree(3)){\n cSquare = 3;\n } else if (arrStr === \"3,9\" && squareFree(6)){\n cSquare = 6;\n } else if (arrStr === \"1,5\" && squareFree(9)){\n cSquare = 9;\n } else if (arrStr === \"5,9\" && squareFree(1)){\n cSquare = 1;\n } else if (arrStr === \"1,9\" && squareFree(5)){\n cSquare = 5;\n } else if (arrStr === \"3,5\" && squareFree(7)){\n cSquare = 7;\n } else if (arrStr === \"5,7\" && squareFree(3)){\n cSquare = 3;\n } else if (arrStr === \"3,7\" && squareFree(5)){\n cSquare = 5;\n }\n }\n }\n //Return the square\n return cSquare;\n}", "function removeSquare(i, j){\n var id = (i * 10 + j).toString();\n document.getElementById(id).style.visibility = \"hidden\";\n}", "function pickSquare (){\n var col =0\n var row =0\n col = Math.floor(Math.random() * dimensions)\n row = Math.floor(Math.random() * dimensions)\n actionMove(col,row)\n}", "removeSquare(square){\n\t\tif (square.type == \"player\"){\n\t\t\tif (square.killer in this.players){\n\t\t\t\tthis.players[square.killer].score += 1; // add 1 to the score of the killer\n\t\t\t}\n\t\t\tdelete this.players[square.id];\n\t\t} else if (square.type == \"enemy\"){\n\t\t\tif (square.killer in this.players){\n\t\t\t\tthis.players[square.killer].score += 1; // add 1 to the score of the killer\n\t\t\t}\n\t\t\tthis.enemies_number -= 1;\n\t\t} else if (square.type == \"box\"){\n\t\t\tthis.boxes_number -= 1;\n\t\t} else if (square.type == \"obstacle\"){\n\t\t\tthis.obstacles_number -= 1;\n\t\t}\n\t\t// remove the square from squares list\n\t\tvar index=this.squares.indexOf(square);\n\t\tif(index!=-1){\n\t\t\tthis.squares.splice(index,1);\n\t\t}\n\t}", "function squareFree(square) {\n return (document.getElementById(`square-${square}`).innerHTML === '') ? true : false ;\n}", "function checkSquare(square, currentId) {\n\tconst isLeftEdge = (currentId % width === 0)\n\tconst isRightEdge = (currentId % width === width - 1)\n\n\tsetTimeout(() => {\n\t\tif (currentId > 0 && !isLeftEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) - 1].id\n\t\t\t//const newId = parseInt(currentId) - 1 ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId > 9 && !isRightEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) + 1 - width].id\n\t\t\t//const newId = parseInt(currentId) +1 -width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId >= 10) {\n\t\t\tconst newId = squares[parseInt(currentId - width)].id\n\t\t\t//const newId = parseInt(currentId) -width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId >= 11 && !isLeftEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) - 1 - width].id\n\t\t\t//const newId = parseInt(currentId) -1 -width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId <= 98 && !isRightEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) + 1].id\n\t\t\t//const newId = parseInt(currentId) +1 ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId < 90 && !isLeftEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) - 1 + width].id\n\t\t\t//const newId = parseInt(currentId) -1 +width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId <= 88 && !isRightEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) + 1 + width].id\n\t\t\t//const newId = parseInt(currentId) +1 +width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId <= 89) {\n\t\t\tconst newId = squares[parseInt(currentId) + width].id\n\t\t\t//const newId = parseInt(currentId) +width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t}, 10)\n}", "function checkSquare(square, currentId) {\n const isLeftEdge = (currentId % width === 0);\n const isRightEdge = (currentId % width === width - 1);\n // west, north-east, north, north-west, east, south-west, south-east, south\n setTimeout(() => {\n if (currentId > 0 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) - 1].id;\n const newSquare = document.getElementById(newId);\n click(newSquare);\n }\n if (currentId > 9 && !isRightEdge) {\n const newId = squares[parseInt(currentId) + 1 - width].id;\n const newSquare = document.getElementById(newId);\n click(newSquare);\n }\n if (currentId > 9) {\n const newId = squares[parseInt(currentId - width)].id;\n const newSquare = document.getElementById(newId);\n click(newSquare);\n }\n if (currentId > 10 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) - 1 - width].id;\n const newSquare = document.getElementById(newId);\n click(newSquare);\n }\n if (currentId < 99 && !isRightEdge) {\n const newId = squares[parseInt(currentId) + 1].id;\n const newSquare = document.getElementById(newId);\n click(newSquare);\n }\n if (currentId < 90 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) - 1 + width].id;\n const newSquare = document.getElementById(newId);\n click(newSquare);\n }\n if (currentId < 89 && !isRightEdge) {\n const newId = squares[parseInt(currentId) + 1 + width].id;\n const newSquare = document.getElementById(newId);\n click(newSquare);\n }\n if (currentId < 90) {\n const newId = squares[parseInt(currentId) + width].id;\n const newSquare = document.getElementById(newId);\n click(newSquare);\n }\n }, 10);\n }", "takeTurn() {\n let myBestMove = this.getBestMove(this.sym);\n let theirSym = this.sym === 'x' ? 'o' : 'x';\n let theirBestMove = this.getBestMove(theirSym);\n let squareNum;\n \n if (theirBestMove.movesLeft === 0 && myBestMove.movesLeft > 0) {\n squareNum = theirBestMove.squareNum;\n } else {\n squareNum = myBestMove.squareNum;\n }\n\n UI.fillSquare(squareNum, this.sym);\n grid[squareNum] = this.sym;\n }", "function create(){\n let randomNumber=Math.floor(Math.random() * box.length )\n if (box[randomNumber].innerHTML == 0){\n box[randomNumber].innerHTML = 2\n\n\n\n gameOver()\n }\n else create()\n}", "function generate()\r\n {\r\n let randomNumber = Math.floor(Math.random() * squares.length)\r\n if(squares[randomNumber].innerHTML == 0){\r\n squares[randomNumber].innerHTML = 2\r\n checkForGameOver()\r\n }else generate()\r\n\r\n }", "function dropPiece(n) {\n if (didSomebodyWin == false) {\n\n // Drops a piece of the current turn's color into the bottom-most empty square in the nth column.\n document.getElementsByClassName(\"row\").item(bottoms[n])\n .getElementsByClassName(\"bigSquare\").item(n)\n .style.backgroundColor = color(currentTurn);\n\n // Updates things.\n didSomebodyWin = checkWin(n);\n if (didSomebodyWin == true) {\n if (color(currentTurn) == \"red\") {\n document.getElementById(\"instructions\").innerHTML = \"Red wins!\";\n }\n if (color(currentTurn) == \"blue\") {\n document.getElementById(\"instructions\").innerHTML = \"Blue wins!\";\n }\n }\n bottoms[n]--;\n currentTurn++;\n changeCounter();\n\n // Writes the move to history.\n for (var i = 0; history[i] != -1; i++);\n history[i] = n;\n\n // Un-comment to see the game history.\n // printHistory();\n }\n }", "function removePossible(rowNo, colNo, squareValue) {\n removePossibleFromRow(rowNo,colNo, squareValue);\n removePossibleFromCol(rowNo,colNo,squareValue);\n removePossibleFromSector(rowNo,colNo,squareValue);\n}", "function adjustAvailable() {\n if (boardIndex > 0) {\n // Remove indexnumber of already taken square from available squares\n for (let i = 0; i < 9; i++) {\n for (let valueNumber = 9; valueNumber > 0; valueNumber--) {\n if (boardFin[rowIndex][i].includes(valueNumber)) {\n indexOfReservedSquare = i;\n let indexToSplice = availableSquares.indexOf(indexOfReservedSquare);\n \n if (indexToSplice >= 0) {\n availableSquares.splice(indexToSplice, 1);\n }\n }\n }\n }\n }\n }", "function generate() {\n randomNumber = Math.floor(Math.random() * squares.length)\n if (squares[randomNumber].innerHTML == 0) {\n squares[randomNumber].innerHTML = 2\n checkForGameOver()\n } else generate()\n }", "function gameMode(num) {\n colors.splice(0, colors.length);\n pushRGB(num);\n squareSetup();\n promptRGB();\n}", "function generateNewNumber() {\n var x = parseInt(Math.random() * 4);\n var y = parseInt(Math.random() * 4);\n var twoOrFour = Math.random() * 10;\n if (board[x][y] == 0) {\n if (twoOrFour < 8) board[x][y] = 2;\n else board[x][y] = 4;\n } else generateNewNumber();\n}", "function checkSquare(square, currentId) {\n const isLeftEdge = (currentId % width === 0)\n const isRightEdge = (currentId % width === width -1)\n\n setTimeout(() => {\n if (currentId > 0 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) -1].id\n //const newId = parseInt(currentId) - 1 ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare)\n }\n if (currentId > 9 && !isRightEdge) {\n const newId = squares[parseInt(currentId) +1 -width].id\n //const newId = parseInt(currentId) +1 -width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare)\n }\n if (currentId > 10) {\n const newId = squares[parseInt(currentId -width)].id\n //const newId = parseInt(currentId) -width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare)\n }\n if (currentId > 11 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) -1 -width].id\n //const newId = parseInt(currentId) -1 -width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare)\n }\n if (currentId < 98 && !isRightEdge) {\n const newId = squares[parseInt(currentId) +1].id\n //const newId = parseInt(currentId) +1 ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare)\n }\n if (currentId < 90 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) -1 +width].id\n //const newId = parseInt(currentId) -1 +width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare)\n }\n if (currentId < 88 && !isRightEdge) {\n const newId = squares[parseInt(currentId) +1 +width].id\n //const newId = parseInt(currentId) +1 +width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare)\n }\n if (currentId < 89) {\n const newId = squares[parseInt(currentId) +width].id\n //const newId = parseInt(currentId) +width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare)\n }\n }, 10)\n }", "function checkSquare(square, currentId) {\n const isLeftEdge = (currentId % width === 0)\n const isRightEdge = (currentId % width === width -1)\n \n setTimeout(() => {\n if (currentId > 0 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) -1].id\n //const newId = parseInt(currentId) - 1 ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare,false)\n }\n if (currentId > 10 && !isRightEdge) {\n const newId = squares[parseInt(currentId) +1 -width].id\n //const newId = parseInt(currentId) +1 -width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare,false)\n }\n if (currentId > 10) {\n const newId = squares[parseInt(currentId -width)].id\n //const newId = parseInt(currentId) -width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare,false)\n }\n if (currentId > 11 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) -1 -width].id\n //const newId = parseInt(currentId) -1 -width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare,false)\n }\n if (currentId < 76 && !isRightEdge) {\n const newId = squares[parseInt(currentId) +1].id\n //const newId = parseInt(currentId) +1 ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare,false)\n }\n if (currentId < 66 && !isLeftEdge) {\n const newId = squares[parseInt(currentId) -1 +width].id\n //const newId = parseInt(currentId) -1 +width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare,false)\n }\n if (currentId < 65 && !isRightEdge) {\n const newId = squares[parseInt(currentId) +1 +width].id\n //const newId = parseInt(currentId) +1 +width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare,false)\n }\n if (currentId < 66) {\n const newId = squares[parseInt(currentId) +width].id\n //const newId = parseInt(currentId) +width ....refactor\n const newSquare = document.getElementById(newId)\n click(newSquare,false)\n }\n }, 10)\n}", "function randomSquare() {\n square.forEach(className => {\n className.classList.remove(\"mole\");\n })\n let randomPosition = square[Math.floor(Math.random() * 9)];\n randomPosition.classList.add(\"mole\");\n \n //assign id of the randomPosition to hitPosition\n hitPosition = randomPosition.id;\n }", "function setSquare(square, OX) {\n document.getElementById(`square-${square}`).innerHTML = `${OX}`;\n\n // Change the active player\n changePlayer(OX); \n}", "function takeBlackPiece(){\n var attemptRow = thisId[0]\n var attemptCol = thisId[1]\n var avgCol = ((parseInt(startingCol) + parseInt(attemptCol)) / 2)\n var avgRow = ((parseInt(startingRow)+parseInt(attemptRow))/2);\n var jump = \"\" + avgRow+''+avgCol\n if ($('#'+jump).hasClass(\"blackPieces\")) { //win move valid\n $('#'+jump).removeClass(\"blackPieces\"); //remove\n blackPiecesTaken = blackPiecesTaken + 1;\n $(\"#blackPiecesTaken\").html(blackPiecesTaken)\n if (blackPiecesTaken == 12) {\n alert(\"Player 2 wins!\")\n }\n $(click).addClass(\"whitePieces\");\n whiteCounter = whiteCounter + 1;\n turn++;\n }\n }", "function change(idName){\n \nlet choice = document.getElementById(idName).innerHTML; //variable gets value displayed in any particualr square\n\n\n if (choice === \"O\" || choice === \"X\"){ //if a square displays an X or an O user is prompted to make a different selection\n alert (\"choose another square\");\n return 0;\n }\n\n if ( counter === 0 || counter % 2 === 0) {\n document.getElementById(idName).innerHTML = \"X\"; //counter is used to determine whether an X or an O is dsplayed\n \n counter += 1; // diplays X on odd and O's on even\n }\n else if( counter % 2 !== 0){ \n document.getElementById(idName).innerHTML = \"O\";\n counter += 1;\n}\n\n\n\n\n}", "function SquareClicked(x) {\n\tvar square = document.getElementById(x);\n\tif (emptyTable) {\n\t\temptyTable = false;\n\t\tsquare.style.backgroundImage = knightChess;\n\t\tpiece = x[4] + x[5];\n\t}\n\n\telse if (x[4] + x[5] == piece) {\n\t\tSearchOption();\n\t\tif (validOption.length == 0) {\n\t\t\tgetGameOverStatus();\n\t\t}\n\t}\n\telse {\n\t\tfor (var i = 0; i < validOption.length; i++) {\n\t\t\tif (x == validOption[i]) {\n\t\t\t\tsquare = document.getElementById(x);\n\t\t\t\tsquare.style.backgroundImage = knightChess;\n\t\t\t\tscore++;\n\t\t\t\tdocument.getElementById(\"score\").innerHTML = score + \" de 64\";\n\t\t\t\tif (square.style.backgroundColor == \"var(--danger)\") {\n\t\t\t\t\tsquare.style.backgroundColor = \"var(--blackChess)\";\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsquare.style.backgroundColor = \"white\";\n\t\t\t\t}\n\t\t\t\tdocument.getElementById(\"elem\" + piece).style.backgroundImage = \"\";\n\t\t\t\tif (document.getElementById(\"elem\" + piece).style.backgroundColor == \"white\") {\n\t\t\t\t\tdocument.getElementById(\"elem\" + piece).style.backgroundColor = \"var(--warning)\";\n\t\t\t\t}\n\t\t\t\telse if (document.getElementById(\"elem\" + piece).style.backgroundColor == \"var(--blackChess)\") {\n\t\t\t\t\tdocument.getElementById(\"elem\" + piece).style.backgroundColor = \"var(--info)\";\n\t\t\t\t}\n\t\t\t\tpiece = x[4] + x[5];\n\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (document.getElementById(validOption[i]).style.backgroundColor == \"var(--pink)\") {\n\t\t\t\t\tdocument.getElementById(validOption[i]).style.backgroundColor = \"white\";\n\t\t\t\t}\n\t\t\t\telse if (document.getElementById(validOption[i]).style.backgroundColor == \"var(--danger)\") {\n\t\t\t\t\tdocument.getElementById(validOption[i]).style.backgroundColor = \"var(--blackChess)\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvalidOption = [];\n\t}\n}", "function getSquare (no) {\n return no * no;\n}", "function nextMove(square){\n if (square.innerHTML ===\"\"){\n square.innerHTML=turn;\n switchTurn();\n }\n else {\n alert(\"Please choose another box\");\n }\n}", "function removeStar() {\n if (moves <= 15) {\n starNum = 3;\n }\n if (moves > 15) {\n document.querySelector('.three').innerHTML = '<i></i>';\n starNum = 2;\n };\n if (moves > 30) {\n document.querySelector('.two').innerHTML = '<i></i>';\n starNum = 1;\n };\n}", "function victory() {\r\n var gameOverCanvas = document.getElementById(\"gameOver\");\r\n var gameOverDisplay = \"You won the Game! Your Score is: \"+score;\r\n gameOverCanvas.innerHTML = gameOverDisplay;\r\n numberOfMissiles = 50;\r\n scene.remove(building);\r\n scene.remove(building1);\r\n scene.remove(building2);\r\n scene.remove(building3);\r\n scene.remove(building4);\r\n scene.remove(building5);\r\n scene.remove(launcher);\r\n\r\n}", "function update_game() {\n // remove old guess\n $(\"#guess\").val(\"\")\n // set new number from new range\n set_num();\n // tell user its a new game\n $(\"#error\").html(\"New Game!\");\n $(\"#error\").show();\n}", "function randomSpawnNumber(){\r\n // Turns 4x4 grid into 1x16 array\r\n let temp = [...gameBoard[0], ...gameBoard[1], ...gameBoard[2], ...gameBoard[3]]\r\n let flag = 1;\r\n // Check that there is an empty element in the array\r\n // Breaks if you find a zero, if you get to the end with no zero array is full\r\n for (let i = 0; i < temp.length; i++){\r\n if (temp[i] === 0){\r\n break;\r\n } else if (temp[15] !== 0 && i === 15){\r\n flag = 0;\r\n }\r\n }\r\n // If you get to here there is an open place to insert a new number\r\n if (flag){\r\n randomNumberX = Math.trunc(Math.random() * 4);\r\n randomNumberY = Math.trunc(Math.random() * 4);\r\n // Find empty space to put new number in\r\n while (gameBoard[randomNumberX][randomNumberY] !== 0){\r\n randomNumberX = Math.trunc(Math.random() * 4);\r\n randomNumberY = Math.trunc(Math.random() * 4);\r\n }\r\n // Spawns a \"4 tile\" 10% of the time else it spawns a \"2 tile\"\r\n let spawn4 = Math.random();\r\n if (spawn4 < 0.1){\r\n gameBoard[randomNumberX][randomNumberY] = 4;\r\n } else {\r\n gameBoard[randomNumberX][randomNumberY] = 2;\r\n }\r\n }\r\n}", "function setStartSquare() {\n let randomSquare = (Math.random() * 16);\n randomSquare = Math.floor(randomSquare);\n // set initial random square\n let currentSquare = allEdges[randomSquare];\n // canSquareMove();\n return currentSquare;\n}", "function clearSquare(){\n\n $(\".square\").remove();\n load(current_size);\n default_color();\n \n\n\n}", "function square(num){\n return num * num\n }", "function resetGame() {\n newSquares = Array(9).fill(null);\n setSquares(newSquares);\n setXTurn(true);\n }", "function riddle() {\n\tif(riddePlayed == false) {\n\t\tif(x==8 && y ==8) {\n\t\t\tconst position = getPosition();\n\t\t\tposition.append(riddeImg);\n\t\t\t\tvar answer = prompt('What gets bigger the more you take away from it?');\n\t\t\t\t\tif(answer.toUpperCase()=='A HOLE') {\n\t\t\t\t\t\tscore += 20;\n\t\t\t\t\t\tscoreCheck();\n\t\t\t\t\t\talert('You just got 20 extra points!');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tscore -= 10;\n\t\t\t\t\t\talert('You just lost 10 points!')\n\t\t\t\t\t\tscoreCheck();\n\t\t\t\t\t}\n\t\t\t\triddePlayed = true;\n\t\t}\n\t}\n}", "function humanPlayerTurn() {\n // what square was clicked?\n var chosenSquare = $(this);\n // get the row and col info from the data attributes\n chosenRow = chosenSquare.data(\"row\");\n chosenCol = chosenSquare.data(\"col\");\n console.log(`Human player chose row ${chosenRow} col ${chosenCol}`);\n\n var squareOccupied = chosenSquare.hasClass(\"human-player\")\n || chosenSquare.hasClass(\"computer-player\");\n if (!squareOccupied) {\n console.log(\"It was free\");\n // Give the square a CSS class\n chosenSquare.addClass(\"human-player\");\n tryNine++;\n\n // Checking for Draw\n // ahh how to access that last square (the missing link)\n if(tryNine !== 9) {\n // let the computer have a turn\n computerPlayerTurn();\n // remember 5 squares placed WITH a win is NOT a draw\n }\n else if (win5 === 5){\n humanFiveWin();\n }\n else if (tryNine === 9 || tryNine === undefined || tryNine === null || tryNine === ''){\n drawAction(); // check on this\n }\n\n // human picture :: Gavin my grand son :)\n var x = document.createElement(\"IMG\");\n x.setAttribute(\"src\", \"gavin.png\");\n x.setAttribute(\"width\", \"180\");\n x.setAttribute(\"height\", \"180\");\n x.setAttribute(\"alt\", \"The Big X\");\n document.body.appendChild(x);\n\n chosenSquare.html(x);\n\n //////////////////////do math //////////////////////////////////\n\n // with human we get a row and col int math them together to make an element value\n\n humanCount = chosenRow*3 + chosenCol;\n pcArray.push(pcCount);\n if(humanCount === 4) {humanArray[0]='x'; win5++;}\n if(humanCount === 5) {humanArray[1]='x'; win5++;}\n if(humanCount === 6) {humanArray[2]='x'; win5++;}\n if(humanCount === 7) {humanArray[3]='x'; win5++;}\n if(humanCount === 8) {humanArray[4]='x'; win5++;}\n if(humanCount === 9) {humanArray[5]='x'; win5++;}\n if(humanCount === 10) {humanArray[6]='x'; win5++;}\n if(humanCount === 11) {humanArray[7]='x'; win5++;}\n if(humanCount === 12) {humanArray[8]='x'; win5++;}\n\n function findFive()\n {\n if(win5 === 5) {\n humanFiveWin();\n }\n else{\n humanWins();\n }\n }\n\n if(humanArray[0] === 'x' && humanArray[1] === 'x' && humanArray[2] === 'x') findFive();\n if(humanArray[3] === 'x' && humanArray[4] === 'x' && humanArray[5] === 'x') findFive();\n if(humanArray[6] === 'x' && humanArray[7] === 'x' && humanArray[8] === 'x') findFive();\n if(humanArray[0] === 'x' && humanArray[3] === 'x' && humanArray[6] === 'x') findFive();\n if(humanArray[1] === 'x' && humanArray[4] === 'x' && humanArray[7] === 'x') findFive();\n if(humanArray[2] === 'x' && humanArray[5] === 'x' && humanArray[8] === 'x') findFive();\n if(humanArray[0] === 'x' && humanArray[4] === 'x' && humanArray[8] === 'x') findFive();\n if(humanArray[2] === 'x' && humanArray[4] === 'x' && humanArray[6] === 'x') findFive();\n if(pcCount === 0) pcArray[0]='x';\n if(pcCount === 1) pcArray[1]='x';\n if(pcCount === 2) pcArray[2]='x';\n if(pcCount === 3) pcArray[3]='x';\n if(pcCount === 4) pcArray[4]='x';\n if(pcCount === 5) pcArray[5]='x';\n if(pcCount === 6) pcArray[6]='x';\n if(pcCount === 7) pcArray[7]='x';\n if(pcCount === 8) pcArray[8]='x';\n if(pcArray[0] === 'x' && pcArray[1] === 'x' && pcArray[2] === 'x') pCWins();\n if(pcArray[3] === 'x' && pcArray[4] === 'x' && pcArray[5] === 'x') pCWins();\n if(pcArray[6] === 'x' && pcArray[7] === 'x' && pcArray[8] === 'x') pCWins();\n if(pcArray[0] === 'x' && pcArray[3] === 'x' && pcArray[6] === 'x') pCWins();\n if(pcArray[1] === 'x' && pcArray[4] === 'x' && pcArray[7] === 'x') pCWins();\n if(pcArray[2] === 'x' && pcArray[5] === 'x' && pcArray[8] === 'x') pCWins();\n if(pcArray[0] === 'x' && pcArray[4] === 'x' && pcArray[8] === 'x') pCWins();\n if(pcArray[2] === 'x' && pcArray[4] === 'x' && pcArray[6] === 'x') pCWins();\n\n // pc gave us a number so no extra calculation needed\n\n //////////////////////////// end math /////////////////////////////\\\\\n\n }\n }", "function removeSquare(square) {\n let squares = checkIfSquare();\n squares.splice(squares.indexOf(square), 1); //deleting 1 element in the place i mentioned\n localStorage.setItem(\"squares\", JSON.stringify(squares)); //localStorage.setItem(<itemName>,<itemValue>),\n}", "removeLife() {\n // const hearts = document.querySelector('#scoreboard > ol').children;\n const lifeHeartHTML = `<img src=\"images/liveHeart.png\" alt=\"Heart Icon\" height=\"35\" width=\"30\">`;\n const lostHeartHTML = `<img src=\"images/lostHeart.png\" alt=\"Heart Icon\" height=\"35\" width=\"30\">`;\n const lifeTaker = arr => {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i].innerHTML == lifeHeartHTML) {\n arr[i].innerHTML = lostHeartHTML;\n break;\n }\n }\n }\n\n this.missed++;\n this.missed > 4 ? this.gameOver() : lifeTaker(hearts);\n }", "function addNewNumber()\r\n{\r\n caseBoitesRemplies++; // Update du chiffre de caseBoitesRemplies (+1)\r\n var x, y; // Positions x et y aleatoires\r\n\r\n // Choix aleatoire du chiffre a rajouter\r\n var value = Math.random() < 0.9 ? 2 : 4;\r\n\r\n // Choix de la position aleatoire\r\n do\r\n { \r\n x = Math.floor(Math.random()*size);\r\n y = Math.floor(Math.random()*size);\r\n }\r\n while(tableDuJeu[x][y]!=null);\r\n \r\n // Assigne la valeur aleatoire a la position aleatoire dans la tableDuJeu\r\n tableDuJeu[x][y] = value;\r\n}", "function square(number)\n {\n return number * number;\n }", "function square(numero) {\n return numero*numero;\n\n }", "function newGame() {\n\tnum = Math.round(Math.random() * 50);\n\tguess.placeholder=\"Make your first guess\";\n\tdocument.getElementById(\"output\").innerHTML=\"You have five attempts to guess my number between 1 and 50\";\n\treset.style.display=\"none\";\n}", "function setSquare(player, row, col) {\n \n checkerboard[row][col] = player;\n return checkerboard;\n \n}", "function resetSquares() {\n for (let i = 1; i <= 9; i++) {\n\n //Resets all game squares to empty\n document.getElementById(`square-${i}`).innerHTML = '';\n }\n //Resets who's turn it is\n document.getElementById(\"game-turn\").innerHTML = \"Your\";\n\n //Shakey!\n shakey();\n\n //Change background back to normal\n document.body.style.backgroundColor = \"darkslategray\";\n}", "function createNum(){\n var posX = Math.floor(Math.random()*4);\n var posY = Math.floor(Math.random()*4);\n var value;\n if (Math.random()<0.5) {\n value = 2;\n } else {\n value = 4;\n }\n while (nums[posX][posY]!=0) {\n posX = Math.floor(Math.random()*4);\n posY = Math.floor(Math.random()*4);\n }\n nums[posX][posY] = value;\n score += value;\n $('#score').text(score);\n showNum(posX,posY,value);\n checkGameOver();\n }", "function square(number) {\n return number * number;\n }", "function pickCardToPlay() :ActionType { // change to use new global variables about the board!!\n\tvar which:ActionType = ActionType.Grow; // default to first card\n\tvar cardNum:int = 0;\n\tvar squares = -1;\n\tvar left:boolean = true;\n\tcantPlay = false;\n\t\n\t\n\t/*\n\tIf choose a Disaster, will destroy own Veggie that are doubled up on their square first.\n\tIf choose a Disaster, will destroy own Veggie that are misplanted on the wrong soil second.\n\tIf choose a Disaster, will destroy random player's Veggies which have exactly the number of Veggies as the card drawn states, third.\n\tIf choose a Disaster, will destroy random player's Veggies which summed up have exactly the number of Veggies as the card drawn states, fourth.\n\tIf choose a Disaster, will destroy random player's Veggies so that it destroys an entire Veggie (or multiple entire Veggie), plus some of another Veggie (if card drawn is large enough), fifth.\n\tIf choose a Cultivator, will plant in first empty square with the correct soil, if available.\n\tIf choose a Cultivator, will plant in first square with the correct soil AND one of its own Veggies on that square, second.\n\tIf choose a Cultivator, will plant in random empty square on the board, fourth.\n\tIf choose a Cultivator, will plant in random square which has one of its own Veggies on that square, third.\n\t*/\n\t\n\t\n\t// do logic to determine card to play\n\t// only play destroy card if other player has some plants\n\tif (GameStateScript.getHumanPlantsInstances(PlayerType.Human) !== null) {\n\t\t// play disaster card first if have one\n\t\tcardNum = getDestroyCard();\n\t\tif (cardNum != -1) {\n\t\t\twhich = ActionType.Destroy;\n\t\t\t\n\t\t\tif (Random.value >= GameStateScript.randomAI) { // do something smart if greater percentage\n\t\t\t\n\t\t\tmyDoubled = getMyDoubled();\n\t\t\t\tif (myDoubled != null) {\n\t\t\t\t\t// let's find the smallest plant in that square\n\t\t\t\t\tvar smallest:int = 0;\n\t\t\t\t\tvar smallestCount:int = 9999;\n\t\t\t\t\tif (myDoubled[0] != null) {\n\t\t\t\t\t\tfor (var index:int =0; index < myDoubled[0].planted.Count; index++) {\n\t\t\t\t\t\t\tif (myDoubled[0].planted[index].num < smallestCount) {\n\t\t\t\t\t\t\t\tsmallest = index;\n\t\t\t\t\t\t\t\tsmallestCount = myDoubled[0].planted[index].num;\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\tleft = GameBoardScript.playCard(cardNum, PlayerType.AI, myDoubled[0].row, myDoubled[0].col, smallest);\n\t\t\t\t\t\n\t\t\t\t\tif (left != 0) {\n\t\t\t\t\t\t// won't do anything with this scenario - when play will destroy all of it\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\t\n\t\t\t\t\tmyMisplanted = getMyMisplanted();\n\t\t\t\t\tif (myMisplanted != null) {\n\t\t\t\t\t\n\t\t\t\t\t\t// get the largest plant that you can kill\n\t\t\t\t\t\tvar largest:int = 0;\n\t\t\t\t\t\tvar largestCount:int = 0;\n\t\t\t\t\t\tif (myMisplanted[0] != null) {\n\t\t\t\t\t\t\tfor (var loc:int =0; loc < myMisplanted[0].planted.Count; loc++) {\n\t\t\t\t\t\t\t\tif (myMisplanted[loc].planted.Item[0].num > largestCount) {\n\t\t\t\t\t\t\t\t\tlargest = index;\n\t\t\t\t\t\t\t\t\tlargestCount = myMisplanted[loc].planted[0].num;\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\tleft = GameBoardScript.playCard(cardNum, PlayerType.AI, myMisplanted[0].row, myMisplanted[0].col, 0);\n\t\n\t\t\t\t\t\tif (left != 0) {\n\t\t\t\t\t\t\t// won't do anything with this scenario yet\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t\t\tothersPlants = GameStateScript.getHumanPlantsInstances(PlayerType.Human);\n\t\t\t\t\t\tif (othersPlants != null) {\n\t\t\t\t\t\t\tvar saveMe = 0; // destroy the first plant found if don't find one that's exactly the right size\n\t\t\t\t\t\t\tif (othersPlants.Count > 0 && othersPlants[0] != null) {\n\t\t\t\t\t\t\t\tfor (var i:int=0; i < othersPlants.Count; i++) {\n\t\t\t\t\t\t\t\t\tif (othersPlants[i].planted.Item[0].num == GameStateScript.getAIAction(cardNum).num) {\n\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tsaveMe = i;\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\t\n\t\t\t\t\t\t\t\t// doesn't like something about the below line - get NULLEXCEPTION error here sometimes\n\t\t\t\t\t\t\t\tleft = GameBoardScript.playCard(cardNum, PlayerType.AI, othersPlants[saveMe].row, othersPlants[saveMe].col, 0);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcantPlay = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcantPlay = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else { // do something random if less than the percentage\n\t\t\t\t// do a random destroy\n\t\t\t\tvar randWhich:int;\n\t\t\t\tvar theirPlants:System.Collections.ArrayList = GameStateScript.getHumanPlantsInstances(PlayerType.Human);\n\t\t\t\tvar myPlants:System.Collections.ArrayList = GameStateScript.getHumanPlantsInstances(PlayerType.AI);\n\t\t\t\tvar plantNum:int;\n\t\t\t\tif (theirPlants.Count != 0 && Random.value >= .5) { // destroy mine as likely as one of theirs\n\t\t\t\t\trandWhich = Mathf.Floor(Random.value * theirPlants.Count);\n\t\t\t\t\tif (theirPlants[randWhich].planted != null && theirPlants[randWhich].planted.Count > 0) {\n\t\t\t\t\t\tplantNum = theirPlants[randWhich].planted.Count - 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcantPlay = true; // something happened and should just grow for now, try again next time\n\t\t\t\t\t}\n\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, theirPlants[randWhich].row, theirPlants[randWhich].col, plantNum);\n\t\t\t\t} else if (myPlants.Count != 0 ){\n\t\t\t\t\trandWhich = Mathf.Floor(Random.value * myPlants.Count);\n\t\t\t\t\tif (myPlants[randWhich].planted != null && myPlants[randWhich].planted.Count > 0) {\n\t\t\t\t\t\tplantNum = myPlants[randWhich].planted.Count - 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcantPlay = true;\n\t\t\t\t\t}\n\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, myPlants[randWhich].row, myPlants[randWhich].col, plantNum);\n\t\t\t\t} else { // can't play\n\t\t\t\t\tcantPlay = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\twhich = ActionType.Grow;\n\t\t\tcardNum = getGrowCard();\n\t\t\tif (cardNum != -1) {\n\t\t\t\n\t\t\t\tif (Random.value >= GameStateScript.randomAI) { // do something planned unless greater number (ie smarter)\n\t\t\t\t\t\n\t\t\t\t\tvar correctSoil = -1;\n\t\t\t\t\tvar plantedCorrectSoil = -1;\n\t\t\t\t\tvar emptySoil = -1;\n\t\t\t\t\tvar plantedSoil = -1;\n\t\t\t\t\tvar checkPt:int = 0;\n\t\t\t\t\tvar soilType:SoilType = getSoil(GameStateScript.getAIAction(cardNum).plant);\n\t\t\t\t\tmyPlanted = GameStateScript.getHumanPlantsInstances(PlayerType.AI, soilType);\n\t\t\t\t\tif (myPlanted.Count != 0) {\n\t\t\t\t\t\twhile (checkPt < myPlanted.Count && plantedCorrectSoil == -1) {\n\t\t\t\t\t\t\tif (myPlanted[checkPt].planted.Count == 1) { // since looking at previously planted squares only, check for only one on there, not two\n\t\t\t\t\t\t\t\tplantedCorrectSoil = checkPt;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcheckPt++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckPt = 0;\n\t\t\t\t\t}\n\t\t\t\t\t// how do I get planted soil that is NOT of the right soil?\n\t\t\t\t\tmyWrongPlanted = GameStateScript.getHumanPlantsNotOfSoilTypeInstances(PlayerType.AI, soilType);\n\t\t\t\t\tif (myWrongPlanted.Count != 0) {\n\t\t\t\t\t\twhile (checkPt < myWrongPlanted.Count && plantedSoil == -1) {\n\t\t\t\t\t\t\tif (myWrongPlanted[checkPt].planted.Count == 1) { // since looking at previously planted squares only, check for only one on there, not two\n\t\t\t\t\t\t\t\tplantedSoil = checkPt;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcheckPt++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckPt = 0;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\temptySoils = GameStateScript.getEmptyCells(soilType);\n\t\t\t\t\tif (emptySoils.Count != 0) {\n\t\t\t\t\t\n\t\t\t\t\t\twhile (checkPt < emptySoils.Count && correctSoil == -1) {\n\t\t\t\t\t\t\tif (emptySoils[checkPt].planted.Count == 0 || emptySoils[checkPt].planted.Count == 1) { \n\t\t\t\t\t\t\t\tcorrectSoil = checkPt;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcheckPt++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckPt = 0;\n\t\t\t\t\t}\n\t\t\t\t\twrongEmptySoils = GameStateScript.getEmptyCellsNotOfSoilType(soilType);\n\t\t\t\t\tif (wrongEmptySoils.Count != 0 && wrongEmptySoils.Count < 2) {\n\t\t\t\t\t\twhile (checkPt < wrongEmptySoils.Count && emptySoil == -1) {\n\t\t\t\t\t\t\tif (wrongEmptySoils[checkPt].planted.Count == 0 || wrongEmptySoils[checkPt].planted.Count == 1) { \n\t\t\t\t\t\t\t\temptySoil = checkPt;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcheckPt++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckPt = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (correctSoil != -1) {\n\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, emptySoils[correctSoil].row, emptySoils[correctSoil].col, 0);\n\t\t\t\t\t\t\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (plantedCorrectSoil != -1) {\n\t\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, myPlanted[plantedCorrectSoil].row, myPlanted[plantedCorrectSoil].col, 0);\n\t\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (emptySoil != -1) {\n\t\t\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, wrongEmptySoils[emptySoil].row, wrongEmptySoils[emptySoil].col, 0);\n\t\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif (plantedSoil != -1) {\n\t\t\t\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, myWrongPlanted[plantedSoil].row, myWrongPlanted[plantedSoil].col, 0);\n\t\t\t\t\t\t\t\t} // should never get to an else here\n\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t} else { // do something random / not as smart\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tvar randWhich2:int;\n\t\t\t\t\tvar emptyPlants2:System.Collections.ArrayList = GameStateScript.getEmptyCells();\n\t\t\t\t\tvar myPlants2:System.Collections.ArrayList = GameStateScript.getHumanPlantsInstances(PlayerType.AI);\n\t\t\t\t\tif (emptyPlants2.Count != 0 && Random.value >= .2) { // grow on empty more likely than on mine\n\t\t\t\t\t\trandWhich2 = Mathf.Floor(Random.value * emptyPlants2.Count);\n\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, emptyPlants2[randWhich2].row, emptyPlants2[randWhich2].col, 0);\n\t\t\t\t\t} else if (myPlants2.Count != 0 ){\n\t\t\t\t\t\trandWhich2 = Mathf.Floor(Random.value * myPlants2.Count);\n\t\t\t\t\t\twhile (myPlants2[randWhich2].planted.Count != 1) { // to prevent over choosing the same square\n\t\t\t\t\t\t\trandWhich2 = Mathf.Floor(Random.value * myPlants2.Count);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, myPlants2[randWhich2].row, myPlants2[randWhich2].col, 0);\n\t\t\t\t\t} else { // have to go on empty square\n\t\t\t\t\t\trandWhich2 = Mathf.Floor(Random.value * emptyPlants2.Count);\n\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, emptyPlants2[randWhich2].row, emptyPlants2[randWhich2].col, 0);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t}\n\t\tif (cantPlay) {\n\t\t\t// then play a grow card instead\n\t\t\twhich = ActionType.Grow;\n\t\t\tcardNum = getGrowCard();\n\t\t\tif (cardNum != -1) {\n\t\t\t\n\t\t\t\tif (Random.value >= GameStateScript.randomAI) {\n\t\t\t\t\n\t\t\t\t\tvar correctSoil1 = -1;\n\t\t\t\t\tvar plantedCorrectSoil1 = -1;\n\t\t\t\t\tvar emptySoil1 = -1;\n\t\t\t\t\tvar plantedSoil1 = -1;\n\t\t\t\t\tvar checkPt1:int = 0;\n\t\t\t\t\tvar soilType1:SoilType = getSoil(GameStateScript.getAIAction(cardNum).plant);\n\t\t\t\t\tmyPlanted1 = GameStateScript.getHumanPlantsInstances(PlayerType.AI, soilType1);\n\t\t\t\t\tif (myPlanted1.Count != 0) {\n\t\t\t\t\t\twhile (checkPt1 < myPlanted1.Count && plantedCorrectSoil1 == -1) {\n\t\t\t\t\t\t\tif (myPlanted1[checkPt1].planted.Count == 1) { // since looking at previously planted squares only, check for only one on there, not two\n\t\t\t\t\t\t\t\tplantedCorrectSoil1 = checkPt1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcheckPt1++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckPt1 = 0;\n\t\t\t\t\t}\n\t\t\t\t\t// how do I get planted soil that is NOT of the right soil?\n\t\t\t\t\tmyWrongPlanted1 = GameStateScript.getHumanPlantsNotOfSoilTypeInstances(PlayerType.AI, soilType1);\n\t\t\t\t\tif (myWrongPlanted1.Count != 0) {\n\t\t\t\t\t\twhile (checkPt1 < myWrongPlanted1.Count && plantedSoil1 == -1) {\n\t\t\t\t\t\t\tif (myWrongPlanted1[checkPt1].planted.Count == 1) { // since looking at previously planted squares only, check for only one on there, not two\n\t\t\t\t\t\t\t\tplantedSoil1 = checkPt1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcheckPt1++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckPt1 = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\temptySoils1 = GameStateScript.getEmptyCells(soilType1);\n\t\t\t\t\tif (emptySoils1.Count != 0) {\n\t\t\t\t\t\n\t\t\t\t\t\twhile (checkPt1 < emptySoils1.Count && correctSoil1 == -1) {\n\t\t\t\t\t\t\tif (emptySoils1[checkPt1].planted.Count == 0 || emptySoils1[checkPt1].planted.Count == 1) { \n\t\t\t\t\t\t\t\tcorrectSoil1 = checkPt1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcheckPt1++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckPt1 = 0;\n\t\t\t\t\t}\n\t\t\t\t\twrongEmptySoils1 = GameStateScript.getEmptyCellsNotOfSoilType(soilType1);\n\t\t\t\t\tif (wrongEmptySoils1.Count != 0 && wrongEmptySoils1.Count < 2) {\n\t\t\t\t\t\twhile (checkPt1 < wrongEmptySoils1.Count && emptySoil1 == -1) {\n\t\t\t\t\t\t\tif (wrongEmptySoils1[checkPt1].planted.Count == 0 || wrongEmptySoils1[checkPt1].planted.Count == 1) { \n\t\t\t\t\t\t\t\temptySoil1 = checkPt1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcheckPt1++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcheckPt1 = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (correctSoil1 != -1) {\n\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, emptySoils1[correctSoil1].row, emptySoils1[correctSoil1].col, 0);\n\t\t\t\t\t\t\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (plantedCorrectSoil1 != -1) {\n\t\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, myPlanted1[plantedCorrectSoil1].row, myPlanted1[plantedCorrectSoil1].col, 0);\n\t\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (emptySoil1 != -1) {\n\t\t\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, wrongEmptySoils1[emptySoil1].row, wrongEmptySoils1[emptySoil1].col, 0);\n\t\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, myWrongPlanted1[plantedSoil1].row, myWrongPlanted1[plantedSoil1].col, 0);\n\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else { // do something random\n\t\t\t\t\tvar randWhich3:int;\n\t\t\t\t\tvar emptyPlants3:System.Collections.ArrayList = GameStateScript.getEmptyCells();\n\t\t\t\t\tvar myPlants3:System.Collections.ArrayList = GameStateScript.getHumanPlantsInstances(PlayerType.AI);\n\t\t\t\t\tif (emptyPlants3.Count != 0 && Random.value >= .2) { // grow on empty more likely than on mine\n\t\t\t\t\t\trandWhich3 = Mathf.Floor(Random.value * emptyPlants3.Count);\n\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, emptyPlants3[randWhich3].row, emptyPlants3[randWhich3].col, 0);\n\t\t\t\t\t} else if (myPlants3.Count != 0 ){\n\t\t\t\t\t\trandWhich3 = Mathf.Floor(Random.value * myPlants3.Count);\n\t\t\t\t\t\twhile (myPlants3[randWhich3].planted.Count != 1) { // to prevent over choosing the same square\n\t\t\t\t\t\t\trandWhich3 = Mathf.Floor(Random.value * myPlants3.Count);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, myPlants3[randWhich3].row, myPlants3[randWhich3].col, 0);\n\t\t\t\t\t} else { // have to go on empty square\n\t\t\t\t\t\trandWhich3 = Mathf.Floor(Random.value * emptyPlants3.Count);\n\t\t\t\t\t\tGameBoardScript.playCard(cardNum, PlayerType.AI, emptyPlants3[randWhich3].row, emptyPlants3[randWhich3].col, 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\tcantPlay = false;\n\t\t}\n\t}\n\t\t\n\n\t\n\t\n\t// play that card, so reset arrays for next turn\n\tmyDoubled = null;\n\tmyMisplanted = null;\n\tothersPlants = null;\n\tmyPlanted = null;\n\temptySoils = null;\n\t\n\treturn which;\t\n}", "function makeMove(strId) { // get game ( remove first two charageters)\n console.log(\"makeMove(\\\"\" + strId + \"\\\");\");\n let y = parseInt(strId.substring(0, 1));\n let x = parseInt(strId.substring(1));\n\n if (boxesTaken > 63) { // game over\n PopUpMessage(\"Please start another game\");\n return;\n }\n\n // if you are not clicking in an OPEN_SPACE square. exit function\n if (board[y][x] != OPEN_SPACE) {\n PopUpMessage(\"Please a valid move \\n(Click one of the shaded squares)\");\n return;\n }\n\n // the square is OPEN_SPACE\n let colorFile = (player == PLAYER1) ? PLAYER1_FILE : PLAYER2_FILE;\n document.getElementById(\"i\" + strId).src = colorFile; // paint it player one's color\n //document.getElementById(strId).style.backgroundColor = url(colorFile); // paint it player one's color\n board[y][x] = player; // put this square's id in the array\n boxesTaken++;\n clearShadeBoxes();\n flipSquares(x, y, colorFile);\n\n if (winner()) {\n PopUpMessage(\"press reset to Play again\");\n return;\n }\n\n player = (player ^ PLAYER1) ? PLAYER1 : PLAYER2; // change player\n shadeBoxes(player); // sahde the next player's available moves\n if (twoNoMovesInARow == 2) {\n PopUpMessage(\"Now More Valid moves\");\n /*\n if (p1Count > p2Count)\n PopUpMessage(\"Dark Player won\");\n if (p1Count < p2Count)\n PopUpMessage(\"Light Player won\");\n if (p1Count == p2Count)\n PopUpMessage(\"It's a tie!\");\n */\n return;\n }\n\n // set next turn color\n let color = (player == PLAYER1) ? PLAYER1_COLOR : PLAYER2_COLOR;\n document.getElementById(\"turnbox\").style.backgroundColor = color;\n\n //document.getElementById('Undo').disabled = false;\n}", "function assignShape(number) {\n player = number; //Assign the shape's selected value to global player variable.\n cpu = number * -1; //Assign the opposite number to global cpu variable.\n}", "function testSquareForMove(x, y, p, count, pieces, squares, energySquares){\r\n\tif (x >= 0 && y >= 0 && x < squares.length && y < squares.length){\r\n\t\t//normal move\r\n\t\tif (squares[x][y].piece === 32 && energySquares[x][y] === 0){\r\n\t\t\tif (testForBattleMove(x, y, p, squares)){\r\n\t\t\t\tpieces[p].moves[count] = {x:x, y:y, moveType:250};\r\n\t\t\t}else{\r\n\t\t\t\tpieces[p].moves[count] = {x:x, y:y, moveType:200};\r\n\t\t\t}\r\n\t\t\tcount++\r\n\t\t}\r\n\t}\r\n\treturn count;\r\n}", "function bestSpot(){\n//return an empty square (a random square for now)\nreturn emptySquares()[Math.floor(Math.random()*emptySquares().length)];\n}", "function playerClick(square){\n //Check if player's turn\n if (document.getElementById(\"game-turn\").innerHTML === \"Your\"){\n\n //Check if square is taken\n if (squareFree(square)) {\n\n //Set the square in the game\n setSquare(`${square}`,\"O\");\n\n } else {\n //Square already taken\n shakey();\n }\n } else {\n //It's not the player's turn!\n shakey();\n }\n}", "function getNewSize() {\n //input defaults to the previously selected size for user convenience \n let newSize = parseInt(prompt(\"How large would you like your etch-a-sketch to be?\", size));\n //input validation\n\n while (!(typeof newSize === 'number' && newSize > 0 && newSize < 101)) {\n newSize = parseInt(prompt(\"Please enter a number between 1 and 100.\", size));\n }\n size = newSize\n numOfSquares = size * size;\n}", "function computersTurn() {\n //boolean for while loop\n let success = false;\n //store a radond num (0-8)\n let pickASquare;\n\n //while keeps trying to find an unselected sqaure\n while(!success) {\n //rand between 0-8 is selected\n pickASquare = String(Math.floor(Math.random()*9));\n //if the rand number returns true, square has not yet been selected\n if (placeXOrO(pickASquare)) {\n //calls the function\n placeXOrO(pickASquare);\n //this changes bool and ends loop\n success = true;\n }\n }\n }", "function computerPlayerTurn() {\n var squareOccupied = false;\n var chosenSquare;\n\n do {\n // pick a random square number\n var randomSquareNum = Math.floor(Math.random() * totalSquares);\n console.log(\"Computer player chose square #\" + randomSquareNum);\n\n pcCount = randomSquareNum;\n\n // select the chosen square\n chosenSquare = $(\".square\").eq(randomSquareNum);\n\n\n // does the square have the class \"computer-player\" or \"human-player\"?\n if (chosenSquare.hasClass(\"computer-player\")\n || chosenSquare.hasClass(\"human-player\")) {\n squareOccupied = true;\n console.log(\"It was already taken!\");\n\n } else {\n squareOccupied = false;\n console.log(\"It was free\");\n tryNine++;\n }\n $(\"#rules\").hide();\n } while (squareOccupied);\n\n // give the square a CSS class\n chosenSquare.addClass(\"computer-player\");\n\n // computer picture\n var x = document.createElement(\"IMG\");\n x.setAttribute(\"src\", \"computer.png\");\n x.setAttribute(\"width\", \"180\");\n x.setAttribute(\"height\", \"180\");\n x.setAttribute(\"alt\", \"The computer\");\n document.body.appendChild(x);\n\n chosenSquare.html(x);\n\n }", "function randomSquare() {\n square.forEach(className => {\n className.classList.remove('mole')\n });\n //define a random position using math random\n let randomPosition = square[Math.floor(Math.random() * 9)];\n //add the mole to the randomPosition so it appears on the grid\n randomPosition.classList.add('mole');\n //assign the id of the randomPosition to hitPosition\n hitPosition = randomPosition.id;\n}", "function noBomb(x){\n squares[x].classList.remove(\"hidden\")\n squares[x].classList.remove(\"flag\")\n let newArround = arround\n //look at the squares arround taking into account if it's in a border\n if(x === 0){\n newArround = upLeftArround\n } else if ( x === 9){\n newArround = upRightArround\n } else if (x === 90){\n newArround = downLeftArround\n } else if (x === 99){\n newArround = downRightArround\n } else if (x<9){\n newArround = upArround\n } else if (x>90){\n newArround = downArround\n } else if (x%10 === 0){\n newArround = leftArround\n } else if ((x+1)%10 ===0){\n newArround = rightArround\n }\n\n //count the bombs arround the square\n let bombs = newArround.reduce(function(accum, square) {\n if(squares[x+square].classList.contains('bomb')){\n return accum + 1\n } else { return accum}\n }, 0)\n //if there are no bombs we repeat the accion with the squares arround it\n if(bombs===0){\n newArround.forEach(y => {if(squares[y+x].classList.contains(\"hidden\")){noBomb(y+x)}})\n } else {\n //write in the square the number of bombs arround\n squares[x].innerHTML = bombs;\n switch(bombs){\n case 1: \n squares[x].style.color = \"blue\";\n break;\n case 2:\n squares[x].style.color = \"rgb(17, 82, 17)\"\n break;\n case 3:\n squares[x].style.color = \"rgb(161, 23, 23)\";\n break;\n case 4:\n squares[x].style.color = \"rgb(56, 22, 90)\";\n break; \n case 5:\n squares[x].style.color = \"rgb(185, 125, 13)\";\n break; \n case 6:\n squares[x].style.color = \"rgb(5, 96, 119)\";\n break; \n case 7:\n squares[x].style.color = \"rgb(80, 35, 23)\";\n break; \n }\n }\n}", "deleteElementFromSquare(square, board){\n\t\tif (this.can_be_eaten){\n\t\t\tboard[square] = null;\n\t\t}\n\t\treturn board;\n\t}", "placePiece(row, square) {\n let piece = this.piece;\n this.board[row][square] = this.piece;\n if ( this.checkForWin(row, square, piece) ) {\n return true;\n }\n this.togglePiece();\n return;\n }", "function pieceMove(number,diceRoll,pieceNumber){\r\n\t//debugger;\r\n\tconst redImage=document.getElementById(\"red\");\r\n\tconst greenImage=document.getElementById(\"green\");\r\n \tconst blueImage=document.getElementById(\"blue\");\r\n\tconst yellowImage=document.getElementById(\"yellow\");\r\n\t/**\r\n\tThe first time the dice is rolled one needs a six to escape, and once one does escape, they will have to move six less\r\n\t**/\r\n\tif(pieceNumber==1){checkTrap(dice1,diceRoll,piece1,trapped1,redImage,pieceNumber,134); return;} //the first dice\r\n\tif(pieceNumber==2){checkTrap(dice2,diceRoll,piece2,trapped2,greenImage,pieceNumber,135);console.log(\"The value is \"+trapped2);return;}\r\n\tif(pieceNumber==3){checkTrap(dice3,diceRoll,piece3,trapped3,yellowImage,pieceNumber,136);return;}\r\n\tif(pieceNumber==4){checkTrap(dice4,diceRoll,piece4,trapped4,blueImage,pieceNumber,137);return;}\r\n\t\r\n\ttrapped1=false; //unfreeze the dice\r\n\ttrapped2=false; //unfreeze the dice\r\n\ttrapped3=false; //unfreeze the dice\r\n\ttrapped4=false; //unfreeze the dice\r\n\tconsole.log(\"The boolean is now \"+trapped2);\r\n\tconsole.log(\"Hammurabi \"+piece1.score);\r\n\tconsole.log(\"The dice 2 number is \"+dice2);\r\n\r\n\tcollision(number,pieceNumber);\r\n\tswitch(pieceNumber){ //this will reset the scores of the ludo pieces so that they will travel back\r\n\t\tcase 1:\r\n \t\tif(dice1==1){\r\n \t\t\tgameBoardArray[number-7].appendChild(redImage);\r\n \t\t\tpiece1.score=piece1.score-6; \r\n \t\t\treturn;\r\n \t\t\t} //for the case where the piece gets lucky and gets a six on their first roll.\r\n \t\t\tgameBoardArray[piece1.score-1].appendChild(redImage);\r\n\t\t\tbreak;\r\n\t\tcase 2:\r\n\t\tif(dice2==1){\r\n \t\t\tgameBoardArray[number-7].appendChild(greenImage);\r\n \t\t\tpiece2.score=piece2.score-6; \r\n \t\t\treturn;\r\n \t\t\t}\r\n \t\t\tgameBoardArray[number-1].appendChild(greenImage);\r\n\t\t\tbreak;\r\n\t\tcase 3:\r\n\t\t\tif(dice3==1){gameBoardArray[number-7].appendChild(yellowImage);}\r\n\t\t\tgameBoardArray[number-1].appendChild(yellowImage);\r\n\t\t\tbreak;\r\n\t\tcase 4:\r\n\t\t\tif(dice4==1){gameBoardArray[number-7].appendChild(blueImage);}\r\n\t\t\tgameBoardArray[number-1].appendChild(blueImage);\r\n\t\t\tbreak;\r\n\t}\r\n\r\n}", "function computerSquareEasy(squareArray){\n //Choose square at random and return the square number\n return squareArray[Math.floor(Math.random() * squareArray.length)];\n}", "function generateNewGame()\n{\n if(state == \"easy\")\n {\n colors = signColors(3);\n pickedColors = pickColor();\n color = squares[Math.floor(Math.random()*(3))].style.backgroundColor;\n }\n else{\n colors = signColors(6);\n pickedColors = pickColor();\n color = squares[Math.floor(Math.random()*(6))].style.backgroundColor;\n }\n \n \n display.textContent = color;\n document.getElementById(\"upper\").style.backgroundColor = \"rgb(203, 214, 175)\";\n resetButton.textContent = \"reset colors\"\n/*\n if(state == \"hard\")\n {\n for(var i = 3; i < squares.length; i++)\n {\n squares[i].style.display = \"block\"\n }\n }\n */ \n}", "function checkForSquare(gridNum, loc) {\n\tlet letter = turn;\n\tlet g = gameBoard[gridNum];\n\n\t// Check for 3 in a row\n\tif (\n\t\t(g.A1 === g.A2 && g.A1 === g.A3 && g.A1) ||\n\t\t(g.B1 === g.B2 && g.B1 === g.B3 && g.B1) ||\n\t\t(g.C1 === g.C2 && g.C1 === g.C3 && g.C1) ||\n\t\t(g.A1 === g.B1 && g.A1 === g.C1 && g.A1) ||\n\t\t(g.A2 === g.B2 && g.A2 === g.C2 && g.A2) ||\n\t\t(g.A3 === g.B3 && g.A3 === g.C3 && g.A3) ||\n\t\t(g.A1 === g.B2 && g.A1 === g.C3 && g.A1) ||\n\t\t(g.C1 === g.B2 && g.C1 === g.A3 && g.C1)\n\t) {\n\t\t// Add letter to board\n\t\t$(`#${gridNum}`).html(`${letter}`);\n\t\t$(`#${gridNum}`).removeClass('grid');\n\t\t$(`#${gridNum}`).addClass('letter');\n\n\t\t// Add letter to gameBoard array\n\t\tgameBoard.bigGrid[gridNum] = letter;\t\t\n\t} \n\t\n\t// Check that all squares have a value\n\telse if (g.A1 && g.A2 && g.A3 && g.B1 && g.B2 && g.B3 && g.C1 && g.C2 && g.C3) {\n\t\tgameBoard.bigGrid[gridNum] = 'Tie';\n\t}\n\t\n\t// Switch turns\n\tturn === 'X' ? turn = 'O': turn = 'X';\n\t$('#turn').text(`${turn}'s Turn`);\n\n\tcheckForWin(letter);\n\n\tif (!($('#turn').text() === 'X Wins' || $('#turn').text() === 'O Wins' || $('#turn').text() === \"It's a Tie Game!\")) {\n\t\tnextTurn(loc);\n\t}\n\n}", "function selectSquare(square) {\n // Square status\n var playerFigure;\n\n if (playerOne.turn) {\n square.value = playerOne.figure;\n playerFigure = playerOne.figure;\n } else if (playerTwo.turn) {\n square.value = playerTwo.figure;\n playerFigure = playerTwo.figure;\n } else {\n console.log(\"Error: No player selected\");\n }\n\n customSquare(square, playerFigure);\n nextTurn();\n square.disabled = \"disabled\";\n\n // Win Condition\n let row_index = parseInt(square.getAttribute(\"data-row-index\"));\n let col_index = parseInt(square.getAttribute(\"data-col-index\"));\n evaluateBoard(row_index, col_index, playerFigure);\n}", "removeLife() {\r\n const scoreboard = document.getElementsByClassName('tries');\r\n // Replace last heart with empty heart.\r\n scoreboard[scoreboard.length-this.missed-1].getElementsByTagName('img')[0].src = 'images/lostHeart.png'\r\n // count up missed property\r\n this.missed += 1;\r\n\r\n // Call gameOver() if player lost all lives\r\n if(this.missed === 5) {\r\n this.gameOver();\r\n }\r\n }", "function squareofNumber(square) {\n return square*square;\n }", "function computersTurn() {\n //this boolean is needed for our while loop\n let success = false;\n //this variable stores a random number 0-8.\n let pickASquare;\n //this condition allows our while loop to keep trying if a square is selected already\n while (!success) {\n //a random number between 0-8 is selected\n pickASquare = String(Math.floor(Math.random() * 9));\n //if the random number evaluated returns true, the square hasnt been selected yet\n if (placeXOrO(pickASquare)) {\n //this line calls the function\n placeXOrO(pickASquare);\n //This changes our boolean and ends the loop\n success = true;\n\n };\n }\n }", "function checkScore() {\n\tif (moves ===16 || moves===24){\n\t\t//alert(\"moves \"+moves);\n\t\tremoveStar();\n\t}\n}", "removeLife() {\r\n const tries = document.getElementsByClassName('tries')[this.missed];\r\n tries.firstChild.src = \"images/lostHeart.png\";\r\n this.missed += 1;\r\n if (this.missed === 5) {\r\n this.gameOver(false)\r\n }\r\n }", "sweep(row, col, e) {\n // if square does not exist, ignore it\n if (row < 0 || row > this.state.height|| col < 0 || col > this.state.width) {\n return;\n }\n if (this.state.grid[row][col].isCleared) {\n return;\n }\n const sweepNeighbors = () => {\n return (() => {\n const rowAbove = row - 1;\n const rowBelow = row + 1;\n for (let c = Math.max(0, col - 1); c < Math.min(this.state.width, col + 2); c++) {\n if (rowAbove >= 0) {\n this.sweep(rowAbove, c);\n }\n if (rowBelow < this.state.height) {\n this.sweep(rowBelow, c);\n }\n }\n if (col >= 1) {\n this.sweep(row, col - 1);\n }\n if (col < this.state.width - 1) {\n this.sweep(row, col + 1);\n }\n })();\n }\n const square = this.state.grid[row][col];\n if (square.val === 'mine' && e && (e.type === 'click' || e.type === 'mousedown')) {\n this.clearSquare(row, col);\n this.setState((prevState) => {\n const newState = {...prevState};\n newState.grid[row][col].char = '🔥';\n return {grid: newState.grid};\n })\n this.endGame(false);\n return;\n }\n // if it is a square and is blank, clear it\n if (square.count > 0) {\n this.clearSquare(row, col, this.endGameIfWon);\n return;\n }\n // if it is also 0 count, clear the neighbors too.\n if (square.val === 'blank' && !this.state.grid[row][col].isCleared) {\n // clear squares around the mine-free area\n this.clearSquare(row, col);\n this.clearSquare(row, col, sweepNeighbors);\n }\n return;\n }", "function computersTurn() {\n let success = false; //this boolean is used in the while loop\n let pickASquare; //This variable stores a random number 0-8\n while (!success) { //this condition allows the while loop to keep trying if a square is selected already\n pickASquare = String(Math.floor(Math.random() * 9)); //A random number between 0 and 8 is selected\n if (placeXOrO(pickASquare)) { //the random number checks for true, if it returns true the square hasnt been selected yet.\n placeXOrO(pickASquare); //this calls the function\n success = true; //this changes the boolean and ends the Loop\n };\n\n }\n }", "function askGrid(){\n $('.box').remove();\n var grid=+prompt(\"Click OK to reset the grid\", 16);\n myFunction(grid);\n makeSquare(grid);\n}", "function setFinishSquare() {\n while (true) {\n let randNum = (Math.random() * 4);\n randNum = Math.floor(randNum);\n\n let x = (allEdges.indexOf(currentSquare) + 6 + randNum);\n\n if (x > 15) {\n x = Math.abs(x - 15);\n }\n\n let finishPoint = allEdges[x];\n\n if (finishPoint !== currentSquare) {\n return finishPoint;\n break;\n };\n };\n}", "function square(numSquare) {\n return numSquare * numSquare;\n }", "removeLife(){\n this.missed++;\n const $lostHeart = $('#scoreboard img[src=\"images/liveHeart.png\"]:last');\n $lostHeart.attr('src', 'images/lostHeart.png');\n if(this.missed >= 5){\n let isWon = false;\n this.gameOver(isWon);\n }\n \n }", "function turn(squareId, player){\n \n //the selected cell take the symbole of the current player (X or O)\n originalBoard[squareId] = player;\n document.getElementById(squareId).innerText = player;\n \n //test if Game is Won\n let gameWon = checkWin(originalBoard, player);\n //call Game Over if the game is Won\n if(gameWon) gameOver(gameWon);\n}", "function btnClick() {\n\n let square = document.createElement(\"div\");\n\n square.className = \"makeSquare\";\n\n square.id = id;\n\n let p = document.createElement(\"p\");\n\n let squareText = document.createTextNode(id);\n\n p.appendChild(squareText);\n\n square.appendChild(p);\n\n document.body.appendChild(square);\n\n p.style.opacity = \"0\";\n\n id++;\n\n\n //what mouse does to text when moved over box.\n \n square.addEventListener(\"mouseover\", hover);\n\n function hover() {\n\n p.style.opacity = \"1\"\n\n }\n\n square.addEventListener(\"mouseleave\", nohover);\n\n function nohover() {\n\n p.style.opacity = \"0\"\n\n }\n\n //changes color of box background when clicked\n\n square.addEventListener(\"click\", randomColor);\n\n function randomColor() {\n\n let ranNum = Math.floor(Math.random() * 6);\n\n if (ranNum === 0) {\n\n square.style.backgroundColor = \"blue\"\n\n } else if (ranNum === 1) {\n\n square.style.backgrounColor = \"red\"\n\n } else if (ranNum === 2) {\n\n square.style.backgroundColor = \"orange\"\n\n } else if (ranNum === 3) {\n\n square.style.backgroundColor = \"yello\"\n\n } else if (ranNum === 4) {\n\n square.style.backgroundColor = \"green\"\n\n } else if (ranNum === 5) {\n\n square.style.backgroundColor = \"Gray\"\n\n };\n\n //delets block according to number.\n\n square.addEventListener(\"dblclick\", doubleClick);\n\n function doubleClick() {\n\n if (square.id % 2 === 0) {\n\n let numID = parseInt(square.id) +1;\n\n let num = document.getElementById(numID);\n\n if (num == null) {\n\n alert(\"Square with ID \" + numID + \" does not exist.\")\n\n } else {\n\n num.parentNode.removeChild(num)\n }\n\n } else {\n\n let numID = parseInt(square.id) -1;\n\n let num = document.getElementById(numID);\n\n if (num == null) {\n\n alert(\"Square with ID \" + numID + \" does not exist.\")\n\n } else {\n\n num.parentNode.removeChild(num)\n\n }\n\n }\n\n }\n }\n\n }", "removeLife() {\n heartNodes[this.missed].src = 'images/lostHeart.png';\n this.missed += 1;\n if (this.missed === heartNodes.length) {\n this.gameOver(false);\n }\n }", "function startRound(){\n guessNumber = Math.floor(Math.random() * (120 - 19)) + 19;\n $(\".GetThisText\").text(\"Your target: \" + guessNumber);\n \n yourNumber = 0\n $(\".YourNumText\").text(yourNumber + \" : Your number\");\n\n orangeStone = Math.floor(Math.random() * (12 - 1)) + 1;\n $(\"#orangeStone\").val(orangeStone);\n\n redStone = Math.floor(Math.random() * (12 - 1)) + 1;\n $(\"#redStone\").val(redStone);\n\n blueStone = Math.floor(Math.random() * (12 - 1)) + 1;\n $(\"#blueStone\").val(blueStone);\n\n purpleStone = Math.floor(Math.random() * (12 - 1)) + 1;\n $(\"#purpleStone\").val(purpleStone);\n\n greenStone = Math.floor(Math.random() * (12 - 1)) + 1;\n $(\"#greenStone\").val(greenStone);\n\n yellowStone = Math.floor(Math.random() * (12 - 1)) + 1;\n $(\"#yellowStone\").val(yellowStone);\n}", "function checkForGameLose() {\r\n let zeros = 0\r\n for (let i = 0; i < squares.length; i++) {\r\n if (squares[i] == 0) {\r\n zeros++\r\n }\r\n }\r\n let gameStatus = \"You Lose!\"\r\n if (zeros === 0) {\r\n for(let i=0;i<16;i+=4){\r\n let totalOne = squares[i] \r\n let totalTwo = squares[i+1] \r\n let totalThree = squares[i+2] \r\n let totalFour = squares[i+3] \r\n let row = [parseInt(totalOne), parseInt(totalTwo), parseInt(totalThree), parseInt(totalFour)]\r\n for(let j=0;j<row.length-1;j++){\r\n if(row[j]==row[j+1]){\r\n gameStatus = \"still playing\"\r\n }\r\n }\r\n let colToNum={0:0,4:1,8:2,12:3};\r\n totalOne = squares[colToNum[i]] \r\n totalTwo = squares[colToNum[i]+width]\r\n totalThree = squares[colToNum[i]+(width*2)] \r\n totalFour = squares[colToNum[i]+(width*3)] \r\n let column = [parseInt(totalOne),parseInt(totalTwo),parseInt(totalThree),parseInt(totalFour)]\r\n\r\n for(let j=0;j<column.length-1;j++){\r\n if(column[j]==column[j+1]){\r\n gameStatus = \"still playing\" \r\n }\r\n }\r\n }\r\n }\r\n if (gameStatus != \"still playing\" && zeros == 0) {\r\n resultDisplay.innerHTML = 'You Lose!'\r\n if (score > bestscore) {\r\n bestscore = score;\r\n bestscoreDisplay.innerHTML = bestscore\r\n }\r\n document.removeEventListener('keyup', control)\r\n }\r\n}", "function killPiece(x, y) {\r\n var bxy = board[x][y];\r\n var ele = document.getElementById(\"piece\" + String(Number(bxy[0]) * 16 + Number(bxy[1])));\r\n if (bxy[0] == 0) ele.style = pos(bxy[1], 9);\r\n else ele.style = pos(bxy[1], 10);\r\n ele.onclick = function () { };\r\n reviveList.push([bxy, 5]); // `5` means reviving after 5 goes\r\n}", "function squareTest(t){ //t=1 for player1, t=2 for player2\n\tj=1;\n\twhile (gotSquare==0 && j<n+1){\n\t\ti=1;\n\t\twhile (gotSquare==0 && i<n+1){\n\t\t\tif (state[i][j]==t){\n\t\t\t\tfor (l=j;l<n+1;l++){\n\t\t\t\t\tif (l==j){start=i+1}else{start=1;}\n\t\t\t\t\tfor (k=start;k<n+1;k++){\n\t\t\t\t\t\tif (state[k][l]==t){\n\t\t\t\t\t\t\tif ((0<k+l-j && k+l-j<n+1 && 0<l-k+i && l-k+i<n+1 &&\n\t\t\t\t\t\t\t\t 0<i+l-j && i+l-j<n+1 && 0<j-k+i && j-k+i<n+1 &&\n\t\t\t\t\t\t\t\t state[k+l-j][l-k+i]==t && state[i+l-j][j-k+i]==t)||\n\t\t\t\t\t\t \t(0<k+j-l && k+j-l<n+1 && 0<l-i+k && l-i+k<n+1 &&\n\t\t\t\t\t\t\t\t 0<i+j-l && i+j-l<n+1 && 0<j-i+k && j-i+k<n+1 &&\n\t\t\t\t\t\t\t\t state[k+j-l][l-i+k]==t && state[i+j-l][j-i+k]==t)){\n\t\t\t\t\t\t\t\tgotSquare=1; \n\t\t\t\t\t\t\t\t_root.conclusion._visible=true;\n\t\t\t\t\t\t\t\tif (opponent==0 && turn==1){_root.conclusion.text=\"Player 1 wins!\";}\n\t\t\t\t\t\t\t\tif (opponent==0 && turn==2){_root.conclusion.text=\"Player 2 wins!\";}\n\t\t\t\t\t\t\t\tif (opponent==1 && turn==1){_root.conclusion.text=\"You win!\";}\n\t\t\t\t\t\t\t\tif (opponent==1 && turn==2){_root.conclusion.text=\"Computer wins!\";}\n\t\t\t\t\t\t\t\tfreeze=1;\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}\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\tj++; \n\t}\n}", "function reset(){\n\ttargetNumber = Math.floor(Math.random() * (120 - 19)) + 2;\n\tconsole.log(\"New goal: \" + targetNumber)\n\t$(\"#number-to-guess\").text(targetNumber);\n\n \tgemOne = Math.floor(Math.random() * 12 - 1) + 2;\n \tgemTwo = Math.floor(Math.random() * 12 - 1) + 2;\n \tgemThree = Math.floor(Math.random() * 12 - 1) + 2;\n \tgemFour = Math.floor(Math.random() * 12 - 1) + 2;\n\n \tnumberCounter = 0;\n $('#counter').text(numberCounter);\n }", "function square() {\n this.currentInput = this.currentInput * this.currentInput;\n this.displayCurrentInput();\n}", "function toggleSize(){\n var elem = document.getElementsByClassName('board')[0];\n while (elem.firstChild) {\n elem.removeChild(elem.firstChild);\n }\n if(board_size === 3){\n board_size = 4;\n } else if(board_size === 4){\n board_size = 6;\n } else if(board_size === 6){\n board_size = 3;\n }\n resetBoard();\n}", "function checkScore() {\n if (score === randGoal) {\n wins++;\n $(\"#wins\").html(wins);\n//Resets game after wins or looses\n greenGem = Math.floor(Math.random() * 11) + 1;\n redGem = Math.floor(Math.random() * 11) + 1;\n purpleGem = Math.floor(Math.random() * 11) + 1;\n blueGem = Math.floor(Math.random() * 11) + 1;\n randGoal = Math.floor(Math.random() * 101)+19;\n score = 0;\n $(\"#randomNum\").html(randGoal);\n $(\"#totalScore\").html(\"\");\n }\n\n else if (score > randGoal) {\n looses++;\n $(\"#looses\").html(looses);\n greenGem = Math.floor(Math.random() * 11) + 1;\n redGem = Math.floor(Math.random() * 11) + 1;\n purpleGem = Math.floor(Math.random() * 11) + 1;\n blueGem = Math.floor(Math.random() * 11) + 1;\n randGoal = Math.floor(Math.random() * 101)+19;\n score = 0;\n $(\"#randomNum\").html(randGoal);\n $(\"#totalScore\").html(\"\");\n }\n }", "aiMakesMove(x, y) {\n boardArr = []\n var boardArr = game.boardToArray(x, y);\n x = boardArr[1]\n y = boardArr[2]\n var move = game.minimax(boardArr[0], game.ai);\n\n var newBoardArr = game.spliceBoard(boardArr[0]);\n\n // Set game difficutly probability\n if (game.difficulty == 'easy') {\n var actualMove = (Math.random() < 0.5) ? move : newBoardArr[Math.floor(Math.random()*newBoardArr.length)]\n console.log(\"EASY MODE\")\n }\n else if (game.difficulty == 'medium') {\n var actualMove = (Math.random() < 0.7) ? move : newBoardArr[Math.floor(Math.random()*newBoardArr.length)]\n console.log(\"MEDIUM MODE\")\n }\n else if (game.difficulty == 'hard') {\n var actualMove = (Math.random() < 0.98) ? move : newBoardArr[Math.floor(Math.random()*newBoardArr.length)]\n\n console.log(\"HARD MODE\")\n }\n console.log(\"MOVE: \", move)\n console.log(\"ACTUAL MOVE: \", actualMove)\n\n if (actualMove == move)\n {\n console.log(\"a\")\n var convertedMove = game.convertMove(actualMove);\n }\n else\n {\n console.log(\"b\")\n\n var convertedMove = game.convertRandMove(actualMove);\n }\n\n console.log(\"AI's move: \", move);\n console.log(\"convertedMove: \", convertedMove);\n\n game.placePieceAt(y, x, convertedMove.row, convertedMove.column, boardArr[0]);\n\n if(game.isOver(x, y, convertedMove.column, convertedMove.row)) {\n game.displayWinner();\n }\n\n\n aiCoords = [x, y, convertedMove.column, convertedMove.row]\n\n return (aiCoords)\n }", "removeLife() {\n this.missed++\n const tries = document.querySelectorAll('.tries img')\n if (this.missed === 1) {\n tries[0].src = 'images/emptyHeart.png'\n } else if (this.missed === 2) {\n tries[1].src = 'images/emptyHeart.png'\n } else if (this.missed === 3) {\n tries[2].src = 'images/emptyHeart.png'\n } else if (this.missed === 4) {\n tries[3].src = 'images/emptyHeart.png'\n } else if (this.missed === 5) {\n tries[4].src = 'images/emptyHeart.png'\n this.gameOver()\n }\n }", "function changeSecretNumber() {\n function resetScore() {\n _score = 20;\n _highScore = 0;\n }\n\n let _secretNumber = 0;\n let _score = 20;\n let _highScore = 0;\n}", "function square()\n {\n current_input = current_input * current_input\n displayCurrentInput();\n }" ]
[ "0.631566", "0.6223127", "0.61635333", "0.6143616", "0.61346024", "0.6128305", "0.61196375", "0.61172324", "0.6089684", "0.60799617", "0.6076921", "0.6067633", "0.60582596", "0.6035072", "0.60323584", "0.60217863", "0.6019556", "0.59916544", "0.59799534", "0.597427", "0.5965498", "0.59608483", "0.5958433", "0.59459555", "0.5928659", "0.59216195", "0.5912993", "0.5911411", "0.59072345", "0.5902013", "0.59015805", "0.5897597", "0.58887166", "0.5870495", "0.58586204", "0.58457917", "0.58351827", "0.58325726", "0.58261746", "0.58210814", "0.58199245", "0.580901", "0.5795535", "0.5793887", "0.57933086", "0.57901764", "0.5783343", "0.5777293", "0.577126", "0.57671034", "0.5762411", "0.5762269", "0.57566136", "0.5752455", "0.5750704", "0.57497805", "0.57462794", "0.57456607", "0.5740525", "0.57387805", "0.5730225", "0.5727404", "0.57259387", "0.5720288", "0.5715244", "0.57099515", "0.57093114", "0.5696853", "0.56932265", "0.5693194", "0.5691408", "0.5683159", "0.56812316", "0.56811273", "0.56763005", "0.5674797", "0.56705993", "0.56644183", "0.5663562", "0.5650975", "0.5645422", "0.56384456", "0.5636232", "0.5636211", "0.5633969", "0.5628712", "0.5626668", "0.5625814", "0.5624215", "0.5618076", "0.56176233", "0.5616096", "0.5615507", "0.5615379", "0.5613507", "0.5612771", "0.5610468", "0.5609409", "0.5605904", "0.55944294" ]
0.6794935
0
This function checks if every square of the game board is filled, meaning the user has won
function checkGridComplete() { // Make an array of all squares in the grid to look through let squares = qsa(".square"); // Make an empty array to store empty squares in let emptySquares = []; for (let i = 0; i < squares.length; i++) { // Define a variable to show the content of the squares within the squares array let squareContent = squares[i].textContent; // If the sqaure's content is an empty string if (squareContent === "") { // All empty squares are pushed onto the emptySquares array emptySquares.push(squareContent); } } // If the array is empty, the game is won. Else the game continues if (emptySquares.length === 0) { return true; } else { return false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function checkdraw() {\n //recall board is 7x6\n for (var row = 0; row < 6; row++) {\n for (var col = 0; col < 7; col++) {\n if (board[row][col] == 0) {\n return false;\n }\n }\n }\n //else board is filled and game is draw\n return true;\n}", "checkCompletedBoard(){\n let totalSquares = board.columnCount * board.rowCount;\n let dustedSquaresCount = 0;\n for(let checkColumn=0; checkColumn<board.columnCount; checkColumn++) {\n for(let checkRow=0; checkRow<board.rowCount; checkRow++) {\n let s = board.squares[checkColumn][checkRow];\n if (board.squares[checkColumn][checkRow].dusted===1) {\n dustedSquaresCount++;\n }\n }\n }\n if (dustedSquaresCount===totalSquares){\n level.boardFinished();\n }\n }", "function isBoardFilled() {\n for (let i = 0; i < squares.length; i++) {\n if (squares[i].innerText === '') {\n return false;\n }\n }\n \n return true;\n}", "function isEntireBoardFilled() {\n return board.every((y) => {\n return y.every((x) => {\n return x !== null;\n });\n });\n}", "function checkBoard() {\n\n\tfor (var w = 0; w < 3; w++) {\n\t\tif (board[w]+board[w+3]+board[w+6]==3 || board[3*w]+board[3*w+1]+board[3*w+2]==3 || board[0]+board[4]+board[8]==3 || board[2]+board[4]+board[6]==3) {\n\t\t\tvar info = isHumanTimes?\"You Win, unbelieveble\":'You lose'\n\t\t\tif (confirm(info+', continue?') == true) {\n \t\t\t\t\treset();\n \t\t\t\t\treturn;\n\t\t\t\t} else {\n \t\t\t\treturn;\n\t\t\t\t}\t\n\t\t}\n\t\tif (board[w]+board[w+3]+board[w+6]==30 || board[3*w]+board[3*w+1]+board[3*w+2]==30 || board[0]+board[4]+board[8]==30 || board[2]+board[4]+board[6]==30) {\n\t\t\tvar info = !isHumanTimes?\"You Win, unbelieveble\":'You lose'\n\t\t\tif (confirm(info+', continue?') == true) {\n \t\t\t\t\treset();\n \t\t\t\t\treturn;\n\t\t\t\t} else {\n \t\t\t\treturn;\n\t\t\t\t}\t\n\t\t}\n\t}\n\tfor (var v = 0; v < 9; v++) {\n\t\tif (board[v] === 0){\n\t\t\treturn;\n\t\t} \n\t\telse if (v === 8) {\n\t\t\t\tvar info = 'Draw, continue?'\n\t\t\t\tif (confirm(info) == true) {\n \t\t\t\t\treset();\n \t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tgameover = false;\n \t\t\t\treturn;\n\t\t\t\t}\t\n\t\t}\n\t}\n}", "function checkWin() {\n var squares = [];\n for (var i = 1; i <= 9; i++) {\n var classname = 'clicked' + symbol;\n squares[i] = $(document.getElementById(i)).hasClass(classname);\n }\n // top row\n var r1 = squares[1] && squares[2] && squares[3];\n // middle row\n var r2 = squares[4] && squares[5] && squares[6];\n // bottom row\n var r3 = squares[7] && squares[8] && squares[9];\n // left column\n var c1 = squares[1] && squares[4] && squares[7];\n // middle column\n var c2 = squares[2] && squares[5] && squares[8];\n // right column\n var c3 = squares[3] && squares[6] && squares[9];\n // left to right diagonal\n var d1 = squares[1] && squares[5] && squares[9];\n // right to left diagonal\n var d2 = squares[3] && squares[5] && squares[7];\n // are all the squares filled in\n var numClicked = $('.clicked').length;\n\n if (r1 || r2 || r3 || c1 || c2 || c3 || d1 || d2) {\n finishGame(symbol);\n } else {\n if (numClicked == 9)\n finishGame('TIE');\n }\n }", "function checkIfBoardFull() {\n\t\tfor (let index = 0; index < board.length; index++) {\n\t\t\tif (checkIfEmpty(index)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "function checkGameBoardIsFull()\n {\n var isFull = true;\n \n $('.game-cell-input').each(function(){\n isFull = !!($(this).val()) && isFull;\n });\n \n return isFull;\n }", "function checkForWin() {\n winningConditions.forEach((row) => {\n // check if the same string is inside each box in row\n // get the info: the string in the box is 'X' or 'O'\n if (didPlayerOneWin(row)) {\n alert('Bacon is the winner!!!')\n gameBoard.gameOver = true\n }\n else if (didPlayerTwoWin(row)) {\n alert('Egg is the winner!!!')\n gameBoard.gameOver = true\n }\n })\n // if the game is NOT over, but the boxes are full, then game over\n // write this outside the loop so there's no alerting x9\n if(!gameBoard.gameOver && boxesAreAllFull()) {\n alert(`It's a draw. Play again.`)\n gameBoard.gameOver = true\n }\n}", "function won(board) {\n const checkX = (el) => el === 'X';\n const checkY = (el) => el === 'Y';\n\n for(let i = 0; i < board.length; i++) {\n didWin = board[i].every(checkX) || board[i].every(checkY);\n if (didWin) return true;\n }\n\n return false;\n}", "function checkTie(board) {\r\n let boardFilled = false\r\n let occurances = 0\r\n board.forEach((value) => {\r\n value.length >= heightLimit ? occurances += 1 : occurances = 0\r\n })\r\n if (occurances === board.length) {\r\n boardFilled = true\r\n }\r\n return boardFilled\r\n}", "function checkForWin() {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n\n return cells.every( //check every cell on the board for a 1 or 2 (piece played)\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n }\n\n for (var y = 0; y < HEIGHT; y++) { \n for (var x = 0; x < WIDTH; x++) {\n var horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]]; //horizonal win\n var vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]]; //vertical win\n var diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]]; //diagonal to the right win\n var diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]]; //diagonal to the left win\n\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) { //if any of these win situations are true, return true\n return true;\n }\n }\n }\n}", "function isBoardFull() {\n for (let i = 0; i < height; i++)\n for (let j = 0; j < width; j++)\n if (gameBoard[i * height + j] === '⬜')\n return false;\n return true;\n }", "function isBoardFull() {\n\t\tif (!gameBoard.includes(\"\")) {\n\t\t\treturn true;\n\t\t} else {\n return false;\n }\n\t}", "function hasEmptyCells() {\n // scan through all cells, looking at text content for empty spaces\n var empty_spaces = 0\n for (let i = 0; i < 9; i++) {\n if (all_squares[i].textContent == ''){\n // return true if an empty cell is identified\n empty_spaces += 1\n } \n }\n if (empty_spaces == 0){\n document.getElementById(\"winMsg\").textContent = \"It's a draw! The board is filled\";\n } else {\n console.log(`${empty_spaces} cells remain`)\n }\n}", "function isFull(board) {\n for (var i = 0; i < 3; i++) {\n for (var j = 0; j < 3; j++) {\n if (board[i][j] == 0)\n return false;\n }\n }\n return true;\n}", "function checkForWin() {\n\tfunction _win(cells) {\n\t\t// Check four cells to see if they're all color of current player\n\t\t// - cells: list of four (y, x) cells\n\t\t// - returns true if all are legal coordinates & all match currPlayer\n\n\t\treturn cells.every(([ y, x ]) => y >= 0 && y < HEIGHT && x >= 0 && x < WIDTH && board[y][x] === currPlayer);\n\t}\n\n\t// TODO: read and understand this code. Add comments to help you.\n\t//for each y coordinate and each x coordinate,\n\t//check to see if the four surrounding coordinates are filled horizontally, vertically, or either direction diagonally.\n\t// if there are four coordinates filled of the same color, return true\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tlet horiz = [ [ y, x ], [ y, x + 1 ], [ y, x + 2 ], [ y, x + 3 ] ];\n\t\t\tlet vert = [ [ y, x ], [ y + 1, x ], [ y + 2, x ], [ y + 3, x ] ];\n\t\t\tlet diagDR = [ [ y, x ], [ y + 1, x + 1 ], [ y + 2, x + 2 ], [ y + 3, x + 3 ] ];\n\t\t\tlet diagDL = [ [ y, x ], [ y + 1, x - 1 ], [ y + 2, x - 2 ], [ y + 3, x - 3 ] ];\n\n\t\t\tif (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n}", "checkBoardFullness() {\n return Object.values(this.state.board).every(arr => Object.values(arr).every(value => value !== \"\"));\n }", "checkForWin() {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n const _win = cells =>\n cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < this.height &&\n x >= 0 &&\n x < this.width &&\n this.board[y][x] === this.currPlayer\n );\n\n\n for (let y = 0; y < this.height; y++) {\n for (let x = 0; x < this.width; x++) {\n // get \"check list\" of 4 cells (starting here) for each of the different\n // ways to win\n const horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n const vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n const diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n const diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n // find winner (only checking each win-possibility as needed)\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n }", "function checkForWin () {\n var numOfCells = board.cells.length\n var clearedSquares = 0\n var markedMines = 0\n var totalMines = 0\n \n for (k=0; k < numOfCells; k++){\n var checkCell = board.cells[k]\n // first count how many mines are present\n if (checkCell.isMine == true) {\n totalMines ++\n }\n //check to see if cell is NOT mine and is visible\n if (checkCell.isMine == false && checkCell.hidden == false){\n clearedSquares++\n }\n //check to see if is mine and is marked\n if (checkCell.isMine == true && checkCell.isMarked == true){\n markedMines ++\n }\n }\n var notMines = numOfCells - totalMines\n\n //console log tests\n console.log(\"wincheck\")\n console.log(clearedSquares,\" cleared squares out of total number of non mines\",notMines)\n console.log(markedMines, \"marked mines out of \",totalMines)\n\n\n if (clearedSquares == notMines || markedMines == totalMines){\n lib.displayMessage('You win!')\n var applause = document.getElementById(\"applause\")\n var applauseFlag = true;\n if (applauseFlag == true) {\n applause.pause();\n applause.curretTime = 0;\n applause.play();\n applauseFlag = false;\n }\n }\n \n}", "function checkGameOver() {\n\t\tvar b = $scope.game.board;\n\t\tvar bs = $scope.game.boardSize;\n\t\tvar row, col;\n\t\t//check rows\n\t\tfor(row = 0; row < bs; row++) {\n\t\t\tfor(col = 1; col < bs; col++) {\n\t\t\t\tif(b[row][col] === '' || b[row][col] !== b[row][col-1]) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(col == bs-1) {\n\t\t\t\t\tsetWinner(b[row][col]);\n\t\t\t\t\t$scope.game.gameOver = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//check columns\n\t\tfor(col = 0; col < bs; col++) {\n\t\t\tfor( row = 1; row < bs; row++) {\n\t\t\t\tif(b[row][col] === '' || b[row][col] !== b[row-1][col]) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (row == bs-1) {\n\t\t\t\t\tsetWinner(b[row][col]);\n\t\t\t\t\t$scope.game.gameOver = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//check diagonals\n\t\tfor(var i = 1; i < bs; i++) {\n\t\t\tif(b[0][0] === '' || b[i][i] !== b[0][0]) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(i == (bs-1)) {\n\t\t\t\tsetWinner(b[0][0]);\n\t\t\t\t$scope.game.gameOver = true;\n\t\t\t}\n\t\t}\n\t\tfor(i = 0; i < bs; i++) {\n\t\t\tif(b[0][bs-1] === '' || b[i][bs-1-i] !== b[0][bs-1]) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(i == (bs-1)) {\n\t\t\t\tsetWinner(b[0][bs-1]);\n\t\t\t\t$scope.game.gameOver = true;\n\t\t\t}\n\t\t}\n\t\t//if we've reached this point, there is no WIN, so check if gameboard is full\n\t\t//and return if not\n\t\tfor(i = 0; i < bs; i++) {\n\t\t\tfor(j = 0; j < bs; j++) {\n\t\t\t\tif(b[i][j] === '') return;\n\t\t\t}\n\t\t}\n\t\t//if we reach this point it's a tie\n\t\t$scope.game.gameOver = true;\n\t\tsetWinner('XO');\n\t}", "function isBoardFull() {\n for (var i = 0; i < 9; i++) {\n if (currentState.board[i] == 0) {\n return false;\n }\n return true;\n }\n}", "function checkWinner() {\r\n\t\t//check rows, cols, diags\r\n\t\t//if empty is 9, then we declare draw and end the game\r\n\r\n\t\tfor(var i = 0; i < winCombo.length; i++) {\r\n\t\t\tif(board[winCombo[i][0]].innerHTML != \" \" &&\r\n\t\t\t\tboard[winCombo[i][0]].innerHTML == board[winCombo[i][1]].innerHTML &&\r\n\t\t\t\tboard[winCombo[i][1]].innerHTML == board[winCombo[i][2]].innerHTML ) {\r\n\t\t\t\tboard[winCombo[i][0]].style.color = \"red\";\r\n\t\t\t\tboard[winCombo[i][1]].style.color = \"red\";\r\n\t\t\t\tboard[winCombo[i][2]].style.color = \"red\";\r\n\t\t\t\tcleanBgColor();\r\n\t\t\t\tdocument.getElementById(\"message\").innerHTML = board[winCombo[i][0]].innerHTML + \" wins!\";\r\n\t\t\t\tendGame();\r\n\t\t\t}\r\n\t\t}\t\t\r\n\t\r\n\t\t//check if the game is a draw \r\n\t\tif (empty == 0) {\r\n\t\t\tdocument.getElementById(\"message\").innerHTML = \"It's a draw.\";\r\n\t\t\tendGame();\r\n\t\t}\r\n\t}", "function checkForWin() {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n }\n\n // TODO: read and understand this code. Add comments to help you.\n\n for (let y = 0; y < HEIGHT; y++) {\n for (let x = 0; x < WIDTH; x++) {\n let horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n let vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n let diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n let diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n}", "function checkForWin() {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n }\n\n // TODO: read and understand this code. Add comments to help you.\n\n for (let y = 0; y < HEIGHT; y++) {\n for (let x = 0; x < WIDTH; x++) {\n let horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n let vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n let diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n let diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n}", "function checkForWin() {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n }\n\n // TODO: read and understand this code. Add comments to help you.\n\n for (let y = 0; y < HEIGHT; y++) {\n for (let x = 0; x < WIDTH; x++) {\n const horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n const vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n const diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n const diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n}", "function isBoardFull(){\n let board = $box.map((index, currBox) => {\n let $currBox = $(currBox);\n return isEmpty($currBox);\n });\n return !board.get().includes(true);\n }", "function checkForWin() {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n }\n for (let y = 0; y < HEIGHT; y++) { // loops through columns\n for (let x = 0; x < WIDTH; x++) { // loops through rows\n const horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]]; // coordinates assigned to this constant will check for a horizontal win\n const vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]]; // coordinates assigned to this constant will check for a vertical win\n const diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]]; // coordinates assigned to this constant will check for a diagonal win moving to the right\n const diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]]; // coordinates assigned to this constant will check for a diagonal win moving to the left\n\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) { // if any of the coordinates pass _win(), then the game is over.\n return true;\n }\n }\n }\n}", "function boxesAreAllFull() {\n result = true\n gameBoard.boxes.forEach((box) => {\n if(box.innerHTML === \" \") {\n result = false\n }\n })\n // we went the through the loop and now we're outside of it\n // and so if we haven't found an empty box, that means all of the boxes are full\n // and then it is a draw\n return result\n}", "checkForWin() {\n const _win = (cells) => {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < this.HEIGHT &&\n x >= 0 &&\n x < this.WIDTH &&\n this.board[y][x] === this.currPlayer\n );\n };\n\n for (let y = 0; y < this.HEIGHT; y++) {\n for (let x = 0; x < this.WIDTH; x++) {\n // get \"check list\" of 4 cells (starting here) for each of the different\n // ways to win\n const horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n const vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n const diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n const diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n // find winner (only checking each win-possibility as needed)\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n }", "function checkBoard()\n{\n //make variables for each square\n var square1 = document.getElementById('square1');\n var square2 = document.getElementById('square2');\n var square3 = document.getElementById('square3');\n var square4 = document.getElementById('square4');\n var square5 = document.getElementById('square5');\n var square6 = document.getElementById('square6');\n var square7 = document.getElementById('square7');\n var square8 = document.getElementById('square8');\n var square9 = document.getElementById('square9');\n\n //check if there is a winning combination\n if \n (\n square1.innerText == square2.innerText && square2.innerText == square3.innerText && square1.innerText != \"\" ||\n square4.innerText == square5.innerText && square5.innerText == square6.innerText && square4.innerText != \"\" ||\n square7.innerText == square8.innerText && square8.innerText == square9.innerText && square7.innerText != \"\" ||\n square1.innerText == square4.innerText && square4.innerText == square7.innerText && square1.innerText != \"\" ||\n square2.innerText == square5.innerText && square5.innerText == square8.innerText && square2.innerText != \"\" ||\n square3.innerText == square6.innerText && square6.innerText == square9.innerText && square3.innerText != \"\" ||\n square1.innerText == square5.innerText && square5.innerText == square9.innerText && square1.innerText != \"\" ||\n square3.innerText == square5.innerText && square5.innerText == square7.innerText && square3.innerText != \"\"\n )\n {\n //it is a win so end the game and display the winner\n if(xTurn)\n {\n document.getElementById('instructions').innerHTML = \"Player X Wins!\";\n gameIsOver = true;\n document.getElementById('button').innerHTML = \"Restart\";\n }\n else\n {\n document.getElementById('instructions').innerHTML = \"Player O Wins!\";\n gameIsOver = true;\n document.getElementById('button').innerHTML = \"Restart\";\n }\n }\n\n //check if there are no other spaces\n var areSpaces = false;\n\n var squareArray = \n [\n square1.innerText, square2.innerText, square3.innerText,\n square4.innerText, square5.innerText, square6.innerText,\n square7.innerText, square8.innerText, square9.innerText\n ];\n\n //check each space to see if it is empty\n for(i = 0; i < 9; i++)\n {\n if (squareArray[i] == \"\")\n areSpaces = true;\n }\n\n if(areSpaces)\n {\n //the game can continue\n return;\n }\n\n else\n {\n //the game needs to end with a tie\n gameIsOver = true;\n document.getElementById('instructions').innerHTML = \"It's a Tie.\";\n document.getElementById('button').innerHTML = \"Restart\";\n }\n}", "function checkForWin() {\n\tfunction _win(cells) {\n\t\t// Check four cells to see if they're all color of current player\n\t\t// - cells: list of four (y, x) cells\n\t\t// - returns true if all are legal coordinates & all match currPlayer\n\n\t\treturn cells.every(([ y, x ]) => y >= 0 && y < HEIGHT && x >= 0 && x < WIDTH && board[y][x] === currPlayer);\n\t}\n\n\t// TODO: read and understand this code. Add comments to help you.\n\t// this part will check each cell if the current player has 4 tokens together horizontically,vertically,and diagonally(right or left), and will return true so i can activate the endgame function.\n\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst horiz = [ [ y, x ], [ y, x + 1 ], [ y, x + 2 ], [ y, x + 3 ] ];\n\t\t\tconst vert = [ [ y, x ], [ y + 1, x ], [ y + 2, x ], [ y + 3, x ] ];\n\t\t\tconst diagDR = [ [ y, x ], [ y + 1, x + 1 ], [ y + 2, x + 2 ], [ y + 3, x + 3 ] ];\n\t\t\tconst diagDL = [ [ y, x ], [ y + 1, x - 1 ], [ y + 2, x - 2 ], [ y + 3, x - 3 ] ];\n\n\t\t\tif (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n}", "checkForWin() {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n const _win = cells =>\n cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < this.height &&\n x >= 0 &&\n x < this.width &&\n this.board[y][x] === this.currPlayer\n );\n\n for (let y = 0; y < this.height; y++) {\n for (let x = 0; x < this.width; x++) {\n // get \"check list\" of 4 cells (starting here) for each of the different\n // ways to win\n const horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n const vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n const diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n const diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n // find winner (only checking each win-possibility as needed)\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n }", "function checkForWin() {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n }\n\n // Checks all cells to see if a win starts there.\n\n for (let y = 0; y < HEIGHT; y++) {\n for (let x = 0; x < WIDTH; x++) {\n let horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n let vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n let diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n let diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n}", "checkWin(board, rows = 10, cols = 10) {\n var swept = true;\n for (var r = 0; r < rows; r ++) {\n for (var c = 0; c < cols; c++) {\n if (!board[r][c].mine && !board[r][c].visible) {\n swept = false;\n return;\n }\n }\n }\n return swept;\n }", "function checkForWin() {\n\tfunction _win(cells) {\n\t\t// Check four cells to see if they're all color of current player\n\t\t// - cells: list of four (y, x) cells\n\t\t// - returns true if all are legal coordinates & all match currPlayer\n\n\t\treturn cells.every(([ y, x ]) => y >= 0 && y < HEIGHT && x >= 0 && x < WIDTH && board[y][x] === currPlayer);\n\t}\n\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tlet horiz = [ [ y, x ], [ y, x + 1 ], [ y, x + 2 ], [ y, x + 3 ] ];\n\t\t\tlet vert = [ [ y, x ], [ y + 1, x ], [ y + 2, x ], [ y + 3, x ] ];\n\t\t\tlet diagDR = [ [ y, x ], [ y + 1, x + 1 ], [ y + 2, x + 2 ], [ y + 3, x + 3 ] ];\n\t\t\tlet diagDL = [ [ y, x ], [ y + 1, x - 1 ], [ y + 2, x - 2 ], [ y + 3, x - 3 ] ];\n\n\t\t\tif (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n}", "function checkForWin() {\n const _win = (cells) => {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n };\n\n // TODO: read and understand this code. Add comments to help you.\n //iterate throught the board\n for (let y = 0; y < HEIGHT; y++) {\n for (let x = 0; x < WIDTH; x++) {\n //to win horizontally, all y's are the same\n const horiz = [\n [y, x],\n [y, x + 1],\n [y, x + 2],\n [y, x + 3],\n ];\n //to win vertically, all x's are the same\n const vert = [\n [y, x],\n [y + 1, x],\n [y + 2, x],\n [y + 3, x],\n ];\n\n //to win diag to the right, x's and y's are all plus 1 every step\n const diagDR = [\n [y, x],\n [y + 1, x + 1],\n [y + 2, x + 2],\n [y + 3, x + 3],\n ];\n //to win diag to the left, x's subtract 1 every step and y's plus 1 every step\n const diagDL = [\n [y, x],\n [y + 1, x - 1],\n [y + 2, x - 2],\n [y + 3, x - 3],\n ];\n\n //one way winning is a win\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n\n //nobody wins return false;\n return false;\n}", "function winCheck (){\n var winCombos = [\n [0,1,2],\n [3,4,5],\n [6,7,8],\n [0,3,6],\n [1,4,7],\n [2,5,8],\n [0,4,8],\n [2,4,6]\n ]\n\n //win check\n for (var i=0; i < winCombos.length; i++) {\n var winCombo = winCombos[i]\n // if (board !== (winCombos[0,1,2,3,4,5,6,7])){\n var square1 = board[winCombo[0]]\n var square2 = board[winCombo[1]]\n var square3 = board[winCombo[2]]\n console.log(square1, square2, square3)\n\n if (square1 !== '' && square1 === square2 && square2 === square3){\n win = square1\n }\n\n }\n\n // tie check\n if (!win) {\n tie = true\n for (var i=0; i < board.length; i++) {\n if(board[i] === '') {\n tie = false\n }\n\n }\n }\n\n }", "function checkForWin() {\n\t// check four cells to see if they're all color of current player\n\t// • cells: list of four (y, x) cells\n\t// • returns true if all are legal coordinates & all match currPlayer\n\tfunction _win(cells) {\n\t\treturn cells.every(([y, x]) =>\n\t\t\ty >= 0 &&\n\t\t\ty < HEIGHT &&\n\t\t\tx >= 0 &&\n\t\t\tx < WIDTH &&\n\t\t\tboard[y][x] === currPlayer\n\t\t);\n\t}\n\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\t// get \"check list\" of 4 cells (starting here) for each of the different ways to win\n\t\t\tconst horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n\t\t\tconst vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n\t\t\tconst diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n\t\t\tconst diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n\t\t\t// find winner (only checking each win-possibility as needed)\n\t\t\tif (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) return true;\n\t\t}\n\t}\n}", "function checkFull(board, i){\n\tfor(let idx = 0; idx < board.WIDTH; idx++){\n\t\tif(board.board[i][idx].isEmpty()){\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}", "function gameIsDraw() {\n for (var y = 0; y <= 5; y++) {\n for (var x = 0; x <= 6; x++) {\n if (board[y][x] === 0) {\n return false;\n }\n }\n }\n // No locations were empty. Return true to indicate that the game is a draw.\n return true;\n}", "function boardFull(size, scoreBlack, scoreWhite) {\n if ((size * size) == scoreBlack + scoreWhite) {\n return true;\n }\n return false;\n}", "checkForWin() {\n if ((this.state.availCells.length <= 4) && (this.state.winner === '')) {\n this.winCheck()\n } else {\n this.nextTurn()\n }\n }", "function isFull(board) {\n return numTurnsPlayed(board) === board.length;\n}", "function checkWin() {\n var i,x,y,v;\n for(i=0; i<81; i++) {\n x = parseInt(spaces[i].dataset.x, 10);\n y = parseInt(spaces[i].dataset.y, 10);\n v = spaces[i].value;\n if ( !v || !valid(x, y, v)) {\n return;\n }\n }\n sudoku.classList.add('winner');\n }", "function checkForWin() {\n var hiddenBlanks = 0;\n var unMarkedMines = 0;\n\n for(var b = 0; b < board.cells.length; b++){\n if(board.cells[b].hidden == true && board.cells[b].isMine == false){\n hiddenBlanks++;}\n if(board.cells[b].isMine == true && board.cells[b].isMarked == false){\n unMarkedMines++;}\n }\n if(hiddenBlanks == 0 && unMarkedMines == 0){\n lib.displayMessage('You win!');\n }\n}", "boardIsFull()\n {\n\n for (var i = 0; i < this.state.board.length; i++) {\n if (this.state.board[i] === \"\") {\n return false;\n }\n }\n return true;\n }", "function checkWin() {\n for(i = 0; i < 3; i++)\n // checks if horizontal rows are equal to each other and not equal to an empty string.\n if($scope.board[i][0] == $scope.board[i][1] && $scope.board[i][2] == $scope.board[i][0] && $scope.board[i][0] !== \"\" && $scope.board[i][0] == \"X\"){\n console.log(\"X win horizontal\");\n p1Wins();\n }\n else if ($scope.board[i][0] == $scope.board[i][1] && $scope.board[i][2] == $scope.board[i][0] && $scope.board[i][0] !== \"\" && $scope.board[i][0] == \"O\"){\n console.log(\"O win horizontal\");\n p2Wins();\n }\n // checks if vertical columns are equal to each other and not equal to an empty string.\n else if ($scope.board[0][i] == $scope.board[1][i] && $scope.board[2][i] == $scope.board[0][i] && $scope.board[0][i] !== \"\" && $scope.board[0][i] == \"X\") {\n console.log(\"X win vertical\");\n p1Wins();\n }\n else if ($scope.board[0][i] == $scope.board[1][i] && $scope.board[2][i] == $scope.board[0][i] && $scope.board[0][i] !== \"\" && $scope.board[0][i] == \"O\") {\n console.log(\"O win vertical\");\n p2Wins();\n // checks diagonal. only true when i = 0\n }\n else if ($scope.board[0][i] == $scope.board[1][i+1] && $scope.board[2][i +2] == $scope.board[0][i] && $scope.board[0][i] !== \"\" && $scope.board[0][i] == \"X\") {\n console.log(\"X win diagonal right\");\n p1Wins();\n }\n else if ($scope.board[0][i] == $scope.board[1][i+1] && $scope.board[2][i +2] == $scope.board[0][i] && $scope.board[0][i] !== \"\" && $scope.board[0][i] == \"O\") {\n console.log(\"O win diagonal right\");\n p2Wins();\n }\n //checks left diagonal. only true when i = 2\n else if ($scope.board[0][i] == $scope.board[1][i-1] && $scope.board[2][i-2] == $scope.board[0][i] && $scope.board[0][i] !== \"\" && $scope.board[0][i] == \"X\") {\n console.log(\"X win diagonal left\");\n p1Wins();\n }\n else if ($scope.board[0][i] == $scope.board[1][i-1] && $scope.board[2][i-2] == $scope.board[0][i] && $scope.board[0][i] !== \"\" && $scope.board[0][i] == \"O\") {\n console.log(\"O win diagonal left\");\n p2Wins();\n }\n // if turnNumber reaches 9 there's been no winner, tie condition is enforced.\n else if ($scope.turnNumber == 9) {\n alert(\"Tie Game!\");\n console.log(\"TIE\");\n }\n}", "function checkForWin() {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n }\n\n // \n // iterate through y axis\n for (let y = 0; y < HEIGHT; y++) {\n // while going through x axis\n for (let x = 0; x < WIDTH; x++) {\n // coordinates for a horizontal win\n let horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n // coordinates for a vertical win\n let vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n // coordinates for a diagonal right win\n let diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n // coordinates for diagonal left win\n let diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n// if a win in any direction return true\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n}", "function checkBoard(i1, i2, i3, i4, i5) {\n if (checkArray(i1, clickedSquares)) {\n if (checkArray(i2, clickedSquares)) {\n if (checkArray(i3, clickedSquares)) {\n if (checkArray(i4, clickedSquares)) {\n if (checkArray(i5, clickedSquares)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n}", "function checkForWin() {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n // array.every returns a boolean for a condition on every elements of an array\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < height &&\n x >= 0 &&\n x < width &&\n board[y][x] === currPlayer\n );\n }\n\n // For each cell of the board, build:\n // - an horizontal array: starting cell and next 3 cell to the right\n // - a verticql array: starting cell and the next 3 down\n // - a right diagonal array: starting cell and 3 next cells down right\n // - a left diagonal array: starting cell and 3 next cells down left\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n const vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n const diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n const diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n // use the _win function on each array and return true if one of them is true\n if(_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)){\n return true;\n }\n }\n }\n}", "function checkForWin() {\n // define a win\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match currPlayer\n\n // if the y and x coordinates are vaild playable coordinates within the grid return true else return false\n return cells.every(\n ([y, x]) =>\n y >= 0 &&\n y < HEIGHT &&\n x >= 0 &&\n x < WIDTH &&\n board[y][x] === currPlayer\n );\n }\n\n // TODO: read and understand this code. Add comments to help you.\n // determining a win with four of the same pieces vertically, horizonally, diagDR, diagDL\n for (let y = 0; y < HEIGHT; y++) {\n for (let x = 0; x < WIDTH; x++) {\n let horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n let vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n let diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n let diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n}", "function checkWin(){\n if ((board.top.col1===board.top.col2 && board.top.col3===\"X\") || (board.top.col1===board.top.col2 && board.top.col3===\"O\")){\n running = false;\n console.log(\"Someone won!\");\n };\n if ((board.middle.col1===board.middle.col2 && board.middle.col3===\"X\") || (board.middle.col1===board.middle.col2 && board.middle.col3===\"O\")){\n running = false;\n console.log(\"Someone won!\");\n };\n if ((board.bottom.col1===board.bottom.col2 && board.bottom.col3===\"X\") || (board.bottom.col1===board.bottom.col2 && board.bottom.col3===\"O\")){\n running = false;\n console.log(\"Someone won!\");\n };\n if ((board.top.col1===board.middle.col2 && board.bottom.col3===\"X\") || (board.top.col1===board.middle.col2 && board.bottom.col3===\"O\")){\n running = false;\n console.log(\"Someone won!\");\n };\n if ((board.top.col3===board.middle.col2 && board.bottom.col1===\"X\") || (board.top.col3===board.middle.col2 && board.bottom.col1===\"O\")){\n running = false;\n console.log(\"Someone won!\");\n };\n}", "function checkForWin(boardstate){\n\tvar result = 0;\n\tvar success = false;\n\tfor(var i = 0; i < 7 && !success; i++){\n\t\tfor(var j = 0; j < boardstate[i].length && !success; j++){\n\t\t\tresult = checkAtSpot(boardstate, i, j, boardstate[i][j]);\n\t\t\tif(result){\n\t\t\t\tsuccess = true;\n\t\t\t\tconsole.log(\"Player\", result, \"has won the game.\");\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}", "function FullBoard(board){\n for(var i=0;i<3;i++){\n for(var s=0;s<3;s++){\n if(board[i][s]==' '){\n return false;\n }\n }\n }\n return true;\n}", "function checkBoard() \n {\n \tvar winner, empty = false\n\n\n\n \t// check board vertically and horizontally by looping through the cell rows and if it is equal\n \t// to a winning combo, it declares a winner\n\n for (var i = 0; i < 3; i++) \n {\n if (cell(i, 0) != '' && cell(i, 0) == cell(i, 1) && cell(i, 1) == cell(i, 2)) \n {\n winner = cell(i, 0)\n }\n if (cell(0, i) != '' && cell(0, i) == cell(1, i) && cell(1, i) == cell(2, i)) \n {\n winner = cell(0, i)\n }\n }\n \n \t// check board diagonally just like it did through vertical and horizontal\n \tif (cell(0, 0) && cell(0, 0) == cell(1, 1) && cell(1, 1) == cell(2, 2)) \n \t{\n \t\twinner = cell(0, 0)\n \t}\n\n \tif (cell(0, 2) && cell(0, 2) == cell(1, 1) && cell(1, 1) == cell(2, 0)) \n \t{\n \t\twinner = cell(0, 2)\n \t}\n\n\t// if there is a winner, set the winner's name to the winner global var\n if (winner) \n {\n $scope.winner = winner\n }\n else\n {\n \t // check for any empty cell by looping through the \"board\" array \n for (var i = 0; i < 3; i++) \n {\n for (var j = 0; j < 3; j++) \n {\n if (cell(i, j) == '') \n empty = true\n }\n }\n\n\t \t// no more empty cell - no winner, if empty is false, returns winner is NONE\n\t \tif (empty == false) \n\t \t{\n\t \t\t$scope.winner = 'NOBODY!'\n\t \t}\n }\n\n }", "checkVictory() {\n const turnsToCheck = this.turn === TURN.OH ? this.ohs : this.exs;\n\n // prettier-ignore\n const winning = [\n [0, 1, 2],\n [0, 3, 6],\n [0, 4, 8],\n [1, 4, 7],\n [2, 4, 6],\n [2, 5, 8],\n [3, 4, 5],\n [6, 7, 8],\n ];\n\n for (let i = 0; i < winning.length; i++) {\n this.won = winning[i].every((w) => turnsToCheck.includes(w));\n if (this.won) {\n this.ctx.fillStyle = '#00FF0040';\n this.ctx.fillRect(0, 0, this.gameWidth, this.gameHeight);\n return;\n }\n }\n }", "function checkBoard(board) {\n let fullCols = 0;\n for (var i = 0; i < board[0].length; i++) {\n let tempBool = isColumnFull(board, targetColumn);\n if (tempBool) {\n fullCols++;\n }\n }\n if (fullCols == 7) {\n return true;\n } else return false;\n}", "function checkBoard() {\n //make const that shows all winning arrays\n const winningArrays = [\n [0, 1, 2, 3], [41, 40, 39, 38], [7, 8, 9, 10], [34, 33, 32, 31], [14, 15, 16, 17], [27, 26, 25, 24], [21, 22, 23, 24],\n [20, 19, 18, 17], [28, 29, 30, 31], [13, 12, 11, 10], [35, 36, 37, 38], [6, 5, 4, 3], [0, 7, 14, 21], [41, 34, 27, 20],\n [1, 8, 15, 22], [40, 33, 26, 19], [2, 9, 16, 23], [39, 32, 25, 18], [3, 10, 17, 24], [38, 31, 24, 17], [4, 11, 18, 25],\n [37, 30, 23, 16], [5, 12, 19, 26], [36, 29, 22, 15], [6, 13, 20, 27], [35, 28, 21, 14], [0, 8, 16, 24], [41, 33, 25, 17],\n [7, 15, 23, 31], [34, 26, 18, 10], [14, 22, 30, 38], [27, 19, 11, 3], [35, 29, 23, 17], [6, 12, 18, 24], [28, 22, 16, 10],\n [13, 19, 25, 31], [21, 15, 9, 3], [20, 26, 32, 38], [36, 30, 24, 18], [5, 11, 17, 23], [37, 31, 25, 19], [4, 10, 16, 22],\n [2, 10, 18, 26], [39, 31, 23, 15], [1, 9, 17, 25], [40, 32, 24, 16], [9, 7, 25, 33], [8, 16, 24, 32], [11, 7, 23, 29],\n [12, 18, 24, 30], [1, 2, 3, 4], [5, 4, 3, 2], [8, 9, 10, 11], [12, 11, 10, 9], [15, 16, 17, 18], [19, 18, 17, 16],\n [22, 23, 24, 25], [26, 25, 24, 23], [29, 30, 31, 32], [33, 32, 31, 30], [36, 37, 38, 39], [40, 39, 38, 37], [7, 14, 21, 28],\n [8, 15, 22, 29], [9, 16, 23, 30], [10, 17, 24, 31], [11, 18, 25, 32], [12, 19, 26, 33], [13, 20, 27, 34]\n ];\n //now take the 4 values in each winningArray and plug them into the squares values\n\n for(let y = 0; y < winningArrays.length; y++) {\n const square1 = squares[winningArrays[y][0]];\n const square2 = squares[winningArrays[y][1]];\n const square3 = squares[winningArrays[y][2]];\n const square4 = squares[winningArrays[y][3]];\n\n //now check those arrays to see if they all have a class of player-one\n\n if(square1.classList.contains('player-one') &&\n square2.classList.contains('player-one') &&\n square3.classList.contains('player-one') &&\n square4.classList.contains('player-one')) {\n //if they do, player-one is passed as the winner\n result2.innerHTML = 'Player one wins!';\n }\n\n //now check to see if they all have the classname player two\n else if (square1.classList.contains('player-two') &&\n square2.classList.contains('player-two') &&\n square3.classList.contains('player-two') &&\n square4.classList.contains('player-two')) {\n result2.innerHTML = 'Player two wins!';\n }\n\n }\n\n }", "function checkForWin() {\n let youWin = true;\n for (let i = 0; i < board.cells.length; i++) {\n if (board.cells[i].isMine === true && board.cells[i].ismarked === false) {\n youWin = false;\n }\n if (board.cells[i].isMine !== true && board.cells[i].hidden === true) {\n youWin = false;\n // console.log(youWin)\n }\n }\n // detected that they've won.\n if (youWin) {\n lib.displayMessage(\"You win!\");\n }\n}", "function checkForWinner(){\n let boardState = [];\n function updateBoardState (filledClass) {\n //Check Columns\n for(let i = 0; i < 3; i++){\n boardState.push($box.eq(i).hasClass(filledClass) && $box.eq(i+3).hasClass(filledClass) && $box.eq(i+6).hasClass(filledClass));\n }\n //Check Rows\n for(let i = 0; i < 7; i += 3){\n boardState.push($box.eq(i).hasClass(filledClass) && $box.eq(i+1).hasClass(filledClass) && $box.eq(i+2).hasClass(filledClass));\n }\n //Check Diagonals\n boardState.push($box.eq(0).hasClass(filledClass) && $box.eq(4).hasClass(filledClass) && $box.eq(8).hasClass(filledClass));\n boardState.push($box.eq(2).hasClass(filledClass) && $box.eq(4).hasClass(filledClass) && $box.eq(6).hasClass(filledClass));\n }\n updateBoardState('box-filled-1');\n updateBoardState('box-filled-2');\n\n //Check if all boxes have been selected\n function isBoardFull(){\n let board = $box.map((index, currBox) => {\n let $currBox = $(currBox);\n return isEmpty($currBox);\n });\n return !board.get().includes(true);\n }\n\n if(boardState.includes(true)){\n if($('.active').attr('id') === 'player1'){\n $('#finish').addClass('screen-win-one');\n $('.message').append('Winner');\n $('#finish').show();\n } else {\n $('#finish').addClass('screen-win-two');\n $('.message').append('Winner');\n $('#finish').show();\n }\n } else if(isBoardFull()) {\n $('.message').append('It\\'s a Tie!');\n $('#finish').addClass('screen-win-tie');\n $('#finish').show();\n }\n }", "check(board) {\n let ok = true;\n this.foreach(function(x, y) {\n ok = ok && board.isInsideOrAbove(x,y) &&\n (board.getCell(x,y) === board.EMPTY);\n });\n return ok;\n }", "function gameOver(board) {\n //VERTICAL\n for (let c = 0; c < 7; c++)\n for (let r = 0; r < 3; r++)\n if (check(board[c][r], board[c][r+1], board[c][r+2], board[c][r+3]))\n return true;\n \n //HORIZONTAL\n for (let r = 0; r < 6; r++)\n for (let c = 0; c < 3; c++)\n if (check(board[c][r], board[c+1][r], board[c+2][r], board[c+3][r]))\n return true;\n \n\n //DIAGONAL\n for (let c = 0; c < 4; c++)\n for (let r = 0; r < 3; r++)\n if (check(board[c][r], board[c+1][r+1], board[c+2][r+2], board[c+3][r+3]))\n return true;\n \n //ANTIDIAGONAL\n for (let r = 5; r > 2; r--)\n for (let c = 6; c > 2; c--)\n if (check(board[c][r], board[c-1][r-1], board[c-2][r-2], board[c-3][r-3]))\n return true;\n return null;\n}", "function checkGameOver() {\r\n for (var i = 0; i < gBoard.length; i++) {\r\n for (var j = 0; j < gBoard[i].length; j++) {\r\n var cell = gBoard[i][j]\r\n if (!cell.isShown) {\r\n if (cell.isMarked) {\r\n if (!cell.isMine) return false;\r\n } else {\r\n return false\r\n }\r\n }\r\n }\r\n }\r\n return true\r\n}", "function checkforWinner(){\n let row1 = cell0.textContent+cell1.textContent+cell2.textContent; //These are all the winning combinations\n let row2 = cell3.textContent+cell4.textContent+cell5.textContent;\n let row3 = cell6.textContent+cell7.textContent+cell8.textContent;\n let col1 = cell0.textContent+cell3.textContent+cell6.textContent;\n let col2 = cell1.textContent+cell4.textContent+cell7.textContent;\n let col3 = cell2.textContent+cell5.textContent+cell8.textContent;\n let diagL = cell0.textContent+cell4.textContent+cell8.textContent;\n let diagR = cell2.textContent+cell4.textContent+cell6.textContent;\n let checkAnswer = [row1, row2, row3, col1, col2, col3, diagL, diagR]; //All winning combinations added to array for iteration\n\n //checks to see if there's a winning or drawn state, if so it gives an alert and calls resetBoard to reset the game board \n checkAnswer.forEach((cond)=>{\n if(cond === \"XXX\"){\n //alert('You win!')\n status.textContent = \"You win!\"\n gameOver = true;\n resetBoard()\n }\n if(cond === \"OOO\"){\n alert('The computer wins!')\n resetBoard()\n }\n //checks if the game has started (to stop drawing on an empty board when the game starts) and if all the cells have text content\n })\n if(gameStarted && allCells.every(element => element.textContent !== \"\")){\n alert(`It's a draw!`);\n resetBoard();\n }\n}", "check() {\r\n //check if all cells are taken\r\n if(this.board.every(row=>row.every(cell=>cell==1 || cell ==2))) return 3;\r\n for (var x = 0; x < 6; x++) {\r\n //For each row\r\n for (var y = 0; y < 7; y++) {\r\n //for each cell in row\r\n if(this.board[x][y] != 0) {\r\n //space occupied, check\r\n\r\n //check right\r\n var n = this.board[x][y]\r\n if(r(x, y, this.board).s) {\r\n this.board = r(x, y, this.board).d\r\n return n\r\n }\r\n if(u(x, y, this.board).s) {\r\n this.board = u(x, y, this.board).d\r\n return n\r\n }\r\n if(dl(x, y, this.board).s) {\r\n this.board = dl(x, y, this.board).d\r\n return n\r\n }\r\n if(dr(x, y, this.board).s) {\r\n this.board = dr(x, y, this.board).d\r\n return n\r\n }\r\n }\r\n\r\n }\r\n }\r\n return 0\r\n }", "checkBoard() {\n // Check three in a row and ties\n let countEmpty = 0;\n for (let row = 0; row < 3; row++) {\n let countX = 0;\n let countO = 0;\n for (let col = 0; col < 3; col++) {\n if (this.board[row][col] === \"X\") countX++;\n if (this.board[row][col] === \"O\") countO++;\n if (this.board[row][col] === \"\") countEmpty++;\n }\n if (countX === 3) this.winner = \"X wins!\";\n if (countO === 3) this.winner = \"O wins!\";\n }\n\n // Check three in a column\n for (let col = 0; col < 3; col++) {\n let countX = 0;\n let countO = 0;\n for (let row = 0; row < 3; row++) {\n if (this.board[row][col] === \"X\") countX++;\n if (this.board[row][col] === \"O\") countO++;\n }\n if (countX === 3) this.winner = \"X wins!\";\n if (countO === 3) this.winner = \"O wins!\";\n }\n\n // Check diagonals\n let countX = 0;\n let countO = 0;\n for (let i = 0; i < 3; i++) {\n if (this.board[i][i] === \"X\") countX++;\n if (this.board[i][i] === \"O\") countO++;\n }\n if (countX === 3) this.winner = \"X wins!\";\n if (countO === 3) this.winner = \"O wins!\";\n\n countX = 0;\n countO = 0;\n for (let i = 0; i < 3; i++) {\n if (this.board[i][2 - i] === \"X\") countX++;\n if (this.board[i][2 - i] === \"O\") countO++;\n }\n if (countX === 3) this.winner = \"X wins!\";\n if (countO === 3) this.winner = \"O wins!\";\n\n if (countEmpty === 0) this.winner = \"It's a tie!\";\n }", "function checkWin(){\r\n\tlet cb = []; //current Board\r\n\tcb[0] = \"\"; //not going to use\r\n\tcb[1] = document.getElementById(\"one\").innerHTML;\r\n\tcb[2] = document.getElementById(\"two\").innerHTML;\r\n\tcb[3] = document.getElementById(\"three\").innerHTML;\r\n\tcb[4] = document.getElementById(\"four\").innerHTML;\r\n\tcb[5] = document.getElementById(\"five\").innerHTML;\r\n\tcb[6] = document.getElementById(\"six\").innerHTML;\r\n\tcb[7] = document.getElementById(\"seven\").innerHTML;\r\n\tcb[8] = document.getElementById(\"eight\").innerHTML;\r\n\tcb[9] = document.getElementById(\"nine\").innerHTML;\r\n\t\r\n\t//top row \r\n\tif(cb[1] != \"\" && cb[1] == cb[2] && cb[2] == cb[3]) {\r\n\t\treturn true;\r\n\t}//if\r\n\t\r\n\t//middle row\r\n\tif(cb[4] != \"\" && cb[4] == cb[5] && cb[5] == cb[6]) {\r\n\t\treturn true;\r\n\t}//if\r\n\t\r\n\t//bottem row\r\n\tif(cb[7] != \"\" && cb[7] == cb[8] && cb[8] == cb[9]) {\r\n\t\treturn true;\r\n\t}//if\r\n\t\r\n\t//first collum\r\n\tif(cb[1] != \"\" && cb[1] == cb[4] && cb[4] == cb[7]) {\r\n\t\treturn true;\r\n\t}//if\r\n\t\r\n\t//second collum\r\n\tif(cb[2] != \"\" && cb[2] == cb[5] && cb[5] == cb[8]) {\r\n\t\treturn true;\r\n\t}//if\r\n\t\r\n\t//third collum\r\n\tif(cb[3] != \"\" && cb[3] == cb[6] && cb[6] == cb[9]) {\r\n\t\treturn true;\r\n\t}//if\r\n\t\r\n\t//digonal left going down\r\n\tif(cb[1] != \"\" && cb[1] == cb[5] && cb[5] == cb[9]) {\r\n\t\treturn true;\r\n\t}//if\r\n\t\r\n\t\r\n\t//digonal right going down\r\n\tif(cb[3] != \"\" && cb[3] == cb[5] && cb[5] == cb[7]) {\r\n\t\treturn true;\r\n\t}//if\r\n\r\n\telse{\r\n\t\t\t\t//check for tie\r\n\t\tif(numTurns == 9){\r\n\t\t\tgameStatus = \"Game Tie\";\r\n\t\t}//numTurns\r\n\t}//else\r\n\t\r\n\r\n\r\n}//check win", "function checkWin(symb){\n\t\t\tconsole.dir(self.squares);\n\t\t\t//check if all squares occupied\n\t\t\tvar allSquaresTaken = self.squares.every(function(i){\n\t\t\t\treturn i.symbol !== \" \";\n\t\t\t});\n\t\t\t// check columns\n\t\t\tif((symb === self.squares[0].symbol && symb === self.squares[3].symbol && symb === self.squares[6].symbol) || (symb === self.squares[1].symbol && symb === self.squares[4].symbol && symb === self.squares[7].symbol) || (symb === self.squares[2].symbol && symb === self.squares[5].symbol && symb === self.squares[8].symbol)){\n\t\t\t\tself.stats.message = symb + \" wins!\";\n\t\t\t\tself.stats.gameEnd = true;\n\t\t\t\tself.stats.$save();\n\t\t\t}\n\t\t\t// check rows\n\t\t\telse if ((symb === self.squares[0].symbol && symb === self.squares[1].symbol && symb === self.squares[2].symbol) || (symb === self.squares[3].symbol && symb === self.squares[4].symbol && symb === self.squares[5].symbol) || (symb === self.squares[6].symbol && symb === self.squares[7].symbol && symb === self.squares[8].symbol)){\n\t\t\t\tself.stats.message = symb + \" wins!\";\n\t\t\t\tself.stats.gameEnd = true;\n\t\t\t\tself.stats.$save();\n\t\t\t}\n\t\t\t//check diagonals\n\t\t\telse if ((symb === self.squares[0].symbol && symb === self.squares[4].symbol && symb === self.squares[8].symbol) || (symb === self.squares[2].symbol && symb === self.squares[4].symbol && symb === self.squares[6].symbol)){\n\t\t\t\tself.stats.message = symb + \" wins!\";\n\t\t\t\tself.stats.gameEnd = true;\n\t\t\t\tself.stats.$save();\n\t\t\t}\n\t\t\t//check for tie\n\t\t\telse if (allSquaresTaken){\n\t\t\t\tself.stats.message = \"It's a tie!\";\n\t\t\t\tself.stats.gameEnd = true;\n\t\t\t\tself.stats.$save();\n\t\t\t}\n\t\t}//function checkWin END", "function checkIfWon(chosenSquare) {\n\n var mulitArr = winningCombos[chosenSquare];\n var playerWon;\n\n for (var i = 0; i < mulitArr.length; i++) { // this nested loop provides the length of the multidimensional array\n playerWon = true;\n for (var j = 0; j < mulitArr[i].length; j++) {\n //value of j starts at zero\n //If j starts at 1 only two more divs must match in order to win.\n //If j is two 2 only one more div must be matched in order to win (which would be any square on the board)\n if (!$(\"#board\").find(\"div\").eq(mulitArr[i][j]).find(\"span\").hasClass(circleOrEx)) {\n // if the #board finds the divs are equal(equal amount of \"x\" and \"o\" then nothing happens)\n playerWon = false;\n }\n }\n\n if (playerWon) { // if they playerWon do this code\n\n for (var j = 0; j < mulitArr[i].length; j++) {\n $(\"#board\").find(\"div\").eq(mulitArr[i][j]).find(\".\" + circleOrEx).addClass(\"green\");\n //This changes the divs i and j (the first two inputs) of the winning combination to green\n }\n $(\"#board\").find(\"div\").eq(chosenSquare).find(\".\" + circleOrEx).addClass(\"green\");\n // this changes the chosenSquare (the deciding div) of the winning combination to green aswell\n alert(\"Winner is \" + circleOrEx.toUpperCase() + \"!\");\n // this makes an alert pop up saying who the winner is\n isGameInProgress = false;\n // at this point the game is not in progress anymore\n return false; //this exits the loop\n }\n }\n\n\n }", "function allFilled() {\n\treturn boards[0].every((val) => val != null); //Return true if td is filled else return false\n}", "function checkForWin() {\n\tfunction _win(cells) {\n\t\t// Check four cells to see if they're all color of current player\n\t\t// - cells: list of four (y, x) cells\n\t\t// - returns true if all are legal coordinates & all match currPlayer\n\n\t\treturn cells.every(([ y, x ]) => y >= 0 && y < HEIGHT && x >= 0 && x < WIDTH && board[y][x] === currPlayer); //???\n\t}\n\n\t// TODO: read and understand this code. Add comments to help you.\n\n\tfor (var y = 0; y < HEIGHT; y++) {\n\t\tfor (var x = 0; x < WIDTH; x++) {\n\t\t\tvar horiz = [ [ y, x ], [ y, x + 1 ], [ y, x + 2 ], [ y, x + 3 ] ]; //4 possible matches per row - total : 24 possible matches\n\t\t\tvar vert = [ [ y, x ], [ y + 1, x ], [ y + 2, x ], [ y + 3, x ] ]; //3 possible matches per column - total : 21 possible matches\n\t\t\tvar diagDR = [ [ y, x ], [ y + 1, x + 1 ], [ y + 2, x + 2 ], [ y + 3, x + 3 ] ]; //4,5,6,6,5,4 - total : 12 possible matches\n\t\t\tvar diagDL = [ [ y, x ], [ y + 1, x - 1 ], [ y + 2, x - 2 ], [ y + 3, x - 3 ] ]; //4,5,6,6,5,4 - total : 12 possible matches\n\t\t\t//total runtime : 69 possible matches?\n\t\t\tif (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n}", "function occupied(i, j) // is this square occupied\r\n{\r\n // Added check to ensure that occupied square is in grid.\r\n if (i <= gridsize && j <= gridsize &&\r\n i >= 0 && j >= 0) {\r\n\r\n switch (GRID[i][j]) {\r\n case GRID_WALL:\r\n case GRID_MAZE:\r\n case GRID_ENEMY:\r\n case GRID_AGENT:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }\r\n // off the grid\r\n return true;\r\n}", "function checkForWin(player,gameboard) {\n function _win(cells) {\n // Check four cells to see if they're all color of current player\n // - cells: list of four (y, x) cells\n // - returns true if all are legal coordinates & all match \n return cells.every(\n ([x, y]) => \n y >= 0 && \n y < HEIGHT && \n x >= 0 && \n x < WIDTH && \n gameboard[x][y] === player\n );\n }\n\n //This code block defines an array of coordinates in each corresponding direction for each cell that's found to have a player piece in it. These arrays are then tested for a win condition using the _win(cell) function (designated private).\n for (let x = 0; x < WIDTH; x++) {\n for (let y = 0; y < HEIGHT; y++) {\n //only process a win analysis on the pieces just played by the current player. Wasteful to analyze conditions with the player that previously went.\n if (gameboard[x][y] === player){\n let vert = [[x, y], [x, y+1], [x, y+2], [x, y+3]];\n\n //Testing as long as there's room to check for patterns to the right\n if (x<WIDTH-3){\n let horiz = [[x, y], [x+1, y], [x+2, y], [x+3, y]];\n let diagDR = [[x, y], [x+1, y-1], [x+2, y-2], [x+3, y-3]];\n let diagUR = [[x, y], [x+1, y+1], [x+2, y+2], [x+3, y+3]];\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagUR)) {\n return true;\n }\n }\n //No space to check for patterns that travel to the right. Only test vertical patterns\n else{\n if (_win(vert)) {\n return true;\n }\n\n }\n\n }\n }\n }\n}", "function checkWin() {\r\n\tlet board = []; // status of the board\r\n\tboard[0] = \"\"; // DO NOT USE\r\n\tboard[1] = document.getElementById(\"one\").innerHTML;\r\n\tboard[2] = document.getElementById(\"two\").innerHTML;\r\n\tboard[3] = document.getElementById(\"three\").innerHTML;\r\n\tboard[4] = document.getElementById(\"four\").innerHTML;\r\n\tboard[5] = document.getElementById(\"five\").innerHTML;\r\n\tboard[6] = document.getElementById(\"six\").innerHTML;\r\n\tboard[7] = document.getElementById(\"seven\").innerHTML;\r\n\tboard[8] = document.getElementById(\"eight\").innerHTML;\r\n\tboard[9] = document.getElementById(\"nine\").innerHTML;\r\n\t\r\n\t// top row\r\n\tif (board[1] != \"\" && board[1] == board[2] && board[2] == board[3]){\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t// second row\r\n\tif (board[4] != \"\" && board[4] == board[5] && board[5] == board[6]){\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t// third row\r\n\tif (board[7] != \"\" && board[7] == board[8] && board[8] == board[9]){\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t// first column\r\n\tif (board[1] != \"\" && board[1] == board[4] && board[4] == board[7]){\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t// second column\r\n\tif (board[2] != \"\" && board[2] == board[5] && board[5] == board[8]){\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t// third column\r\n\tif (board[3] != \"\" && board[3] == board[6] && board[6] == board[9]){\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t// top-left to bottom-right diagonal\r\n\tif (board[1] != \"\" && board[1] == board[5] && board[5] == board[9]){\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t// bottom-left to top-right diagonal\r\n\tif (board[3] != \"\" && board[3] == board[5] && board[5] == board[7]){\r\n\t\treturn true;\r\n\t}\r\n} // checkWin", "function checkForWin () {\n for (var i = 0; i < board.cells.length; i++) {\n if (!board.cells[i].isMine && board.cells[i].hidden) {return}\n if (board.cells[i].isMine && !board.cells[i].isMarked) {return}\n }\nlib.displayMessage('no rabies for you!')\n }", "function checkWin() {\n\tlet cb = []; // current board\n\t\t\n\tcb[0] = \"\"; // not going to use\n\tcb[1] = document.getElementById(\"one\").innerHTML;\n\tcb[2] = document.getElementById(\"two\").innerHTML;\n\tcb[3] = document.getElementById(\"three\").innerHTML;\n\tcb[4] = document.getElementById(\"four\").innerHTML;\n\tcb[5] = document.getElementById(\"five\").innerHTML;\n\tcb[6] = document.getElementById(\"six\").innerHTML\n\tcb[7] = document.getElementById(\"seven\").innerHTML;\n\tcb[8] = document.getElementById(\"eight\").innerHTML;\n\tcb[9] = document.getElementById(\"nine\").innerHTML;\n\n\n\t// top row\n\tif (cb[1] != \"\" && cb[1] == cb[2] && cb[2] == cb[3]) {\n\t\treturn true;\n\t} // if\n\t\n\t// middle row\n\tif (cb[4] != \"\" && cb[4] == cb[5] && cb[5] == cb[6]) {\n\t\treturn true;\n\t} // if\n\n\t// bottom row\n\tif (cb[7] != \"\" && cb[7] == cb[8] && cb[8] == cb[9]) {\n\t\treturn true;\n\t} // if\n\t\n\t// colomn one\n\tif (cb[1] != \"\" && cb[1] == cb[4] && cb[4] == cb[7]) {\n\t\treturn true;\n\t} // if\n\t\n\t// colomn two\n\tif (cb[2] != \"\" && cb[2] == cb[5] && cb[5] == cb[8]) {\n\t\treturn true;\n\t} // if\n\t\n\t// colomn three\n\tif (cb[3] != \"\" && cb[3] == cb[6] && cb[6] == cb[9]) {\n\t\treturn true;\n\t} // if\n\t\n\t// top left to bottom right diagonal\n\tif (cb[1] != \"\" && cb[1] == cb[5] && cb[5] == cb[9]) {\n\t\treturn true;\n\t} // if\n\t\n\t// top right to bottom left diagonal\n\tif (cb[3] != \"\" && cb[3] == cb[5] && cb[5] == cb[7]) {\n\t\treturn true;\n\t} // if\n\n} // checkWin()", "function checkForWin() {\n /** _win:\n * takes input array of 4 cell coordinates [ [y, x], [y, x], [y, x], [y, x] ]\n * returns true if all are legal coordinates for a cell & all cells match\n * currPlayer\n */\n\n /**\n * _wins \n * @param {*} cells -- list of coordinates of the game state board \n */\n\n function _win(cells) {\n let [y, x] = cells[0];\n let currentPlayer = board[y][x];\n if (currentPlayer !== null) {\n\n return cells.every(cell => {\n return validCoord(cell) && board[cell[0]][cell[1]] === currentPlayer\n })\n\n }\n return false;\n }\n\n // using HEIGHT and WIDTH, generate \"check list\" of coordinates\n // for 4 cells (starting here) for each of the different\n // ways to win: horizontal, vertical, diagonalDR, diagonalDL\n for (var y = 0; y < HEIGHT; y++) {\n for (var x = 0; x < WIDTH; x++) {\n\n\n let horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];\n let vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];\n let diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];\n let diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];\n\n // find winner (only checking each win-possibility as needed)\n if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {\n return true;\n }\n }\n }\n}", "checkWinner() {\n // Check rows\n let win = false;\n\n const checkEqual = arr => arr.every(v => (v === arr[0] && v !== ''));\n console.log(\"CHECK WINNER.\");\n const board = this.state.board;\n for (let i = 0; i < this.width; i++) {\n\n for (let j = 0; j < this.height; j++) {\n\n // Check row win\n if (j <= this.height - 4) {\n //console.log(\"LINE:\" + [board[i][j+1],board[i][j+2],board[i][j+3],board[i][j]]);\n win = checkEqual([board[i][j + 1], board[i][j + 2], board[i][j + 3], board[i][j]]) ? board[i][j] : false;\n if (win !== false) break;\n }\n\n // Check line & diagonal win \n if (i <= this.width - 4) {\n //console.log(\"ROW:\" + [board[i+1][j],board[i+2][j],board[i+3][j],board[i][j]]);\n win = checkEqual([board[i + 1][j], board[i + 2][j], board[i + 3][j], board[i][j]]) ? board[i][j] : false;\n if (win !== false) break;\n\n // Check diagonal line\n if (j <= this.height - 4) {\n win = checkEqual([board[i + 1][j + 1], board[i + 2][j + 2], board[i + 3][j + 3], board[i][j]]) ? board[i][j] : false;\n //console.log(\"MAYBE WIN? \" + [board[i][j],board[i+1][j+1],board[i+2][j+2],board[i+3][j+3]] + \"LINE: \" + i + \",ROW: \" + j);\n if (win !== false) break;\n }\n }\n\n if (i <= this.width - 4 && j >= 3) {\n win = checkEqual([board[i][j], board[i + 1][j - 1], board[i + 2][j - 2], board[i + 3][j - 3]]) ? board[i][j] : false;\n //console.log(\"MAYBE WIN? \" + [board[i + 3][j - 3], board[i + 2][j - 2], board[i + 1][j - 1], board[i][j]] + \"LINE: \" + i + \",ROW: \" + j);\n if (win !== false) break;\n }\n\n\n }\n\n // Break out from second for loop\n if (win !== false) {\n break;\n }\n }\n\n if (win !== false) return win;\n return false;\n }", "function checkForWin () {\nvar unhiddenCells = board.cells.filter(cell => {\n return ((cell.isMine && !cell.isMarked) || (!cell.isMine && cell.isHidden))\n})\nif (unhiddenCells.length === 0) {\n lib.displayMessage('You win!')\n }\n}", "function checkDraw() {\n for(i = 0; i < 7; i++){\n for(j = 0; j < 6; j++){\n if(grid[i][j] == null) \n return false;\n }\n }\n return true;\n}", "function evaluateBoard () {\n // Step 4a - Set a variable to capture how many\n // pieces are currently on the board\n let boardFull = 0;\n\n // Step 4c - Iterate through the win conditions using the\n // newer ES5 method for iterating through a\n // loop\n for (let win of winConditions) {\n // Step 4d - Using destructoring, store the elements of the win array\n // into 3 new index variables\n let [i1, i2, i3] = win;\n\n // Step 4e - Using destructuring again, as well as the handy array\n // method, .map(), pass the textContent of each cell into 3 new\n // variables\n let [c1, c2, c3] = [cells[i1], cells[i2], cells[i3]].map(ele => ele.textContent);\n \n // Step 4f - Evaluate if the 3 variables have values\n if (c1.length > 0 && c2.length > 0 && c3.length > 0) {\n // Step 4g - If they do, add 1 to the board\n boardFull += 1;\n\n // Step 4h - Evaluate if the 3 variables are equal\n if (c1 === c2 && c2 === c3) {\n // Step 4i - If so, inform the players the player who has won\n h1.textContent = `Player ${currentPlayer + 1} Wins!`;\n\n // Step 4j - Kill the game\n killGame();\n\n // Step 4k - Return false to prevent the toggle event from\n // changing the message\n return false;\n }\n }\n }\n\n // Step 4l - Evaluate if the board is full by checking if\n // it equals the size of the winConditions array\n if (boardFull === winConditions.length) {\n // Step 4m - If so, inform the players the player who has won\n h1.textContent = \"No more moves!\";\n\n // Step 4n - Kill the game\n killGame();\n\n // Step 4o - Return false to prevent the toggle event from\n // changing the message\n return false;\n }\n\n // Step 4p - Return true. This will happen if neither of\n // the events above are executed. This will tell toggle\n // to proceed as normal.\n return true;\n}", "function checkWin() {\n return Winning_combinations.some(combination => {\n return combination.every( index => {\n if (move % 2 !== 0) {\n return cells[index].classList.contains('x');\n }\n else {\n return cells[index].classList.contains('o');\n }\n })\n })\n}", "function winCheck() {\n\n // Traverses the entire grid and checks for any discrepancy between the current grid and the answer grid, if there is then the player has not won yet\n for (var row = 0; row < 9; row++) {\n for (var col = 0; col < 9; col++) {\n if (grid[row][col].textContent != answerGrid[row][col]) {\n return false;\n }\n }\n }\n return true;\n}", "function solved(board){\r\n for(var i=0; i < 9; i++){\r\n for(var j = 0; j<9; j++){\r\n //if there is a square with nothing, the board is not solved\r\n if(board[i][j] == null){\r\n return false\r\n }\r\n }\r\n }\r\n return true\r\n}", "checkInHorizontal(color){\n let value = 0;\n for(let row=0; row<15; row++){\n value = 0;\n for(let col=0; col<15; col++){\n if(game.board[row][col] != color){\n value = 0;\n }else{\n value++;\n }\n if(value == 5){\n this.announceWinner();\n return;\n }\n }\n }\n }", "function checkForWin () {\n var winCount = 0;\n for (var i = 0; i < board.cells.length; i++) {\n var cell = board.cells[i];\n if (cell.isMine && cell.isMarked) {\n winCount++;\n } if (cell.isMine == false && cell.hidden == false) {\n winCount++;\n } \n }\n if (winCount === board.cells.length) {\n lib.displayMessage('You win!')\n }\n}", "function checkWinner(gameField) {\n // check for horizontal win\n for (var i = 0; i < 5; i++) {\n if (gameField[i][0] !== null && gameField[i][0] === gameField[i][1] && gameField[i][1] === gameField[i][2] && gameField[i][2] === gameField[i][3] && gameField[i][3] === gameField[i][4]) {\n return true;\n }\n } // check for vertical win\n\n\n for (var j = 0; j < 5; j++) {\n if (gameField[0][j] !== null && gameField[0][j] === gameField[1][j] && gameField[0][j] === gameField[2][j] && gameField[0][j] === gameField[3][j] && gameField[0][j] === gameField[4][j]) {\n return 1;\n }\n } // check for diagonal top-left-bottom-right\n\n\n if (gameField[0][0] !== null && gameField[0][0] === gameField[1][1] && gameField[0][0] === gameField[2][2] && gameField[0][0] === gameField[3][3] && gameField[0][0] === gameField[4][4]) {\n return 1;\n } // check for diagonal bottom-left-top-right\n\n\n if (gameField[4][0] !== null && gameField[4][0] === gameField[3][1] && gameField[4][0] === gameField[2][2] && gameField[4][0] === gameField[1][3] && gameField[4][0] === gameField[0][4]) {\n return 1;\n }\n\n return 0;\n} // Function for checking 3 by 3 grid for a tie", "function checkWin(){\n //Across horizontals\n for(i=0; i<3; i++){\n if(check3Checked(board[`${rowCode[i]}${colCode[0]}`],board[`${rowCode[i]}${colCode[1]}`],board[`${rowCode[i]}${colCode[2]}`]) === true){\n win = true;\n //Checks first column of row to see who won. X = player, O = computer\n if(board[`${rowCode[i]}${colCode[0]}`] === 'X'){\n console.log('Player has won!');\n } else if(board[`${rowCode[i]}${colCode[0]}`] === 'O'){\n console.log('Computer has won!');\n } \n }\n }\n //Across verticals\n for(i=0; i<3; i++){\n if(check3Checked(board[`${rowCode[0]}${colCode[i]}`],board[`${rowCode[1]}${colCode[i]}`],board[`${rowCode[2]}${colCode[i]}`]) === true){\n win = true;\n //Checks first row of column to see who won. X = player, O = computer\n if(board[`${rowCode[0]}${colCode[i]}`] === 'X'){\n console.log('Player has won!');\n } else if(board[`${rowCode[i]}${colCode[i]}`] === 'O'){\n console.log('Computer has won!');\n } \n }\n }\n //Across diagonals\n if (check3Checked(board[`${rowCode[0]}${colCode[0]}`],board[`${rowCode[1]}${colCode[1]}`],board[`${rowCode[2]}${colCode[2]}`]) === true){\n win = true;\n if(board[`${rowCode[0]}${colCode[0]}`] === 'X'){\n console.log('Player has won!');\n } else if(board[`${rowCode[0]}${colCode[0]}`] === 'O'){\n console.log('Computer has won!');\n }\n }\n if (check3Checked(board[`${rowCode[0]}${colCode[2]}`],board[`${rowCode[1]}${colCode[1]}`],board[`${rowCode[2]}${colCode[0]}`]) === true){\n win = true;\n if(board[`${rowCode[0]}${colCode[2]}`] === 'X'){\n console.log('Player has won!');\n } else if(board[`${rowCode[0]}${colCode[2]}`] === 'O'){\n console.log('Computer has won!');\n }\n }\n\n //Tie: No win despite all avaiableMoves ===0 (all possible moves exhausted)\n if (availableMoves.length === 0 && win === false){\n console.log(\"Tie!\")\n }\n }", "function checkWin () {\r\n\tlet cb = []; // current board\r\n\tcb[0] = \"\";\r\n\tcb[1] = document.getElementById(\"one\").innerHTML;\r\n\tcb[2] = document.getElementById(\"two\").innerHTML;\r\n\tcb[3] = document.getElementById(\"three\").innerHTML;\r\n\tcb[4] = document.getElementById(\"four\").innerHTML;\r\n\tcb[5] = document.getElementById(\"five\").innerHTML;\r\n\tcb[6] = document.getElementById(\"six\").innerHTML;\r\n\tcb[7] = document.getElementById(\"seven\").innerHTML;\r\n\tcb[8] = document.getElementById(\"eight\").innerHTML;\r\n\tcb[9] = document.getElementById(\"nine\").innerHTML;\r\n\t\r\n\t//top row\r\n\tif (cb[1] != \"\" && cb[1] == cb[2] && cb[2] == cb[3]) {\r\n\t\treturn true;\r\n\t}\r\n\telse if (cb[4] != \"\" && cb[4] == cb[5] && cb[5] == cb[6]) {\r\n\t\treturn true;\r\n\t}\r\n\telse if (cb[7] != \"\" && cb[7] == cb[8] && cb[8] == cb[9]) {\r\n\t\treturn true;\r\n\t}\r\n\telse if (cb[1] != \"\" && cb[1] == cb[4] && cb[4] == cb[7]) {\r\n\t\treturn true;\r\n\t}\r\n\telse if (cb[2] != \"\" && cb[2] == cb[5] && cb[5] == cb[8]) {\r\n\t\treturn true;\r\n\t}\r\n\telse if (cb[3] != \"\" && cb[3] == cb[6] && cb[6] == cb[9]) {\r\n\t\treturn true;\r\n\t}\r\n\telse if (cb[1] != \"\" && cb[1] == cb[5] && cb[5] == cb[9]) {\r\n\t\treturn true;\r\n\t}\r\n\telse if (cb[3] != \"\" && cb[3] == cb[5] && cb[5] == cb[7]) {\r\n\t\treturn true;\r\n\t} else {\r\n\t\treturn false;\r\n\t}\r\n}//check win", "function checkForGameWin(player)\n{\n //Check for win\n //Down left column\n if(wonCells[0][0] == player && wonCells[0][1] == player && wonCells[0][2] == player)\n return player;\n //Down middle column\n if(wonCells[1][0] == player && wonCells[1][1] == player && wonCells[1][2] == player)\n return player;\n //Down right column\n if(wonCells[2][0] == player && wonCells[2][1] == player && wonCells[2][2] == player)\n return player;\n //Across top row\n if(wonCells[0][0] == player && wonCells[1][0] == player && wonCells[2][0] == player)\n return player; \n //Across middle row\n if(wonCells[0][1] == player && wonCells[1][1] == player && wonCells[2][1] == player)\n return player;\n //Across bottom row\n if(wonCells[0][2] == player && wonCells[1][2] == player && wonCells[2][2] == player)\n return player; \n //Top left to bottom right\n if(wonCells[0][0] == player && wonCells[1][1] == player && wonCells[2][2] == player)\n return player;\n //Top right to bottom left\n if(wonCells[0][2] == player && wonCells[1][1] == player && wonCells[2][0] == player)\n return player; \n \n //If no win, check for tie\n var countOfWonCells = 0;\n for(var i = 0; i < 3; i++)\n {\n for(var j = 0; j < 3; j++)\n {\n if(wonCells[i][j] != 0)\n countOfWonCells++;\n }\n }\n\n if(countOfWonCells == 9)\n return -1;\n else\n return 0;\n}", "function checkForWin () {\nfor(var x = 0; x<board.cells.length;x++){\nif(board.cells[x].isMine === true && board.cells[x].isMarked === false){\n\treturn;\n\t}else if(board.cells[x].isMine === false && board.cells[x].hidden === true){\n\t\treturn;\n\t}\n\n}\n\t\n // You can use this function call to declare a winner (once you've\n // detected that they've won, that is!)\n lib.displayMessage('You win!')\n}", "function checkForWin() {\r\n // You can use this function call to declare a winner (once you've\r\n // detected that they've won, that is!)\r\n // lib.displayMessage('You win!')\r\n for (let i = 0; i < board.cells.length; i++) {\r\n const cell = board.cells[i];\r\n if ((cell.isMine && !cell.isMarked) || (!cell.isMine && cell.hidden)) {\r\n return;\r\n }\r\n }\r\n lib.displayMessage(\"You win!\");\r\n}", "function checkIfWinner()\n{\n var count = 1;\n for (var i = 0; i < rows; i++)\n {\n for (var j = 0; j < columns; j++)\n {\n if (arrayForBoard[i][j] != count)\n {\n\tif ( !(count === rows * columns && arrayForBoard[i][j] === 0 ))\n\t{\n\t return false;\n\t}\n }\n count++;\n }\n }\n \n return true;\n}", "function _checkMoves() {\n\t\t\n\t\t// iterate through the rows\n\t\tfor(row = 0; row < _rows; row++) {\n\t\t\t\n\t\t\t// iterate through the cols\n\t\t\tfor (col = 0; col < _cols; col++) {\n\t\t\t\t\n\t\t\t\t// check top and bottom\n\t\t\t\tif(row - 1 >= 0 && typeof _board[row - 1][col] !== \"undefined\"\n\t\t\t\t && row + 1 < _rows && typeof _board[row + 1][col] !== \"undefined\"){\n\t\t\t\t\t\n\t\t\t\t\tif(_board[row - 1][col] === _board[row][col] && _board[row + 1][col] === _board[row][col]) {\n\t\t\t\t\t\t_winnerFound = true;\n\t\t\t\t\t\t_winner = _board[row][col];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// check left and right\n\t\t\t\tif(col - 1 >= 0 && typeof _board[row][col - 1] !== \"undefined\"\n\t\t\t\t && col + 1 < _cols && typeof _board[row][col + 1] !== \"undefined\"){\n\t\t\t\t\t\n\t\t\t\t\tif(_board[row][col - 1] === _board[row][col] && _board[row][col + 1] === _board[row][col]) {\n\t\t\t\t\t\t_winnerFound = true;\n\t\t\t\t\t\t_winner = _board[row][col];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// check diagonals\n\t\t\t\tif(col - 1 >= 0 && col + 1 < _cols && row - 1 >= 0 && row + 1 < _rows){\n\n\t\t\t\t\tif(typeof _board[row - 1][col - 1] !== \"undefined\"\n\t\t\t\t\t && typeof _board[row + 1][col + 1] !== \"undefined\"\n\t\t\t\t\t && _board[row - 1][col - 1] === _board[row][col] \n\t\t\t\t\t && _board[row + 1][col + 1] === _board[row][col]) {\n\t\t\t\t\t\t_winnerFound = true;\n\t\t\t\t\t\t_winner = _board[row][col];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if(typeof _board[row - 1][col + 1] !== \"undefined\"\n\t\t\t\t\t && typeof _board[row + 1][col - 1] !== \"undefined\"\n\t\t\t\t\t && _board[row - 1][col + 1] === _board[row][col] \n\t\t\t\t\t\t&& _board[row + 1][col - 1] === _board[row][col]) {\n\t\t\t\t\t\t_winnerFound = true;\n\t\t\t\t\t\t_winner = _board[row][col];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t// if winner was found, then break out of loop\n\t\t\tif(_winnerFound) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}", "function checkForWin () {\n for (let cell of board.cells) {\n if (cell.isMine) {\n if (!cell.isMarked) {\n return false;\n }\n } else {\n if(cell.hidden) {\n return false;\n }\n }\n }\n // setEndTime\n endTime = new Date().getTime()\n // You can use this function call to declare a winner (once you've\n // detected that they've won, that is!)\n lib.displayMessage('You win!')\n // Play win audio\n document.getElementById(\"audio_win\").play()\n // reveal all mines after win\n revealMines()\n removeListeners()\n return true;\n}", "gameIsFinished() {\n return this.rows[0].some(\n cell => cell.filled \n );\n }", "function test26() {\n for (let i = 0; i < 100; i++) {\n reset();\n let num = Math.floor(Math.random() * 20);\n for (let j = 0; j < num; j++) {\n let row = Math.floor(Math.random() * 20) + 4\n while (!board[row].includes(\"#ffffff\")) row = Math.floor(Math.random() * 20) + 4\n board[row].fill(\"#420420\")\n }\n check10Row();\n if (board.some(x => !x.includes(\"#ffffff\"))) return false\n }\n return true\n}", "function checkWin() {\r\n\tlet cb =[]; //current board\r\n\tcb[0] = \"\"; // not going to use it\r\n\tcb[1] = document.getElementById(\"one\").innerHTML;\r\n\tcb[2] = document.getElementById(\"two\").innerHTML;\r\n\tcb[3] = document.getElementById(\"three\").innerHTML;\r\n\tcb[4] = document.getElementById(\"four\").innerHTML;\r\n\tcb[5] = document.getElementById(\"five\").innerHTML;\r\n\tcb[6] = document.getElementById(\"six\").innerHTML;\r\n\tcb[7] = document.getElementById(\"seven\").innerHTML;\r\n\tcb[8] = document.getElementById(\"eight\").innerHTML;\r\n\tcb[9] = document.getElementById(\"nine\").innerHTML;\r\n\t\r\n\t//top row\r\n\tif(cb[1] != \"\" && cb[1] == cb[2] && cb[2] ==cb[3]) {\r\n\t\treturn true;\t\r\n\t\t\t\r\n\t}//if\r\n\t\r\n\t\t//middle row\r\n\tif(cb[4] != \"\" && cb[4] == cb[5] && cb[5] ==cb[6]) {\r\n\t\treturn true;\t\r\n\t\t\t\r\n\t}//if\r\n\t\r\n\t\t//bottom row\r\n\tif(cb[7] != \"\" && cb[7] == cb[8] && cb[8] ==cb[9]) {\r\n\t\treturn true;\t\r\n\t\t\t\r\n\t}//if\r\n\t\r\n\t\t//left side\r\n\tif(cb[1] != \"\" && cb[1] == cb[4] && cb[4] ==cb[7]) {\r\n\t\treturn true;\t\r\n\t\t\t\r\n\t}//if\r\n\t\r\n\t\t//middle\r\n\tif(cb[2] != \"\" && cb[2] == cb[5] && cb[5] ==cb[8]) {\r\n\t\treturn true;\t\r\n\t\t\t\r\n\t}//if\r\n\t\r\n\t\t//right side\r\n\tif(cb[3] != \"\" && cb[3] == cb[6] && cb[6] ==cb[9]) {\r\n\t\treturn true;\t\r\n\t\t\t\r\n\t}//if\r\n\t\r\n\t\t//diagonal 1\r\n\tif(cb[1] != \"\" && cb[1] == cb[5] && cb[5] ==cb[9]) {\r\n\t\treturn true;\t\r\n\t\t\t\r\n\t}//if\r\n\t\r\n\t\t//diagonal 2\r\n\tif(cb[3] != \"\" && cb[3] == cb[5] && cb[5] ==cb[7]) {\r\n\t\treturn true;\t\r\n\t\t\t\r\n\t}//if\r\n\t\r\n}//check wins", "function checkForWin () {\n for (i = 0; i < board.cells.length; i ++){\n if (board.cells[i['isMine']]===true && board.cells[i['isMarked']]===false){\n return\n }\n else if (board.cells[i['isMine']]===true && board.cells[i['hidden']]===true) {\n return\n }\n lib.displayMessage('You win!')\n\n }\n\n}" ]
[ "0.82348824", "0.82010305", "0.8076892", "0.8006752", "0.7894706", "0.78840613", "0.7828072", "0.781161", "0.7785721", "0.7764963", "0.77531546", "0.7707633", "0.7705774", "0.7705438", "0.7696609", "0.76917857", "0.768961", "0.7666565", "0.76551497", "0.7652551", "0.76495224", "0.76488775", "0.7641069", "0.7627811", "0.7627811", "0.7627037", "0.7622166", "0.76215637", "0.76139253", "0.76107043", "0.7604467", "0.7598154", "0.75893724", "0.7582701", "0.757924", "0.7563571", "0.75618345", "0.7555818", "0.7548762", "0.75364053", "0.7535678", "0.7531474", "0.75295097", "0.75220567", "0.75186", "0.751708", "0.75120646", "0.75003177", "0.750012", "0.7499446", "0.7494352", "0.74906194", "0.7488041", "0.7487771", "0.7481541", "0.74793124", "0.74757123", "0.746614", "0.74593085", "0.74544626", "0.7442789", "0.7425398", "0.74236524", "0.7417684", "0.7412948", "0.74124485", "0.74057096", "0.740078", "0.7396948", "0.73905504", "0.7388106", "0.73774105", "0.7376477", "0.7374112", "0.73575336", "0.7356164", "0.73529047", "0.7349454", "0.73343265", "0.7332824", "0.7321257", "0.73088133", "0.7306894", "0.73047453", "0.72970766", "0.7295873", "0.72934675", "0.7291545", "0.72879916", "0.7273471", "0.7269472", "0.7267143", "0.72632676", "0.72626376", "0.7262105", "0.7262035", "0.7260663", "0.7259692", "0.7259186", "0.72568595" ]
0.8009917
3
Check if a number/square pair is correct when compared to the solution
function checkIfCorrect(square) { // Assign the solution based on the difficulty setting chosen let solution; if (id("easy-diff").checked) { solution = easy[1]; } else if (id("medium-diff").checked) { solution = medium[1]; } else if (id("hard-diff").checked) { solution = hard[1]; } else { solution = hardcore[1]; } // If square's number matches the solution number if (solution.charAt(square.id) === square.textContent) { return true; } else { return false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function isSquare(number) {\n for(var i = 0; i < number; i++) {\n if( number / i === i) { //alt i * i === number. Return true;\n return true;\n }\n }\n return false; //return false after loop.\n //if inside loop, may return false WAY too early. Checking 2 * 2,\n //if its not case return false BEFORE we come upon 4 * 4 forr 16.\n\n //check ALL possible i's in loop.\n //THEN if we havent found it, return false.\n}", "function perfectSquare(number){\n for (i = 1; i < number/i+1; i++){\n console.log(i);\n if(i * i === number){\n return true;\n }\n }\n return false;\n}", "function solutionChecker(solution) {\n\t// check rows\n\tfor(let i = 0; i <= 8; i++) {\n\t\tif(!checkRow(solution[i])) return false;\n\t}\n\t// check collums\n\tlet auxRow;\n\tfor(let i = 0; i <= 8; i++) {\n\t\tauxRow = [];\n\t\tfor(let j = 0; j <= 8; j++) {\n\t\t\tauxRow.push(solution[j][i]);\t\t// \t the numbers of the collumn are put in an array,\n\t\t}\t\t\t\t\t\t\t\t\t\t// so its easier to analyse\n\t\tif(!checkRow(auxRow)) return false;\t\t\n\t}\n\t// check big squares\n\tfor(let i = 0; i <= 2; i++) {\n\t\tfor(let j = 0; j <= 2; j++) {\n\t\t\tauxRow = solution[i*3].slice(j*3, j*3+3) // the same is done to the numbers of a big square\n\t\t\t\t.concat(\n\t\t\t\t\tsolution[i*3+1].slice(j*3, j*3+3)\n\t\t\t\t).concat(\n\t\t\t\t\tsolution[i*3+2].slice(j*3, j*3+3)\t\t\t\n\t\t\t\t);\n\t\t\tif(!checkRow(auxRow)) return false;\t\t\n\t\t}\n\t}\n\treturn true;\n\tfunction checkRow(row) {\n\t\treturn numbers.every(number => {\n\t\t\treturn row.some(num => num == number);\n\t\t});\n\t}\n}", "function solve() {\n board = Board();\n previous = Board();\n var u = unknowns();\n for (;;) {\n var v = u;\n if (show()) {\n put(\"The board is inconsistent.\");\n board = null;\n return true;\n }\n if (u == dim2 * dim2)\n break;\n uniqall();\n u = unknowns();\n if (u < v) {\n put(\"By known value must be unique in row, column, and square.\");\n continue;\n }\n uniqsqr();\n u = unknowns();\n if (u < v) {\n put(\"By only one place for value in square.\");\n continue;\n }\n uniqrow();\n u = unknowns();\n if (u < v) {\n put(\"By only one place for value in row.\");\n continue;\n }\n uniqcol();\n u = unknowns();\n if (u < v) {\n put(\"By only one place for value in column.\");\n continue;\n }\n uniqrowline();\n u = unknowns();\n if (u < v) {\n put(\"By values in square preclude others in a row.\");\n continue;\n }\n uniqcolline();\n u = unknowns();\n if (u < v) {\n put(\"By values in square preclude others in a column.\");\n continue;\n }\n uniqcolsqr();\n u = unknowns();\n if (u < v) {\n put(\"By only one columm value in square.\");\n continue;\n }\n uniqrowsqr();\n u = unknowns();\n if (u < v) {\n put(\"By only one row for value in square.\");\n continue;\n }\n pairsqr();\n u = unknowns();\n if (u < v) {\n put(\"By pair has only two places in square.\");\n continue;\n }\n pairrow();\n u = unknowns();\n if (u < v) {\n put(\"By pair has only two places in row.\");\n continue;\n }\n paircol();\n u = unknowns();\n if (u < v) {\n put(\"By pair has only two places in column.\");\n continue;\n }\n triplesqr();\n u = unknowns();\n if (u < v) {\n put(\"By triple has only three places in square.\");\n continue;\n }\n triplerow();\n u = unknowns();\n if (u < v) {\n put(\"By triple has only three places in row.\");\n continue;\n }\n triplecol();\n u = unknowns();\n if (u < v) {\n put(\"By triple has only three places in column.\");\n continue;\n }\n quadsqr();\n u = unknowns();\n if (u < v) {\n put(\"By quad has only four places in square.\");\n continue;\n }\n quadrow();\n u = unknowns();\n if (u < v) {\n put(\"By quad has only four places in row.\");\n continue;\n }\n quadcol();\n u = unknowns();\n if (u < v) {\n put(\"By quad has only four places in column.\");\n continue;\n }\n break;\n }\n put(\"Final board.\");\n if (show()) {\n put(\"The board is inconsistent.\");\n board = null;\n return true;\n }\n if (u > dim2 * dim2)\n put(\"The board is unfinished.\");\n board = null;\n return true;\n}", "function checkSquare(x, y, e) {\n let r = Math.floor(x / 3) * 3;\n let c = Math.floor(y / 3) * 3;\n\n for (let i = r; i < r + 3; i++) {\n for (let j = c; j < c + 3; j++) {\n if (a[i][j] === e) {\n return false;\n }\n }\n }\n\n for (let j = 0; j < 9; j++) {\n if (a[x][j] === e) {\n return false;\n }\n }\n for (let i = 0; i < 9; i++) {\n if (a[i][y] === e) {\n return false;\n }\n }\n\n return true;\n}", "function isSquareOk(grid, row, col, num) {\n row = Math.floor(row / 3) * 3;\n col = Math.floor(col / 3) * 3;\n \n for (var r = 0; r < 3; r++) {\n for (var c = 0; c < 3; c++) {\n if (grid[row + r][col + c] === num) {\n return false; \n }\n }\n }\n return true;\n }", "checkSquareIsValid (x, y, lastX, lastY) {\n if(x < 0 || y < 0 || x >= boardSize || y >= boardSize) return false;\n if(this.board[x][y] !== 1) return false;\n let neighbors = [\n [x + 1, y],\n [x - 1, y],\n [x, y + 1],\n [x, y - 1],\n ]\n\n for(let neighbor of neighbors) {\n const neighborX = neighbor[0];\n const neighborY = neighbor[1];\n if(neighborX >= 0 && neighborY >= 0 && neighborX < boardSize && neighborY < boardSize && (neighborX !== lastX || neighborY !== lastY) && this.board[neighborX][neighborY] !== 1) {\n return false;\n }\n }\n return true;\n }", "function checkSquare(sudoko , row , column , value) {\n boxRow = Math.floor(row / 3 ) * 3;\n boxCol = Math.floor(column / 3) * 3;\n let r , c ;\n while(r < 3){\n r = 0;\n r++;\n while(c < 3){\n c = 0;\n c++;\n if(sudoko[boxRow + r][boxCol + c] === value)\n return false;\n }\n }\n return true;\n}", "function isSquareNumber(num) {\n\n}", "function squareTest(t){ //t=1 for player1, t=2 for player2\n\tj=1;\n\twhile (gotSquare==0 && j<n+1){\n\t\ti=1;\n\t\twhile (gotSquare==0 && i<n+1){\n\t\t\tif (state[i][j]==t){\n\t\t\t\tfor (l=j;l<n+1;l++){\n\t\t\t\t\tif (l==j){start=i+1}else{start=1;}\n\t\t\t\t\tfor (k=start;k<n+1;k++){\n\t\t\t\t\t\tif (state[k][l]==t){\n\t\t\t\t\t\t\tif ((0<k+l-j && k+l-j<n+1 && 0<l-k+i && l-k+i<n+1 &&\n\t\t\t\t\t\t\t\t 0<i+l-j && i+l-j<n+1 && 0<j-k+i && j-k+i<n+1 &&\n\t\t\t\t\t\t\t\t state[k+l-j][l-k+i]==t && state[i+l-j][j-k+i]==t)||\n\t\t\t\t\t\t \t(0<k+j-l && k+j-l<n+1 && 0<l-i+k && l-i+k<n+1 &&\n\t\t\t\t\t\t\t\t 0<i+j-l && i+j-l<n+1 && 0<j-i+k && j-i+k<n+1 &&\n\t\t\t\t\t\t\t\t state[k+j-l][l-i+k]==t && state[i+j-l][j-i+k]==t)){\n\t\t\t\t\t\t\t\tgotSquare=1; \n\t\t\t\t\t\t\t\t_root.conclusion._visible=true;\n\t\t\t\t\t\t\t\tif (opponent==0 && turn==1){_root.conclusion.text=\"Player 1 wins!\";}\n\t\t\t\t\t\t\t\tif (opponent==0 && turn==2){_root.conclusion.text=\"Player 2 wins!\";}\n\t\t\t\t\t\t\t\tif (opponent==1 && turn==1){_root.conclusion.text=\"You win!\";}\n\t\t\t\t\t\t\t\tif (opponent==1 && turn==2){_root.conclusion.text=\"Computer wins!\";}\n\t\t\t\t\t\t\t\tfreeze=1;\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}\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\tj++; \n\t}\n}", "function findInSquare(num, square, puzzle){ \n let isInSquare = false;\n let x;\n let y;\n let numInSquare;\n for(let i=0; i<3; i++){ \n for(let j=0; j<3; j++){ \n x = square[i][j][0];\n y = square[i][j][1]; \n numInSquare = puzzle[x][y];\n if(numInSquare == num){ \n isInSquare = true; \n break; \n } \n }\n }\n \n return isInSquare;\n \n}", "function isPerfectSquare(input) {\n // Square numbers are non-negative\n if (input < 0) return false;\n\n let count = 0;\n while (true) {\n const squared = count * count;\n if (input === squared) {\n return true;\n } else if (input < squared) {\n return false;\n }\n count++;\n }\n}", "solutionCheck() {\n for (let row = 0; row < HEIGHT; row++) {\n for (let col = 0; col < WIDTH; col++) {\n let num = this._puzzle[row][col];\n this._puzzle[row][col] = 0;\n if (num === 0 || !this.isSafe(this._puzzle, row, col, num)) {\n this._puzzle[row][col] = num;\n return false;\n }\n this._puzzle[row][col] = num;\n }\n }\n return true;\n }", "function get_squares(array) {\n if(Math.sqrt(array) % 1 === 0) {\n console.log(\"Number is a Perfect Square\");\n } else {\n console.log(\"Number is NOT a Perfect Square\");\n }\n}", "function verify_state() {\n let s=read_state();\n\n let cnt=Array(10).fill(0);\n for(let j=0;j<3;++j)\n for(let i=0;i<3;++i) {\n let pos=\"Row \"+j+\", Col \"+i;\n if(isNaN(s.grid[j][i])) {\n helper_log_write(pos+\" is not a number\");\n return false;\n }\n if(s.grid[j][i] < 0 || s.grid[j][i] > 8) {\n helper_log_write(pos+\" is out of range\");\n return false;\n }\n ++cnt[s.grid[j][i]];\n }\n \n for(let i=0;i<9;++i) {\n let val=\"\"+i;\n if(i==0) val=\"blank\";\n if(cnt[i]==0) {\n helper_log_write(\"Missing \"+val);\n return false;\n }\n if(cnt[i]>1) {\n helper_log_write(\"Too many \"+val+\"s\");\n return false;\n }\n }\n \n //Count inversions to see if puzzle is solveable\n let inv=0;\n let g=[];\n for(let j=0;j<3;++j)\n for(let i=0;i<3;++i)\n g.push(s.grid[j][i]);\n g=g.filter(function(x){return x>0;});\n for(let i=0;i<8;++i)\n for(let j=i+1;j<8;++j)\n if(g[i]>g[j]) ++inv;\n if(inv%2==0) {\n helper_log_write(\"Not solveable\");\n return false;\n }\n \n return true;\n}", "function isValidBoard(board){\n \n //Row Check\n for (let i = 0; i < 9; i++){ //row\n let numsInRow = []\n for (let j = 0; j < 9; j++){ //col\n if (board[i][j] != 0){\n for (let k = 0; k < numsInRow.length; k++){\n if (board[i][j] == numsInRow[k]){\n return false\n }\n }\n numsInRow[numsInRow.length] = board[i][j]\n }\n }\n }\n\n //Column Check\n for (let i = 0; i < 9; i++){ //col\n let numsInCol = []\n for (let j = 0; j < 9; j++){ //row\n if (board[j][i] != 0){\n for (let k = 0; k < numsInCol.length; k++){\n if (board[j][i] == numsInCol[k]){\n return false\n }\n }\n numsInCol[numsInCol.length] = board[j][i]\n }\n }\n }\n\n //Square Check\n for(let g = 0; g < 3; g++){\n for(let h = 0; h < 3; h++){\n let numsInSquare = []\n for(let i = g * 3; i < g * 3 + 3; i++){\n for(let j = h * 3; j < h * 3 + 3; j++){\n if (board[i][j] != 0){\n for (let k = 0; k < numsInSquare.length; k++){\n if (board[i][j] == numsInSquare[k]){\n return false\n }\n }\n numsInSquare[numsInSquare.length] = board[i][j]\n }\n }\n }\n }\n }\n\n return true\n}", "function solve(board, pickFirstOfTwo = false, pickSecondOfTwo = false) {\n for (let i = 0; i < board.length; i++) {\n let row = board[i];\n let squareI = Math.floor(i / 3) * 3;\n\n for (let j = 0; j < row.length; j++) {\n if (row[j]) continue; //already filled with a number\n const rowMissingNumbers = getMissingNumbers(row);\n //console.log(\"\\n\");\n let squareJ = Math.floor(j / 3) * 3;\n const squareMissingNumbers = getSquareMissingNumbers(\n squareI,\n squareJ,\n board\n );\n //console.log(`looking at (${i}, ${j})`);\n //console.log(`Square Missing: `, squareMissingNumbers);\n const columnMissingNumbers = getColumnMissingNumbers(j, board);\n //console.log(`Row Missing: `, rowMissingNumbers);\n //console.log(`Column Missing:`, columnMissingNumbers);\n // const possibleNumbers\n let possibleNumbers = squareMissingNumbers.filter(value =>\n rowMissingNumbers.includes(value)\n );\n possibleNumbers = possibleNumbers.filter(value =>\n columnMissingNumbers.includes(value)\n );\n if (possibleNumbers.length == 1) {\n setNumber(i, j, possibleNumbers[0], board);\n } else if (pickFirstOfTwo && possibleNumbers.length == 2) {\n setNumber(i, j, possibleNumbers[0], board);\n pickFirstOfTwo = false;\n } else if (pickSecondOfTwo && possibleNumbers.length == 2) {\n setNumber(i, j, possibleNumbers[1], board);\n pickSecondOfTwo = false;\n }\n if (possibleNumbers.length == 0) {\n //Empty slot with no possible numbers to go into it.\n // console.log(`looking at (${i}, ${j})`);\n // console.log(`Square Missing: `, squareMissingNumbers);\n // console.log(`Row Missing: `, rowMissingNumbers);\n // console.log(`Column Missing:`, columnMissingNumbers);\n // console.log(`possible numbers`, possibleNumbers);\n // printBoard(board);\n return false;\n }\n }\n }\n //printBoard(board);\n return true;\n}", "function isLegal(square) { return (square & 136) == 0; }", "function isSafe(i,j,n){\n for(let k=0;k<N;k++){\n if(board[k][j]==n||board[i][k]==n){\n console.log(\"inside issafe\");\n foundYa(i,j);\n return false;\n }\n }\n let s = Math.sqrt(N);\n let rs = i - i%s;\n let cs = j -j%s;\n for(i = 0;i<s;i++){\n for(j = 0;j<s;j++){\n if(board[i+rs][j+cs]==n){\n return false;\n }\n }\n }\n return true;\n}", "function isLucky(n) {\n const nString = n.toString();\n let firstHalfSum = 0;\n let secondHalfSum = 0;\n debugger;\n for (let i = 0; i < nString.length / 2; i++) {\n firstHalfSum += parseInt(nString[i])\n }\n for (let i = nString.length / 2; i < nString.length; i++) {\n secondHalfSum += parseInt(nString[i])\n }\n console.log(firstHalfSum, secondHalfSum)\n if (firstHalfSum === secondHalfSum) {\n return true\n } else {\n return false\n }\n}", "function test() {\n function square(x) {\n return Math.pow(x, 2);\n }\n function cube(x) {\n return Math.pow(x, 3);\n }\n function quad(x) {\n return Math.pow(x, 4);\n }\n if (square(2) !== 4 || cube (3) !== 27 || quad(4) !== 256) {\n console.log(\"check question 1\");\n }\n else {\n console.log(\"You are great at math!\");\n }\n}", "function isSolved(puzzle) {\n return puzzle.reduce((b, values) => {\n return values.reduce((b, value) => {\n return b && (value > 0 && value < 10);\n }, b);\n }, true);\n}", "function validSolution(board){\n // Check rows\n for (let i = 0; i < 9; i++) {\n if (board[i].reduce((a, n) => a + n) !== 45) return false\n }\n \n // Check columns\n for (let i = 0; i < 9; i++) {\n const col = board.map(row => row[i])\n if (col.reduce((a, n) => a + n) !== 45) return false\n }\n \n // Check blocks (TODO: this is clunky, fix it)\n const b = board.reduce((acc, c) => acc.concat(c));\n let flag45 = true;\n [0, 3, 6, 27, 30, 33, 54, 57, 60].forEach(i => {\n if (b[i] + b[i+1] + b[i+2] + b[i+9] + b[i+10] + b[i+11] + b[i+18] + b[i+19] + b[i+20] !== 45) {\n flag45 = false\n return\n }\n })\n if (!flag45) return false\n \n return true\n}", "function checksolution(player,solution){\n\t//checks true if whole row , cloumn or diagonal belongs to player\n\t//checks 3 boxes in each mini arrays\n\t//solution[0], solution[1] and solution[2] is position 0,1,2 in\n\t//all miniarrays that are row , cloumn or diagonal\n\treturn squareBelongsToPlayer(player,solution[0])&&\n\t\tsquareBelongsToPlayer(player,solution[1])&&\n\t\tsquareBelongsToPlayer(player,solution[2])\n}", "is_valid_solve(node) {\n const value = node.possibles[0];\n\n for (var i = 0; i < node.row.length; i++) {\n if (this.nodes[node.row[i]].value == value) return false;\n if (this.nodes[node.col[i]].value == value) return false;\n if (this.nodes[node.sqr[i]].value == value) return false;\n }\n\n return true;\n }", "function isConsistent(selectedVariableIndex, currentValue) {\n var i;\n var j;\n var row = selectedVariableIndex[0];\n var col = selectedVariableIndex[1];\n //check column\n for (i = 0; i < 9; i++) {\n if (i == row) {\n continue;\n }\n value = parseInt(document.getElementById(\"cell\"+i+col).value);\n if (value == currentValue) {\n return false;\n }\n }\n //check row\n for (j = 0; j < 9; j++) {\n if (j == col) {\n continue;\n }\n value = parseInt(document.getElementById(\"cell\"+row+j).value);\n if (value == currentValue) {\n return false;\n }\n }\n //check square\n var i_init = (Math.floor(row/3))*3;\n var j_init = (Math.floor(col/3))*3;\n for (i = i_init; i < i_init+3; i++) {\n for (j = j_init; j < j_init+3; j++) {\n if (i == row || j == col) {\n continue;\n }\n value = parseInt(document.getElementById(\"cell\"+i+j).value);\n if (value == currentValue) {\n return false;\n }\n }\n }\n return true;\n}", "function isSquare(arr) {\n \n}", "function perfect_sq(candidate){\n var lo = BigInteger.ZERO,\n hi = candidate,\n mid,\n element;\n while (lo.compare(hi) <=0) {\n mid = lo.add(hi).divide(BigInteger.small[2]);\n if (mid.square().compare(candidate)<0) {\n lo = mid.next();\n } else if (mid.square().compare(candidate)>0) {\n hi = mid.prev();\n } else {\n return true;;\n }\n }\n return false;\n}", "function checkAnswers() {\n console.log(\"Max value is: \", maxValue(firstNum, secondNum));\n console.log(\"Min value is: \", minValue(firstNum, secondNum));\n if (checkParity(num)) console.log(`${num} is even`);\n else console.log(`${num} is odd`);\n}", "function isperfsq(max){\n if (max % Math.sqrt(max) === 0) {\n console.log(max + \" is a perfect square\");\n}\n}", "function squaresquare(a, b){\n\n a.left = a.x\n b.left = b.x\n a.right = a.x + a.width\n b.right = b.x + b.width\n a.top = a.y \n b.top = b.y\n a.bottom = a.y + a.height\n b.bottom = b.y + b.height\n\n\n\n if (a.left > b.right || a.top > b.bottom || \n a.right < b.left || a.bottom < b.top)\n {\n return false\n }\n else\n {\n return true\n }\n}", "function isSolvable(board) {\n var inversionSum = 0; // If this sum is even it is solvable\n\n for (var i = 0; i < board.length; i++) {\n // For empty square add row number to inversionSum\n if (board[i] == 0) {\n inversionSum += ((i / DIM) + 1); // add Row number\n continue;\n }\n var count = 0;\n for (var j = i + 1; j < board.length; j++) {\n if (board[j] == 0) {\n continue;\n } else if (board[i] > board[j]) {\n count++;\n }\n }\n inversionSum += count;\n }\n\n // if inversionSum is even return true, otherwise false\n return inversionSum % 2 == 0;\n\n }", "function checkPerfectNumber(number) {\n\t\tlet temp = 0;\n\t\tfor (let i = 1; i <= number / 2; i++) {\n\t\t\tif (number % i === 0) {\n\t\t\t\ttemp += i;\n\t\t\t}\n\t\t}\n\n\t\tif (temp === number && temp !== 0) {\n\t\t\treturn true//'It is a perfect number.';\n\t\t}\n\t\telse {\n\t\t\treturn false //'It is not a perfect number.';\n\t\t}\n\t}", "function checkPairPlus(hand) {\n let pointArray = [];\n for (let card of hand) {\n pointArray.push(card.point);\n }\n pointArray.sort((a, b) => {\n return a - b;\n });\n let checkPair = new Set(pointArray);\n if (checkPair.size > 3) return;\n if (pointArray[1] != pointArray[2] && checkPair.size == 2) {\n // showHand(hand, \"Pair with pair card\");\n return true;\n }\n\n if (\n (pointArray[2] - pointArray[1] == 1 &&\n pointArray[1] - pointArray[0] == 1) ||\n (pointArray[3] - pointArray[2] == 1 && pointArray[2] - pointArray[1] == 1)\n ) {\n if (checkSuit(hand) > 0) return true;\n // showHand(hand, \"Pairs with suited and connected side cards\");\n }\n}", "function isValid(number, row, col, board){\n //Row + Column Check\n for(let i = 0; i < 9; i ++){\n if (board[row][i] == number && i != col){\n return false\n }else if (board[i][col] == number && i!= row){\n return false\n }\n }\n\n //Square Check\n let bigRow = Math.floor(row / 3)\n let bigCol = Math.floor(col / 3)\n for(let i = 3 * bigRow; i < 3 * bigRow + 3; i++){\n for(let j = 3 * bigCol; j < 3 * bigCol + 3; j++){\n if (board[i][j] == number && i != row && j != col){\n return false\n }\n }\n }\n \n return true\n}", "function isPerfectSquare(x){\n\tvar root = Math.sqrt(x);\n\treturn Number.isInteger(root);\n}", "function isSquare(one, two, three, four, threshold=0.0) {\n let l = [];\n\n l.push(distance(one, two));\n l.push(distance(one, three));\n l.push(distance(one, four));\n l.push(distance(two, three));\n l.push(distance(two, four));\n l.push(distance(three, four));\n\n console.log(l)\n l = l.sort((a, b) => {\n return a-b;\n });\n console.log(l)\n\n let t = threshold**2;\n if (l[3]-l[4] ) return false;\n if (l[4] !== l[5]) return false;\n\n console.log(\"banana\")\n\n if (!(l[0] == l[1] &&\n l[1] == l[2] &&\n l[2] == l[3])) {\n return false;\n }\n\n return true;\n}", "function isSolved() {\n for (let row = 0; row < numRows; row++) {\n for (let col = 0; col < numCols; col++) {\n if (isCellValidTest(row, col) === false) {\n return false;\n }\n }\n }\n return true;\n}", "function checkWin() {\n for (let i = 0; i < winningCombinations.length; i++) {\n let pattern = winningCombinations[i];\n let [a, b, c] = pattern;\n if ( currentCells[a] === currentCells[b] && currentCells[b] === currentCells[c] ) {\n return true;\n }\n }\n return false;\n}", "function win(squares)\n{\n\tconst lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6]\n ];\n for (let i = 0; i < lines.length; i++) {\n const [a, b, c] = lines[i];\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\n return true;\n }\n }\n return false;\n}", "isPossibleValueValid(possibleValue,currentSquare){\r\n \r\n let isValid = false\r\n let currentRow = this.grid.gridObj[currentSquare[0]]\r\n let currentCol = this.grid.getColByCoordinate(currentSquare)\r\n \r\n if(!currentRow.includes(possibleValue)){\r\n if(!currentCol.includes(possibleValue)){\r\n let currentBox = this.grid.getBox(currentSquare, false)\r\n \r\n if(!currentBox.includes(possibleValue)){\r\n isValid = true\r\n }\r\n }\r\n }\r\n return isValid\r\n }", "function findPerfectSquare(startingNumber) { \n let numberBuilder = [];\n findPermutations(startingNumber.toString());\n\n console.log(`prefect squares: ${prefectSquares}`);\n //console.log('The largest perfect square using all the digits from 1 to 9 exactly once is: ' + largestSquare);\n console.log(`The findPermutations function was called ${howManyTimesIsFindPermutationsCalled} times`);\n}", "function is_valid(){\n var aa = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];\n var bb = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];\n var i, j, k, l;\n\n // Check rows and colunms\n for(i=0;i<9;i++){\n aa = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];\n bb = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];\n for(j=0;j<9;j++){\n // Check rows\n if(board[i][j]!=0){\n if(aa[board[i][j]]==-1) aa[board[i][j]] = 0;\n else return 0;\n }\n // Check colunms\n if(board[j][i]!=0){\n if(bb[board[j][i]]==-1) bb[board[j][i]] = 0;\n else return 0;\n }\n }\n }\n\n // Check 3x3 squares\n var idx = [0,3,6];\n for(i=0;i<3;i++){\n for(j=0;j<3;j++){\n aa = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];\n for(k=0;k<3;k++){\n for(l=0;l<3;l++){\n if(board[idx[i]+k][idx[j]+l]!=0){\n if(aa[board[idx[i]+k][idx[j]+l]]==-1) aa[board[idx[i]+k][idx[j]+l]] = 0;\n else return 0;\n }\n }\n }\n }\n }\n\n return 1;\n\n}//tinha board", "function checkPairSum(arr, num){\n\tfor (var i= 0; i < arr.length; i++){\n\t\tfor (var j= i+1; j<arr.length; j++)\n\t\tif (arr[i]+arr[j] == num){\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function pSqrRe(num){\n\t// edge case: if num is 1, 0, or a negitive number\n\tif (num <= 1) {\n\t\treturn true;\n\t}\n\tvar newNum = 0;\n\t// solve with sum\n\tfor (var i = 1; i < num/2; i++) {\n\t\tif (i % 2 !== 0) {\n\t\t\tnewNum += i;\n\t\t}\n\t\tif (newNum === num) {\n\t\treturn true;\n\t\t}\n\t} \t\n}", "function is_pythagorean(a, b, c)\n{\n if (a * a + b * b === c * c)\n return true;\n return false;\n}", "function checkTwoNumbers(x, y) \n{\n return ((x == 50 || y == 50) || (x + y == 50));\n}", "function hasPairWithSum(array, sum) {\n var length = array.length;\n for (var i = 0; i < length - 1; i++) { // start-index : 0 , end-index : 10 - 1 (9)\n for (var j = i + 1; j < length; j++) { // start-index : 1 , end-index : 10\n if (array[i] + array[j] === sum) {\n console.log(true);\n return true;\n }\n }\n }\n return false;\n}", "function isLucky(n) {\n let N = n.toString().split(\"\");\n let sumFirst = 0;\n let sumSecond = 0;\n for(let i =0,j=N.length/2; i < N.length/2;i++) {\n sumFirst += parseInt(N[i]);\n sumSecond += parseInt(N[j]); \n j++\n }\n return (sumFirst == sumSecond);\n}", "function isValid(guess) {\n return !hasDuplicates(guess)\n}", "function isPerfectSquare(value) {\n var result = false;\n\n var sqrt = Math.floor(Math.sqrt(value));\n\n result = value == sqrt * sqrt;\n\n return result;\n}", "function magicSquare(arr) {\n let flattenedArr = [].concat(...arr)\n let cost = Infinity\n\n const possibilities = [\n [\n [8, 1, 6],\n [3, 5, 7],\n [4, 9, 2],\n ],\n [\n [6, 1, 8],\n [7, 5, 3],\n [2, 9, 4],\n ],\n [\n [4, 9, 2],\n [3, 5, 7],\n [8, 1, 6],\n ],\n [\n [2, 9, 4],\n [7, 5, 3],\n [6, 1, 8],\n ],\n [\n [8, 3, 4],\n [1, 5, 9],\n [6, 7, 2],\n ],\n [\n [4, 3, 8],\n [9, 5, 1],\n [2, 7, 6],\n ],\n [\n [6, 7, 2],\n [1, 5, 9],\n [8, 3, 4],\n ],\n [\n [2, 7, 6],\n [9, 5, 1],\n [4, 3, 8],\n ],\n ]\n\n return possibilities.reduce((cost, magicSquare) => {\n const flatSquare = [].concat(...magicSquare)\n let tempCost = 0\n\n for (let i = 0; i < flatSquare.length; i++) {\n tempCost += Math.abs(flatSquare[i] - flattenedArr[i])\n if (tempCost > cost) return cost\n }\n\n return tempCost\n }, cost)\n}", "function makeBricks(small ,big, goal) {\n possible = false;\n if (big * 5 === goal || small * 1 === goal || small * 1 + big * 5 === goal)\n {possible = true;}\n console.log(possible);\n return big * 5 === goal || small * 1 === goal || small * 1 + big * 5 === goal\n}", "function squares(a, b) {\n let countSquares = 0;\n for (let i = Math.ceil(Math.sqrt(a)); i <= Math.ceil(Math.sqrt(b)); i++) {\n const sqr = Math.pow(i,2);\n if ((sqr-a)*(sqr-b) <= 0) countSquares++;\n }\n return countSquares;\n}", "function checkCell(rowNo,colNo) {\n if (possibles[rowNo][colNo].length === 1) {\n var squareValue = possibles[rowNo][colNo][0]\n console.log(\"Cell: \" + rowNo+\",\"+colNo+\",\"+squareValue);\n setValue(rowNo,colNo,squareValue);\n return true;\n }\n return false;\n}", "function evaluateWinnerVsPc(evenOrOdd, number) {\n var rndNum = randomGenerator(5, 1);\n sum = rndNum + number;\n var sumResult = pariodispari(sum);\n if (evenOrOdd === sumResult) {\n console.log('Hai scelto un numero ' + evenOrOdd + \", il totale risulta \" + sum + ' quindi Hai Vinto');\n } else {\n console.log('Hai scelto un numero ' + evenOrOdd + \", il totale risulta \" + sum + ' quindi NON hai Vinto');\n }\n}", "function validate() {\n\tvar combinations = [\n\t\t\t\t\t\t\t\t\t\t\t[0, 1, 2],\n\t\t\t\t\t\t\t\t\t\t\t[3, 4, 5],\n\t\t\t\t\t\t\t\t\t\t\t[6, 7, 8],\n\t\t\t\t\t\t\t\t\t\t\t[0, 3, 6],\n\t\t\t\t\t\t\t\t\t\t\t[1, 4, 7],\n\t\t\t\t\t\t\t\t\t\t\t[2, 5, 8],\n\t\t\t\t\t\t\t\t\t\t\t[0, 4, 8],\n\t\t\t\t\t\t\t\t\t\t\t[2, 4, 6],];\n\tfor (var i = 0; i < 8; i++) { //iterate over all combinations\n\t\tvar all_x = true;\n\t\tvar all_o = true;\n\t\tfor (var j = 0; j < 3; j++) { //iterate over each space in the combination\n\t\t\tvar ind = combinations[i][j];\n\t\t\tif (board_state[ind] == 1 || board_state[ind] == -1) all_o = false; //it isn't all O's\n\t\t\tif (board_state[ind] == 0 || board_state[ind] == -1) all_x = false; //it isn't all X's\n\t\t}\n\t\tif (all_x) return 1;\n\t\tif (all_o) return 0;\n\t}\n\treturn -1; //no winner\n}", "function abundantCheck(number) {\n let sum = 1;\n for (let i = 2; i <= Math.sqrt(number); i++) {\n if (number % i === 0) {\n sum += i + +(i !== Math.sqrt(number) && number / i);\n }\n }\n return sum > number;\n}", "function perfectRoots(n) {\n let x = Math.sqrt(n)\n let y = Math.sqrt(x)\n let z = Math.sqrt(y)\n if (x % 1 || y % 1 || z % 1) return false;\n return true;\n }", "function specialPythagoreanTriplet() {\n var SUM = 1000;\n var a, b, c;\n //only search the case a < b < c\n for(c = Math.ceil(1000/3); c < 1000/2; c++) {\n for(b = Math.ceil((SUM - c)/2); b < c; b++) {\n a = SUM - c - b;\n if(a*a + b*b - c*c === 0) {\n console.log(a, b, c);\n return a * b * c;\n }\n }\n }\n}", "function is(x,y){// SameValue algorithm\nif(x===y){// Steps 1-5, 7-10\n// Steps 6.b-6.e: +0 != -0\n// Added the nonzero y check to make Flow happy, but it is redundant\nreturn x!==0||y!==0||1/x===1/y;}else{// Step 6.a: NaN == NaN\nreturn x!==x&&y!==y;}}", "function pairCheck(plane1, plane2) { // checks the distance between two pairs\n distanceX = plane1.x - plane2.x;\n distanceX = Math.pow(distanceX, 2);\n distanceY = plane1.y - plane2.y;\n distanceY = Math.pow(distanceY, 2);\n finDistance = distanceX + distanceY;\n finDistance = Math.sqrt(finDistance);\n return finDistance;\n}", "function checkSolution () {\n let failed = false\n solutionPlaying = true\n for (let z = 0; z < mySolution.length; z++) {\n if (mySolution[z] !== solution[z]) {\n failed = true\n banner.innerHTML = 'Sorry!'\n setTimeout(() => {\n new Audio('sounds/fail.mp3').play()\n }, 700)\n setTimeout(introAnimation, 500)\n setTimeout(checkHighScore, 3000)\n setTimeout(resetGame, 3000)\n }\n }\n if (mySolution.length >= solution.length && failed !== true) {\n if (mySolution.toString() === solution.toString()) {\n theScore++\n updateScore()\n banner.innerHTML = 'Good!'\n setTimeout(generateSolution, 1000)\n }\n mySolution = []\n failed = false\n }\n solutionPlaying = false\n}", "function scoreSquare(s) {\n if (!s) {\n return 0;\n }\n // console.log(\"Square detected at \" + s.x + \", \" + s.y + \" with side \" + s.side);\n var score = 0,\n fillBox;\n for (let i = s.x; i <= s.x + s.side; i++) {\n for (let j = s.y; j <= s.y + s.side; j++) {\n fillBox = board.box(i, j);\n if (!squareCorner(s, fillBox)) {\n score = score + scoreBox(fillBox.color, s.color);\n // console.log(\"fill box at \" + i + \", \" + j + \" with color \" + fillBox.color + \" gets a score of \" + scoreBox(fillBox.color, s.color) + \". Score is now \" + score);\n }\n }\n }\n return score;\n}", "function isTheInputPresolved(unsolvedSudoku) {\n\n //check horizontally if 0 or repeated entries exist.\n\n for (let i = 0; i < unsolvedSudoku.length; i++) {\n\n for (let j = 0; j < unsolvedSudoku[i].length - 1; j++) {\n\n if (unsolvedSudoku[i][j] == 0) {\n isUnsolved = true;\n return false;\n }\n }\n }\n\n //check vertically for repeated entries except 0.\n\n for (let k = 0; k < unsolvedSudoku.length; k++) {\n\n for (let l = 0; l < unsolvedSudoku[k].length - 1; l++) {\n\n var currentValue;\n\n if (unsolvedSudoku[l][k] != 0) {\n currentValue = unsolvedSudoku[l][k];\n\n if (unsolvedSudoku[l + 1][k] == currentValue) {\n console.log(\"Invalid Input\")\n console.log(`The number ${unsolvedSudoku[l + 1][k]} is already existed in column ${k + 1}`);\n return false\n }\n }\n\n }\n }\n}", "function checkForCheck(someBoard, player){\n\n\tvar tempsq = positionOf(\"K\", someBoard, player);\n\n\tfor (var a = 0; a <= 11; a++){\n\n\t\tfor (var b = 0; b <= 11; b++){\n\n\t\t\tif (someBoard[a][b].player !== 0 && someBoard[a][b].player !== player){\n\n\t\t\t\tvar tempSquares = computeMoves(someBoard[a][b].symbol, a, b, someBoard);\n\t\t\t\t//if(someBoard[a][b].symbol === )\n\t\t\t\tfor(var x = 0; x < tempSquares.length; x++){\n\t\t\t\t\tif (tempSquares[x].row === tempsq.row && tempSquares[x].col === tempsq.col){\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn false;\n}", "function checkWin() {\n const combinations = [\n [0,1,2], [3,4,5], [6,7,8], \n [0,3,6], [1,4,7], [2,5,8], \n [0,4,8], [2,4,6],\n ];\n\n let check = false;\n combinations.forEach((items) => {\n const value0 = board[items[0]]; \n const value1 = board[items[1]]; \n const value2 = board[items[2]]; \n check |= value0 != \"\" && value0 == value1 && value1 == value2;\n });\n\n return check;\n}", "function isPossibleNumber(cell,number,sudoku) {\n\tvar row = returnRow(cell);\n\tvar col = returnCol(cell);\n\tvar block = returnBlock(cell);\n\treturn isPossibleRow(number,row,sudoku) && isPossibleCol(number,col,sudoku) && isPossibleBlock(number,block,sudoku);\n}", "function solequa(n) {\n // (x - 2y)*(x + 2y) = n\n const findDividers = (n) => {\n const results = []\n \n for (let i = 1; i <= Math.sqrt(n); i++) {\n if (Number.isInteger(n / i)) {\n results.push([i, n / i])\n }\n }\n \n return results\n }\n \n const solve = (m1, m2) => {\n // {x - 2y = m1; x + 2y = m2;} => {x = m1 + 2y; 4y = m2 - m1} => {x = (m1 + m2)/2; y = (m2 - m1)/4}\n const y = (m1 + m2) / 2\n const x = (m2 - m1) / 4\n \n if (Number.isInteger(x) && Number.isInteger(y)) {\n return (x > y) ? [x, y] : [y, x]\n }\n \n return null\n }\n \n const dividers = findDividers(n)\n const solutions = dividers.map(([d1, d2]) => solve(d1, d2)).filter(s => s !== null)\n \n return solutions\n}", "function verifyBoard() {\n\n var validDesert = true;\n var validMats = true;\n var validValues = true;\n var warning = \"WARNING: Your board is not set up in a valid way. The program will still run fine but parts of the algorithm may produce less accurate results, \" +\n \"specifically the resource plenty score. The board's issue is: \\n\\n\"\n\n var goalMatArray = [0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 5, 5, 5, 5, 6]\n var goalNumArray = [0, 2, 3, 3, 4, 4, 5, 5, 6, 6, 8, 8, 9, 9, 10, 10, 11, 11, 12]\n\n var tileMatArray = []\n var tileNumArray = []\n\n for (x = 0; x < tilesList.length; x++) {\n tileMatArray.push(tilesList[x].mat)\n tileNumArray.push(tilesList[x].value)\n\n if (tilesList[x].mat == 6 && tilesList[x].value != 0) {\n validDesert = false\n }\n }\n\n validMats = arraysEqual(goalMatArray, tileMatArray)\n validValues = arraysEqual(goalNumArray, tileNumArray)\n\n if (!validMats) {\n warning += \"- The board does not contain the correct number of tile materials. See the help link for the correct number of each material \\n\"\n }\n\n if (!validValues) {\n warning += \"- The board does not contain the correct number of tile values. See the help link for the correct values for a board \\n\"\n }\n\n if (!validDesert) {\n warning += \"- Make sure deserts are given a value of 0 \\n\"\n }\n\n if (!validMats || !validValues || !validDesert) {\n alert(warning)\n }\n\n}", "function isValidSquare(row, col, size) {\n\tif (isValidRow(row, size) && isValidColumn(col, size) && isValidDiagonal(row, col, size) )\n\t\treturn true;\n\telse\n\t\treturn false;\n}", "function diffSquares(num) {\r\n var sumNums = 0;\r\n var sumSq = 0;\r\n for (var i = 1; i <= num; i += 1) {\r\n sumNums += i;\r\n sumSq += i*i;\r\n }\r\n return sumNums*sumNums - sumSq;\r\n}", "function checkForSquare(gridNum, loc) {\n\tlet letter = turn;\n\tlet g = gameBoard[gridNum];\n\n\t// Check for 3 in a row\n\tif (\n\t\t(g.A1 === g.A2 && g.A1 === g.A3 && g.A1) ||\n\t\t(g.B1 === g.B2 && g.B1 === g.B3 && g.B1) ||\n\t\t(g.C1 === g.C2 && g.C1 === g.C3 && g.C1) ||\n\t\t(g.A1 === g.B1 && g.A1 === g.C1 && g.A1) ||\n\t\t(g.A2 === g.B2 && g.A2 === g.C2 && g.A2) ||\n\t\t(g.A3 === g.B3 && g.A3 === g.C3 && g.A3) ||\n\t\t(g.A1 === g.B2 && g.A1 === g.C3 && g.A1) ||\n\t\t(g.C1 === g.B2 && g.C1 === g.A3 && g.C1)\n\t) {\n\t\t// Add letter to board\n\t\t$(`#${gridNum}`).html(`${letter}`);\n\t\t$(`#${gridNum}`).removeClass('grid');\n\t\t$(`#${gridNum}`).addClass('letter');\n\n\t\t// Add letter to gameBoard array\n\t\tgameBoard.bigGrid[gridNum] = letter;\t\t\n\t} \n\t\n\t// Check that all squares have a value\n\telse if (g.A1 && g.A2 && g.A3 && g.B1 && g.B2 && g.B3 && g.C1 && g.C2 && g.C3) {\n\t\tgameBoard.bigGrid[gridNum] = 'Tie';\n\t}\n\t\n\t// Switch turns\n\tturn === 'X' ? turn = 'O': turn = 'X';\n\t$('#turn').text(`${turn}'s Turn`);\n\n\tcheckForWin(letter);\n\n\tif (!($('#turn').text() === 'X Wins' || $('#turn').text() === 'O Wins' || $('#turn').text() === \"It's a Tie Game!\")) {\n\t\tnextTurn(loc);\n\t}\n\n}", "function solution_1 (n) {\r\n function sumSquaresOfDigits (n) {\r\n return String(n)\r\n .split('')\r\n .map(digit => +digit)\r\n .reduce((sum, digit) => sum + digit ** 2, 0);\r\n }\r\n const seen = new Set([n]); // this set is here to detect cycles\r\n let processedN = sumSquaresOfDigits(n) // i introduce this variable here to avoid calculating it twice (in the while loop condition and in the subsequent line)\r\n while (processedN !== 1) {\r\n n = processedN;\r\n if (seen.has(n)) return false;\r\n seen.add(n);\r\n processedN = sumSquaresOfDigits(n);\r\n }\r\n return true;\r\n}", "classic_validate() {\n\t\t// check each column\n\t\tfor (var x = 0 ; x < this.width ; x++) {\n\t\t\tvar found_digits = new Array(this.max)\n\t\t\tfor (var i = 0 ; i < this.max ; i++)\n\t\t\t\tfound_digits[i] = false;\n\t\t\tfor (var y = 0 ; y < this.height ; y++) {\n\t\t\t\tvar digit = this.cells[x][y].value\n\t\t\t\t// if incorrect number\n\t\t\t\tif (!check_digit(digit,this.max))\n\t\t\t\t\treturn false\n\t\t\t\t// if two of the same in the column\n\t\t\t\tif (found_digits[digit-1])\n\t\t\t\t\treturn false\n\t\t\t\tfound_digits[digit-1] = true\n\t\t\t}\n\t\t\t// TODO : check if it works (had issues with for in)\n\t\t\tfor (var b in found_digits) {\n\t\t\t\tif (!b)\n\t\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\t// check each row\n\t\tfor (var y = 0 ; y < this.height ; y++) {\n\t\t\tvar found_digits = new Array(this.max)\n\t\t\tfor (var i = 0 ; i < this.max ; i++)\n\t\t\t\tfound_digits[i] = false;\n\t\t\tfor (var x = 0 ; x < this.width ; x++) {\n\t\t\t\tvar digit = this.cells[x][y].value\n\t\t\t\t// if incorrect number\n\t\t\t\tif (!check_digit(digit,this.max))\n\t\t\t\t\treturn false\n\t\t\t\t// if two of the same in the row\n\t\t\t\tif (found_digits[digit-1])\n\t\t\t\t\treturn false\n\t\t\t\tfound_digits[digit-1] = true\n\t\t\t}\n\t\t\tfor (var b in found_digits) {\n\t\t\t\tif (!b)\n\t\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\t// check each square\n\t\tfor (var i = 0 ; i < (this.width/3)*(this.height/3) ; i++) {\n\t\t\tvar found_digits = new Array(this.max)\n\t\t\tfor (var i = 0 ; i < this.max ; i++)\n\t\t\t\tfound_digits[i] = false;\n\t\t\tfor (var x = 3*(i%3) ; x < 3*((i%3)+1) ; x++) {\n\t\t\t\tfor (var y = 3*Math.floor(i/3) ; y < 3*(Math.floor((i+1)/3)) ; y++) {\n\t\t\t\t\tvar digit = this.cells[x][y].value\n\t\t\t\t\t// if incorrect number\n\t\t\t\t\tif (!check_digit(digit,this.max))\n\t\t\t\t\t\treturn false\n\t\t\t\t\t// if two of the same in the row\n\t\t\t\t\tif (found_digits[digit-1])\n\t\t\t\t\t\treturn false\n\t\t\t\t\tfound_digits[digit-1] = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (var b in found_digits) {\n\t\t\t\tif (!b)\n\t\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}", "function checkPair() {\n\n}", "function isSolved(board) {\n //check for wins\n for (let i = 0; i <= 2; i++){\n //check vertical win\n if (board[0][i] === board[1][i] && board[0][i] === board[2][i] && board[0][i] !== 0){\n return board[0][i];\n }\n //check horizontal win\n if (board[i][0] === board[i][1] && board[i][0] === board[i][2] && board[i][0] !== 0){\n return board[i][0];\n }\n }\n //check diagonal\n if (board[0][0] === board[1][1] && board[0][0] === board[2][2] && board[0][0] !== 0){\n return board[0][0];\n }\n //other diagonal\n if (board[2][0] === board[1][1] && board[2][0] === board[0][2] && board[2][0] !== 0){\n return board[2][0];\n }\n //check for unsolved board\n for (let i = 0; i <= 2; i++){\n for (let j = 0; j <= 2; j++){\n console.log(i, j)\n if (board[i][j] === 0){\n return -1;\n }\n }\n }\n //by default, the only thing left is a cat\n return 0;\n}", "function is(x,y){// SameValue algorithm\nif(x===y){// Steps 1-5, 7-10\n// Steps 6.b-6.e: +0 != -0\nreturn x!==0||1/x===1/y;}else{// Step 6.a: NaN == NaN\nreturn x!==x&&y!==y;}}", "function is(x,y){// SameValue algorithm\nif(x===y){// Steps 1-5, 7-10\n// Steps 6.b-6.e: +0 != -0\nreturn x!==0||1/x===1/y;}else{// Step 6.a: NaN == NaN\nreturn x!==x&&y!==y;}}", "function is(x,y){// SameValue algorithm\nif(x===y){// Steps 1-5, 7-10\n// Steps 6.b-6.e: +0 != -0\nreturn x!==0||1/x===1/y;}else{// Step 6.a: NaN == NaN\nreturn x!==x&&y!==y;}}", "async function checkSolution(gridData) {\n let seedPhrase = parseSolutionSeedPhrase(data, gridData);\n const { secretKey, publicKey } = parseSeedPhrase(seedPhrase);\n // Compare crossword solution's public key with the known public key for this puzzle\n // (It was given to us when we first fetched the puzzle in index.js)\n if (publicKey === crosswordSolutionPublicKey) {\n console.log(\"You're correct!\");\n // Send transaction TO the crossword puzzle smart contract FROM the crossword puzzle account.\n // Learn more about access keys here: https://docs.near.org/docs/concepts/account#access-keys\n const keyStore = new nearAPI.keyStores.InMemoryKeyStore();\n const keyPair = nearAPI.utils.key_pair.KeyPair.fromString(secretKey);\n await keyStore.setKey(nearConfig.networkId, nearConfig.contractName, keyPair);\n nearConfig.keyStore = keyStore;\n const near = await nearAPI.connect(nearConfig);\n const crosswordAccount = await near.account(nearConfig.contractName);\n\n let playerPublicKey = playerKeyPair.publicKey;\n console.log('Unique public key for you as the player: ', playerPublicKey);\n\n let transaction;\n try {\n setShowLoader(true);\n transaction = await crosswordAccount.functionCall(\n {\n contractId: nearConfig.contractName,\n methodName: 'submit_solution',\n args: {\n solver_pk: playerPublicKey,\n },\n gas: '300000000000000', // You may omit this for default gas\n attachedDeposit: 0 // You may also omit this for no deposit\n }\n );\n localStorage.setItem('playerSolvedPuzzle', crosswordSolutionPublicKey);\n setSolvedPuzzle(crosswordSolutionPublicKey);\n } catch (e) {\n if (e.message.contains('Can not sign transactions for account')) {\n // Someone has submitted the solution before the player!\n console.log(\"Oof, that's rough, someone already solved this.\")\n }\n } finally {\n setShowLoader(false);\n console.log('Transaction status:', transaction.status);\n console.log('Transaction hash:', transaction.transaction.hash);\n }\n } else {\n console.log(\"That's not the correct solution. :/\");\n }\n }", "function is(x,y){// SameValue algorithm\nif(x===y){// Steps 1-5, 7-10\n// Steps 6.b-6.e: +0 != -0\nreturn x!==0||1/x===1/y;}else {// Step 6.a: NaN == NaN\nreturn x!==x&&y!==y;}}", "function happyNumber(number){\n console.log(number);\n let squaredNumber = (number*number);\n console.log(squaredNumber);\n for(i = 0; i < number.length; i++){\n \n }\n}", "function ArraySquareChecker(a1,a2){\r\n // checking if the length of the both arrays is same or not\r\n if(a1.length !== a2.length){\r\n return false;\r\n }\r\n // checking if the correct square number is present in the second array in correct frequency or not.\r\n else{\r\n for(let i=0;i<a1.length;i++){\r\n let orderIndex = a2.indexOf(a1[i] ** 2);\r\n if(orderIndex===-1){\r\n return false;\r\n }\r\n else{\r\n a2.splice(orderIndex,1); \r\n }\r\n \r\n }\r\n // resulting out the message for the perfect match for the square in the second array\r\n if(a2.length===0){\r\n return true;\r\n }\r\n }\r\n}", "function solved(board){\r\n for(var i=0; i < 9; i++){\r\n for(var j = 0; j<9; j++){\r\n //if there is a square with nothing, the board is not solved\r\n if(board[i][j] == null){\r\n return false\r\n }\r\n }\r\n }\r\n return true\r\n}", "function calculateWinner(squares) {\n // Declares a multidimensional array ‘lines’, that holds all the winning combinations\n // i.e. there is a winner if there is the same letter (i.e 'X') in boxes 0, 1, and 2 (the first combination below).\n const lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6]\n ];\n //\n for (let i = 0; i < lines.length; i++) {\n // create a new array with the same values as each winning combo. i.e. when i = 0 the new array of [a, b, c] is [0, 1, 2]\n const [a, b, c] = lines[i];\n // 'if' statement compares current combination of iteration with the board’s clicked squares combinations\n // and if there's a match, it returns the current combination, otherwise it returns null.\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\n // The squares[a] by itself is checking if there is a value in that particular square (null is a falsy value)\n // and the remainder of the condition makes sure they are all the same type (either X or O).\n \n // If the value of a, b, c are the same, return the value of 'a' (either X or O).\n // If the value can be converted to false (e.g. if the value is null) the 'if' statement returns false.\n return squares[a];\n // square’s values can only be 'X', 'O', or null.\n }\n }\n return null;\n // The if statement checks if the there are 3 of the same letters for the winning combos\n // i.e. for winning combo [0, 1, 2] it looks up the values in the squares array -> squares[0], squares[1], squares[2].\n // E.g. here's how it breaks down for the first winning combo [0, 1, 2] in lines:\n // since a is 0, then squares[a] is squares[0] and the value of squares [0] is 'X'\n // squares[a] is true since it has a value, the value is 'X'\n // squares[a] === squares[b] is true because the value of squares[b] (i.e. squares[1]) is 'X', the same as squares[a]\n // squares[a] === squares[c] is true because squares[c] (i.e. squares[2] is 'X'), the same as squares [a]\n // since all three parts in the if are true the function returns the value of squares[a], which is 'X' and thus the player 'X'\n }", "getPossibleSquares(sq) {\n const piece = this.board[sq];\n const colorOfPiece = PieceColor[piece];\n if (piece === SQUARES.OFFBOARD) throw Error(\"Square is offboard\");\n if (piece === PIECES.EMPTY) throw Error(\"Square is empty\");\n\n //* Pawns *//\n if (PiecePawn[piece]) {\n const directions = [10, 20, 11, 9];\n const conditions = [\n // 1 step forward\n (move) =>\n this.board[sq + move] !== SQUARES.OFFBOARD &&\n this.board[sq + move] === PIECES.EMPTY,\n // 2 steps forward\n (move) =>\n ((colorOfPiece === COLORS.WHITE &&\n Square2FileRank(sq)[1] === RANKS._2) ||\n (colorOfPiece === COLORS.BLACK &&\n Square2FileRank(sq)[1] === RANKS._7)) &&\n this.board[sq + move / 2] === PIECES.EMPTY &&\n this.board[sq + move] === PIECES.EMPTY,\n // capture forward right\n (move) =>\n this.board[sq + move] !== SQUARES.OFFBOARD &&\n this.board[sq + move] !== PIECES.EMPTY &&\n PieceColor[this.board[sq + move]] === oppositeColor(colorOfPiece),\n // capture forward left\n (move) =>\n this.board[sq + move] !== SQUARES.OFFBOARD &&\n this.board[sq + move] !== PIECES.EMPTY &&\n PieceColor[this.board[sq + move]] === oppositeColor(colorOfPiece),\n ];\n const squares = [];\n const mult = PieceColor[piece] === COLORS.WHITE ? 1 : -1;\n directions.map((dir, index) => {\n if (conditions[index](mult * dir)) {\n const move = [sq, sq + mult * dir];\n // promotion\n if (\n (PieceColor[this.board[sq]] === COLORS.WHITE &&\n Square2FileRank(sq + mult * dir)[1] === RANKS._8) ||\n (PieceColor[this.board[sq]] === COLORS.BLACK &&\n Square2FileRank(sq + mult * dir)[1] === RANKS._1)\n ) ;\n // todo en passant\n squares.push(move);\n }\n });\n return squares;\n }\n\n //* Knights *//\n if (PieceKnight[piece]) {\n return KnightDirections.filter(\n (dir) =>\n this.board[sq + dir] === PIECES.EMPTY ||\n PieceColor[this.board[sq + dir]] === oppositeColor(colorOfPiece)\n ).map((dir) => [sq, sq + dir]);\n }\n return [];\n }", "function checkSquare(square, currentId) {\n\tconst isLeftEdge = (currentId % width === 0)\n\tconst isRightEdge = (currentId % width === width - 1)\n\n\tsetTimeout(() => {\n\t\tif (currentId > 0 && !isLeftEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) - 1].id\n\t\t\t//const newId = parseInt(currentId) - 1 ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId > 9 && !isRightEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) + 1 - width].id\n\t\t\t//const newId = parseInt(currentId) +1 -width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId >= 10) {\n\t\t\tconst newId = squares[parseInt(currentId - width)].id\n\t\t\t//const newId = parseInt(currentId) -width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId >= 11 && !isLeftEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) - 1 - width].id\n\t\t\t//const newId = parseInt(currentId) -1 -width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId <= 98 && !isRightEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) + 1].id\n\t\t\t//const newId = parseInt(currentId) +1 ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId < 90 && !isLeftEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) - 1 + width].id\n\t\t\t//const newId = parseInt(currentId) -1 +width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId <= 88 && !isRightEdge) {\n\t\t\tconst newId = squares[parseInt(currentId) + 1 + width].id\n\t\t\t//const newId = parseInt(currentId) +1 +width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t\tif (currentId <= 89) {\n\t\t\tconst newId = squares[parseInt(currentId) + width].id\n\t\t\t//const newId = parseInt(currentId) +width ....refactor\n\t\t\tconst newSquare = document.getElementById(newId)\n\t\t\tclick(newSquare) //A recursive approach to check for valid squares around \n\t\t}\n\t}, 10)\n}", "function checkSolved() {\n var orientation;\n for (i = 0; i < 3; i++) {\n for (j = 0; j < 3; j++) {\n orientation = cubeState[0][0][0][3];\n for (x = -1; x < 2; x++) {\n for (y = -1; y < 2; y++) {\n for (z = -1; z < 2; z++) {\n if (cubeState[x+1][y+1][z+1][3][i][j] !== orientation[i][j]) {\n if (x === 0 && z === 0) {\n if (cubeState[x+1][y+1][z+1][3][1][j] !== orientation[1][j])\n return false;\n } else if (x === 0 && y === 0) {\n if (cubeState[x+1][y+1][z+1][3][2][j] !== orientation[2][j])\n return false;\n } else if (y === 0 && z === 0) {\n if (cubeState[x+1][y+1][z+1][3][0][j] !== orientation[0][j])\n return false;\n } else\n return false;\n }\n }\n }\n }\n }\n }\n return true; // Only reached if all match\n}", "function solution(n) {\n d = new Array(30);\n l = 0;\n while (n > 0) {\n d[l] = n % 2;\n n = Math.floor(n / 2);\n l += 1;\n }\n console.log('l = ', l);\n console.log('d = ', d);\n for (p = 1; p < 1 + l; ++p) {\n ok = true;\n for (i = 0; i < l - p; ++i) {\n if (d[i] != d[i + p]) {\n ok = false;\n break;\n }\n }\n if (ok) {\n return p;\n }\n }\n return -1;\n}", "function isSolved() {\n\t\tvar i, j;\n\t\tvar tobesolved = 0;\n\t\tvar solved = false;\n\n\t\tfor (i=0; i<9; i++) {\n\t\t\tfor (j=0; j<9; j++) {\n\t\t\t\tif ( puzzle[i][j] === 0) {\n\t\t\t\t\ttobesolved++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (tobesolved === 0) {\n\t\t\tsolved = true;\n\t\t}\n\t\treturn solved;\n\t}", "function checkWinner(gameBoard){\n for(let combo of matched){\n let [a,b,c] =combo;\n if(gameBoard[a] === gameBoard[b] && gameBoard[a] === gameBoard[c]){\n return {state:true,nums:[a,b,c]}\n }\n }\n return false\n}", "function backtrackingCheck(tileGroup, markedTiles, pairAlreadyFound) {\n // If every tile is marked as true (winning), the hand is winning\n if (markedTiles.every(e => e)) {\n return true;\n }\n // If we haven't found a pair yet, look for one\n if (!pairAlreadyFound) {\n // First, check tiles one by one\n for (let firstIndex = 0; firstIndex < tileGroup.length; firstIndex++) {\n // For each tile, check if it has a twin\n // No need to look at previous elements because those have already been paired\n for (let secondIndex = firstIndex + 1; secondIndex < tileGroup.length; secondIndex++) {\n // Exclude tiles which have already been marked as winning\n if (!markedTiles[firstIndex] && !markedTiles[secondIndex]) {\n // If the tiles match suit and value they are twins\n if (tileGroup[firstIndex].suit == tileGroup[secondIndex].suit && tileGroup[firstIndex].value == tileGroup[secondIndex].value) {\n // Mark indices for paired tiles as winning\n markedTiles[firstIndex] = true;\n markedTiles[secondIndex] = true;\n // Call recursively with the pair marked; if true, the hand is winning\n if (backtrackingCheck(tileGroup, markedTiles, true)) {\n return true;\n }\n // Otherwise we didn't find a win, so we unmark those indices\n markedTiles[firstIndex] = false;\n markedTiles[secondIndex] = false;\n }\n }\n }\n }\n } else {\n // Otherwise, look for triplets\n for (let firstIndex = 0; firstIndex < tileGroup.length; firstIndex++) {\n for (let secondIndex = firstIndex + 1; secondIndex < tileGroup.length; secondIndex++) {\n for (let thirdIndex = secondIndex + 1; thirdIndex < tileGroup.length; thirdIndex++) {\n // Exclude tiles which have already been marked as winning\n if (!markedTiles[firstIndex] && !markedTiles[secondIndex] && !markedTiles[thirdIndex]) {\n // Save min and max values to check for sequential values\n const minValue = Math.min(tileGroup[firstIndex].value, tileGroup[secondIndex].value, tileGroup[thirdIndex].value);\n const maxValue = Math.max(tileGroup[firstIndex].value, tileGroup[secondIndex].value, tileGroup[thirdIndex].value);\n\n // Make an array for each triplet to be checked\n const triplet = [tileGroup[firstIndex], tileGroup[secondIndex], tileGroup[thirdIndex]];\n\n // For any triplet, the suits must all match\n if (checkForTriplets(triplet, minValue, maxValue)) {\n // Mark indices for grouped tiles as winning\n markedTiles[firstIndex] = true;\n markedTiles[secondIndex] = true;\n markedTiles[thirdIndex] = true;\n // Recursive call; we have already found a pair by this point\n if (backtrackingCheck(tileGroup, markedTiles, true)) {\n console.log(tileGroup[firstIndex].value + \" \" + tileGroup[secondIndex].value + \" \" + tileGroup[thirdIndex].value);\n return true;\n }\n // Otherwise we didn't find a win, so we unmark those indices\n markedTiles[firstIndex] = false;\n markedTiles[secondIndex] = false;\n markedTiles[thirdIndex] = false;\n }\n }\n }\n }\n }\n }\n return false;\n}", "function _isSolutionUnique(board) {\n\n function _solveSudokuDFS(board, result) {\n for (var i = 0; i < 9; i++) {\n for (var j = 0; j < 9; j++) {\n\n // find a slot to fill\n if (!board[i][j]) {\n\n var numbers = [0, 0, 0, 0, 0, 0, 0, 0, 0];\n\n _markNonAvailableNumbers(board, numbers, i, j);\n\n for (var k = 0; k < numbers.length; k++) {\n\n if (numbers[k] === 0) {\n board[i][j] = k + 1;\n _solveSudokuDFS(board, result);\n }\n }\n board[i][j] = \"\";\n return;\n }\n }\n }\n result.count++;\n };\n\n\n var result = {\n count: 0\n };\n\n _solveSudokuDFS(board, result);\n return result.count == 1;\n }", "function specialPythagoreanTriplet(n) {\n\n for (let a = 1; a < n; a++) {\n for (let b = a + 1; b < n - a; b++) {\n const c = n - a - b;\n\n if (c ** 2 === a ** 2 + b ** 2) {\n return a * b * c;\n }\n }\n }\n\n return 0;\n}", "function hasTwoPairs(newPassword) {\n let count = 0;\n\n for (let i = 0; i < newPassword.length; i++) {\n if (newPassword[i] === newPassword[i + 1]) {\n count++;\n i++; // to skip so a triple isn't considered two doubles\n }\n }\n\n return count === 2;\n}", "function checkIfSolved(level) {\n\tvar one;\n\tvar zero;\n\n\t//both full grid of 0 and 1 are valid winning conditions\n\tfor (var i = 0; i < cells.length; i++) {\n\t\tif (cells[i].activity) return false;\n\t\tif (cells[i].value == 1) one = true;\n\t\tif (cells[i].value == 0) zero = true;\n\t}\n\tif (zero && one) return false;\n\tif (!zero && !one) return false;\n\t\n\t//return false on all cases that do not point to victory\n\tdecryptingOngoing = false;\n\tsolvedPuzzles[level] = true;\n\tdecryptorFeedback.innerHTML = 'File decrypted.';\n\n\t//load decrypted data if puzzle completion was successful\n\tvar t = 0;\n\n\tsetTimeout(function() {\n\t\tdecryptorFeedback.innerHTML = 'loading decrypted data...';\n\t}, t += randomRange(500, 1000));\n\n\tsetTimeout(function() {\n\t\t\tdecryptorFeedback.innerHTML = '';\n\t\t\tdisplayResult(level, true);\n\t}, t += randomRange(500, 1000));\n}", "function is(x,y){return x===y&&(x!==0||1/x===1/y)||x!==x&&y!==y// eslint-disable-line no-self-compare\n;}", "function is(x,y){return x===y&&(x!==0||1/x===1/y)||x!==x&&y!==y// eslint-disable-line no-self-compare\n;}", "function is(x,y){return x===y&&(x!==0||1/x===1/y)||x!==x&&y!==y// eslint-disable-line no-self-compare\n;}" ]
[ "0.7403783", "0.69677645", "0.6871938", "0.6852753", "0.68112", "0.67071897", "0.66064626", "0.6602473", "0.65732485", "0.65462554", "0.6521942", "0.6474136", "0.6396237", "0.638038", "0.6363018", "0.63210046", "0.6293471", "0.62910724", "0.62816775", "0.6280572", "0.6278807", "0.62610394", "0.6255908", "0.62375194", "0.621324", "0.6189844", "0.61848044", "0.6179818", "0.61617976", "0.6158791", "0.615025", "0.61493516", "0.6142604", "0.61412305", "0.61400145", "0.6139676", "0.6135624", "0.61247706", "0.61209345", "0.6105164", "0.610319", "0.6100935", "0.60590225", "0.6035961", "0.6031056", "0.60283864", "0.6000786", "0.5984264", "0.5982586", "0.5977896", "0.5963959", "0.5961978", "0.5936877", "0.5929585", "0.59277123", "0.59211814", "0.5919047", "0.59042984", "0.5901505", "0.5889533", "0.5888559", "0.5888028", "0.5882459", "0.5880936", "0.58726877", "0.5868449", "0.5860222", "0.5853435", "0.58497995", "0.58497477", "0.5842669", "0.5840528", "0.5840111", "0.5839892", "0.5837421", "0.5837027", "0.5834388", "0.5822169", "0.5822169", "0.5822169", "0.5816969", "0.5816924", "0.58152854", "0.581525", "0.5812743", "0.5806254", "0.5801052", "0.580007", "0.578704", "0.5785544", "0.5782675", "0.5782346", "0.5781137", "0.5778954", "0.5774238", "0.5772254", "0.5768238", "0.5761928", "0.5761928", "0.5761928" ]
0.7262081
1
This function clears the previously played game board
function clearPrevGrid(){ // Select all the squares let squares = qsa(".square"); // Remove the contents of all squares for (let i = 0; i < squares.length; i++) { squares[i].remove(); } // Clear any remaining time on timer if (timer) { clearTimeout(timer); } // Deselect any numbers still selected for (let i = 0; i < id("number-selector").children.length; i++) { id("number-selector").children[i].classList.remove("selected"); } // Clear all selected variables selectedNumber = null; selectedSquare = null; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function clearBoard(){\n sendChatMessage(\"Clearing game board...\");\n lives = 1;\n current = 0;\n modifiers = [];\n board = [];\n sendChatMessage(\"Everything cleared! Ready for new game... Please rechoose tags.\");\n}", "function clearBoard() {\n board.clear();\n pause();\n}", "function clearBoard() {\r\n\tcells.forEach(element => {\r\n\t\tvar cell = document.getElementById(element);\r\n\t\tcell.innerHTML='';\r\n\t});\r\n\r\n\tstate.board = Array(9).fill(null);\r\n}", "function reset() {\n\t\t\tclear_board()\n\t\t}", "function clearBoard() {\n\tlet existingCards = gameBoard.firstElementChild;\n\twhile (existingCards) {\n\t\tgameBoard.removeChild(existingCards);\n\t\texistingCards = gameBoard.firstElementChild;\n\t}\n}", "function clear() {\r\n\r\n\t\tturn = \"\";\r\n\t\tgrid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];\r\n\t\tmsg(\"\");\r\n\t\t// We use map to generate a new empty array\r\n\t\t$(\".tile\").map(function () {\r\n\t\t\t$(this).text(\"\");\r\n\r\n\t\t});\r\n\r\n\t\twinner = 0;\r\n\t\tcount = 0;\r\n\t}", "function resetBoard() {\n board = [];\n makeBoard();\n currPlayer = 1;\n\n // TODO: destroy htmlBoard \n document.getElementById(\"board\").remove();\n}", "function clearBoard() {\n debug(\"clearBoard\");\n document.querySelector('.deck').innerHTML = \"\";\n }", "function clearBoard() {\n\tboard.reset();\n\treturn false;\n}", "function clearBoard()\r\n{\r\n 'use strict';\r\n \r\n var i;\r\n data.game.running = false;\r\n \r\n for(i = 0; i < data.board.line; i++)\r\n {\r\n document.getElementById(\"board\").deleteRow(0);\r\n } \r\n clearInterval(data.game.clock);\r\n}", "function clearBoard() {\n\tuserWrongGuesses = 0;\n\tmaxWrongGuesses = 0;\n\n\twhile (board.firstChild) {\n\t\tboard.removeChild(board.firstChild); //remove board elements\n\t}\n\n\twhile (strikes.firstChild) {\n\t\tstrikes.removeChild(strikes.firstChild); //remove strikes elements (missed guesses)\n\t}\n\n\twhile (userGuessesArr.length) {\n\t\tuserGuessesArr.pop(); //reset array of user guesses\n\t}\n}", "function reset_game_board(){\n $('.community_cards').empty();\n $('.players_cards').empty();\n $('.feedback').empty();\n }", "function clearBoard(){\n if (gameButton.textContent === \"Restart Game\" || gameButton.textContent === \"New Game\") {\n for (var i = 0; i < cells.length; i++) {\n cells[i].textContent = \".\";\n cells[i].style.color = \"white\";\n cells[i].style.backgroundColor = \"white\";\n }\n gameStarted = false;\n gameOver = false;\n }\n}", "function resetBoard() {\n\n\tif (gameOverStatus) {\n\t\tgameReset();\n\t}\n\n\t//reset cards in play\n\tcardsInPlay = [];\n\n\t//remove cards in game-board\n\tvar usedCards = document.getElementById('game-board');\n\twhile (usedCards.hasChildNodes()) {\n\t\tusedCards.removeChild(usedCards.firstChild);\n\t}\n\n\t//fill board with cards again\n\tcreateBoard();\n}", "function clearBoard() {\n $('td').empty();\n $('td').removeClass('played');\n $('td').data('player', '');\n }", "function resetBoard() {\n \n // prevents a game reset when a game is in progress\n if (self.gameBoard.gameStatus === \"Game in progress\") {\n alert(\"Whoa! One game at a time!\");\n return;\n }\n else if (self.gameBoard.gameStatus === \"Waiting for players\") {\n alert(\"We need two players to start a game.\")\n return;\n }\n // clears the board for a new game\n else {\n for (var i = 0; i < self.gameBoard.boxes.length; i++) {\n self.gameBoard.boxes[i].isX = false;\n self.gameBoard.boxes[i].isO = false;\n self.gameBoard.$save(self.gameBoard.boxes[i]);\n }\n\n //resets the game status for the new game\n self.gameBoard.gameStatus = \"Game in progress\";\n self.gameBoard.$save(self.gameBoard.gameStatus);\n }\n \n }", "function clearBoard() {\n $('[data-board-position]').attr('data-user-token', '0');\n computerMoves = 0;\n}", "function clearBoard() {\n\tdocument.getElementById('gridClear').play();\n\tfor(x = 0; x < 7; x++){\n\t\tfor(y = 0; y < 6; y++) {\n\t\t\tgrid[x][y] = null;\n\t\t\t$('#'+(x+1)+'_'+(y+1)).css('visibility', 'hidden');\n\t\t}\n\t}\n}", "function resetBoard() {\n var elem = document.getElementsByClassName('board')[0];\n while (elem.firstChild) {\n elem.removeChild(elem.firstChild);\n }\n startGame();\n}", "function reset(){\n document.getElementById('game-board').innerHTML = ''\n cardsInPlay = []\n createBoard()\n}", "function clearBoard() {\n for (i = 0; i < cells.length; i++) {\n cells[i].textContent = '';\n }\n messageBox.textContent = \"\";\n playersTurn = 0;\n gameOver = false;\n}", "function clearBoard() {\n \"use strict\";\n var endArea = document.getElementsByClassName('endgameText')[0];\n\n endArea.innerHTML = \"\";\n board.innerHTML = \"\";\n board.setAttribute('style', 'opacity: 1;');\n endState = false;\n drawBoard();\n return false;\n}", "function clearPiece() {\n for (var i=0; i<prevPieceArray.length; i++){\n for (j=0; j<prevPieceArray.length; j++) {\n if (prevPieceArray[i][j] != 0)\n gameBoard[prevYPosition+i][prevXPosition+j] = 0;\n\n }\n }\n ctx.clearRect(150, 20, 400, 500);\n drawGameArea();\n}", "reset () {\n this.chessGame.reset()\n this.syncBoard()\n }", "function reset(){\n\tdocument.getElementById('game-board').innerHTML = \" \"; //to clear the game board.\n\tcardsInPlay = []; //to clear the array content so the alert will be effective again once we reset the board.\n\tcreateBoard(); //to create a new game board :)\n}", "function resetBoard() {\r\n store.score = 0;\r\n store.head = {top: 0, left: 0};\r\n store.speed = 300;\r\n store.body = [];\r\n store.gameOver = false;\r\n store.currentDirection = 'down';\r\n store.bodyPartId = 0;\r\n \r\n // Empty the elements from the board\r\n while(board.firstChild) {\r\n document.querySelector('#board').removeChild(board.firstChild)\r\n }\r\n \r\n // Remove the elements from the container\r\n const playAgainElem = document.getElementById('play-again');\r\n const congratsElem = document.getElementById('congrats');\r\n playAgainElem.remove();\r\n if (congratsElem) congratsElem.remove();\r\n \r\n \r\n // Reset the score display\r\n document.querySelector('#score').innerHTML = `Score: <span>${store.score} </span>`;\r\n newGame();\r\n }", "function clearBoard() {\n clearInterval(timeIntervalId);\n $(\"#timer\").html(\"0d 0h 0m 0s\");\n card.removeClass('open show match fail bounce locked');\n cardIcon.removeClass();\n stars.removeClass('fa-star-o').addClass('fa-star');\n moveCount.html('0');\n moves = 0;\n wrongAnswer = 1;\n correctPairs = 0;\n placeCards(shuffle(cards));\n}", "clearBoard () {\n $('.mushroom-container').empty();\n }", "function clearBoard() {\n\tbgTileLayer.removeChildren();\n\tpieceLayer.removeChildren();\n\tfgTileLayer.removeChildren();\n}", "function resetBoard() {\n resetState()\n renderBoard()\n}", "function reset() {\n\t\tdrawSimpleBoard(board = new Board());\n}", "function clearBoard() {\n location.reload(false);\n}", "function clearBoard(){\r\n \tfor(var i=0; i< squares.length; i++){\r\n \t\tsquares[i].textContent= '';\r\n \t}\r\n }", "clear() {\n this._board = Array(this.height).fill(this.EMPTY.repeat(this.width));\n }", "function eraseBoard() {\n context.clearRect(0, 0, canvas.width, canvas.height);\n }", "function resetBoard() {\n $(\".zero\").empty();\n $(\".one\").empty();\n $(\".two\").empty();\n $(\".three\").empty();\n $(\".four\").empty();\n $(\".five\").empty();\n $(\".six\").empty();\n $(\".seven\").empty();\n $(\".eight\").empty();\n}", "function clearBoard(){\n\t\tclientService.emit(ServerMessagesConstant.CLEAR_BOARD);\n\t}", "function reset() {\n chessboard = new Set();\n for(i = 0; i < 9; i++) {\n chessboard.add(i);\n place(i, \"\");\n }\n playerO = new Set();\n playerX = new Set();\n lock = false;\n setState(\"YOUR TURN\");\n}", "clearMoves() {\n\t\tthis.baseboard = [[],[],[],[],[],[],[],[]];\n\t\tthis.moves = [];\n\t}", "function clearBoard() {\n\tfor (i = 0; i < blockArr.length; i++) {\n\t\tfor (j = 0; j < blockArr[i].length; j++) {\n\t\t\tfor (k = 0; k < blockArr[i][j].length; k++) {\n\t\t\t\tblockArr[i][j][k] = 0;\n\t\t\t}\n\t\t\tblockArr[i][j][5] = -5;\n\t\t\tmechArr[i][j] = 0;\n\t\t\talchArr[i][j] = 0;\n\t\t}\n\t}\n}", "function resetBoard(){\n allCells.forEach(cell => cell.textContent = \"\");\n gameStarted = false;\n startButton.disabled = false;\n playerTurn = false;\n}", "resetBoard() {\n this._gameBoard = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\",];\n this._gameOver = false;\n this._tiedGame = false;\n this.changePlayer(); //alternate between starting players \n }", "function resetBoard() {\n isOneTileFlipped = false;\n lockBoard = false;\n firstTile = null;\n secondTile = null;\n}", "function reset() {\n graphics.clearAll();\n for (var i = 0; i < grid.length; i++) {\n for (var j = 0; j < grid[i].length; j++) {\n $(\"#\" + grid[i][j]).parent().removeClass(\"red\");\n squares[grid[i][j]] = \"empty\";\n p2Move = false;\n }\n }\n timesPlayed = 0;\n $(\"#screen3\").children().hide();\n $(\"#screen1\").children().show();\n talker.notice(\"start up\");\n}", "function clearGame() {\r\n\tupdateScore(gScore = 0);\r\n\trenderCell(gGamerPos, '');\r\n\tgGamerPos = { i: 2, j: 9 };\r\n\tdocument.querySelector('.restart').classList.add('hide');\r\n\tinitGame();\r\n}", "function resetBoard() {\n for (var i = boxes.length - 1; i >= 0; i--) {\n boxes[i].innerHTML = '';\n boxes[i].setAttribute('class', 'clear');\n }\n OMoves = [];\n XMoves = [];\n winCounter = 0;\n counter = 1;\n turnText.innerHTML = 'Kick off the game, Player X';\n}", "function clearGame() {\n if (DEBUG) console.log('inside clearGame(), removing cards from board, clearing stacks, and disabling the Battle button...');\n $(opponentCardsDivId).children().remove();\n $(opponentBattlefieldDivId).children().remove();\n $(playerBattlefieldDivId).children().remove();\n $(playerCardsDivId).children().remove();\n\n playerStack.clear();\n opponentStack.clear();\n playerWarStack.clear();\n opponentWarStack.clear();\n\n // disable the Battle button since it is only applicable when a game is being played\n $(battleButtonId).attr(\"disabled\", \"disabled\");\n\n // clear any remaining timed operations\n window.clearTimeout(delayOperation);\n }", "function resetGame() {\r\n\t\r\n\t\tfor(var i=0; i<board.length; i++) {\r\n\t\t\tboard[i].innerHTML = \" \";\r\n\t\t\tboard[i].style.color = 'navy';\r\n\t\t\tboard[i].style.backgroundColor = 'transparent';\r\n\t\t}\r\n\t\tgameOver = false;\r\n\t\tempty = 9;\r\n\t\tsetMessage(player + \" gets to start.\");\r\n\t\tsetMessage2(\"Go!\");\r\n\t\tconsole.log(\"visited resetGame\");\r\n\t}", "function conway_clear() {\n for (let row = 0; row < board_size; row++) {\n for (let col = 0; col < board_size; col++) {\n grid[row][col] = 0;\n }\n }\n conway_draw();\n conway_dump();\n}", "function clearBoard() {\r\n for (var i = 1; i <= 9; i++)\r\n {\r\n document.getElementById(i).innerText = \"\";\r\n }\r\n document.symbol = null;\r\n document.player = null;\r\n document.winner = null;\r\n}", "function clearBoard() {\n allPieceLocations.forEach(function(x) {\n document.getElementById(x).classList.remove(\"avaliableMove\");\n document.getElementById(x).classList.remove(\"redKing\");\n document.getElementById(x).classList.remove(\"redPiece\");\n document.getElementById(x).classList.remove(\"blackKing\");\n document.getElementById(x).classList.remove(\"blackPiece\");\n })\n }", "function reset_board() {\n $.each(cells, function (i, v) {\n v.className = \"\";\n $(v).addClass(cell + \" \" + empty_cell);\n });\n final_message_str = \"\";\n $(message_element_id).html(\"Keep playing!!\");\n computer_first_move = true;\n computer_second_move = true;\n }", "function pressReset(){\r\n\tfor (var i = 0; i < boardArray.length; i++) {\r\n\t\tboardArray[i] = undefined;\r\n\t\tvar event_Id = \"box_\"+i;\r\n\t\tvar box_canvas = document.getElementById(event_Id);\r\n\t\tvar box_context = box_canvas.getContext(\"2d\");\r\n\t\tbox_context.clearRect(0, 0, box_canvas.width, box_canvas.height);\r\n\t}\r\n\tisTurnCirlce = true;\r\n\twinGame = false;\r\n}", "function resetRenderBoard() {\n\t\tlet boardPositions = document.getElementsByClassName(\"positions\");\n\t\tfor (let position of boardPositions) {\n\t\t\tposition.innerHTML = \"\";\n\t\t\tposition.classList.remove(\"played\");\n\t\t\tposition.classList.remove(\"winner-position\");\n\t\t}\n\t\tupdatePlayerInfo(); // updates the player info box\n\t}", "function resetBoard(full){\n\tif(full){\n\t\tdocument.getElementById('drawBody').innerHTML = '';\n\t\tfor(var i = 0; i < 100; i++){\n\t\t$(\"#\"+i+\"\").removeClass();\n\t\t}\n\t} else {\n\t\tfor(var i = 0; i < 100; i++){\n\t\t\tif (!$(\"#\"+i+\"\").hasClass(\"filled\") && $(\"#\"+i+\"\").hasClass(\"playable\")) {\n\t\t\t\t$(\"#\"+i+\"\").removeClass(\"playable\");\n\t\t\t}\n\t\t}\n\t}\n}", "reset() {\n this.grid = this.getEmptyBoard();\n }", "function resetButton() {\n\t\tvar newBoard = document.querySelector('div');\n\t\tnewBoard.innerHTML = \" \";\n\t\tcardsInPlay.length = 0;\n\t\tcreateBoard();\n\t\n}", "function clearPieceBoard() {\n for(var i = 0; i < 3; i++)\n for(var j = 0; j < 7; j++)\n drawPixelNext( j, i, boardColour);\n}", "function resetBoard() {\n\t\tfor (var i = $boxes.length -1; i>= 0; i--) {\n\t\t\tvar $box = $($boxes[i]);\n\t\t\t$box.attr('class', 'clear');\n\t\t}\n\t\tredMoves = [];\n\t\tyellowMoves = [];\n\t\twinCounter = 0;\n\t\tcounter = 0;\n\t\tconsole.log('resetBoard')\n\t\taddRedandYellowListeners()\n\t\t$turnText.html(\"It's Player 1 turn RED\")\n\t\tremoveRedandYellowListeners();\n\t\tstart();\n\t\n\t}", "reset() {\n this.grid = this.getEmptyBoard();\n }", "function clearBoard() {\n for(x = 0; x < 7; x += 1){\n for(y = 0; x <7; x += 1){\n checkerboard[x][y] === null;\n }\n }\n \n}", "function resetBoard() {\n\t\tboard = new Array(9);\n\t}", "function resetBoard() {\n\tgame.score = 0;\n\tgame.dot.exists = false;\n\tworms = new Array();\n\n\tfor (var i = 0; i < game.players; i++) {\n\t\tworms.push(new Object());\n\t\tworms[i].direction = \"none\";\n\t\tworms[i].previousCells = new Array();\n\t\tworms[i].length = 1;\n\t\tworms[i].movedThisTurn = false; \n\t\tworms[i].cachedMove = 'none';\n\t\tworms[i].maxSize = 100;\n\n\t\tgame.dots = new Array();\n\t\tgame.foodOut = false;\n\t\t\n\t\tworms[i].position = new Object();\n\t\tworms[i].position.x = 1 + Math.floor(Math.random()*(game.grid.width/game.grid.size - 2));\n\t\tworms[i].position.y = 1 + Math.floor(Math.random()*(game.grid.height/game.grid.size - 2));\n\t}\t\n}", "function clearBoard() {\n SOLVE = false;\n for (var i = 0; i < PUZZLE_LENGTH; ++i) {\n if (document.getElementById('cell' + i).disabled === false) {\n document.getElementById('cell' + i).value = '';\n }\n }\n }", "function clearBoard(event) {\n\t\tfor (i = 0; i < squares.length; i++) {\n\t\t\tsquares[i].className = \"col-sm-2 unUsedSquare\";\n\t\t\tsquares[i].style.backgroundColor= \"white\";\n\t\t\tsquares[i].innerHTML=\"\";\n\t\t}\n\t}", "function resetGame() {\n newSquares = Array(9).fill(null);\n setSquares(newSquares);\n setXTurn(true);\n }", "function clear_board() {\n // Select the colour to fill the drawing\n snakeboard_ctx.fillStyle = board_background;\n // Select the colour for the border of the canvas\n snakeboard_ctx.strokestyle = board_border;\n // Draw a \"filled\" rectangle to cover the entire canvas\n snakeboard_ctx.fillRect(0, 0, snakeboard.width, snakeboard.height);\n // Draw a \"border\" around the entire canvas\n snakeboard_ctx.strokeRect(0, 0, snakeboard.width, snakeboard.height);\n }", "function resetBoard() {\n\t\"use strict\";\n\t// Mark all cells as empty and give default background.\n\tfor (var i = 0; i < size; i++) {\n\t\tfor (var j = 0; j < size; j++) {\n\t\t\tvar cell = getCell(i, j);\n\t\t\tcell.style.backgroundColor = background;\n\t\t\tcell.occupied = false;\n\t\t\tcell.hasFood = false;\n\t\t}\n\t}\n\t// Reset snake head node.\n\tsnakeHead = null;\n\t// Reset curent direction.\n\tcurrDirection = right;\n\t// Reset direction lock.\n\tdirectionLock = false;\n\t// Reset difficulty level.\n\tmoveInterval = difficultyLevels[level];\n\t// Reset points and time.\n\tpoints = -10;\n\taddPoints();\n\ttime = 0;\n\t// Reset countdown label\n\t$(\"#countdown\").html(\"The force is strong with this one...\");\n}", "function clearBoard() {\n for (i=0; i<=maxX; i++) {\n for (j=0; j<=maxY; j++) {\n with (cellArray[arrayIndexOf(i,j)]) {\n isExposed = false;\n isBomb = false;\n isFlagged = false;\n isMarked = false;\n isQuestion = false;\n neighborBombs = 0; } } } }", "function clearGame() {\n disableButton();\n clearForms();\n removeBunny();\n}", "function clearBoard() {\r\n for (var i = 0;i< squares.length;i++) {\r\n squares[i].textContent = '';}\r\n }", "function resetGame(){\n //resets the boardArray\n boardArray = [['','',''], ['','',''], ['','','']];\n //resets the move counter\n moves = 0;\n \n var i = boardSquares.length;\n while(i--) {\n boardSquares[i].innerHTML = \"\"; //removes all the x's and o's from the game board\n boardSquares[i].classList.remove('win'); //removes the win class from any squares that may have it\n }\n gameState = \"running\"; //sets the game state to running so a new game may begin\n}", "function clearGame() {\n playerArrayOfChoicestoMatch = [];\n computerArrayOfChoicesToMatch = [];\n}", "function clearBoard() {\n // Select the colour to fill the drawing\n snakeBoardCTX.fillStyle = boardBackground;\n // Draw a \"filled\" rectangle to cover the entire canvas\n snakeBoardCTX.fillRect(0, 0, snakeBoard.width, snakeBoard.height);\n // Draw a \"border\" around the entire canvas\n snakeBoardCTX.strokeRect(0, 0, snakeBoard.width, snakeBoard.height);\n}", "function resetBoard()\n{\n\tfor(let i = 0; i < allChips.length; i++)\n\t{\n\t\tfor(let j = 0; j < 6; j++)\n\t\t{\n\t\t\tallChips[i][j] = 0;\n\t\t}\n\t}\n}", "function resetGame () {\n clearBoard();\n window.location.reload();\n}", "resetBoard() {\n this.board.resetBoard();\n }", "function clearBox2(){\n countPlayer1=0;\n countPlayer2=0;\n countTIE=0;\n $(\"#message\").text(\"\");\n gameOver=false;\n $(\"#box1\").text(\"\");//replace the text with empty string\n $(\"#box2\").text(\"\");\n $(\"#box3\").text(\"\");\n $(\"#box4\").text(\"\");\n $(\"#box5\").text(\"\");\n $(\"#box6\").text(\"\");\n $(\"#box7\").text(\"\");\n $(\"#box8\").text(\"\");\n $(\"#box9\").text(\"\");\n countGame=0;\n arr1=[[\"\",\"\",\"\"],[\"\",\"\",\"\"],[\"\",\"\",\"\"]];//the board will be empty\n XO=\"X\";\n $(\"#TIE\").text(\"TIE: \"+\" \"+(0));\n $(\"#player1\").text(\"player1: \"+(0));\n $(\"#player2\").text(\"player2: \"+(0));}", "function resetGame() {\n boardSquares.forEach((square)=> {\n square.reset();\n });\n}", "function resetBoard() {\r\n paper.classList.remove('active');\r\n paper.classList.remove('win');\r\n paperHouse.classList.remove('active');\r\n paperHouse.classList.remove('win');\r\n\r\n rock.classList.remove('active');\r\n rock.classList.remove('win');\r\n rockHouse.classList.remove('active');\r\n rockHouse.classList.remove('win');\r\n\r\n scissors.classList.remove('active');\r\n scissors.classList.remove('win');\r\n scissorsHouse.classList.remove('active');\r\n scissorsHouse.classList.remove('win');\r\n\r\n gameText.classList.remove('active');\r\n houseMoves.classList.remove('active');\r\n\r\n winMsg.classList.remove('active');\r\n drawMsg.classList.remove('active');\r\n loseMsg.classList.remove('active');\r\n replayBtn.classList.remove('active');\r\n\r\n document.querySelector('.game-wrapper').style.backgroundImage = \"url(images/bg-triangle.svg)\";\r\n allChoices.forEach(choice => {\r\n choice.style.animation = \"none\";\r\n })\r\n}", "function resetGame() {\n boardSquares.forEach((square)=> {\n square.reset()\n });\n}", "function clear_board() {\n // Select the colour to fill the drawing\n snakeboard_ctx.fillStyle = board_background;\n // Select the colour for the border of the canvas\n snakeboard_ctx.strokestyle = board_border;\n // Draw a \"filled\" rectangle to cover the entire canvas\n snakeboard_ctx.fillRect(0, 0, snakeboard.width, snakeboard.height);\n // Draw a \"border\" around the entire canvas\n snakeboard_ctx.strokeRect(0, 0, snakeboard.width, snakeboard.height);\n}", "function resetBoard() {\n for (row = 0; row < 6; row++) {\n for (col = 0; col < 7; col++) {\n board[row][col] = 0;\n count = 0;\n document.getElementById(\"cell\" + row + col).style.backgroundColor = \"#FFFFFF\";\n document.getElementById('winnerInfo').innerHTML = \"\";\n document.getElementById('board').classList.remove(\"avoid-clicks\");\n document.getElementById('colorTurn').innerHTML = \"\";\n }\n }\n\n}", "function resetBoard() {\n var checkerIndex = 0;\n currentColor = \"black\";\n document.getElementById(\"currentPlayer\").innerHTML = \"Current player: \" + currentColor;\n for(var i = checkerIndex; i < 48; i++) {\n checkerArray[i].style.display = \"none\";\n if(checkerArray[i].classList.contains(\"jumpAvailable\")) {\n checkerArray[i].classList.remove(\"jumpAvailable\");\n }\n }\n var boardString = \"b:bbbbbbbbbbbb--------rrrrrrrrrrrr\";\n setBoard(boardString);\n document.getElementById(\"boardInput\").value = boardString;\n document.getElementById(\"blackCBox\").checked = false;\n document.getElementById(\"redCBox\").checked = false;\n document.getElementById(\"forcedJump\").innerHTML = \"No forced jumps.\";\n document.getElementById(\"promptButton\").disabled = true;\n turnCounter = 1;\n while(document.getElementById(\"gameRecord\").rows.length > 1) {\n document.getElementById(\"gameRecord\").deleteRow(-1);\n }\n}", "function reset() {\n for (var x = 0; x < BOARD_SIZE; x++) {\n board[x][0] = new Piece(START_POSITION.charAt(x), WHITE);\n board[x][1] = new Piece(PAWN, WHITE);\n \n board[x][6] = new Piece(PAWN, BLACK);\n board[x][7] = new Piece(START_POSITION.charAt(x), BLACK);\n }\n }", "function clearBoard()\r\n{\r\n snake_board_x.fillStyle = board_background;\r\n snake_board_x.strokestyle = board_border;\r\n snake_board_x.fillRect(0,0,snake_board.width,snake_board.height);\r\n snake_board_x.strokeRect(0,0,snake_board.width,snake_board.height);\r\n}", "function resetGame() {\n // Clear the main boxes and the minimap boxes\n for(var rIndex = 0; rIndex < NUM_ROWS; rIndex++) {\n for(var cIndex = 0; cIndex < NUM_COLS; cIndex++) {\n // Clear main boxes\n boxes[rIndex][cIndex].classList.remove(xClass, oClass);\n boxes[rIndex][cIndex].textContent = \"\";\n // Clear minimap boxes\n miniboxes[rIndex][cIndex].classList.remove(xClass, oClass);\n miniboxes[rIndex][cIndex].textContent = \"\";\n }\n }\n\n // Hide end game text\n $(victoryText).hide();\n\n // Reset number of filled boxes\n boxCount = 0;\n\n // Start the game again\n gameOver = false;\n }", "function resetGame() {\n\t// Repopulate card deck\n\tcardDeck = masterDeck.map(function(card) { return card }); \n\t// Empty all containers of their elements\n\t$('#game-board').html('')\n\t$('#p1-hand').html(''); \n\t$('#p2-hand').html('');\n\t$('#p1-points').html('');\n\t$('#p2-points').html('');\n\t$('#turn-count').html('');\n\t// Reset board array\n\tgameBoard = [0, 1, 2, 3, 4, 5, 6, 7, 8]; \n\t// Reset turn count\n\tturnCount = 0;\n\t// Reset points\n\tplayer1.points = 5; \n\tplayer2.points = 5;\n}", "function resetGame() {\n gBoard = buildBoard();\n gGame.shownCount = 0;\n gGame.isOn = false;\n gLivesCount = 3;\n}", "function boardReset() {\n turn.innerHTML = \"X's turn\";\n move = 0;\n won = false;\n tiles.forEach(tile => {\n tile.innerHTML = \"\";\n })\n}", "function clearBoard(){\r\n for(var i=0;i<squares.length;i++)\r\n squares[i].textContent = '';\r\n}", "function clearBoard(){\n\tfor(var i = 0; i < theBoxes.length; i++) {\n\t\ttheBoxes[i].innerHTML =\"\";\n\t\ttheBoxes[i].style.backgroundColor = \"white\";\n\t}\n\tif (clearButton.innerText === \"Play Again\"){\n\t\tclearButton.innerText = \"Clear\";\n\t} \n\n}", "function clearBoard(){\n\n\tfor( var i =0;i<squares.length;i++){\n\t\tsquares[i].textContent=\"\";\n\t}\n\n}", "function restartGame() {\n //clear all playing pieces\n gameboard = [[null, null, null], [null, null, null], [null, null, null]];\n console.log('[restartGame] resetting gameboard');\n //clear up images\n for(let box of boxes) {\n box.innerHTML = '';\n }\n turn = 1;\n gameover = false;\n}", "function clearAll(){\n\n\t//clear all 9 boxes\n\tdocument.getElementById(\"r1c1\").innerHTML=\"\";\n\tdocument.getElementById(\"r1c2\").innerHTML=\"\";\n\tdocument.getElementById(\"r1c3\").innerHTML=\"\";\n\tdocument.getElementById(\"r2c1\").innerHTML=\"\";\n\tdocument.getElementById(\"r2c2\").innerHTML=\"\";\n\tdocument.getElementById(\"r2c3\").innerHTML=\"\";\n\tdocument.getElementById(\"r3c1\").innerHTML=\"\";\n\tdocument.getElementById(\"r3c2\").innerHTML=\"\";\n\tdocument.getElementById(\"r3c3\").innerHTML=\"\";\n\n\t//reseet gameOver so players can play again\n\tgameOver = false;\n}", "function resetGame() {\n cardShuffle();\n resetBoard();\n cardsInPlay = [];\n cardInPlayId = -1;\n}", "function resetGame() {\n console.log(\"resetGame was called\");\n \n playerCount = 0;\n\n for (i=0; i<globalBoard.length; i++)\n for (j=0; j<globalBoard.length; j++)\n globalBoard[i][j] = null;\n\n return globalBoard;\n}", "function resetBoard() {\n\t// re-initialize board\n\tinitialize();\n\n\t// set/reset player turn\n\tplayerIndicator.className = 'player1';\n\tplayerIndicator.innerText = gs.getPlayerName(1);\n\tgs.setP1Turn();\n}", "function clearBoard(){\r\n for (var i = 0; i < squares.length; i++) {\r\n squares[i].textContent = '';\r\n }\r\n}", "function resetBoard() {\n\t//return board to starting position\n\tboard = [\"r\",\"r\",\"_\",\"b\", \"b\"];\n\t//reset completion status\n\tstatus = false;\n\t//reset empty space\n\temptySpace = 2;\n\t//reset move counter\n\tmoveCounter = 0;\n\t\n\t//change box colours back to starting positions\n\tvar button0 = document.getElementById('piece0');\n\tbutton0.style.background = \"rgb(193,28,28)\";\n\tbutton0.style.border = \"1px solid black\";\n\n\tvar button1 = document.getElementById('piece1');\n\tbutton1.style.background = \"rgb(193,28,28)\";\n\tbutton1.style.border = \"1px solid black\";\n\n\tvar button2 = document.getElementById('piece2');\n\tbutton2.style.background = \"white\";\n\tbutton2.style.border = \"none\";\n\n\tvar button3 = document.getElementById('piece3');\n\tbutton3.style.background = \"black\";\n\tbutton3.style.border = \"1px solid black\";\n\n\tvar button4 = document.getElementById('piece4');\n\tbutton4.style.background = \"black\";\n\tbutton4.style.border = \"1px solid black\";\n\n\t//reset move counter\n\tdocument.getElementById('yourMoves').innerHTML=String(moveCounter);\n\t//change text of start button\n\tdocument.getElementById('textButton').innerHTML='Restart Game';\n\thideResult();\n\t\n}", "function resetBoard() {\n [app.hasFlippedCard, app.lockBoard] = [false, false];\n [app.firstCard, app.secondCard] = [null, null];\n}" ]
[ "0.8653472", "0.85424453", "0.82889265", "0.82236856", "0.8210962", "0.81993014", "0.81949574", "0.817742", "0.8169628", "0.81675285", "0.81483865", "0.8135175", "0.81025004", "0.80984175", "0.8025854", "0.8010913", "0.79907864", "0.79464453", "0.7941973", "0.79218495", "0.7909035", "0.7873203", "0.7860456", "0.78594965", "0.78429055", "0.7836572", "0.78037494", "0.77896684", "0.7782644", "0.77498883", "0.7747711", "0.77417576", "0.7738957", "0.7737563", "0.7733739", "0.7726458", "0.77202106", "0.769726", "0.7694802", "0.7686836", "0.76784647", "0.7646706", "0.76407385", "0.7627057", "0.7623544", "0.7601913", "0.7594045", "0.75862616", "0.7583148", "0.7576929", "0.7565805", "0.7553986", "0.75520027", "0.75470406", "0.75434196", "0.754026", "0.7539048", "0.7533667", "0.7532648", "0.75235397", "0.7519837", "0.7504289", "0.7503767", "0.7499561", "0.7498257", "0.7495736", "0.7490717", "0.74862057", "0.7480632", "0.7478487", "0.7469954", "0.74666625", "0.74629027", "0.74610966", "0.74602306", "0.7459236", "0.7441605", "0.7441043", "0.7433422", "0.7425054", "0.74190944", "0.7418431", "0.74174136", "0.7408036", "0.7407672", "0.7406994", "0.73992765", "0.7386435", "0.7380149", "0.7374154", "0.7372559", "0.7368175", "0.73631847", "0.73504734", "0.7348027", "0.73479325", "0.73443013", "0.733408", "0.73337686", "0.73305523", "0.7318326" ]
0.0
-1
This function ends the game
function gameOver() { // Disables any further moves and stops the timer noSelect = true; clearTimeout(timer); // Display a win or loss message if (lives === 0 || timeLeft === 0) { id("lives").textContent = "Uh oh! You lost! Want to try again?"; } else { id("lives").textContent = "Woohoo! You won! Want to try again?"; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function end() {\n game.end();\n console.log('End!!, thank you for playing');\n }", "function endGame() {\n \n}", "function handleEndGame() {\n\n}", "function endGame() {\r\n\t\tgameOver = true;\r\n\t\tsetMessage2(\"Game Over\");\r\n\t}", "function endgame() {\n \tclearInterval(intervalId);\n }", "function endGame() {\r\n\r\n\t\tclearInterval(timer);\r\n\t\tclearInterval(target);\r\n\t\tclearInterval(cursor);\r\n\t\tclearTimeout(warnTimeout);\r\n\t\twarning.finish();\r\n\r\n\t\tscoreBox.text(\"Targets Destroyed: \" + targetCount);\r\n\r\n\t\t$('.target').remove();\r\n\r\n\t\t$('body').css(\"cursor\", \"crosshair\");\r\n\r\n\t\t$(\"#timer\").stop().animate({\r\n\t\t\t\t\"width\": \"0px\"\r\n\t\t}, 0);\r\n\r\n\t\t$(\"#message\").css({\"display\": \"block\"})\r\n\r\n\t\t$(\"#text\").text(\"Game Over\").css({\r\n\t\t\t\"display\": \"block\",\r\n\t\t\t\"font-size\": \"100px\",\r\n\t\t\t\"margin-top\": \"3.5em\",\r\n\t\t\t\"width\": \"100%\"\r\n\t\t});\r\n\r\n\t\t$(\"span\").text(\"Retry\");\r\n\t}", "function endSala() {\r\n\tgame.endSala();\r\n}", "function endGame() {\n gameStarted = false;\n}", "function endGame() {\n //Update UI\n const winner = document.getElementById(`player${logic.getActivePlayer()}-name`);\n winner.innerText = 'WINNER';\n logic.getActivePlayer() === 1 ? score0++ : score1++;\n displayScores();\n gameFieldsEl.forEach(el => el.style.cursor = 'default');\n //Remove game board event listener\n gameBoardEl.removeEventListener('click', makeMove);\n }", "endGame(){\n score.addToScore(this.result, 'somejsontoken');\n this.scene.pause();\n const sceneEnd = this.scene.get('end');\n sceneEnd.scene.start();\n //this.scene.add(\"end\", new End(this.result));\n }", "function endOfGame() {\n\tcreatesMensg();\n\tstopTime();\n\tshowModal();\n}", "function endGame() {\n resetMainContainer();\n loadTemplate(\"result\", displayResults);\n}", "function endGame(win) {\n that.pause();\n running = false;\n if(win) {\n console.log(\"BOUT 2 ALERT\")\n alert(\"You've reached the highest score!\");\n console.log(\"DONE ALERTING\")\n } else {\n $(\"#ship\").height(0);\n drawBoard();\n alert(\"Looks like you got squashed. Game over!\");\n }\n submitTurk();\n }", "end() {\n this.isOver = true;\n this.isRunning = false;\n\n if (typeof this.onGameOver === 'function') {\n this.onGameOver();\n }\n }", "function endGame() {\n // Réinitialisation de l'affichage du dé\n resetImage(); \n // Position du sélecteur\n selector();\n //Lancement nouvelle partie\n newGame();\n}", "endGame() {\n setTimeout(function () {\n collectedItemsFin.innerHTML = player.collected;\n collectedFliesFin.innerHTML = player.collectedFly;\n collectedDragonfliesFin.innerHTML = player.collectedDragonfly;\n collectedButterfliesFin.innerHTML = player.collectedButterfly;\n scoreboardFin.innerHTML = player.score;\n scoreboardWaterFin.textContent = player.scoreWater;\n player.modalShow(gameoverModal, replayBtn);\n player.reset();\n start();\n }, 500);\n }", "function endGame() {\n //exit to the main menu w/o saving\n gameStart = false; //set flag to false\n TimeMe.resetAllRecordedPageTimes(); //reset timer\n clearInterval(handle); //clear score, time, intervals\n clearInterval(spawn);\n clearInterval(addp);\n clearInterval(addb);\n\n handle = 0;\n spawn = 0;\n addp = 0;\n addb = 0;\n score = 0;\n powerUpScore = 0;\n time = 0;\n $(\"#gameOver\").hide(); //hide game over menu and show main menu\n menu();\n }", "function endGame(){\n\t//plays the end game audio\n\twindow.window.deathsound.play();\n\t//sets timeout of 2.5 seconds so the game doesnt reset straight away\n\tsetTimeout((function(){\n\t\twindow.reset();//resets game variables\n\t\tconsole.log(\"Resetting the game\");\n\t\tlocalPlayer.resetHealth();\t//resets players health\n\t\t//makes all players alive\n\t\tfor(var i = 0; i < remotePlayers.length; i++){\n\t\t\tremotePlayers[i].setDead(false);\n\t\t};\t\n\t\t//calls to update user information until death of the player\n\t\tupdateUserLocation();\n\n\t}),2500);\n}", "function endGame() {\n\n\tclearInterval(interval);\n\tinterval = null;\n\ttime = null;\n}", "function endGame(data) {\n var gameID = data.gameID;\n\n gameloop.clearGameLoop(games[gameID].gameloopID);\n}", "function endGame() {\n\n partidas++;\n tiempoJugadores();\n\n //Si se termina la segunda ronda va al estado ranking\n if (partidas == 2)\n game.state.start('ranking', true, false, tj1, tj2);\n\n //Si termina la primera ronda, va al estado win\n else\n game.state.start('win', true, false);\n\n}", "function endGame() {\n // Overlay\n // Show score\n // Show table \n // Give user chance to restart\n // TODO: add high score to renderGUI\n\n uploadScore(score);\n score = 0;\n}", "function endGame(){\n gameOver = true;\n gameStarted = false;\n allEnemies = [];\n allFruit = [];\n pickedFruit = [];\n //displayResult();\n resultMessage();\n updateInfo();\n}", "function endGame() {\n $('.home').css({ 'margin-top': '0px' });\n disappear('.instructions');\n hide('.view-button');\n disappear('.follow-circle');\n disappear('.instructions');\n state = \"view\";\n }", "function endGame(){\n // Make the correct scenes visible\n titleScene.visible = false;\n gameScene.visible = false;\n gameOverScene.visible = true;\n // Set the background\n renderer.backgroundColor = GAME_OVER_BACKGROUND_COLOR;\n // Use white audio icons\n audioHelper.whiteIcons();\n // Add the game over message to the end scene\n gameOverMessage = new PIXI.Text(\n \"GAME OVER!\",\n {fontFamily: GAME_FONT, fontSize: 60, fill: 0xEA212E}\n );\n gameOverMessage.position.set(GAME_WIDTH/2-gameOverMessage.width/2, GAME_HEIGHT/2-gameOverMessage.height);\n gameOverScene.addChild(gameOverMessage);\n // Create a score ScoreSubmitter\n scoreSubmitter = new ScoreSubmitter();\n // Bind the end-game keys\n bindEndKeys();\n // Stop the timer and set to end\n gameTimer.stop();\n gameTimer.whiteText();\n scoreKeeper.whiteText();\n gameState = end;\n}", "function endGame() {\n\ttoggle(\"gameContainer\");\n\t\n\tdatabase.ref('players/' + player).set({score : playerScore, isDone : true});\n\tendInterval = setInterval(\"getResults()\", 250);\n\t\n\ttoggle(\"outcome\");\n}", "endGameAction() {\n\n }", "function quitGame() {\r\n //add exit logic\r\n \texitGame();\r\n}", "function gameEnd(){\n\n game.startBanner = game.add.image(phaser.config.width / 2, phaser.config.height / 2, \"start-banner\")\n \n //If your score is higher than the opponent score, you win, else, you lose.\n if(score > oppScore){\n game.youWin = game.add.image(phaser.config.width / 2, phaser.config.height / 2, \"you-win\")\n }else{\n game.youLose = game.add.image(phaser.config.width / 2, phaser.config.height / 2, \"you-lose\")\n }\n\n game.scene.pause(); //Pause the scene\n\n setTimeout(function(){ //Set timeout then return to menu\n game.scene.start('menu')\n score = 0; //Set score back to 0\n Client.socket.emit('gameEnd');\n },5000)\n }", "function endGameChecker() {\n\tif (endGame) {\n\t\tremoveEvent();\n\t}\n}", "function endGame(){\n\tspawnBall();\n\tcenterBall();\n\tspawnPlayerOne();\n\tspawnPlayerTwo();\n\tupdateScore();\n\t$('#menuCanvas').show();\n}", "function endOfGame() {\n clearInterval(gameInterval)\n}", "function endGame() {\n p.onSetAppState(state => ({ newGame: false, game: { ...state.game, playedGames: 0 } }));\n p.startGame = false;\n clearTimeout(p.timeOut1);\n clearTimeout(p.timeOut2);\n }", "end () {\n this.game.newTurn()\n }", "function endGame() {\n dingSFX.play();\n speak(lineEndGame);\n boxWrite(boxTextEndGame);\n gameState = 20;\n}", "function endGame()\n{\n\tfor(var i = 0; i < 16; i++)\n\t{\n\t\tapp.coverImgArr[i].style.visibility = 'hidden';\n\t\t//app.tileImgArr[i].style.visibility = 'hidden';\n\t}\n\n\tapp.pairsFound = 0;\n\n\tapp.startBtn.disabled = false;\n\tapp.endBtn.disabled = true;\n\n\tremoveTiles();\n\t\n\tinitVars();\n}", "function endGame() {\n clearInterval(scorePanel.intervalManager);\n showCongratulationModal();\n}", "function endGame(){ \n\tconsole.log(\"You Crashed!!!\") \n}", "function endGame() {\n // Update the max level achieved board\n if (level > maxLevelAchieved) {\n maxLevelAchieved = level;\n $(\".max-level\").text(maxLevelAchieved);\n }\n\n // Make game over sound\n let sound = new Audio(\"sounds/wrong.mp3\");\n sound.play();\n\n // Add visual aspects of game over\n $(\"body\").addClass(\"game-over\");\n setTimeout(function() {\n $(\"body\").removeClass(\"game-over\");\n }, 100);\n $(\"h1\").text(\"Game Over! Press Any Key to Replay\");\n\n // Reinitializing letiables for a new round\n level = 0;\n newGame = true;\n}", "function endGame() {\n console.log(\"BOOM\");\n console.log(\"GAME OVER\");\n renderAllCells(\"bomb-cell\");\n renderAllCells(\"isRevealed\");\n toggleBombPanel(\"hide\");\n}", "function endGame(){\n $('.card-container').removeClass(\"selected-card\");\n $('.card-container').remove();\n while(model.getCardObjArr().length > 0){\n model.removeFromCardObjArr(0);\n }\n\n while(model.getDisplayedCardArr().length > 0){\n model.removeFromDisplayedCardArr(0)\n }\n\n while(model.getSelectedCardObjArr().length > 0){\n model.removeFromSelectedCardArr(0)\n }\n if(($(\".card-display-container\").find(\".game-over-page\").length) === 0){\n createGameOverPage();\n createWinnerPage();\n } else {\n return;\n }\n }", "function endGame() {\n verifyLine();\n verifyColumn();\n // verifyDiagonalUp();\n // verifyDiagonalDown();\n }", "function endGame() {\r\n clearInterval(game_timer);\r\n timer_start = false;\r\n\r\n modal_element.css('display', 'block');\r\n\r\n performance_raiting.text(rating_string + rating);\r\n time_taken.text(\r\n time_string + \r\n $('.minutes').text() +\r\n $('.colon_two').text() +\r\n $('.seconds').text());\r\n moves_taken.text(moved_string + counter);\r\n }", "function gameEnd(){\n\tplayer.start = false;\n}", "function endGame() {\n\t\tgameOver = true;\n\t\t$('#gameBorder').hide();\n\t\t$('#stats').show();\n\t\twindow.clearInterval(timerFun);\n\t\tvar finishTime = (GAME_DURATION * 1000) / 60000;\n\t\tconsole.log(finishTime);\n \tvar wpm = Math.round(wordCount / finishTime);\n \t$('#totalWords').html(\"Total Words: \" + wordCount);\n \t$('#wpm').html(\"WPM: \" + wpm);\n \t$('#mistakes').html(\"Total Errors: \" + mistakeCount);\n \t$('#playAgain').on('click', function() {\n \t\tgame();\t\n \t});\n \treturn;\n\t}", "function endGame()\r\n{\r\n\tisGameOver=true;\r\n\t\r\n\taudio.stop({channel : 'custom'});\r\n\taudio.stop({channel : 'secondary'});\r\n\taudio.stop({channel : 'tertiary'});\r\n\t\r\n\t//Clear the screen\r\n\tcontext2D.fillStyle=\"rgb(255, 255, 255)\";\r\n\tcontext2D.beginPath();\r\n\tcontext2D.rect(0, 0, canvas.width, canvas.height);\r\n\tcontext2D.closePath();\r\n\tcontext2D.fill();\r\n\t\r\n\tplaySound('Other_Sounds/game_over', 'default', 1, false, none);\r\n\tspeak('You have fallen into a trap and died. Game over, Your final score is: '+score, 'default', false);\r\n}", "function gameEnd() {\n cancelAnimationFrame(frame);\n canvas.style.cursor = 'crosshair'; // #crosshair\n finalScore.textContent = 'Score: ' + score;\n modal.style.display = \"block\";\n closeSpan.onclick = function () {\n modal.style.display = \"none\";\n }\n retry.onclick = function () {\n location.reload();\n }\n}", "function endGame(msg) {\n\t// TODO: pop up alert message\n\talert(msg);\n\tgameLive = false;\n}", "function endgame() {\r\n gameOver = true;\r\n\tmusic.playGameOver();\r\n}", "function gameEnd() {\n clearTimeout(timeoutID)\n clearTimeout(autoTimeOutID)\n removeEventListener('keydown', keydown_fn)\n endScreen()\n end = true\n}", "function end_game_flow () {\n\t// console.log(\"end...\");\n\t// block all the event to gems\n\tthis.backgroundView.updateOpts({\n\t\tblockEvents: true\n\t});\n\t// disable scoreboard\n\tthis._scoreboard.updateOpts({\n\t\tvisible: false\n\t});\n\t// show end screen\n\tthis._endheader.updateOpts({\n\t\tvisible: true,\n\t\tcanHandleEvents: true\n\t});\n\tanimate(this._endheader).wait(800).then({y: 0}, 100, animate.easeIn).then({y: 35}, 1000, animate.easeIn);\n\n\t// show score\n\tvar scoreText = new TextView({\n\t\tsuperview: this._endheader,\n\t\tx: 0,\n\t\ty: 35, // endscreen animate end point\n\t\twidth: 350,\n\t\theight: 233,\n\t\tautoSize: true,\n\t\ttext: \"You achieved \" + score.toString(),\n\t\tsize: 38,\n\t\tverticalAlign: 'middle',\n\t\thorizontalAlign: 'center',\n\t\tcanHandleEvents: false\n\t});\n\t// //slight delay before allowing a tap reset\n\tsetTimeout(emit_endgame_event.bind(this), 2000);\n\tconsole.log('end game flow.. \\n');\n}", "function endGame() {\n isPlayingGame = false;\n timeElapsedMs = 0;\n id(\"start-button\").innerHTML = \"Play again\";\n if (!isPlayingGame && !id(\"lose-message\")) {\n showLose();\n }\n clearInterval(interval);\n }", "function endGame() {\n\tif(matchedCards.length === 16){\n\t\ttimer.stop();\n\t\tdisplayPopup();\n\t}\n}", "function finishGame(isVictory) {\n if (isVictory) {\n highestScore(gLevel.type, gGame.secsPassed);\n renderSmiley(true);\n winningAudio.play();\n // alert('You Win!');\n openModal('You Won!');\n gGame.isOn = false;\n } else {\n gGame.isOn = false;\n losingAudio.play();\n openModal('You Lost :(');\n revealMines();\n }\n clearInterval(gTimerInterval);\n}", "function endGame (msg) {\n // DONE TODO: pop up alert message\n alert (msg);\n console.log ('game over');\n}", "function endGame() {\r\n newGameCounter = 0;\r\n gameStarted = false;\r\n players = players.concat(audience);\r\n audience = [];\r\n io.emit('update users', players, audience)\r\n io.emit('end game on client');\r\n\r\n }", "function end() {\n gameScene.visible = false;\n gameOverScene.visible = true;\n}", "function end() {\n gameScene.visible = false;\n gameOverScene.visible = true;\n}", "function endGame() {\n console.log(\"game ended\");\n\n // clear timer and result\n $(\"#timer\").empty();\n $(\"#result\").empty();\n\n // show final scores\n $(\"#result\").append(\"<h2>GAME OVER! <h2>\");\n $(\"#result\").append(\"Number correct: \" + numAnsRight);\n $(\"#result\").append(\"<BR>Number wrong: \" + numAnsWrong);\n $(\"#result\").append(\"<BR> Number timed out: \" + numTimedOut);\n\n // show button to restart game\n $(\"#restart-btn\").show();\n }", "endGame(){\n this.state = END;\n }", "function endGame()\n{\n stopTimer();\n $('#timer').text(\"\");\n $('#timer').css('width','0%');\n backgroundMusic.pause();\n disableUnflipped();\n gameOverPopup();\n return;\n}", "function endGame(endReason) {\n game_on = false;\n clearIntervals();\n stopGameMusic();\n\n if (endReason !== undefined)\n endReason();\n // addMessageToGameOverWindow(endReason);\n // // shows the game over window\n // document.getElementById('game_over_div').style.display = \"block\";\n}", "function GameEnd(){\n\t\t\tif(poker._cash == 0 && poker._bet == 0)\n\t\t\t\talert(\"Thanks for playing better luck next time.\\nRefresh the browser to start a new game.\");\n\t}", "function endGame() {\n\tclearInterval(gameTimer);\n\tshowEndScreen();\n\n\tsetInterval(function() {\n\t\tfor (let i = 0; i < 3; i++) {\n\t\t\tsetTimeout(victoryAnimation, 1000);\n\t\t}\n\t}, 500);\n}", "function endGame() {\n fill(start.color.c,start.color.saturation, start.color.brightness);\n stroke(start.color.c,start.color.saturation,start.color.brightness);\n if(score.score1 == score.limit) {\n start.color.c+=2;\n textSize(70);\n background(colours.background);\n text(\"Player 1 Wins!\", start.textX, start.textY);\n movementMoveX = 0;\n movementMoveY = 0;\n }\n if(score.score2 == score.limit) {\n start.color.c+=2;\n textSize(70);\n background(colours.background);\n text(\"Player 2 Wins\", start.textX, start.textY);\n movementMoveX = 0;\n movementMoveY = 0;\n }\n if(start.color.c > 360) start.color.c = 0\n }", "function endGame() {\n // console.log('game finished!');\n let $messageBox = $('#message');\n let $dealButton = $('#deal-button');\n let $hitButton = $('#hit-button');\n let $standButton = $('#stand-button');\n let $dealerFirstCard = $('#dealer-hand div:nth-child(1)')\n\n $dealerFirstCard.removeClass('flyin');\n $dealerFirstCard.addClass('loop');\n setTimeout(function() {\n $('#dealer-box').removeClass('hidden');\n $dealerFirstCard.css('background-image', `url(${dealer.hand[0].img}`);\n }, 500);\n\n $hitButton.off('click');\n $hitButton.addClass('subdued');\n\n $standButton.off('click');\n $standButton.addClass('subdued');\n\n $('#player-bet p').html('$0');\n localStorage.setItem('playerMoney', player.money);\n\n $dealButton.removeClass('subdued');\n $dealButton.text('DEAL');\n $dealButton.one('click', resetGame);\n}", "function endGame()\n {\n // Displays the game over message, number of questions answered correctly, and number of questions answered incorrectly in the console for debugging purposes\n console.log(\"Game over!\")\n console.log(\"Correct Answers: \" + correctCount);\n console.log(\"Wrong Answers: \" + wrongCount);\n\n // Updates the DOM with the game over message, number of questions answered correctly, and number of questions answered incorrectly\n $(\"#timer-label\").hide();\n $(\"#timer\").text(\"Game over!\");\n $(\"#question2\").text(\"Wrong Answers: \" + wrongCount);\n $(\"#question\").text(\"Correct Answers: \" + correctCount);\n $(\"#question2\").show();\n $(\"#question2\").text(\"Wrong Answers: \" + wrongCount);\n $(\"#answers-div\").hide();\n\n // Updates the DOM with play again button so the player can start the game again\n $(\"#play-again-button\").show();\n\n }", "function endGame() {\n\tif (board.turn >= 5 && board.hasEnded() === \"x\") {\n \talert(\"x won!\");\n \treset();\n } else if (board.turn >= 6 && board.hasEnded() === \"o\") {\n \talert(\"o won!\");\n \treset();\n } else if (board.turn === 9) {\n alert(\"Draw!\");\n reset();\n }\n}", "function gameEnd() {\n\tmoves += 1;\n\tstopTimer();\n\toverLay.show();\n\tmodal.show();\n\t$('.score-panel').hide();\n\t$('.final-moves').html(moves);\n}", "endGame() {\n this.inProgress = false;\n this.currentPlayer = null;\n this.pendingChip = null;\n this.emit('game:end');\n this.type = null;\n if (this.debug) {\n this.columnHistory.length = 0;\n }\n }", "function endGame() {\n let coinsEarned = yagooCoinValue * hitCount\n clearTimer()\n\n if (spawnTimeouts.length > 0) {\n for (let t = 0; t < spawnTimeouts.length; t++) {\n clearTimeout(spawnTimeouts[t])\n }\n spawnTimeouts = []\n }\n\n if (remainingSpawns <= 0 || remainingTime <= 0) {\n document.getElementById('postgame-header').innerHTML = 'GAME END'\n document.getElementById('resume-btn').style.visibility = 'hidden'\n document.getElementById('coin-count').innerHTML = `HoloCoins earned: ${coinsEarned}`\n addHoloCoin(coinsEarned)\n } else {\n document.getElementById('postgame-header').innerHTML = 'GAME PAUSED'\n document.getElementById('resume-btn').style.visibility = 'visible'\n document.getElementById('coin-count').innerHTML = ''\n }\n\n document.getElementById('hit-count').innerHTML = `${hitCount} / ${maxSpawns}`\n togglePanel(panel.POSTGAME)\n}", "function endGame(msg) {\n // TODO: pop up alert message\n alert(msg)\n}", "function quitFunction(){\r\n\tgame.destroy();\r\n}", "endGame() {\r\n setTimeout(function () {\r\n alert(currentEnnemy.name + ' a gagné. Cliquez sur OK pour relancer la partie'),\r\n window.location.reload()\r\n }, 200)\r\n }", "function endGame() {\n // Close down game screen, also set hearts back and open endgame\n $('#gameScreen').addClass('hidden');\n $('#heart1').removeClass('removed');\n $('#heart2').removeClass('removed');\n $('#heart3').removeClass('removed');\n $('#endGameText').text(\"Your score was: \" + $('#playerScore').text());\n $('#end-page').removeClass('hidden');\n obstacleSpeed = 0.5;\n spawnRate = 500;\n playerAlive = false;\n playerScore = 0;\n customFlag = 0;\n flag = 1;\n playerScore = 0;\n customFlag = 0;\n seconds = 0; minutes = 0; hours = 0;\n}", "function endGame() {\n location.reload();\n}", "function endGame(){\n if(trivia[currentQAndA] === (trivia.length)){\n stop();\n \n $(\".quiz\").html(\"<h1>\" + 'Done!' + \"</h1>\")\n }\n else{\n loading();\n }\n }", "function endGame () {\n\t\t$(\"#timer\").empty();\n\t\t$(\"#game\").html(\"<h2>Game Over! Next stop the Musicians Hall of Fame.</h2>\")\n\t\t$(\"#game\").append(\"<p>Correct answers: \" + correct + \"</p>\");\n\t\t$(\"#game\").append(\"<p>Incorrect answers: \" + incorrect + \"</p>\");\n\t\t$(\"#game\").append(\"<p>A bad guess is better than no guess. Unanswered: \" + unanswered + \"</p>\");\n\t\t$(\"#restart\").css(\"visibility\", \"visible\");\n\t}", "function endGame(score) { // import score from game\n // bug/feature when player clicks end game from game window; gameover doesn't get the score\n // EITHER REMOVE THE QUIT GAME BUTTON FROM GAME WINDOW OR MAKE IT AN ACTUAL FEATURE\n removeScreen();\n createGameOver(gameOverStr, score);\n //console.log(`I got the score: -- ${score} pts -- from game obj, hopefully`)\n // display hiscores at some point in life\n}", "function endGame(event){\n\tif (game_state === false){\n\t\tstate = true;\n\t\tvar lose = document.getElementById(\"status\");\n\t\tlose.innerHTML = \"you're a loser :0\";\n\t\tvar wall = document.querySelectorAll(\"div#maze div.boundary\");\n\t\tfor (var i = 0; i<wall.length;i++){\n\t\t\twall[i].classList.add(\"youlose\");\n\t\t}\n\t\tclearInterval(stopclock);\n\t\tstopclock = null;\n\t\ttotaltime = 0;\n\t\t//alive = 1;\n\t}\n}", "endTurn() {\n if (this.board.checkWin(this.players[this.turn].token)) {\n console.log(`${this.players[this.turn].name} has won, starting a new game`);\n this.board.resetBoard();\n this.board.printBoard();\n this.turn = (this.turn + 1) % 2;\n } else {\n this.turn = (this.turn + 1) % 2;\n console.log(`It is now ${this.players[this.turn].name}s turn`);\n this.board.printBoard();\n }\n }", "function end(){\n Manager.clearGame();\n changeState(gameConfig.GAME_STATE_START_SCENE);\n}", "function endGame(state){\n\t//render the board visible\n\trenderState(1,state,[]);\n\t//close the loading popup\n\thideLoader();\n\t//show the dialog popup\n\t$('#popupDialog').jqmShow();\n\t//call the interaction function, passing in the state.\n\tendGameInteraction(state);\n}", "function endGame(msg) {\n // TODO: pop up alert message\n alert(msg);\n}", "function endGame(msg) {\n // TODO: pop up alert message\n alert(msg);\n}", "function endGame(msg) {\n // TODO: pop up alert message\n alert(msg);\n}", "function endGame(msg) {\n // TODO: pop up alert message\n alert(msg);\n}", "function endGame() {\n if (typeof runningTimer != 'undefined') {\n clearInterval(runningTimer);\n }\n endStars.html(stars.html());\n endMoves.html(moves);\n endMinutes.html(parseInt(seconds/60,10));\n endSeconds.html(seconds%60);\n winningModal.css('display', 'block');\n}", "function endGame() {\r\n clearInterval(animate);\r\n\r\n audioBackground.pause();\r\n alert(`Game over ! Your Score: ${score}`);\r\n\r\n canv.style.display = \"none\";\r\n div1[0].style.display = \"block\";\r\n }", "function handleGameEndDialogClose() {\n setGameEndDialogOpen(false);\n setCurrentRound(1);\n setScore(0);\n }", "function endGame() {\n //stop timer\n clearInterval(setTimer);\n //remove event listener so no more moves can be made\n deck.removeEventListener('click', showCard);\n //open popup\n showScore();\n}", "function endgame(){\n\tplayer.kill();\n\tscorelabel.text=\"GAME OVER! \\n You scored \"+score;\n\tscoretext.visible=false;\n\tlifelabel.visible=false;\n\tlifetext.visible=false;\n\n}", "function endGame() {\n disableButtons();\n if (isWinner) {\n msgEl.innerHTML = `Congratulations! You're memory is too great for this game!\n Press restart and play again!`;\n yahoo.play();\n } else {\n msgEl.innerHTML = `Wrong answer! Press restart to try again!`;\n }\n}", "EndGame() {\n state.current.gameOver = true;\n state.current.moving = false;\n pipeMan.Stop();\n ui.ShowGameOver();\n\n //Set highscore\n const best = localStorage.getItem('best');\n if (state.current.score > best)\n localStorage.setItem('best', state.current.score);\n }", "function finish() {\n module.exports.gameOver = true;\n}", "async function endGame(gameWinner) {\n\n clearGameDisplay();\n\n // make API call to get a new deck and new starting draw\n const gameData = await fetch(`/game/${game.gameName}/endGame/${gameWinner}`);\n\n game = await gameData.json();\n\n initGame();\n}", "function endGame(finshingCode) {\n clearInterval(gameTimerId);\n clearInterval(slidinginterval);\n document.removeEventListener(\"keydown\", keydownListener);\n localStorage.setItem(\"last score\", targetsDestroyed); //storing last score in local storage\n //clearing certain variable for next play\n seconds = 0;\n minutes = 0;\n targetsDestroyed = 0;\n //change title to SWAL\n if (finshingCode === gameOver.win) {\n confirmObject.title = \"Winner\";\n } else if (finshingCode === gameOver.lose) {\n confirmObject.title = \"Better luck next time!\";\n }\n //alerting using sweet alert 2 javascript popup libirary\n Swal.fire(confirmObject).then((result) => {\n if (result.value) {\n //removeing the container childrens\n container.innerHTML = \"\";\n startGame();\n } else {\n //window.location.replace(\"Home.html\");\n window.location.href = \"Home.html\"; //redirecting to home page\n }\n });\n\n }", "function endGame() {\n // stop the interval timer\n clearInterval(interval);\n\n // turn off event handlers\n $(document).off();\n }", "function endGame(result){\n if(result){\n clientGame.screen = 'goodWinScreen';\n } else {\n clientGame.screen = 'evilWinScreen';\n }\n\n socket.emit('syncMasterGamestate', clientGame);\n generateView();\n}", "function endGame(){\n \tsetTimeout(function() {\n // \t\tvar highScore = localStorage.getItem('highScore');\n // \t\tif (score > highScore) {\n // \t\t\tlocalStorage.removeItem('highScore');\n // \t\t\thighScore = localStorage.setItem('highScore', score);\n // \t\t\t//$('#high-score').text('High Score: ' + score);\n // \t\t} else {\n // \t\t\thighScore = localStorage.getItem('highScore');\n // \t\t\t//$('#high-score').text('High Score: ' + highScore);\n // \t\t}\n \t\t$('#game-board').hide();\n \t\tinputScore.show();\n \t\t$('#play-again').show();\n \t\t$('#exit-game').show();\n \t\t$('#leader-board').show();\n \t\t$('#end-image').show();\n \t\t$('.counter').hide();\n \t}, 13000);\n }", "function endGame() {\n clearInterval(timer);\n timer = null;\n id(\"start\").disabled = false;\n id(\"stop\").disabled = true;\n text = null;\n index = 0;\n qs(\"textarea\").disabled = false;\n id(\"output\").innerText = \"\";\n }" ]
[ "0.8695062", "0.8652793", "0.842223", "0.84094644", "0.82225084", "0.82072544", "0.81989086", "0.81869495", "0.8170868", "0.8165294", "0.81194997", "0.8096833", "0.80869603", "0.80722296", "0.8029245", "0.8025281", "0.80249494", "0.8019394", "0.80151635", "0.7997619", "0.7972375", "0.79698265", "0.7956648", "0.79528207", "0.79469067", "0.7939349", "0.79162115", "0.78984207", "0.78956825", "0.78797346", "0.787751", "0.7853471", "0.78532785", "0.78520274", "0.78488827", "0.78408545", "0.78352785", "0.78325593", "0.7811948", "0.7807138", "0.7781304", "0.77713454", "0.7761058", "0.77579963", "0.7757015", "0.7756516", "0.77556103", "0.7752935", "0.7749835", "0.7747511", "0.7728808", "0.771401", "0.7713552", "0.7712305", "0.7708704", "0.7701675", "0.7696098", "0.7696098", "0.7683351", "0.76810837", "0.76810396", "0.7681024", "0.7672237", "0.76683843", "0.7664036", "0.76561797", "0.7647361", "0.76279974", "0.7626206", "0.76256", "0.76179665", "0.7616072", "0.76046646", "0.76037186", "0.7601653", "0.7598793", "0.759657", "0.7587485", "0.75726795", "0.75724614", "0.7567792", "0.75660336", "0.755588", "0.7548574", "0.7548574", "0.7548574", "0.7548574", "0.7538632", "0.75298566", "0.75268334", "0.752183", "0.75207484", "0.7517563", "0.75124305", "0.75076365", "0.74944407", "0.7492708", "0.74873906", "0.7466791", "0.74629086", "0.7462602" ]
0.0
-1